mirror of
https://github.com/PepperDash/PepperDashCore.git
synced 2026-01-11 19:44:44 +00:00
Merge branch 'release' into feature-2/camera-list-config
This commit is contained in:
BIN
._Readme.md
BIN
._Readme.md
Binary file not shown.
21
.github/workflows/EssentialsPlugins-builds-4-series-caller.yml
vendored
Normal file
21
.github/workflows/EssentialsPlugins-builds-4-series-caller.yml
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
name: Build PepperDash Core
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
getVersion:
|
||||||
|
uses: PepperDash/workflow-templates/.github/workflows/essentialsplugins-getversion.yml@main
|
||||||
|
secrets: inherit
|
||||||
|
build-4Series:
|
||||||
|
uses: PepperDash/workflow-templates/.github/workflows/essentialsplugins-4Series-builds.yml@main
|
||||||
|
secrets: inherit
|
||||||
|
needs: getVersion
|
||||||
|
if: needs.getVersion.outputs.newVersion == 'true'
|
||||||
|
with:
|
||||||
|
newVersion: ${{ needs.getVersion.outputs.newVersion }}
|
||||||
|
version: ${{ needs.getVersion.outputs.version }}
|
||||||
|
tag: ${{ needs.getVersion.outputs.tag }}
|
||||||
|
channel: ${{ needs.getVersion.outputs.channel }}
|
||||||
85
.github/workflows/docker.yml
vendored
85
.github/workflows/docker.yml
vendored
@@ -1,85 +0,0 @@
|
|||||||
name: Branch Build Using Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- feature-2/*
|
|
||||||
- hotfix-2/*
|
|
||||||
- release-2/*
|
|
||||||
- development-2
|
|
||||||
|
|
||||||
env:
|
|
||||||
# solution path doesn't need slashes unless there it is multiple folders deep
|
|
||||||
# solution name does not include extension. .sln is assumed
|
|
||||||
SOLUTION_PATH: .
|
|
||||||
SOLUTION_FILE: PepperDash Core
|
|
||||||
# Do not edit this, we're just creating it here
|
|
||||||
VERSION: 0.0.0-buildtype-buildnumber
|
|
||||||
# Defaults to debug for build type
|
|
||||||
BUILD_TYPE: Debug
|
|
||||||
# Defaults to main as the release branch. Change as necessary
|
|
||||||
RELEASE_BRANCH: main
|
|
||||||
jobs:
|
|
||||||
Build_Project_4-Series:
|
|
||||||
runs-on: windows-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
# Fetch all tags
|
|
||||||
- name: Fetch tags
|
|
||||||
run: git fetch --tags
|
|
||||||
# Generate the appropriate version number
|
|
||||||
- name: Set Version Number
|
|
||||||
id: setVersion
|
|
||||||
shell: powershell
|
|
||||||
run: |
|
|
||||||
$latestVersion = [version]"2.0.0"
|
|
||||||
|
|
||||||
$newVersion = [version]$latestVersion
|
|
||||||
$phase = ""
|
|
||||||
$newVersionString = ""
|
|
||||||
|
|
||||||
switch -regex ($Env:GITHUB_REF) {
|
|
||||||
'^refs\/pull\/*.' {
|
|
||||||
$phase = 'beta';
|
|
||||||
$newVersionString = "{0}-{1}-{2}" -f $newVersion, $phase, $Env:GITHUB_RUN_NUMBER
|
|
||||||
}
|
|
||||||
'^refs\/heads\/feature-2\/*.' {
|
|
||||||
$phase = 'alpha'
|
|
||||||
$newVersionString = "{0}-{1}-{2}" -f $newVersion, $phase, $Env:GITHUB_RUN_NUMBER
|
|
||||||
}
|
|
||||||
'development-2' {
|
|
||||||
$phase = 'beta'
|
|
||||||
$newVersionString = "{0}-{1}-{2}" -f $newVersion, $phase, $Env:GITHUB_RUN_NUMBER
|
|
||||||
}
|
|
||||||
}
|
|
||||||
echo "version=$newVersionString" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
|
||||||
- name: Setup MS Build
|
|
||||||
uses: microsoft/setup-msbuild@v1.1
|
|
||||||
- name: restore Nuget Packages
|
|
||||||
run: nuget restore .\$($Env:SOLUTION_FILE).sln
|
|
||||||
# Build the solutions in the docker image
|
|
||||||
- name: Build Solution
|
|
||||||
run: msbuild .\$($Env:SOLUTION_FILE).sln /p:Platform="Any CPU" /p:Configuration="Debug" /p:Version="${{ steps.setVersion.outputs.version }}"
|
|
||||||
- name: Create tag for non-rc builds
|
|
||||||
if: contains(steps.setVersion.outputs.version, 'alpha')
|
|
||||||
run: |
|
|
||||||
git tag ${{ steps.setVersion.outputs.version }}
|
|
||||||
git push --tags origin
|
|
||||||
# Create the release on the source repo
|
|
||||||
- name: Create Release
|
|
||||||
id: create_release
|
|
||||||
if: contains(steps.setVersion.outputs.version,'-rc-') ||
|
|
||||||
contains(steps.setVersion.outputs.version,'-hotfix-') ||
|
|
||||||
contains(steps.setVersion.outputs.version, 'beta')
|
|
||||||
uses: ncipollo/release-action@v1
|
|
||||||
with:
|
|
||||||
artifacts: '**\*.clz'
|
|
||||||
generateReleaseNotes: true
|
|
||||||
prerelease: ${{contains('debug', env.BUILD_TYPE)}}
|
|
||||||
tag: ${{ steps.setVersion.outputs.version }}
|
|
||||||
- name: Publish to Nuget
|
|
||||||
run: |
|
|
||||||
nuget sources add -name github -source https://nuget.pkg.github.com/pepperdash/index.json -username Pepperdash -password ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
nuget setApiKey ${{ secrets.NUGET_API_KEY }}
|
|
||||||
nuget push ".\package\PepperDashCore.${{ steps.setVersion.outputs.version }}.nupkg" -Source github
|
|
||||||
nuget push ".\package\PepperDashCore.${{ steps.setVersion.outputs.version }}.nupkg" -Source https://api.nuget.org/v3/index.json
|
|
||||||
54
.github/workflows/main.yml
vendored
54
.github/workflows/main.yml
vendored
@@ -1,54 +0,0 @@
|
|||||||
name: Main Build using Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
release:
|
|
||||||
types:
|
|
||||||
- created
|
|
||||||
branches:
|
|
||||||
- main-2
|
|
||||||
env:
|
|
||||||
# solution path doesn't need slashes unless there it is multiple folders deep
|
|
||||||
# solution name does not include extension. .sln is assumed
|
|
||||||
SOLUTION_PATH: .
|
|
||||||
SOLUTION_FILE: Pepperdash Core
|
|
||||||
# Do not edit this, we're just creating it here
|
|
||||||
VERSION: 0.0.0-buildtype-buildnumber
|
|
||||||
# Defaults to debug for build type
|
|
||||||
BUILD_TYPE: Release
|
|
||||||
# Defaults to main as the release branch. Change as necessary
|
|
||||||
RELEASE_BRANCH: main
|
|
||||||
jobs:
|
|
||||||
Build_Project_4-Series:
|
|
||||||
runs-on: windows-latest
|
|
||||||
steps:
|
|
||||||
# First we checkout the source repo
|
|
||||||
- name: Checkout repo
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
# Generate the appropriate version number
|
|
||||||
- name: Set Version Number
|
|
||||||
shell: powershell
|
|
||||||
env:
|
|
||||||
TAG_NAME: ${{ github.event.release.tag_name }}
|
|
||||||
run: echo "VERSION=$($Env:TAG_NAME)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
|
||||||
- name: Setup MS-Build
|
|
||||||
uses: microsoft/setup-msbuild@v1
|
|
||||||
- name: restore Nuget Packages
|
|
||||||
run: nuget restore .\$($Env:SOLUTION_FILE).sln
|
|
||||||
- name: Build Solution
|
|
||||||
run: msbuild .\$($Env:SOLUTION_FILE).sln /p:Platform="Any CPU" /p:Configuration="Release" /p:Version="${{ steps.setVersion.outputs.version }}"
|
|
||||||
- name: Update Existing Release
|
|
||||||
id: create_release
|
|
||||||
uses: ncipollo/release-action@v1
|
|
||||||
with:
|
|
||||||
artifacts: '**\*.clz'
|
|
||||||
generateReleaseNotes: false
|
|
||||||
prerelease: false
|
|
||||||
tag: ${{ github.event.release.tag_name }}
|
|
||||||
- name: Add nuget.exe
|
|
||||||
uses: nuget/setup-nuget@v1
|
|
||||||
- name: Publish to Nuget
|
|
||||||
run: |
|
|
||||||
nuget sources add -name github -source https://nuget.pkg.github.com/pepperdash/index.json -username Pepperdash -password ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
nuget setApiKey ${{ secrets.NUGET_API_KEY }}
|
|
||||||
nuget push ".\package\PepperDashCore.${{ github.event.release.tag_name }}.nupkg" -Source github
|
|
||||||
nuget push ".\package\PepperDashCore.${{ github.event.release.tag_name }}.nupkg" -Source https://api.nuget.org/v3/index.json
|
|
||||||
36
.releaserc.json
Normal file
36
.releaserc.json
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"plugins": [
|
||||||
|
[
|
||||||
|
"@semantic-release/commit-analyzer",
|
||||||
|
{
|
||||||
|
"releaseRules": [
|
||||||
|
{ "scope": "force-patch", "release": "patch" },
|
||||||
|
{ "scope": "no-release", "release": false }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"@semantic-release/release-notes-generator",
|
||||||
|
["@semantic-release/changelog",
|
||||||
|
{
|
||||||
|
"changelogFile": "CHANGELOG.md"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"@semantic-release/exec",
|
||||||
|
{
|
||||||
|
"verifyReleaseCmd": "echo \"newVersion=true\" >> $GITHUB_OUTPUT",
|
||||||
|
"publishCmd": "echo \"version=${nextRelease.version}\" >> $GITHUB_OUTPUT && echo \"tag=${nextRelease.gitTag}\" >> $GITHUB_OUTPUT && echo \"type=${nextRelease.type}\" >> $GITHUB_OUTPUT && echo \"channel=${nextRelease.channel}\" >> $GITHUB_OUTPUT"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"branches": [
|
||||||
|
"main",
|
||||||
|
{"name": "development", "prerelease": "beta", "channel": "beta"},
|
||||||
|
{"name": "release", "prerelease": "rc", "channel": "rc"},
|
||||||
|
{
|
||||||
|
"name": "replace-me-feature-branch",
|
||||||
|
"prerelease": "replace-me-prerelease",
|
||||||
|
"channel": "replace-me-prerelease"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio Version 17
|
|
||||||
VisualStudioVersion = 17.1.32228.430
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash_Core", "src\Pepperdash Core\PepperDash_Core.csproj", "{85BC97D4-5564-4268-8F7B-1532E2DE0456}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Any CPU = Debug|Any CPU
|
|
||||||
Release|Any CPU = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{85BC97D4-5564-4268-8F7B-1532E2DE0456}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{85BC97D4-5564-4268-8F7B-1532E2DE0456}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{85BC97D4-5564-4268-8F7B-1532E2DE0456}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{85BC97D4-5564-4268-8F7B-1532E2DE0456}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
|
||||||
SolutionGuid = {E4615FA3-8C8C-4DC0-897B-E85408B4E341}
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
||||||
@@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
|||||||
# Visual Studio Version 17
|
# Visual Studio Version 17
|
||||||
VisualStudioVersion = 17.1.32228.430
|
VisualStudioVersion = 17.1.32228.430
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash_Core", "Pepperdash Core\PepperDash_Core.csproj", "{66EB9188-E7AC-410D-AD59-931131DA7C2E}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Core.4Series", "src\PepperDash.Core.4Series.csproj", "{100ABA44-9471-4B18-8092-4D94D7D82223}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
@@ -11,10 +11,10 @@ Global
|
|||||||
Release|Any CPU = Release|Any CPU
|
Release|Any CPU = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
{66EB9188-E7AC-410D-AD59-931131DA7C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{100ABA44-9471-4B18-8092-4D94D7D82223}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{66EB9188-E7AC-410D-AD59-931131DA7C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{100ABA44-9471-4B18-8092-4D94D7D82223}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{66EB9188-E7AC-410D-AD59-931131DA7C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{100ABA44-9471-4B18-8092-4D94D7D82223}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{66EB9188-E7AC-410D-AD59-931131DA7C2E}.Release|Any CPU.Build.0 = Release|Any CPU
|
{100ABA44-9471-4B18-8092-4D94D7D82223}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
BIN
output/PepperDashCore.2.0.0-local.clz
Normal file
BIN
output/PepperDashCore.2.0.0-local.clz
Normal file
Binary file not shown.
@@ -1,10 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
using Crestron.SimplSharp;
|
using Crestron.SimplSharp;
|
||||||
using Crestron.SimplSharp.CrestronSockets;
|
using Crestron.SimplSharp.CrestronSockets;
|
||||||
using Crestron.SimplSharp.Ssh;
|
using Org.BouncyCastle.Utilities;
|
||||||
using Crestron.SimplSharp.Ssh.Common;
|
using PepperDash.Core.Logging;
|
||||||
|
using Renci.SshNet;
|
||||||
|
using Renci.SshNet.Common;
|
||||||
|
|
||||||
namespace PepperDash.Core
|
namespace PepperDash.Core
|
||||||
{
|
{
|
||||||
@@ -133,7 +135,8 @@ namespace PepperDash.Core
|
|||||||
CTimer ReconnectTimer;
|
CTimer ReconnectTimer;
|
||||||
|
|
||||||
//Lock object to prevent simulatneous connect/disconnect operations
|
//Lock object to prevent simulatneous connect/disconnect operations
|
||||||
private CCriticalSection connectLock = new CCriticalSection();
|
//private CCriticalSection connectLock = new CCriticalSection();
|
||||||
|
private SemaphoreSlim connectLock = new SemaphoreSlim(1);
|
||||||
|
|
||||||
private bool DisconnectLogged = false;
|
private bool DisconnectLogged = false;
|
||||||
|
|
||||||
@@ -144,13 +147,31 @@ namespace PepperDash.Core
|
|||||||
base(key)
|
base(key)
|
||||||
{
|
{
|
||||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||||
Key = key;
|
Key = key;
|
||||||
Hostname = hostname;
|
Hostname = hostname;
|
||||||
Port = port;
|
Port = port;
|
||||||
Username = username;
|
Username = username;
|
||||||
Password = password;
|
Password = password;
|
||||||
AutoReconnectIntervalMs = 5000;
|
AutoReconnectIntervalMs = 5000;
|
||||||
|
|
||||||
|
ReconnectTimer = new CTimer(o =>
|
||||||
|
{
|
||||||
|
if (ConnectEnabled)
|
||||||
|
{
|
||||||
|
Connect();
|
||||||
|
}
|
||||||
|
}, System.Threading.Timeout.Infinite);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// S+ Constructor - Must set all properties before calling Connect
|
||||||
|
/// </summary>
|
||||||
|
public GenericSshClient()
|
||||||
|
: base(SPlusKey)
|
||||||
|
{
|
||||||
|
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||||
|
AutoReconnectIntervalMs = 5000;
|
||||||
|
|
||||||
ReconnectTimer = new CTimer(o =>
|
ReconnectTimer = new CTimer(o =>
|
||||||
{
|
{
|
||||||
@@ -158,8 +179,8 @@ namespace PepperDash.Core
|
|||||||
{
|
{
|
||||||
Connect();
|
Connect();
|
||||||
}
|
}
|
||||||
}, Timeout.Infinite);
|
}, System.Threading.Timeout.Infinite);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// S+ Constructor - Must set all properties before calling Connect
|
/// S+ Constructor - Must set all properties before calling Connect
|
||||||
@@ -170,33 +191,16 @@ namespace PepperDash.Core
|
|||||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||||
AutoReconnectIntervalMs = 5000;
|
AutoReconnectIntervalMs = 5000;
|
||||||
|
|
||||||
ReconnectTimer = new CTimer(o =>
|
/// <summary>
|
||||||
{
|
/// Handles closing this up when the program shuts down
|
||||||
if (ConnectEnabled)
|
/// </summary>
|
||||||
{
|
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||||
Connect();
|
{
|
||||||
}
|
if (programEventType == eProgramStatusEventType.Stopping)
|
||||||
}, Timeout.Infinite);
|
{
|
||||||
}
|
if (Client != null)
|
||||||
|
{
|
||||||
/// <summary>
|
this.LogDebug("Program stopping. Closing connection");
|
||||||
/// Just to help S+ set the key
|
|
||||||
/// </summary>
|
|
||||||
public void Initialize(string key)
|
|
||||||
{
|
|
||||||
Key = key;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles closing this up when the program shuts down
|
|
||||||
/// </summary>
|
|
||||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
|
||||||
{
|
|
||||||
if (programEventType == eProgramStatusEventType.Stopping)
|
|
||||||
{
|
|
||||||
if (Client != null)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Program stopping. Closing connection");
|
|
||||||
Disconnect();
|
Disconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -211,7 +215,7 @@ namespace PepperDash.Core
|
|||||||
if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535
|
if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535
|
||||||
|| Username == null || Password == null)
|
|| Username == null || Password == null)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Connect failed. Check hostname, port, username and password are set or not null");
|
this.LogError("Connect failed. Check hostname, port, username and password are set or not null");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,25 +223,25 @@ namespace PepperDash.Core
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
connectLock.Enter();
|
connectLock.Wait();
|
||||||
if (IsConnected)
|
if (IsConnected)
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Connection already connected. Exiting Connect()");
|
this.LogDebug("Connection already connected. Exiting Connect");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Attempting connect");
|
this.LogDebug("Attempting connect");
|
||||||
|
|
||||||
// Cancel reconnect if running.
|
// Cancel reconnect if running.
|
||||||
if (ReconnectTimer != null)
|
if (ReconnectTimer != null)
|
||||||
{
|
{
|
||||||
ReconnectTimer.Stop();
|
ReconnectTimer.Stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cleanup the old client if it already exists
|
// Cleanup the old client if it already exists
|
||||||
if (Client != null)
|
if (Client != null)
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Cleaning up disconnected client");
|
this.LogDebug("Cleaning up disconnected client");
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,7 +250,7 @@ namespace PepperDash.Core
|
|||||||
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(kauth_AuthenticationPrompt);
|
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(kauth_AuthenticationPrompt);
|
||||||
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
|
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
|
||||||
|
|
||||||
Debug.Console(1, this, "Creating new SshClient");
|
this.LogDebug("Creating new SshClient");
|
||||||
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, Port, Username, pauth, kauth);
|
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, Port, Username, pauth, kauth);
|
||||||
Client = new SshClient(connectionInfo);
|
Client = new SshClient(connectionInfo);
|
||||||
Client.ErrorOccurred += Client_ErrorOccurred;
|
Client.ErrorOccurred += Client_ErrorOccurred;
|
||||||
@@ -263,7 +267,7 @@ namespace PepperDash.Core
|
|||||||
string str = TheStream.Read();
|
string str = TheStream.Read();
|
||||||
}
|
}
|
||||||
TheStream.DataReceived += Stream_DataReceived;
|
TheStream.DataReceived += Stream_DataReceived;
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connected");
|
this.LogInformation("Connected");
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
||||||
DisconnectLogged = false;
|
DisconnectLogged = false;
|
||||||
}
|
}
|
||||||
@@ -273,35 +277,52 @@ namespace PepperDash.Core
|
|||||||
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
||||||
|
|
||||||
if (ie is SocketException)
|
if (ie is SocketException)
|
||||||
Debug.Console(1, this, errorLogLevel, "'{0}' CONNECTION failure: Cannot reach host, ({1})", Key, ie.Message);
|
|
||||||
else if (ie is System.Net.Sockets.SocketException)
|
|
||||||
Debug.Console(1, this, errorLogLevel, "'{0}' Connection failure: Cannot reach host '{1}' on port {2}, ({3})",
|
|
||||||
Key, Hostname, Port, ie.GetType());
|
|
||||||
else if (ie is SshAuthenticationException)
|
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, errorLogLevel, "Authentication failure for username '{0}', ({1})",
|
this.LogException(ie, "CONNECTION failure: Cannot reach host, ({1})", Key, ie.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ie is System.Net.Sockets.SocketException socketException)
|
||||||
|
{
|
||||||
|
this.LogException(ie, "'{0}' Connection failure: Cannot reach host '{1}' on port {2}, ({3})",
|
||||||
|
Key, Hostname, Port, ie.GetType());
|
||||||
|
}
|
||||||
|
if (ie is SshAuthenticationException)
|
||||||
|
{
|
||||||
|
this.LogException(ie, "Authentication failure for username '{0}', ({1})", this,
|
||||||
Username, ie.Message);
|
Username, ie.Message);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
Debug.Console(1, this, errorLogLevel, "Error on connect:\r({0})", ie.Message);
|
this.LogException(ie, "Error on connect");
|
||||||
|
|
||||||
DisconnectLogged = true;
|
DisconnectLogged = true;
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||||
if (AutoReconnect)
|
if (AutoReconnect)
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||||
|
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(SshOperationTimeoutException ex)
|
||||||
|
{
|
||||||
|
this.LogWarning("Connection attempt timed out: {message}", ex.Message);
|
||||||
|
|
||||||
|
DisconnectLogged = true;
|
||||||
|
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||||
|
if (AutoReconnect)
|
||||||
|
{
|
||||||
|
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
||||||
Debug.Console(1, this, errorLogLevel, "Unhandled exception on connect:\r({0})", e.Message);
|
this.LogException(e, "Unhandled exception on connect");
|
||||||
DisconnectLogged = true;
|
DisconnectLogged = true;
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||||
if (AutoReconnect)
|
if (AutoReconnect)
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -309,22 +330,22 @@ namespace PepperDash.Core
|
|||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
connectLock.Leave();
|
connectLock.Release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Disconnect the clients and put away it's resources.
|
/// Disconnect the clients and put away it's resources.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void Disconnect()
|
public void Disconnect()
|
||||||
{
|
{
|
||||||
ConnectEnabled = false;
|
ConnectEnabled = false;
|
||||||
// Stop trying reconnects, if we are
|
// Stop trying reconnects, if we are
|
||||||
if (ReconnectTimer != null)
|
if (ReconnectTimer != null)
|
||||||
{
|
{
|
||||||
ReconnectTimer.Stop();
|
ReconnectTimer.Stop();
|
||||||
// ReconnectTimer = null;
|
// ReconnectTimer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||||
}
|
}
|
||||||
@@ -345,40 +366,12 @@ namespace PepperDash.Core
|
|||||||
Client.Dispose();
|
Client.Dispose();
|
||||||
Client = null;
|
Client = null;
|
||||||
ClientStatus = status;
|
ClientStatus = status;
|
||||||
Debug.Console(1, this, "Disconnected");
|
this.LogDebug("Disconnected");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Exception in Kill Client:{0}", ex);
|
this.LogException(ex,"Exception in Kill Client");
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Anything to do with reestablishing connection on failures
|
|
||||||
/// </summary>
|
|
||||||
void HandleConnectionFailure()
|
|
||||||
{
|
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
|
||||||
|
|
||||||
Debug.Console(1, this, "Client nulled due to connection failure. AutoReconnect: {0}, ConnectEnabled: {1}", AutoReconnect, ConnectEnabled);
|
|
||||||
if (AutoReconnect && ConnectEnabled)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
|
||||||
if (ReconnectTimer == null)
|
|
||||||
{
|
|
||||||
ReconnectTimer = new CTimer(o =>
|
|
||||||
{
|
|
||||||
Connect();
|
|
||||||
}, AutoReconnectIntervalMs);
|
|
||||||
Debug.Console(1, this, "Attempting connection in {0} seconds",
|
|
||||||
(float)(AutoReconnectIntervalMs / 1000));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "{0} second reconnect cycle running",
|
|
||||||
(float)(AutoReconnectIntervalMs / 1000));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -386,7 +379,7 @@ namespace PepperDash.Core
|
|||||||
/// Kills the stream
|
/// Kills the stream
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void KillStream()
|
void KillStream()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (TheStream != null)
|
if (TheStream != null)
|
||||||
@@ -395,85 +388,84 @@ namespace PepperDash.Core
|
|||||||
TheStream.Close();
|
TheStream.Close();
|
||||||
TheStream.Dispose();
|
TheStream.Dispose();
|
||||||
TheStream = null;
|
TheStream = null;
|
||||||
Debug.Console(1, this, "Disconnected stream");
|
this.LogDebug("Disconnected stream");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Exception in Kill Stream:{0}", ex);
|
this.LogException(ex, "Exception in Kill Stream:{0}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handles the keyboard interactive authentication, should it be required.
|
/// Handles the keyboard interactive authentication, should it be required.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
|
void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
|
||||||
{
|
{
|
||||||
foreach (AuthenticationPrompt prompt in e.Prompts)
|
foreach (AuthenticationPrompt prompt in e.Prompts)
|
||||||
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
|
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
|
||||||
prompt.Response = Password;
|
prompt.Response = Password;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
|
/// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void Stream_DataReceived(object sender, Crestron.SimplSharp.Ssh.Common.ShellDataEventArgs e)
|
void Stream_DataReceived(object sender, ShellDataEventArgs e)
|
||||||
{
|
{
|
||||||
if (((ShellStream)sender).Length <= 0L)
|
if (((ShellStream)sender).Length <= 0L)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var response = ((ShellStream)sender).Read();
|
var response = ((ShellStream)sender).Read();
|
||||||
|
|
||||||
var bytesHandler = BytesReceived;
|
var bytesHandler = BytesReceived;
|
||||||
|
|
||||||
if (bytesHandler != null)
|
if (bytesHandler != null)
|
||||||
{
|
{
|
||||||
var bytes = Encoding.UTF8.GetBytes(response);
|
var bytes = Encoding.UTF8.GetBytes(response);
|
||||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
this.LogInformation("Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||||
}
|
}
|
||||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||||
}
|
}
|
||||||
|
|
||||||
var textHandler = TextReceived;
|
var textHandler = TextReceived;
|
||||||
if (textHandler != null)
|
if (textHandler != null)
|
||||||
{
|
{
|
||||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||||
Debug.Console(0, this, "Received: '{0}'", ComTextHelper.GetDebugText(response));
|
this.LogInformation("Received: '{0}'", ComTextHelper.GetDebugText(response));
|
||||||
|
|
||||||
textHandler(this, new GenericCommMethodReceiveTextArgs(response));
|
textHandler(this, new GenericCommMethodReceiveTextArgs(response));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
|
/// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
|
||||||
/// event
|
/// event
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void Client_ErrorOccurred(object sender, Crestron.SimplSharp.Ssh.Common.ExceptionEventArgs e)
|
void Client_ErrorOccurred(object sender, ExceptionEventArgs e)
|
||||||
{
|
{
|
||||||
CrestronInvoke.BeginInvoke(o =>
|
CrestronInvoke.BeginInvoke(o =>
|
||||||
{
|
{
|
||||||
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
|
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Disconnected by remote");
|
this.LogError("Disconnected by remote");
|
||||||
else
|
else
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled SSH client error: {0}", e.Exception);
|
this.LogException(e.Exception, "Unhandled SSH client error");
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
connectLock.Enter();
|
connectLock.Wait();
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
connectLock.Leave();
|
connectLock.Release();
|
||||||
}
|
}
|
||||||
if (AutoReconnect && ConnectEnabled)
|
if (AutoReconnect && ConnectEnabled)
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -490,96 +482,87 @@ namespace PepperDash.Core
|
|||||||
|
|
||||||
#region IBasicCommunication Members
|
#region IBasicCommunication Members
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends text to the server
|
/// Sends text to the server
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="text"></param>
|
/// <param name="text"></param>
|
||||||
public void SendText(string text)
|
public void SendText(string text)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (Client != null && TheStream != null && IsConnected)
|
if (Client != null && TheStream != null && IsConnected)
|
||||||
{
|
{
|
||||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||||
Debug.Console(0,
|
this.LogInformation(
|
||||||
this,
|
"Sending {length} characters of text: '{text}'",
|
||||||
"Sending {0} characters of text: '{1}'",
|
text.Length,
|
||||||
text.Length,
|
ComTextHelper.GetDebugText(text));
|
||||||
ComTextHelper.GetDebugText(text));
|
|
||||||
|
|
||||||
TheStream.Write(text);
|
TheStream.Write(text);
|
||||||
TheStream.Flush();
|
TheStream.Flush();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Client is null or disconnected. Cannot Send Text");
|
this.LogDebug("Client is null or disconnected. Cannot Send Text");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (ObjectDisposedException ex)
|
catch (ObjectDisposedException ex)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Exception: {0}", ex.Message);
|
this.LogException(ex, "ObjectDisposedException sending {message}", text);
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Stack Trace: {0}", ex.StackTrace);
|
|
||||||
|
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||||
ReconnectTimer.Reset();
|
ReconnectTimer.Reset();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Exception: {0}", ex.Message);
|
this.LogException(ex, "Exception sending text: {message}", text);
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Stack Trace: {0}", ex.StackTrace);
|
}
|
||||||
|
}
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends Bytes to the server
|
/// Sends Bytes to the server
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="bytes"></param>
|
/// <param name="bytes"></param>
|
||||||
public void SendBytes(byte[] bytes)
|
public void SendBytes(byte[] bytes)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (Client != null && TheStream != null && IsConnected)
|
if (Client != null && TheStream != null && IsConnected)
|
||||||
{
|
{
|
||||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
this.LogInformation("Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||||
|
|
||||||
TheStream.Write(bytes, 0, bytes.Length);
|
TheStream.Write(bytes, 0, bytes.Length);
|
||||||
TheStream.Flush();
|
TheStream.Flush();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Client is null or disconnected. Cannot Send Bytes");
|
this.LogDebug("Client is null or disconnected. Cannot Send Bytes");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (ObjectDisposedException ex)
|
catch (ObjectDisposedException ex)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Exception: {0}", ex.Message);
|
this.LogException(ex, "ObjectDisposedException sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Stack Trace: {0}", ex.StackTrace);
|
|
||||||
|
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||||
ReconnectTimer.Reset();
|
ReconnectTimer.Reset();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Exception: {0}", ex.Message);
|
this.LogException(ex, "Exception sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Stack Trace: {0}", ex.StackTrace);
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed");
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
//*****************************************************************************************************
|
||||||
}
|
//*****************************************************************************************************
|
||||||
|
/// <summary>
|
||||||
//*****************************************************************************************************
|
/// Fired when connection changes
|
||||||
//*****************************************************************************************************
|
/// </summary>
|
||||||
/// <summary>
|
public class SshConnectionChangeEventArgs : EventArgs
|
||||||
/// Fired when connection changes
|
{
|
||||||
/// </summary>
|
|
||||||
public class SshConnectionChangeEventArgs : EventArgs
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Connection State
|
/// Connection State
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -219,7 +219,8 @@ namespace PepperDash.Core
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public GenericTcpIpClient()
|
public GenericTcpIpClient()
|
||||||
: base(SplusKey)
|
: base(SplusKey)
|
||||||
{
|
{
|
||||||
|
StreamDebugging = new CommunicationStreamDebugging(SplusKey);
|
||||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||||
AutoReconnectIntervalMs = 5000;
|
AutoReconnectIntervalMs = 5000;
|
||||||
BufferSize = 2000;
|
BufferSize = 2000;
|
||||||
19
src/Directory.build.props
Normal file
19
src/Directory.build.props
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<Version>2.0.0-local</Version>
|
||||||
|
<Authors>PepperDash Technologies</Authors>
|
||||||
|
<Company>PepperDash Technologies</Company>
|
||||||
|
<Product>PepperDash Essentials</Product>
|
||||||
|
<Copyright>Copyright © 2025</Copyright>
|
||||||
|
<RepositoryType>git</RepositoryType>
|
||||||
|
<PackageTags>Crestron; 4series</PackageTags>
|
||||||
|
<PackageOutputPath>../output</PackageOutputPath>
|
||||||
|
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||||
|
<PackageLicenseFile>LICENSE.md</PackageLicenseFile>
|
||||||
|
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="..\LICENSE.md" Pack="true" PackagePath=""/>
|
||||||
|
<None Include="..\README.md" Pack="true" PackagePath=""/>
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
43
src/Directory.build.targets
Normal file
43
src/Directory.build.targets
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<Project>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="$(TargetDir)\$(TargetName).$(Version).cpz" Condition="$(ProjectType) == 'Program'">
|
||||||
|
<Pack>true</Pack>
|
||||||
|
<PackagePath>content;</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Include="$(PackageOutputPath)\$(TargetName).$(Version).cplz" Condition="$(ProjectType) == 'ProgramLibrary'">
|
||||||
|
<Pack>true</Pack>
|
||||||
|
<PackagePath>content;</PackagePath>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
<Target Name="Create CPLZ" AfterTargets="Build; Rebuild" Condition="$(ProjectType) == 'ProgramLibrary'">
|
||||||
|
<Message Text="Creating CPLZ"></Message>
|
||||||
|
<MakeDir Directories="$(PackageOutputPath)" Condition="!Exists($(PackageOutputPath))"></MakeDir>
|
||||||
|
<ZipDirectory SourceDirectory="$(TargetDir)" DestinationFile="$(PackageOutputPath)\$(TargetName).$(Version).cplz" Overwrite="true"/>
|
||||||
|
</Target>
|
||||||
|
<Target Name="Clean CPLZ" AfterTargets="AfterClean" Condition="$(ProjectType) == 'ProgramLibrary'">
|
||||||
|
<Delete Files="$(PackageOutputPath)\$(TargetName).$(Version).cplz"/>
|
||||||
|
</Target>
|
||||||
|
<Target Name="Copy CPZ" AfterTargets="SimplSharpPostProcess" Condition="$(ProjectType) == 'Program'">
|
||||||
|
<Message Text="Copying CPZ"></Message>
|
||||||
|
<Move SourceFiles="$(TargetDir)\$(TargetName).cpz" DestinationFiles="$(TargetDir)\$(TargetName).$(Version).cpz"/>
|
||||||
|
<Copy SourceFiles="$(TargetDir)\$(TargetName).$(Version).cpz" DestinationFiles="$(PackageOutputPath)\$(TargetName).$(Version).cpz"/>
|
||||||
|
</Target>
|
||||||
|
<Target Name="Clean CPZ" AfterTargets="AfterClean" Condition="$(ProjectType) == 'Program'">
|
||||||
|
<Delete Files="$(PackageOutputPath)\$(TargetName).$(Version).cpz"/>
|
||||||
|
</Target>
|
||||||
|
<Target Name="Copy CLZ" AfterTargets="SimplSharpPostProcess">
|
||||||
|
<Message Text="Copying CLZ"></Message>
|
||||||
|
<Move SourceFiles="$(TargetDir)\$(TargetName).clz" DestinationFiles="$(TargetDir)\$(TargetName).$(Version).clz"/>
|
||||||
|
<Copy SourceFiles="$(TargetDir)\$(TargetName).$(Version).clz" DestinationFiles="$(PackageOutputPath)\$(TargetName).$(Version).clz"/>
|
||||||
|
</Target>
|
||||||
|
<Target Name="Clean CLZ" AfterTargets="AfterClean">
|
||||||
|
<Delete Files="$(PackageOutputPath)\$(TargetName).$(Version).clz"/>
|
||||||
|
</Target>
|
||||||
|
<Target Name="SimplSharpNewtonsoft" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
|
||||||
|
<ItemGroup>
|
||||||
|
<ReferencePath Condition="'%(FileName)' == 'Newtonsoft.Json.Compact'">
|
||||||
|
<Aliases>doNotUse</Aliases>
|
||||||
|
</ReferencePath>
|
||||||
|
</ItemGroup>
|
||||||
|
</Target>
|
||||||
|
</Project>
|
||||||
21
src/EssentialsPlugins-builds-4-series-caller.yml
Normal file
21
src/EssentialsPlugins-builds-4-series-caller.yml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
name: Build Essentials Plugin
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
getVersion:
|
||||||
|
uses: PepperDash/workflow-templates/.github/workflows/essentialsplugins-getversion.yml@main
|
||||||
|
secrets: inherit
|
||||||
|
build-4Series:
|
||||||
|
uses: PepperDash/workflow-templates/.github/workflows/essentialsplugins-4Series-builds.yml@main
|
||||||
|
secrets: inherit
|
||||||
|
needs: getVersion
|
||||||
|
if: needs.getVersion.outputs.newVersion == 'true'
|
||||||
|
with:
|
||||||
|
newVersion: ${{ needs.getVersion.outputs.newVersion }}
|
||||||
|
version: ${{ needs.getVersion.outputs.version }}
|
||||||
|
tag: ${{ needs.getVersion.outputs.tag }}
|
||||||
|
channel: ${{ needs.getVersion.outputs.channel }}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
using Crestron.SimplSharp;
|
using Crestron.SimplSharp;
|
||||||
using Crestron.SimplSharp.CrestronIO;
|
using Crestron.SimplSharp.CrestronIO;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
@@ -159,7 +160,11 @@ namespace PepperDash.Core.JsonToSimpl
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static JObject ParseObject(string json)
|
public static JObject ParseObject(string json)
|
||||||
{
|
{
|
||||||
using (var reader = new JsonTextReader(new StringReader(json)))
|
#if NET6_0
|
||||||
|
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
|
||||||
|
#else
|
||||||
|
using (var reader = new JsonTextReader(new Crestron.SimplSharp.CrestronIO.StringReader(json)))
|
||||||
|
#endif
|
||||||
{
|
{
|
||||||
var startDepth = reader.Depth;
|
var startDepth = reader.Depth;
|
||||||
var obj = JObject.Load(reader);
|
var obj = JObject.Load(reader);
|
||||||
@@ -176,7 +181,11 @@ namespace PepperDash.Core.JsonToSimpl
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static JArray ParseArray(string json)
|
public static JArray ParseArray(string json)
|
||||||
{
|
{
|
||||||
using (var reader = new JsonTextReader(new StringReader(json)))
|
#if NET6_0
|
||||||
|
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
|
||||||
|
#else
|
||||||
|
using (var reader = new JsonTextReader(new Crestron.SimplSharp.CrestronIO.StringReader(json)))
|
||||||
|
#endif
|
||||||
{
|
{
|
||||||
var startDepth = reader.Depth;
|
var startDepth = reader.Depth;
|
||||||
var obj = JArray.Load(reader);
|
var obj = JArray.Load(reader);
|
||||||
@@ -1,11 +1,16 @@
|
|||||||
using Serilog;
|
using Serilog;
|
||||||
using Serilog.Events;
|
using Serilog.Events;
|
||||||
|
using System;
|
||||||
using Log = PepperDash.Core.Debug;
|
using Log = PepperDash.Core.Debug;
|
||||||
|
|
||||||
namespace PepperDash.Core.Logging
|
namespace PepperDash.Core.Logging
|
||||||
{
|
{
|
||||||
public static class DebugExtensions
|
public static class DebugExtensions
|
||||||
{
|
{
|
||||||
|
public static void LogException(this IKeyed device, Exception ex, string message, params object[] args)
|
||||||
|
{
|
||||||
|
Log.LogMessage(ex, message, device, args);
|
||||||
|
}
|
||||||
public static void LogVerbose(this IKeyed device, string message, params object[] args)
|
public static void LogVerbose(this IKeyed device, string message, params object[] args)
|
||||||
{
|
{
|
||||||
Log.LogMessage(LogEventLevel.Verbose, device, message, args);
|
Log.LogMessage(LogEventLevel.Verbose, device, message, args);
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<RootNamespace>PepperDash.Core</RootNamespace>
|
<RootNamespace>PepperDash.Core</RootNamespace>
|
||||||
<AssemblyName>PepperDashCore</AssemblyName>
|
<AssemblyName>PepperDashCore</AssemblyName>
|
||||||
<TargetFrameworks>net472;net6</TargetFrameworks>
|
<TargetFramework>net472</TargetFramework>
|
||||||
<Deterministic>true</Deterministic>
|
<Deterministic>true</Deterministic>
|
||||||
<NeutralLanguage>en</NeutralLanguage>
|
<NeutralLanguage>en</NeutralLanguage>
|
||||||
<OutputPath>bin\$(Configuration)\</OutputPath>
|
<OutputPath>bin\$(Configuration)\</OutputPath>
|
||||||
@@ -12,11 +12,9 @@
|
|||||||
<Company>PepperDash Technologies</Company>
|
<Company>PepperDash Technologies</Company>
|
||||||
<RepositoryType>git</RepositoryType>
|
<RepositoryType>git</RepositoryType>
|
||||||
<RepositoryUrl>https://github.com/PepperDash/PepperDashCore</RepositoryUrl>
|
<RepositoryUrl>https://github.com/PepperDash/PepperDashCore</RepositoryUrl>
|
||||||
<PackageTags>crestron;4series;</PackageTags>
|
<PackageTags>crestron;4series;</PackageTags>
|
||||||
<Version>2.0.0-local</Version>
|
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||||
<InformationalVersion>$(Version)</InformationalVersion>
|
<InformationalVersion>$(Version)</InformationalVersion>
|
||||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
|
||||||
<PackageOutputPath>../../package</PackageOutputPath>
|
|
||||||
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||||
@@ -41,15 +39,19 @@
|
|||||||
<Reference Include="System.Net.Http" />
|
<Reference Include="System.Net.Http" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="BouncyCastle" Version="1.8.9" />
|
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
|
||||||
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.20.66" />
|
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.21.90" />
|
||||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||||
<PackageReference Include="Serilog.Expressions" Version="4.0.0" />
|
<PackageReference Include="Serilog.Expressions" Version="4.0.0" />
|
||||||
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
|
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
|
||||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
||||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||||
|
<PackageReference Include="SSH.NET" Version="2024.2.0" />
|
||||||
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
|
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup Condition="'$(TargetFramework)' == 'net6'">
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Remove="Comm\._GenericSshClient.cs" />
|
<Compile Remove="Comm\._GenericSshClient.cs" />
|
||||||
<Compile Remove="Comm\._GenericTcpIpClient.cs" />
|
<Compile Remove="Comm\._GenericTcpIpClient.cs" />
|
||||||
Binary file not shown.
@@ -1,16 +0,0 @@
|
|||||||
|
|
||||||
namespace PepperDash.Core.Web.RequestHandlers
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Web API default request handler
|
|
||||||
/// </summary>
|
|
||||||
public class DefaultRequestHandler : WebApiBaseRequestHandler
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Constructor
|
|
||||||
/// </summary>
|
|
||||||
public DefaultRequestHandler()
|
|
||||||
: base(true)
|
|
||||||
{ }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using Crestron.SimplSharp.WebScripting;
|
|
||||||
|
|
||||||
namespace PepperDash.Core.Web.RequestHandlers
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// CWS Base Handler, implements IHttpCwsHandler
|
|
||||||
/// </summary>
|
|
||||||
public abstract class WebApiBaseRequestHandler : IHttpCwsHandler
|
|
||||||
{
|
|
||||||
private readonly Dictionary<string, Action<HttpCwsContext>> _handlers;
|
|
||||||
protected readonly bool EnableCors;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Constructor
|
|
||||||
/// </summary>
|
|
||||||
protected WebApiBaseRequestHandler(bool enableCors)
|
|
||||||
{
|
|
||||||
EnableCors = enableCors;
|
|
||||||
|
|
||||||
_handlers = new Dictionary<string, Action<HttpCwsContext>>
|
|
||||||
{
|
|
||||||
{"CONNECT", HandleConnect},
|
|
||||||
{"DELETE", HandleDelete},
|
|
||||||
{"GET", HandleGet},
|
|
||||||
{"HEAD", HandleHead},
|
|
||||||
{"OPTIONS", HandleOptions},
|
|
||||||
{"PATCH", HandlePatch},
|
|
||||||
{"POST", HandlePost},
|
|
||||||
{"PUT", HandlePut},
|
|
||||||
{"TRACE", HandleTrace}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Constructor
|
|
||||||
/// </summary>
|
|
||||||
protected WebApiBaseRequestHandler()
|
|
||||||
: this(false)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles CONNECT method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandleConnect(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles DELETE method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandleDelete(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles GET method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandleGet(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles HEAD method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandleHead(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles OPTIONS method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandleOptions(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles PATCH method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandlePatch(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles POST method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandlePost(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles PUT method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandlePut(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles TRACE method requests
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
protected virtual void HandleTrace(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 501;
|
|
||||||
context.Response.StatusDescription = "Not Implemented";
|
|
||||||
context.Response.End();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Process request
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
public void ProcessRequest(HttpCwsContext context)
|
|
||||||
{
|
|
||||||
Action<HttpCwsContext> handler;
|
|
||||||
|
|
||||||
if (!_handlers.TryGetValue(context.Request.HttpMethod, out handler))
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (EnableCors)
|
|
||||||
{
|
|
||||||
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
|
|
||||||
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
|
||||||
}
|
|
||||||
|
|
||||||
handler(context);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,284 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using Crestron.SimplSharp;
|
|
||||||
using Crestron.SimplSharp.WebScripting;
|
|
||||||
using Newtonsoft.Json;
|
|
||||||
using Newtonsoft.Json.Linq;
|
|
||||||
using PepperDash.Core.Web.RequestHandlers;
|
|
||||||
|
|
||||||
namespace PepperDash.Core.Web
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Web API server
|
|
||||||
/// </summary>
|
|
||||||
public class WebApiServer : IKeyName
|
|
||||||
{
|
|
||||||
private const string SplusKey = "Uninitialized Web API Server";
|
|
||||||
private const string DefaultName = "Web API Server";
|
|
||||||
private const string DefaultBasePath = "/api";
|
|
||||||
|
|
||||||
private const uint DebugTrace = 0;
|
|
||||||
private const uint DebugInfo = 1;
|
|
||||||
private const uint DebugVerbose = 2;
|
|
||||||
|
|
||||||
private readonly CCriticalSection _serverLock = new CCriticalSection();
|
|
||||||
private HttpCwsServer _server;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Web API server key
|
|
||||||
/// </summary>
|
|
||||||
public string Key { get; private set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Web API server name
|
|
||||||
/// </summary>
|
|
||||||
public string Name { get; private set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// CWS base path, will default to "/api" if not set via initialize method
|
|
||||||
/// </summary>
|
|
||||||
public string BasePath { get; private set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Indicates CWS is registered with base path
|
|
||||||
/// </summary>
|
|
||||||
public bool IsRegistered { get; private set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Http request handler
|
|
||||||
/// </summary>
|
|
||||||
//public IHttpCwsHandler HttpRequestHandler
|
|
||||||
//{
|
|
||||||
// get { return _server.HttpRequestHandler; }
|
|
||||||
// set
|
|
||||||
// {
|
|
||||||
// if (_server == null) return;
|
|
||||||
// _server.HttpRequestHandler = value;
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Received request event handler
|
|
||||||
/// </summary>
|
|
||||||
//public event EventHandler<HttpCwsRequestEventArgs> ReceivedRequestEvent
|
|
||||||
//{
|
|
||||||
// add { _server.ReceivedRequestEvent += new HttpCwsRequestEventHandler(value); }
|
|
||||||
// remove { _server.ReceivedRequestEvent -= new HttpCwsRequestEventHandler(value); }
|
|
||||||
//}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Constructor for S+. Make sure to set necessary properties using init method
|
|
||||||
/// </summary>
|
|
||||||
public WebApiServer()
|
|
||||||
: this(SplusKey, DefaultName, null)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Constructor
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="key"></param>
|
|
||||||
/// <param name="basePath"></param>
|
|
||||||
public WebApiServer(string key, string basePath)
|
|
||||||
: this(key, DefaultName, basePath)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Constructor
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="key"></param>
|
|
||||||
/// <param name="name"></param>
|
|
||||||
/// <param name="basePath"></param>
|
|
||||||
public WebApiServer(string key, string name, string basePath)
|
|
||||||
{
|
|
||||||
Key = key;
|
|
||||||
Name = string.IsNullOrEmpty(name) ? DefaultName : name;
|
|
||||||
BasePath = string.IsNullOrEmpty(basePath) ? DefaultBasePath : basePath;
|
|
||||||
|
|
||||||
if (_server == null) _server = new HttpCwsServer(BasePath);
|
|
||||||
|
|
||||||
_server.setProcessName(Key);
|
|
||||||
_server.HttpRequestHandler = new DefaultRequestHandler();
|
|
||||||
|
|
||||||
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
|
|
||||||
CrestronEnvironment.EthernetEventHandler += CrestronEnvironment_EthernetEventHandler;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Program status event handler
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="programEventType"></param>
|
|
||||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
|
||||||
{
|
|
||||||
if (programEventType != eProgramStatusEventType.Stopping) return;
|
|
||||||
|
|
||||||
Debug.Console(DebugInfo, this, "Program stopping. stopping server");
|
|
||||||
|
|
||||||
Stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ethernet event handler
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="ethernetEventArgs"></param>
|
|
||||||
void CrestronEnvironment_EthernetEventHandler(EthernetEventArgs ethernetEventArgs)
|
|
||||||
{
|
|
||||||
// Re-enable the server if the link comes back up and the status should be connected
|
|
||||||
if (ethernetEventArgs.EthernetEventType == eEthernetEventType.LinkUp && IsRegistered)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Ethernet link up. Server is alreedy registered.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Debug.Console(DebugInfo, this, "Ethernet link up. Starting server");
|
|
||||||
|
|
||||||
Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Initializes CWS class
|
|
||||||
/// </summary>
|
|
||||||
public void Initialize(string key, string basePath)
|
|
||||||
{
|
|
||||||
Key = key;
|
|
||||||
BasePath = string.IsNullOrEmpty(basePath) ? DefaultBasePath : basePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Adds a route to CWS
|
|
||||||
/// </summary>
|
|
||||||
public void AddRoute(HttpCwsRoute route)
|
|
||||||
{
|
|
||||||
if (route == null)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Failed to add route, route parameter is null");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_server.Routes.Add(route);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Removes a route from CWS
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="route"></param>
|
|
||||||
public void RemoveRoute(HttpCwsRoute route)
|
|
||||||
{
|
|
||||||
if (route == null)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Failed to remote route, orute parameter is null");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_server.Routes.Remove(route);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns a list of the current routes
|
|
||||||
/// </summary>
|
|
||||||
public HttpCwsRouteCollection GetRouteCollection()
|
|
||||||
{
|
|
||||||
return _server.Routes;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Starts CWS instance
|
|
||||||
/// </summary>
|
|
||||||
public void Start()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_serverLock.Enter();
|
|
||||||
|
|
||||||
if (_server == null)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Server is null, unable to start");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IsRegistered)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Server has already been started");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
IsRegistered = _server.Register();
|
|
||||||
|
|
||||||
Debug.Console(DebugInfo, this, "Starting server, registration {0}", IsRegistered ? "was successful" : "failed");
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Start Exception Message: {0}", ex.Message);
|
|
||||||
Debug.Console(DebugVerbose, this, "Start Exception StackTrace: {0}", ex.StackTrace);
|
|
||||||
if (ex.InnerException != null)
|
|
||||||
Debug.Console(DebugVerbose, this, "Start Exception InnerException: {0}", ex.InnerException);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_serverLock.Leave();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Stop CWS instance
|
|
||||||
/// </summary>
|
|
||||||
public void Stop()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_serverLock.Enter();
|
|
||||||
|
|
||||||
if (_server == null)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Server is null or has already been stopped");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
IsRegistered = _server.Unregister() == false;
|
|
||||||
|
|
||||||
Debug.Console(DebugInfo, this, "Stopping server, unregistration {0}", IsRegistered ? "failed" : "was successful");
|
|
||||||
|
|
||||||
_server.Dispose();
|
|
||||||
_server = null;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "Server Stop Exception Message: {0}", ex.Message);
|
|
||||||
Debug.Console(DebugVerbose, this, "Server Stop Exception StackTrace: {0}", ex.StackTrace);
|
|
||||||
if (ex.InnerException != null)
|
|
||||||
Debug.Console(DebugVerbose, this, "Server Stop Exception InnerException: {0}", ex.InnerException);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_serverLock.Leave();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Received request handler
|
|
||||||
/// </summary>
|
|
||||||
/// <remarks>
|
|
||||||
/// This is here for development and testing
|
|
||||||
/// </remarks>
|
|
||||||
/// <param name="sender"></param>
|
|
||||||
/// <param name="args"></param>
|
|
||||||
public void ReceivedRequestEventHandler(object sender, HttpCwsRequestEventArgs args)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var j = JsonConvert.SerializeObject(args.Context, Formatting.Indented);
|
|
||||||
Debug.Console(DebugVerbose, this, "RecieveRequestEventHandler Context:\x0d\x0a{0}", j);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Debug.Console(DebugInfo, this, "ReceivedRequestEventHandler Exception Message: {0}", ex.Message);
|
|
||||||
Debug.Console(DebugVerbose, this, "ReceivedRequestEventHandler Exception StackTrace: {0}", ex.StackTrace);
|
|
||||||
if (ex.InnerException != null)
|
|
||||||
Debug.Console(DebugVerbose, this, "ReceivedRequestEventHandler Exception InnerException: {0}", ex.InnerException);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Binary file not shown.
Binary file not shown.
@@ -9,7 +9,6 @@ using Org.BouncyCastle.Asn1.X509;
|
|||||||
using Org.BouncyCastle.Crypto;
|
using Org.BouncyCastle.Crypto;
|
||||||
using Org.BouncyCastle.Crypto.Generators;
|
using Org.BouncyCastle.Crypto.Generators;
|
||||||
using Org.BouncyCastle.Crypto.Prng;
|
using Org.BouncyCastle.Crypto.Prng;
|
||||||
using Org.BouncyCastle.Math;
|
|
||||||
using Org.BouncyCastle.Pkcs;
|
using Org.BouncyCastle.Pkcs;
|
||||||
using Org.BouncyCastle.Security;
|
using Org.BouncyCastle.Security;
|
||||||
using Org.BouncyCastle.Utilities;
|
using Org.BouncyCastle.Utilities;
|
||||||
@@ -17,10 +16,7 @@ using Org.BouncyCastle.X509;
|
|||||||
using X509Certificate2 = System.Security.Cryptography.X509Certificates.X509Certificate2;
|
using X509Certificate2 = System.Security.Cryptography.X509Certificates.X509Certificate2;
|
||||||
using X509KeyStorageFlags = System.Security.Cryptography.X509Certificates.X509KeyStorageFlags;
|
using X509KeyStorageFlags = System.Security.Cryptography.X509Certificates.X509KeyStorageFlags;
|
||||||
using X509ContentType = System.Security.Cryptography.X509Certificates.X509ContentType;
|
using X509ContentType = System.Security.Cryptography.X509Certificates.X509ContentType;
|
||||||
using System.Text;
|
|
||||||
using Org.BouncyCastle.Crypto.Operators;
|
using Org.BouncyCastle.Crypto.Operators;
|
||||||
using System.Numerics;
|
|
||||||
using System.Security.Cryptography.X509Certificates;
|
|
||||||
using BigInteger = Org.BouncyCastle.Math.BigInteger;
|
using BigInteger = Org.BouncyCastle.Math.BigInteger;
|
||||||
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
|
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
|
||||||
|
|
||||||
@@ -284,7 +280,7 @@ namespace PepperDash.Core
|
|||||||
// Now to convert the Bouncy Castle certificate to a .NET certificate.
|
// Now to convert the Bouncy Castle certificate to a .NET certificate.
|
||||||
// See http://web.archive.org/web/20100504192226/http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx
|
// See http://web.archive.org/web/20100504192226/http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx
|
||||||
// ...but, basically, we create a PKCS12 store (a .PFX file) in memory, and add the public and private key to that.
|
// ...but, basically, we create a PKCS12 store (a .PFX file) in memory, and add the public and private key to that.
|
||||||
var store = new Pkcs12Store();
|
var store = new Pkcs12StoreBuilder().Build();
|
||||||
|
|
||||||
// What Bouncy Castle calls "alias" is the same as what Windows terms the "friendly name".
|
// What Bouncy Castle calls "alias" is the same as what Windows terms the "friendly name".
|
||||||
string friendlyName = certificate.SubjectDN.ToString();
|
string friendlyName = certificate.SubjectDN.ToString();
|
||||||
17
src/Web/RequestHandlers/DefaultRequestHandler.cs
Normal file
17
src/Web/RequestHandlers/DefaultRequestHandler.cs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
using Crestron.SimplSharp.WebScripting;
|
||||||
|
|
||||||
|
namespace PepperDash.Core.Web.RequestHandlers
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Web API default request handler
|
||||||
|
/// </summary>
|
||||||
|
public class DefaultRequestHandler : WebApiBaseRequestHandler
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Constructor
|
||||||
|
/// </summary>
|
||||||
|
public DefaultRequestHandler()
|
||||||
|
: base(true)
|
||||||
|
{ }
|
||||||
|
}
|
||||||
|
}
|
||||||
165
src/Web/RequestHandlers/WebApiBaseRequestHandler.cs
Normal file
165
src/Web/RequestHandlers/WebApiBaseRequestHandler.cs
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Crestron.SimplSharp.WebScripting;
|
||||||
|
|
||||||
|
namespace PepperDash.Core.Web.RequestHandlers
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// CWS Base Handler, implements IHttpCwsHandler
|
||||||
|
/// </summary>
|
||||||
|
public abstract class WebApiBaseRequestHandler : IHttpCwsHandler
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, Action<HttpCwsContext>> _handlers;
|
||||||
|
protected readonly bool EnableCors;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Constructor
|
||||||
|
/// </summary>
|
||||||
|
protected WebApiBaseRequestHandler(bool enableCors)
|
||||||
|
{
|
||||||
|
EnableCors = enableCors;
|
||||||
|
|
||||||
|
_handlers = new Dictionary<string, Action<HttpCwsContext>>
|
||||||
|
{
|
||||||
|
{"CONNECT", HandleConnect},
|
||||||
|
{"DELETE", HandleDelete},
|
||||||
|
{"GET", HandleGet},
|
||||||
|
{"HEAD", HandleHead},
|
||||||
|
{"OPTIONS", HandleOptions},
|
||||||
|
{"PATCH", HandlePatch},
|
||||||
|
{"POST", HandlePost},
|
||||||
|
{"PUT", HandlePut},
|
||||||
|
{"TRACE", HandleTrace}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Constructor
|
||||||
|
/// </summary>
|
||||||
|
protected WebApiBaseRequestHandler()
|
||||||
|
: this(false)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles CONNECT method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandleConnect(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles DELETE method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandleDelete(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles GET method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandleGet(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles HEAD method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandleHead(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles OPTIONS method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandleOptions(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles PATCH method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandlePatch(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles POST method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandlePost(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles PUT method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandlePut(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles TRACE method requests
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void HandleTrace(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 501;
|
||||||
|
context.Response.StatusDescription = "Not Implemented";
|
||||||
|
context.Response.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Process request
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
public void ProcessRequest(HttpCwsContext context)
|
||||||
|
{
|
||||||
|
Action<HttpCwsContext> handler;
|
||||||
|
|
||||||
|
if (!_handlers.TryGetValue(context.Request.HttpMethod, out handler))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (EnableCors)
|
||||||
|
{
|
||||||
|
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
|
||||||
|
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
||||||
|
}
|
||||||
|
|
||||||
|
handler(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
284
src/Web/WebApiServer.cs
Normal file
284
src/Web/WebApiServer.cs
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Crestron.SimplSharp;
|
||||||
|
using Crestron.SimplSharp.WebScripting;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using PepperDash.Core.Web.RequestHandlers;
|
||||||
|
|
||||||
|
namespace PepperDash.Core.Web
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Web API server
|
||||||
|
/// </summary>
|
||||||
|
public class WebApiServer : IKeyName
|
||||||
|
{
|
||||||
|
private const string SplusKey = "Uninitialized Web API Server";
|
||||||
|
private const string DefaultName = "Web API Server";
|
||||||
|
private const string DefaultBasePath = "/api";
|
||||||
|
|
||||||
|
private const uint DebugTrace = 0;
|
||||||
|
private const uint DebugInfo = 1;
|
||||||
|
private const uint DebugVerbose = 2;
|
||||||
|
|
||||||
|
private readonly CCriticalSection _serverLock = new CCriticalSection();
|
||||||
|
private HttpCwsServer _server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Web API server key
|
||||||
|
/// </summary>
|
||||||
|
public string Key { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Web API server name
|
||||||
|
/// </summary>
|
||||||
|
public string Name { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// CWS base path, will default to "/api" if not set via initialize method
|
||||||
|
/// </summary>
|
||||||
|
public string BasePath { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Indicates CWS is registered with base path
|
||||||
|
/// </summary>
|
||||||
|
public bool IsRegistered { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Http request handler
|
||||||
|
/// </summary>
|
||||||
|
//public IHttpCwsHandler HttpRequestHandler
|
||||||
|
//{
|
||||||
|
// get { return _server.HttpRequestHandler; }
|
||||||
|
// set
|
||||||
|
// {
|
||||||
|
// if (_server == null) return;
|
||||||
|
// _server.HttpRequestHandler = value;
|
||||||
|
// }
|
||||||
|
//}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Received request event handler
|
||||||
|
/// </summary>
|
||||||
|
//public event EventHandler<HttpCwsRequestEventArgs> ReceivedRequestEvent
|
||||||
|
//{
|
||||||
|
// add { _server.ReceivedRequestEvent += new HttpCwsRequestEventHandler(value); }
|
||||||
|
// remove { _server.ReceivedRequestEvent -= new HttpCwsRequestEventHandler(value); }
|
||||||
|
//}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Constructor for S+. Make sure to set necessary properties using init method
|
||||||
|
/// </summary>
|
||||||
|
public WebApiServer()
|
||||||
|
: this(SplusKey, DefaultName, null)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Constructor
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <param name="basePath"></param>
|
||||||
|
public WebApiServer(string key, string basePath)
|
||||||
|
: this(key, DefaultName, basePath)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Constructor
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <param name="name"></param>
|
||||||
|
/// <param name="basePath"></param>
|
||||||
|
public WebApiServer(string key, string name, string basePath)
|
||||||
|
{
|
||||||
|
Key = key;
|
||||||
|
Name = string.IsNullOrEmpty(name) ? DefaultName : name;
|
||||||
|
BasePath = string.IsNullOrEmpty(basePath) ? DefaultBasePath : basePath;
|
||||||
|
|
||||||
|
if (_server == null) _server = new HttpCwsServer(BasePath);
|
||||||
|
|
||||||
|
_server.setProcessName(Key);
|
||||||
|
_server.HttpRequestHandler = new DefaultRequestHandler();
|
||||||
|
|
||||||
|
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
|
||||||
|
CrestronEnvironment.EthernetEventHandler += CrestronEnvironment_EthernetEventHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Program status event handler
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="programEventType"></param>
|
||||||
|
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||||
|
{
|
||||||
|
if (programEventType != eProgramStatusEventType.Stopping) return;
|
||||||
|
|
||||||
|
Debug.Console(DebugInfo, this, "Program stopping. stopping server");
|
||||||
|
|
||||||
|
Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ethernet event handler
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ethernetEventArgs"></param>
|
||||||
|
void CrestronEnvironment_EthernetEventHandler(EthernetEventArgs ethernetEventArgs)
|
||||||
|
{
|
||||||
|
// Re-enable the server if the link comes back up and the status should be connected
|
||||||
|
if (ethernetEventArgs.EthernetEventType == eEthernetEventType.LinkUp && IsRegistered)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Ethernet link up. Server is alreedy registered.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Debug.Console(DebugInfo, this, "Ethernet link up. Starting server");
|
||||||
|
|
||||||
|
Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes CWS class
|
||||||
|
/// </summary>
|
||||||
|
public void Initialize(string key, string basePath)
|
||||||
|
{
|
||||||
|
Key = key;
|
||||||
|
BasePath = string.IsNullOrEmpty(basePath) ? DefaultBasePath : basePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds a route to CWS
|
||||||
|
/// </summary>
|
||||||
|
public void AddRoute(HttpCwsRoute route)
|
||||||
|
{
|
||||||
|
if (route == null)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Failed to add route, route parameter is null");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_server.Routes.Add(route);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes a route from CWS
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="route"></param>
|
||||||
|
public void RemoveRoute(HttpCwsRoute route)
|
||||||
|
{
|
||||||
|
if (route == null)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Failed to remote route, orute parameter is null");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_server.Routes.Remove(route);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns a list of the current routes
|
||||||
|
/// </summary>
|
||||||
|
public HttpCwsRouteCollection GetRouteCollection()
|
||||||
|
{
|
||||||
|
return _server.Routes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Starts CWS instance
|
||||||
|
/// </summary>
|
||||||
|
public void Start()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_serverLock.Enter();
|
||||||
|
|
||||||
|
if (_server == null)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Server is null, unable to start");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsRegistered)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Server has already been started");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
IsRegistered = _server.Register();
|
||||||
|
|
||||||
|
Debug.Console(DebugInfo, this, "Starting server, registration {0}", IsRegistered ? "was successful" : "failed");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Start Exception Message: {0}", ex.Message);
|
||||||
|
Debug.Console(DebugVerbose, this, "Start Exception StackTrace: {0}", ex.StackTrace);
|
||||||
|
if (ex.InnerException != null)
|
||||||
|
Debug.Console(DebugVerbose, this, "Start Exception InnerException: {0}", ex.InnerException);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_serverLock.Leave();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Stop CWS instance
|
||||||
|
/// </summary>
|
||||||
|
public void Stop()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_serverLock.Enter();
|
||||||
|
|
||||||
|
if (_server == null)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Server is null or has already been stopped");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
IsRegistered = _server.Unregister() == false;
|
||||||
|
|
||||||
|
Debug.Console(DebugInfo, this, "Stopping server, unregistration {0}", IsRegistered ? "failed" : "was successful");
|
||||||
|
|
||||||
|
_server.Dispose();
|
||||||
|
_server = null;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "Server Stop Exception Message: {0}", ex.Message);
|
||||||
|
Debug.Console(DebugVerbose, this, "Server Stop Exception StackTrace: {0}", ex.StackTrace);
|
||||||
|
if (ex.InnerException != null)
|
||||||
|
Debug.Console(DebugVerbose, this, "Server Stop Exception InnerException: {0}", ex.InnerException);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_serverLock.Leave();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Received request handler
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// This is here for development and testing
|
||||||
|
/// </remarks>
|
||||||
|
/// <param name="sender"></param>
|
||||||
|
/// <param name="args"></param>
|
||||||
|
public void ReceivedRequestEventHandler(object sender, HttpCwsRequestEventArgs args)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var j = JsonConvert.SerializeObject(args.Context, Formatting.Indented);
|
||||||
|
Debug.Console(DebugVerbose, this, "RecieveRequestEventHandler Context:\x0d\x0a{0}", j);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.Console(DebugInfo, this, "ReceivedRequestEventHandler Exception Message: {0}", ex.Message);
|
||||||
|
Debug.Console(DebugVerbose, this, "ReceivedRequestEventHandler Exception StackTrace: {0}", ex.StackTrace);
|
||||||
|
if (ex.InnerException != null)
|
||||||
|
Debug.Console(DebugVerbose, this, "ReceivedRequestEventHandler Exception InnerException: {0}", ex.InnerException);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user