mirror of
https://github.com/PepperDash/Essentials.git
synced 2026-01-13 12:35:03 +00:00
Compare commits
66 Commits
plugin-min
...
net8-updat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4dce9e493 | ||
|
|
63f86e7499 | ||
|
|
a088166de9 | ||
|
|
c2ab2f34b7 | ||
|
|
083c270cf3 | ||
|
|
9c81546a07 | ||
|
|
d83266f634 | ||
|
|
bc60106afd | ||
|
|
4ee62088fa | ||
|
|
90b6f258f0 | ||
|
|
e1e32cea6f | ||
|
|
e31df338d6 | ||
|
|
d14058fc32 | ||
|
|
04d6508c80 | ||
|
|
1cbc8194ec | ||
|
|
6d2cd75cbe | ||
|
|
8b873b7248 | ||
|
|
58a2a5c008 | ||
|
|
cc7e2ab675 | ||
|
|
dc900f3f31 | ||
|
|
562f0ba793 | ||
|
|
9c3c924a29 | ||
|
|
9b5af60a46 | ||
|
|
a99b0a1fac | ||
|
|
7591913a9c | ||
|
|
66a6612b65 | ||
|
|
688cf34153 | ||
|
|
0c59237232 | ||
|
|
88eec9a3f1 | ||
|
|
fda4a5a816 | ||
|
|
471d5b701b | ||
|
|
96ac266d24 | ||
|
|
c1809459a6 | ||
|
|
1a9e1087de | ||
|
|
8d55615837 | ||
|
|
19e799f11d | ||
|
|
a3c1c444b7 | ||
|
|
9f70e3c721 | ||
|
|
c9b3205736 | ||
|
|
253b2cddaf | ||
|
|
d96edfa8d0 | ||
|
|
95c1c01396 | ||
|
|
9c94806e4f | ||
|
|
183879f1c4 | ||
|
|
f3159738ce | ||
|
|
2c5cae9f41 | ||
|
|
7178d8e284 | ||
|
|
af98a92f8c | ||
|
|
0a6896910d | ||
|
|
9b1dd099f6 | ||
|
|
3f5269de2f | ||
|
|
60f1adcd35 | ||
|
|
12c8660015 | ||
|
|
ec6aeb17f6 | ||
|
|
e7c3fcbbd9 | ||
|
|
0c7ec82529 | ||
|
|
feb99ecbb6 | ||
|
|
91dc655103 | ||
|
|
bf31fb10eb | ||
|
|
d78b9ea313 | ||
|
|
15172a5509 | ||
|
|
5e21bad596 | ||
|
|
a4de9f2241 | ||
|
|
13cd84b73d | ||
|
|
81a01b7960 | ||
|
|
d9dc70bea2 |
56
.github/workflows/ci.yml
vendored
Normal file
56
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
name: CI Build and Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop, net8-updates ]
|
||||
pull_request:
|
||||
branches: [ main, develop, net8-updates ]
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v3
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore
|
||||
|
||||
- name: Build
|
||||
run: dotnet build --configuration Release --no-restore
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test --no-restore --verbosity normal --collect:"XPlat Code Coverage" --results-directory ./coverage
|
||||
|
||||
- name: Generate coverage report
|
||||
uses: danielpalme/ReportGenerator-GitHub-Action@5.2.0
|
||||
with:
|
||||
reports: coverage/**/coverage.cobertura.xml
|
||||
targetdir: coverage-report
|
||||
reporttypes: Html;Cobertura;MarkdownSummary
|
||||
|
||||
- name: Upload coverage reports to Codecov
|
||||
uses: codecov/codecov-action@v3
|
||||
with:
|
||||
file: ./coverage-report/Cobertura.xml
|
||||
flags: unittests
|
||||
name: codecov-umbrella
|
||||
fail_ci_if_error: false
|
||||
|
||||
- name: Write coverage summary
|
||||
run: cat coverage-report/Summary.md >> $GITHUB_STEP_SUMMARY
|
||||
if: always()
|
||||
|
||||
- name: Upload test results
|
||||
uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: test-results
|
||||
path: |
|
||||
coverage/
|
||||
coverage-report/
|
||||
247
.github/workflows/essentials-3-dev-build.yml
vendored
Normal file
247
.github/workflows/essentials-3-dev-build.yml
vendored
Normal file
@@ -0,0 +1,247 @@
|
||||
name: Essentials v3 Development Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- feature-3.0.0/*
|
||||
- hotfix-3.0.0/*
|
||||
- release-3.0.0/*
|
||||
- development-3.0.0
|
||||
|
||||
env:
|
||||
SOLUTION_PATH: .
|
||||
SOLUTION_FILE: PepperDash.Essentials
|
||||
VERSION: 0.0.0-buildtype-buildnumber
|
||||
BUILD_TYPE: Debug
|
||||
RELEASE_BRANCH: main
|
||||
jobs:
|
||||
Build_Project_4-Series:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
# Detect environment (Act vs GitHub)
|
||||
- name: Detect environment
|
||||
id: detect_env
|
||||
run: |
|
||||
if [ -n "$ACT" ]; then
|
||||
echo "is_local=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "is_local=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Install prerequisites
|
||||
run: |
|
||||
if [ "${{ steps.detect_env.outputs.is_local }}" == "true" ]; then
|
||||
# For Act - no sudo needed
|
||||
apt-get update
|
||||
apt-get install -y curl wget libicu-dev git unzip
|
||||
else
|
||||
# For GitHub runners - sudo required
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl wget libicu-dev git unzip
|
||||
fi
|
||||
|
||||
- name: Set Version Number
|
||||
id: setVersion
|
||||
shell: bash
|
||||
run: |
|
||||
latestVersion="3.0.0"
|
||||
newVersion=$latestVersion
|
||||
phase=""
|
||||
newVersionString=""
|
||||
|
||||
if [[ $GITHUB_REF =~ ^refs/pull/.* ]]; then
|
||||
phase="beta"
|
||||
newVersionString="${newVersion}-${phase}-${GITHUB_RUN_NUMBER}"
|
||||
elif [[ $GITHUB_REF =~ ^refs/heads/hotfix-3.0.0/.* ]]; then
|
||||
phase="hotfix"
|
||||
newVersionString="${newVersion}-${phase}-${GITHUB_RUN_NUMBER}"
|
||||
elif [[ $GITHUB_REF =~ ^refs/heads/feature-3.0.0/.* ]]; then
|
||||
phase="alpha"
|
||||
newVersionString="${newVersion}-${phase}-${GITHUB_RUN_NUMBER}"
|
||||
elif [[ $GITHUB_REF == "refs/heads/development-3.0.0" ]]; then
|
||||
phase="beta"
|
||||
newVersionString="${newVersion}-${phase}-${GITHUB_RUN_NUMBER}"
|
||||
elif [[ $GITHUB_REF =~ ^refs/heads/release-3.0.0/.* ]]; then
|
||||
version=$(echo $GITHUB_REF | awk -F '/' '{print $NF}' | sed 's/v//')
|
||||
phase="rc"
|
||||
newVersionString="${version}-${phase}-${GITHUB_RUN_NUMBER}"
|
||||
else
|
||||
# For local builds or unrecognized branches
|
||||
newVersionString="${newVersion}-local"
|
||||
fi
|
||||
|
||||
echo "version=$newVersionString" >> $GITHUB_OUTPUT
|
||||
|
||||
# Create Build Properties file
|
||||
- name: Create Build Properties
|
||||
run: |
|
||||
cat > Directory.Build.props << EOF
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>${{ steps.setVersion.outputs.version }}</Version>
|
||||
<AssemblyVersion>${{ steps.setVersion.outputs.version }}</AssemblyVersion>
|
||||
<FileVersion>${{ steps.setVersion.outputs.version }}</FileVersion>
|
||||
<InformationalVersion>${{ steps.setVersion.outputs.version }}</InformationalVersion>
|
||||
<PackageVersion>${{ steps.setVersion.outputs.version }}</PackageVersion>
|
||||
<NuGetVersion>${{ steps.setVersion.outputs.version }}</NuGetVersion>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
EOF
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v3
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: Restore NuGet Packages
|
||||
run: dotnet restore ${SOLUTION_FILE}.sln
|
||||
|
||||
- name: Build Solution
|
||||
run: dotnet build ${SOLUTION_FILE}.sln --configuration ${BUILD_TYPE} --no-restore
|
||||
|
||||
# Copy the CPZ file to the output directory with version in the filename
|
||||
- name: Copy and Rename CPZ Files
|
||||
run: |
|
||||
mkdir -p ./output/cpz
|
||||
|
||||
# Find the main CPZ file in the build output
|
||||
if [ -f "./src/PepperDash.Essentials/bin/${BUILD_TYPE}/net8/PepperDashEssentials.cpz" ]; then
|
||||
cp "./src/PepperDash.Essentials/bin/${BUILD_TYPE}/net8/PepperDashEssentials.cpz" "./output/cpz/PepperDashEssentials.${{ steps.setVersion.outputs.version }}.cpz"
|
||||
echo "Main CPZ file copied and renamed successfully."
|
||||
else
|
||||
echo "Warning: Main CPZ file not found at expected location."
|
||||
find ./src -name "*.cpz" | xargs -I {} cp {} ./output/cpz/
|
||||
fi
|
||||
|
||||
- name: Pack Solution
|
||||
run: dotnet pack ${SOLUTION_FILE}.sln --configuration ${BUILD_TYPE} --output ./output/nuget --no-build
|
||||
|
||||
# List build artifacts (runs in both environments)
|
||||
- name: List Build Artifacts
|
||||
run: |
|
||||
echo "=== Build Artifacts ==="
|
||||
echo "NuGet Packages:"
|
||||
find ./output/nuget -type f | sort
|
||||
echo ""
|
||||
echo "CPZ/CPLZ Files:"
|
||||
find ./output -name "*.cpz" -o -name "*.cplz" | sort
|
||||
echo "======================="
|
||||
|
||||
# Enhanced package inspection for local runs
|
||||
- name: Inspect NuGet Packages
|
||||
if: steps.detect_env.outputs.is_local == 'true'
|
||||
run: |
|
||||
echo "=== NuGet Package Details ==="
|
||||
for pkg in $(find ./output/nuget -name "*.nupkg"); do
|
||||
echo "Package: $(basename "$pkg")"
|
||||
echo "Size: $(du -h "$pkg" | cut -f1)"
|
||||
|
||||
# Extract and show package contents
|
||||
echo "Contents:"
|
||||
unzip -l "$pkg" | tail -n +4 | head -n -2
|
||||
echo "--------------------------"
|
||||
|
||||
# Try to extract and show the nuspec file (contains metadata)
|
||||
echo "Metadata:"
|
||||
unzip -p "$pkg" "*.nuspec" 2>/dev/null | grep -E "(<id>|<version>|<description>|<authors>|<dependencies>)" || echo "Metadata extraction failed"
|
||||
echo "--------------------------"
|
||||
done
|
||||
echo "==========================="
|
||||
|
||||
# Tag creation - GitHub version
|
||||
- name: Create tag for non-rc builds (GitHub)
|
||||
if: ${{ !contains(steps.setVersion.outputs.version, 'rc') && steps.detect_env.outputs.is_local == 'false' }}
|
||||
run: |
|
||||
git config --global user.name "GitHub Actions"
|
||||
git config --global user.email "actions@github.com"
|
||||
git tag ${{ steps.setVersion.outputs.version }}
|
||||
git push --tags origin
|
||||
|
||||
# Tag creation - Act mock version
|
||||
- name: Create tag for non-rc builds (Act Mock)
|
||||
if: ${{ !contains(steps.setVersion.outputs.version, 'rc') && steps.detect_env.outputs.is_local == 'true' }}
|
||||
run: |
|
||||
echo "Would create git tag: ${{ steps.setVersion.outputs.version }}"
|
||||
echo "Would push tag to: origin"
|
||||
|
||||
# Release creation - GitHub version
|
||||
- name: Create Release (GitHub)
|
||||
if: steps.detect_env.outputs.is_local == 'false'
|
||||
id: create_release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
artifacts: 'output/cpz/*,output/**/*.cplz'
|
||||
generateReleaseNotes: true
|
||||
prerelease: ${{contains('debug', env.BUILD_TYPE)}}
|
||||
tag: ${{ steps.setVersion.outputs.version }}
|
||||
|
||||
# Release creation - Act mock version with enhanced output
|
||||
- name: Create Release (Act Mock)
|
||||
if: steps.detect_env.outputs.is_local == 'true'
|
||||
run: |
|
||||
echo "=== Mock Release Creation ==="
|
||||
echo "Would create release with:"
|
||||
echo "- Tag: ${{ steps.setVersion.outputs.version }}"
|
||||
echo "- Prerelease: ${{contains('debug', env.BUILD_TYPE)}}"
|
||||
echo "- Artifacts matching pattern: output/cpz/*,output/**/*.cplz"
|
||||
echo ""
|
||||
echo "Matching artifacts:"
|
||||
find ./output/cpz -type f
|
||||
find ./output -name "*.cplz"
|
||||
|
||||
# Detailed info about release artifacts
|
||||
echo ""
|
||||
echo "Artifact Details:"
|
||||
for artifact in $(find ./output/cpz -type f; find ./output -name "*.cplz"); do
|
||||
echo "File: $(basename "$artifact")"
|
||||
echo "Size: $(du -h "$artifact" | cut -f1)"
|
||||
echo "Created: $(stat -c %y "$artifact")"
|
||||
echo "MD5: $(md5sum "$artifact" | cut -d' ' -f1)"
|
||||
echo "--------------------------"
|
||||
done
|
||||
echo "============================"
|
||||
|
||||
# NuGet setup - GitHub version
|
||||
- name: Setup NuGet (GitHub)
|
||||
if: steps.detect_env.outputs.is_local == 'false'
|
||||
run: |
|
||||
dotnet nuget add source https://nuget.pkg.github.com/pepperdash/index.json -n github -u pepperdash -p ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text
|
||||
|
||||
# NuGet setup - Act mock version
|
||||
- name: Setup NuGet (Act Mock)
|
||||
if: steps.detect_env.outputs.is_local == 'true'
|
||||
run: |
|
||||
echo "=== Mock NuGet Setup ==="
|
||||
echo "Would add GitHub NuGet source: https://nuget.pkg.github.com/pepperdash/index.json"
|
||||
echo "======================="
|
||||
|
||||
# Publish to NuGet - GitHub version
|
||||
- name: Publish to Nuget (GitHub)
|
||||
if: steps.detect_env.outputs.is_local == 'false'
|
||||
run: dotnet nuget push ./output/nuget/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
|
||||
|
||||
# Publish to NuGet - Act mock version
|
||||
- name: Publish to Nuget (Act Mock)
|
||||
if: steps.detect_env.outputs.is_local == 'true'
|
||||
run: |
|
||||
echo "=== Mock Publish to NuGet ==="
|
||||
echo "Would publish the following packages to https://api.nuget.org/v3/index.json:"
|
||||
find ./output/nuget -name "*.nupkg" | sort
|
||||
echo "============================="
|
||||
|
||||
# Publish to GitHub NuGet - GitHub version
|
||||
- name: Publish to Github Nuget (GitHub)
|
||||
if: steps.detect_env.outputs.is_local == 'false'
|
||||
run: dotnet nuget push ./output/nuget/*.nupkg --source github --api-key ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# Publish to GitHub NuGet - Act mock version
|
||||
- name: Publish to Github Nuget (Act Mock)
|
||||
if: steps.detect_env.outputs.is_local == 'true'
|
||||
run: |
|
||||
echo "=== Mock Publish to GitHub NuGet ==="
|
||||
echo "Would publish the following packages to the GitHub NuGet registry:"
|
||||
find ./output/nuget -name "*.nupkg" | sort
|
||||
echo "=================================="
|
||||
0
Crestron-Library-Usage-Analysis.md
Normal file
0
Crestron-Library-Usage-Analysis.md
Normal file
88
PROGRESS_NET8_MOCKING.md
Normal file
88
PROGRESS_NET8_MOCKING.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# .NET 8 Upgrade Progress - Crestron Mocking
|
||||
|
||||
## Current Status (August 13, 2025)
|
||||
|
||||
### ✅ Completed Tasks
|
||||
1. **Namespace Migration**: Successfully migrated 26+ files from `Crestron.SimplSharp.CrestronIO` to `System.IO`
|
||||
2. **Main Projects Building**: All main solution projects (PepperDash.Essentials, PepperDash.Essentials.Core, etc.) are building successfully for .NET 8
|
||||
3. **CrestronMock Project Structure**: Established comprehensive mock structure with proper namespace hierarchy
|
||||
4. **Duplicate Definition Resolution**: Resolved 37+ duplicate type definition errors by cleaning up conflicting files
|
||||
5. **HTTP/HTTPS Client Mocks**: Implemented complete HTTP/HTTPS client mocks with proper instance-based architecture
|
||||
6. **Core Networking Mocks**: Basic TCP/UDP client/server mock implementations created
|
||||
|
||||
### 🔄 In Progress - PepperDash.Core Test Configuration
|
||||
Currently working on making PepperDash.Core build successfully with Test configuration using CrestronMock implementations.
|
||||
|
||||
#### Recent Progress:
|
||||
- ✅ Removed duplicate WebAndNetworking_New.cs file (eliminated 37 duplicate errors)
|
||||
- ✅ Cleaned duplicate type definitions from Extensions.cs
|
||||
- ✅ Implemented comprehensive HTTP/HTTPS client mocks with proper method signatures
|
||||
- ✅ Added missing TCP client properties and methods (LocalPortNumberOfClient, callback overloads)
|
||||
- 🔄 **Currently fixing**: TCPServer missing _bufferSize field and additional constructor overloads
|
||||
|
||||
#### Last Action Taken:
|
||||
Working on TCPServer.cs - added 2-parameter constructor but need to add missing `_bufferSize` private field.
|
||||
|
||||
### 🎯 Immediate Next Steps
|
||||
1. **Fix TCPServer.cs**:
|
||||
- Add missing `private int _bufferSize;` field
|
||||
- Add missing event handler properties (SocketStatusChange)
|
||||
- Add missing method overloads for SendDataAsync/ReceiveDataAsync
|
||||
|
||||
2. **Complete Remaining Mock Types**:
|
||||
- UDPServer properties (IPAddressLastMessageReceivedFrom, IPPortLastMessageReceivedFrom, IncomingDataBuffer)
|
||||
- SecureTCPServer/SecureTCPClient missing methods
|
||||
- CrestronQueue.TryToEnqueue method
|
||||
- ProgramStatusEventHandler delegate
|
||||
- Console command response methods
|
||||
|
||||
3. **System Types & Environment**:
|
||||
- InitialParametersClass properties (ApplicationNumber, RoomId, RoomName, etc.)
|
||||
- CrestronEnvironment methods (Sleep, OSVersion, GetTimeZone, etc.)
|
||||
- CrestronDataStoreStatic methods (InitCrestronDataStore, SetLocalIntValue, etc.)
|
||||
- IPAddress type and related networking types
|
||||
|
||||
### 📊 Build Status
|
||||
- **Main Projects**: ✅ All building successfully for .NET 8
|
||||
- **PepperDash.Core Test Config**: ❌ Multiple compilation errors (see below)
|
||||
- **Error Count**: ~150+ compilation errors remaining (down from 200+)
|
||||
|
||||
### 🚨 Key Error Categories Remaining
|
||||
1. **Missing Properties/Methods**: TCPClient.LocalPortNumberOfClient, UDPServer properties, etc.
|
||||
2. **Missing Types**: ProgramStatusEventHandler, SocketException, IPAddress
|
||||
3. **Method Signature Mismatches**: SendDataAsync/ReceiveDataAsync parameter counts
|
||||
4. **Enum Values**: eProgramStatusEventType.Stopping, ETHERNET_PARAMETER_TO_GET constants
|
||||
5. **Constructor Overloads**: TCPServer 2-parameter constructor, CrestronQueue constructor
|
||||
|
||||
### 📁 File Status
|
||||
#### ✅ Complete/Stable:
|
||||
- `WebAndNetworking.cs` - HTTP/HTTPS clients with proper namespace separation
|
||||
- `Extensions.cs` - CrestronInvoke and CrestronEthernetHelper (cleaned of duplicates)
|
||||
- `Console.cs` - ErrorLog, CrestronDataStoreStatic basics
|
||||
- `CrestronLogger.cs` - Proper namespace structure
|
||||
|
||||
#### 🔄 In Progress:
|
||||
- `TCPClient.cs` - Added most properties/methods, needs final validation
|
||||
- `TCPServer.cs` - Missing _bufferSize field, needs event handlers
|
||||
- `UDPServer.cs` - Missing properties and method overloads
|
||||
- `SystemTypes.cs` - Needs InitialParametersClass and CrestronEnvironment extensions
|
||||
|
||||
### 🧪 Test Strategy
|
||||
- **Transparent Mocking**: No modifications to PepperDash.Core source files required
|
||||
- **Test Configuration**: Uses CrestronMock project references instead of real Crestron libraries
|
||||
- **API Compatibility**: Mock implementations maintain identical public API surface
|
||||
|
||||
### 🔄 Command to Continue
|
||||
```bash
|
||||
cd /Users/awelker/source/pepperdash/Essentials
|
||||
dotnet build src/PepperDash.Core/PepperDash.Core.csproj -c Test --verbosity minimal
|
||||
```
|
||||
|
||||
### 📝 Notes
|
||||
- User has been manually editing files, so always check current file contents before making changes
|
||||
- Focus on Test configuration only - don't modify Debug/Release builds
|
||||
- All namespace migration work is complete and should be preserved
|
||||
- HTTP/HTTPS mocking architecture is solid and working well
|
||||
|
||||
### 🎯 Success Criteria
|
||||
Goal: Clean build of PepperDash.Core with Test configuration, enabling .NET 8 unit testing with transparent Crestron API mocking.
|
||||
@@ -1,97 +1,234 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.4.33213.308
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash.Essentials.Devices.Common", "src\PepperDash.Essentials.Devices.Common\PepperDash.Essentials.Devices.Common.csproj", "{53E204B7-97DD-441D-A96C-721DF014DF82}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash.Essentials", "src\PepperDash.Essentials\PepperDash.Essentials.csproj", "{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash.Essentials.Core", "src\PepperDash.Essentials.Core\PepperDash.Essentials.Core.csproj", "{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Mobile Control", "Mobile Control", "{B24989D7-32B5-48D5-9AE1-5F3B17D25206}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Essentials.MobileControl", "src\PepperDash.Essentials.MobileControl\PepperDash.Essentials.MobileControl.csproj", "{F6D362DE-2256-44B1-927A-8CE4705D839A}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Essentials.MobileControl.Messengers", "src\PepperDash.Essentials.MobileControl.Messengers\PepperDash.Essentials.MobileControl.Messengers.csproj", "{B438694F-8FF7-464A-9EC8-10427374471F}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Essentials", "Essentials", "{AD98B742-8D85-481C-A69D-D8D8ABED39EA}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Core", "src\PepperDash.Core\PepperDash.Core.csproj", "{E5336563-1194-501E-BC4A-79AD9283EF90}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug 4.7.2|Any CPU = Debug 4.7.2|Any CPU
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug 4.7.2|Any CPU.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug 4.7.2|Any CPU.Build.0 = Debug 4.7.2|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug 4.7.2|Any CPU.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug 4.7.2|Any CPU.Build.0 = Debug 4.7.2|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug 4.7.2|Any CPU.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug 4.7.2|Any CPU.Build.0 = Debug 4.7.2|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug 4.7.2|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug 4.7.2|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug 4.7.2|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug 4.7.2|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug 4.7.2|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug 4.7.2|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82} = {AD98B742-8D85-481C-A69D-D8D8ABED39EA}
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E} = {AD98B742-8D85-481C-A69D-D8D8ABED39EA}
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B} = {AD98B742-8D85-481C-A69D-D8D8ABED39EA}
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A} = {B24989D7-32B5-48D5-9AE1-5F3B17D25206}
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F} = {B24989D7-32B5-48D5-9AE1-5F3B17D25206}
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {6907A4BF-7201-47CF-AAB1-3597F3B8E1C3}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.4.33213.308
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash.Essentials.Devices.Common", "src\PepperDash.Essentials.Devices.Common\PepperDash.Essentials.Devices.Common.csproj", "{53E204B7-97DD-441D-A96C-721DF014DF82}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash.Essentials", "src\PepperDash.Essentials\PepperDash.Essentials.csproj", "{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PepperDash.Essentials.Core", "src\PepperDash.Essentials.Core\PepperDash.Essentials.Core.csproj", "{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Mobile Control", "Mobile Control", "{B24989D7-32B5-48D5-9AE1-5F3B17D25206}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Essentials.MobileControl", "src\PepperDash.Essentials.MobileControl\PepperDash.Essentials.MobileControl.csproj", "{F6D362DE-2256-44B1-927A-8CE4705D839A}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Essentials.MobileControl.Messengers", "src\PepperDash.Essentials.MobileControl.Messengers\PepperDash.Essentials.MobileControl.Messengers.csproj", "{B438694F-8FF7-464A-9EC8-10427374471F}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {E5336563-1194-501E-BC4A-79AD9283EF90}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Essentials", "Essentials", "{AD98B742-8D85-481C-A69D-D8D8ABED39EA}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Core", "src\PepperDash.Core\PepperDash.Core.csproj", "{E5336563-1194-501E-BC4A-79AD9283EF90}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CrestronMock", "src\CrestronMock\CrestronMock.csproj", "{01191C7B-606D-4169-81B0-BC8BC1623CE9}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EssentialsTests", "Tests\EssentialsTests\EssentialsTests.csproj", "{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Essentials.Core.Tests", "src\tests\PepperDash.Essentials.Core.Tests\PepperDash.Essentials.Core.Tests.csproj", "{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
Test|Any CPU = Test|Any CPU
|
||||
Test|x64 = Test|x64
|
||||
Test|x86 = Test|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|x64.Build.0 = Release|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Release|x86.Build.0 = Release|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Test|x64.Build.0 = Test|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Test|x86.Build.0 = Test|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Release|x86.Build.0 = Release|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Test|x64.Build.0 = Test|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Test|x86.Build.0 = Test|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|x64.Build.0 = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Release|x86.Build.0 = Release|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Test|x64.Build.0 = Test|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Test|x86.Build.0 = Test|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|x64.Build.0 = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Release|x86.Build.0 = Release|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Test|x64.Build.0 = Test|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Test|x86.Build.0 = Test|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Test|x64.Build.0 = Test|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Test|x86.Build.0 = Test|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Release|x86.Build.0 = Release|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Test|x64.Build.0 = Test|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Test|x86.Build.0 = Test|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Release|x86.Build.0 = Release|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Test|x64.Build.0 = Test|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9}.Test|x86.Build.0 = Test|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Release|x64.Build.0 = Release|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Release|x86.Build.0 = Release|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Test|Any CPU.ActiveCfg = Test|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Test|Any CPU.Build.0 = Test|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Test|x64.ActiveCfg = Test|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Test|x64.Build.0 = Test|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Test|x86.ActiveCfg = Test|Any CPU
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB}.Test|x86.Build.0 = Test|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Release|x86.Build.0 = Release|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Test|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Test|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Test|x64.ActiveCfg = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Test|x64.Build.0 = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Test|x86.ActiveCfg = Debug|Any CPU
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6}.Test|x86.Build.0 = Debug|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82} = {AD98B742-8D85-481C-A69D-D8D8ABED39EA}
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E} = {AD98B742-8D85-481C-A69D-D8D8ABED39EA}
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B} = {AD98B742-8D85-481C-A69D-D8D8ABED39EA}
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A} = {B24989D7-32B5-48D5-9AE1-5F3B17D25206}
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F} = {B24989D7-32B5-48D5-9AE1-5F3B17D25206}
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{01191C7B-606D-4169-81B0-BC8BC1623CE9} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{3EEC6E2D-ED96-4929-8BBB-C73BE499A4EB} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{E86229FE-9400-4F7E-B4CB-C43637FEE6A6} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {6907A4BF-7201-47CF-AAB1-3597F3B8E1C3}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
166
TESTING_STRATEGY.md
Normal file
166
TESTING_STRATEGY.md
Normal file
@@ -0,0 +1,166 @@
|
||||
# PepperDash Essentials Unit Testing Strategy
|
||||
|
||||
## Problem Statement
|
||||
The PepperDash Essentials framework is tightly coupled to Crestron hardware libraries that only run on Crestron devices, making it impossible to run unit tests on development machines or in CI/CD pipelines.
|
||||
|
||||
## Solution: Abstraction Layer Pattern
|
||||
|
||||
### 1. Core Abstractions Created
|
||||
We've implemented abstraction interfaces that decouple business logic from Crestron hardware:
|
||||
|
||||
- **`ICrestronControlSystem`** - Abstracts the control system hardware
|
||||
- **`IRelayPort`** - Abstracts relay functionality
|
||||
- **`IDigitalInput`** - Abstracts digital inputs with event handling
|
||||
- **`IVersiPort`** - Abstracts VersiPort I/O
|
||||
|
||||
### 2. Adapter Pattern Implementation
|
||||
Created adapter classes that wrap Crestron objects in production:
|
||||
|
||||
```csharp
|
||||
// Production code uses adapters
|
||||
var controlSystem = new CrestronControlSystemAdapter(Global.ControlSystem);
|
||||
var processor = new CrestronProcessorTestable("key", controlSystem);
|
||||
|
||||
// Test code uses mocks
|
||||
var mockControlSystem = new Mock<ICrestronControlSystem>();
|
||||
var processor = new CrestronProcessorTestable("key", mockControlSystem.Object);
|
||||
```
|
||||
|
||||
### 3. Testable Classes
|
||||
Refactored classes to accept abstractions via dependency injection:
|
||||
|
||||
- **`CrestronProcessorTestable`** - Accepts `ICrestronControlSystem`
|
||||
- **`GenericRelayDeviceTestable`** - Accepts `IRelayPort`
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Identify Dependencies
|
||||
```bash
|
||||
# Find Crestron dependencies
|
||||
grep -r "using Crestron" --include="*.cs"
|
||||
```
|
||||
|
||||
### Step 2: Create Abstractions
|
||||
Define interfaces that mirror the Crestron API surface you need:
|
||||
```csharp
|
||||
public interface IRelayPort
|
||||
{
|
||||
void Open();
|
||||
void Close();
|
||||
void Pulse(int delayMs);
|
||||
bool State { get; }
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Implement Adapters
|
||||
Wrap Crestron objects with adapters:
|
||||
```csharp
|
||||
public class RelayPortAdapter : IRelayPort
|
||||
{
|
||||
private readonly Relay _relay;
|
||||
public void Open() => _relay.Open();
|
||||
// ... other methods
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Refactor Classes
|
||||
Accept abstractions in constructors:
|
||||
```csharp
|
||||
public class CrestronProcessorTestable
|
||||
{
|
||||
public CrestronProcessorTestable(string key, ICrestronControlSystem processor)
|
||||
{
|
||||
// Use abstraction instead of concrete type
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 5: Write Tests
|
||||
Use mocking frameworks to test business logic:
|
||||
```csharp
|
||||
[Fact]
|
||||
public void OpenRelay_CallsRelayPortOpen()
|
||||
{
|
||||
var mockRelay = new Mock<IRelayPort>();
|
||||
var device = new GenericRelayDeviceTestable("test", mockRelay.Object);
|
||||
|
||||
device.OpenRelay();
|
||||
|
||||
mockRelay.Verify(r => r.Open(), Times.Once);
|
||||
}
|
||||
```
|
||||
|
||||
## Test Project Structure
|
||||
```
|
||||
tests/
|
||||
├── PepperDash.Essentials.Core.Tests/
|
||||
│ ├── Abstractions/ # Tests for abstraction adapters
|
||||
│ ├── Devices/ # Device-specific tests
|
||||
│ └── *.csproj # Test project file
|
||||
└── README.md # Testing documentation
|
||||
```
|
||||
|
||||
## CI/CD Integration
|
||||
|
||||
### GitHub Actions Workflow
|
||||
The `.github/workflows/ci.yml` file runs tests automatically on:
|
||||
- Push to main/develop branches
|
||||
- Pull requests
|
||||
- Generates code coverage reports
|
||||
|
||||
### Running Tests Locally
|
||||
```bash
|
||||
# Run all tests
|
||||
dotnet test
|
||||
|
||||
# Run with coverage
|
||||
dotnet test --collect:"XPlat Code Coverage"
|
||||
|
||||
# Run specific tests
|
||||
dotnet test --filter "FullyQualifiedName~CrestronProcessor"
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Unit Testing Without Hardware** - Tests run on any machine
|
||||
2. **CI/CD Integration** - Automated testing in pipelines
|
||||
3. **Better Design** - Encourages SOLID principles
|
||||
4. **Faster Development** - No need for hardware to test logic
|
||||
5. **Higher Code Quality** - Catch bugs before deployment
|
||||
|
||||
## Migration Guide
|
||||
|
||||
### For Existing Code
|
||||
1. Identify classes with Crestron dependencies
|
||||
2. Create abstraction interfaces
|
||||
3. Implement adapters
|
||||
4. Create testable versions accepting abstractions
|
||||
5. Write unit tests
|
||||
|
||||
### For New Code
|
||||
1. Always code against abstractions, not Crestron types
|
||||
2. Use dependency injection
|
||||
3. Write tests first (TDD approach)
|
||||
|
||||
## Current Test Coverage
|
||||
- ✅ CrestronProcessor relay management
|
||||
- ✅ GenericRelayDevice operations
|
||||
- ✅ Digital input event handling
|
||||
- ✅ VersiPort analog/digital operations
|
||||
|
||||
## Next Steps
|
||||
1. Expand abstractions for more Crestron components
|
||||
2. Increase test coverage across all modules
|
||||
3. Add integration tests with mock hardware
|
||||
4. Document testing best practices
|
||||
5. Create code generation tools for adapters
|
||||
|
||||
## Tools Used
|
||||
- **xUnit** - Test framework
|
||||
- **Moq** - Mocking library
|
||||
- **FluentAssertions** - Readable assertions
|
||||
- **Coverlet** - Code coverage
|
||||
- **GitHub Actions** - CI/CD
|
||||
|
||||
## Summary
|
||||
By introducing an abstraction layer between the business logic and Crestron hardware dependencies, we've successfully enabled unit testing for the PepperDash Essentials framework. This approach allows development and testing without physical hardware while maintaining full compatibility with Crestron systems in production.
|
||||
7
runtimeconfig.json
Normal file
7
runtimeconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"runtimeOptions": {
|
||||
"configProperties": {
|
||||
"System.Globalization.Invariant": false
|
||||
}
|
||||
}
|
||||
}
|
||||
183
src/CrestronMock/CCriticalSection.cs
Normal file
183
src/CrestronMock/CCriticalSection.cs
Normal file
@@ -0,0 +1,183 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Mock implementation of Crestron CCriticalSection for testing purposes
|
||||
/// Provides the same public API surface as the real CCriticalSection
|
||||
/// </summary>
|
||||
public class CCriticalSection : IDisposable
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private readonly object _lockObject = new object();
|
||||
private readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim();
|
||||
private bool _disposed = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Constructor
|
||||
|
||||
/// <summary>Initializes a new instance of the CCriticalSection class</summary>
|
||||
public CCriticalSection()
|
||||
{
|
||||
// Mock implementation - no actual initialization required
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>Enters the critical section</summary>
|
||||
public void Enter()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CCriticalSection));
|
||||
Monitor.Enter(_lockObject);
|
||||
}
|
||||
|
||||
/// <summary>Tries to enter the critical section</summary>
|
||||
/// <returns>True if the critical section was entered successfully</returns>
|
||||
public bool TryEnter()
|
||||
{
|
||||
if (_disposed) return false;
|
||||
return Monitor.TryEnter(_lockObject);
|
||||
}
|
||||
|
||||
/// <summary>Tries to enter the critical section with a timeout</summary>
|
||||
/// <param name="timeout">Timeout in milliseconds</param>
|
||||
/// <returns>True if the critical section was entered successfully</returns>
|
||||
public bool TryEnter(int timeout)
|
||||
{
|
||||
if (_disposed) return false;
|
||||
return Monitor.TryEnter(_lockObject, timeout);
|
||||
}
|
||||
|
||||
/// <summary>Tries to enter the critical section with a TimeSpan timeout</summary>
|
||||
/// <param name="timeout">Timeout as TimeSpan</param>
|
||||
/// <returns>True if the critical section was entered successfully</returns>
|
||||
public bool TryEnter(TimeSpan timeout)
|
||||
{
|
||||
if (_disposed) return false;
|
||||
return Monitor.TryEnter(_lockObject, timeout);
|
||||
}
|
||||
|
||||
/// <summary>Leaves the critical section</summary>
|
||||
public void Leave()
|
||||
{
|
||||
if (_disposed) return;
|
||||
try
|
||||
{
|
||||
Monitor.Exit(_lockObject);
|
||||
}
|
||||
catch (SynchronizationLockException)
|
||||
{
|
||||
// Ignore if not held by current thread
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Enters a read lock</summary>
|
||||
public void EnterReadLock()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CCriticalSection));
|
||||
_readerWriterLock.EnterReadLock();
|
||||
}
|
||||
|
||||
/// <summary>Tries to enter a read lock</summary>
|
||||
/// <returns>True if the read lock was acquired successfully</returns>
|
||||
public bool TryEnterReadLock()
|
||||
{
|
||||
if (_disposed) return false;
|
||||
return _readerWriterLock.TryEnterReadLock(0);
|
||||
}
|
||||
|
||||
/// <summary>Tries to enter a read lock with a timeout</summary>
|
||||
/// <param name="timeout">Timeout in milliseconds</param>
|
||||
/// <returns>True if the read lock was acquired successfully</returns>
|
||||
public bool TryEnterReadLock(int timeout)
|
||||
{
|
||||
if (_disposed) return false;
|
||||
return _readerWriterLock.TryEnterReadLock(timeout);
|
||||
}
|
||||
|
||||
/// <summary>Exits the read lock</summary>
|
||||
public void ExitReadLock()
|
||||
{
|
||||
if (_disposed) return;
|
||||
try
|
||||
{
|
||||
_readerWriterLock.ExitReadLock();
|
||||
}
|
||||
catch (SynchronizationLockException)
|
||||
{
|
||||
// Ignore if not held by current thread
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Enters a write lock</summary>
|
||||
public void EnterWriteLock()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CCriticalSection));
|
||||
_readerWriterLock.EnterWriteLock();
|
||||
}
|
||||
|
||||
/// <summary>Tries to enter a write lock</summary>
|
||||
/// <returns>True if the write lock was acquired successfully</returns>
|
||||
public bool TryEnterWriteLock()
|
||||
{
|
||||
if (_disposed) return false;
|
||||
return _readerWriterLock.TryEnterWriteLock(0);
|
||||
}
|
||||
|
||||
/// <summary>Tries to enter a write lock with a timeout</summary>
|
||||
/// <param name="timeout">Timeout in milliseconds</param>
|
||||
/// <returns>True if the write lock was acquired successfully</returns>
|
||||
public bool TryEnterWriteLock(int timeout)
|
||||
{
|
||||
if (_disposed) return false;
|
||||
return _readerWriterLock.TryEnterWriteLock(timeout);
|
||||
}
|
||||
|
||||
/// <summary>Exits the write lock</summary>
|
||||
public void ExitWriteLock()
|
||||
{
|
||||
if (_disposed) return;
|
||||
try
|
||||
{
|
||||
_readerWriterLock.ExitWriteLock();
|
||||
}
|
||||
catch (SynchronizationLockException)
|
||||
{
|
||||
// Ignore if not held by current thread
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Implementation
|
||||
|
||||
/// <summary>Disposes the critical section and releases resources</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>Protected dispose method</summary>
|
||||
/// <param name="disposing">True if disposing managed resources</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_readerWriterLock?.Dispose();
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
191
src/CrestronMock/CTimer.cs
Normal file
191
src/CrestronMock/CTimer.cs
Normal file
@@ -0,0 +1,191 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
/// <summary>Mock timer event handler</summary>
|
||||
/// <param name="userObject">User-defined object</param>
|
||||
public delegate void CTimerEventHandler(object? userObject);
|
||||
|
||||
/// <summary>
|
||||
/// Mock implementation of Crestron CTimer for testing purposes
|
||||
/// Provides the same public API surface as the real CTimer
|
||||
/// </summary>
|
||||
public class CTimer : IDisposable
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private Timer? _timer;
|
||||
private readonly object _lockObject = new object();
|
||||
private bool _disposed = false;
|
||||
private readonly CTimerEventHandler? _callback;
|
||||
private readonly object? _userObject;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>Gets whether the timer is currently running</summary>
|
||||
public bool Running { get; private set; } = false;
|
||||
|
||||
/// <summary>Gets the timer interval in milliseconds</summary>
|
||||
public long TimeToFire { get; private set; } = 0;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Constructors
|
||||
|
||||
/// <summary>Initializes a new instance of the CTimer class</summary>
|
||||
/// <param name="callbackFunction">Function to call when timer fires</param>
|
||||
/// <param name="userObject">User-defined object to pass to callback</param>
|
||||
/// <param name="dueTime">Time before timer first fires (milliseconds)</param>
|
||||
/// <param name="period">Interval between timer fires (milliseconds), or -1 for one-shot</param>
|
||||
public CTimer(CTimerEventHandler callbackFunction, object? userObject, long dueTime, long period)
|
||||
{
|
||||
_callback = callbackFunction;
|
||||
_userObject = userObject;
|
||||
TimeToFire = period;
|
||||
|
||||
var dueTimeInt = dueTime > int.MaxValue ? Timeout.Infinite : (int)dueTime;
|
||||
var periodInt = period > int.MaxValue || period < 0 ? Timeout.Infinite : (int)period;
|
||||
|
||||
_timer = new Timer(TimerCallback, null, dueTimeInt, periodInt);
|
||||
Running = dueTime != Timeout.Infinite;
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of the CTimer class</summary>
|
||||
/// <param name="callbackFunction">Function to call when timer fires</param>
|
||||
/// <param name="userObject">User-defined object to pass to callback</param>
|
||||
/// <param name="dueTime">Time before timer first fires (milliseconds)</param>
|
||||
public CTimer(CTimerEventHandler callbackFunction, object? userObject, long dueTime)
|
||||
: this(callbackFunction, userObject, dueTime, -1)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of the CTimer class</summary>
|
||||
/// <param name="callbackFunction">Function to call when timer fires</param>
|
||||
/// <param name="userObject">User-defined object to pass to callback</param>
|
||||
public CTimer(CTimerEventHandler callbackFunction, object? userObject)
|
||||
: this(callbackFunction, userObject, Timeout.Infinite, -1)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of the CTimer class</summary>
|
||||
/// <param name="callbackFunction">Function to call when timer fires</param>
|
||||
public CTimer(CTimerEventHandler callbackFunction)
|
||||
: this(callbackFunction, null, Timeout.Infinite, -1)
|
||||
{
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>Resets the timer with a new due time</summary>
|
||||
/// <param name="dueTime">New due time in milliseconds</param>
|
||||
/// <returns>True if successful</returns>
|
||||
public bool Reset(long dueTime)
|
||||
{
|
||||
return Reset(dueTime, -1);
|
||||
}
|
||||
|
||||
/// <summary>Resets the timer with new due time and period</summary>
|
||||
/// <param name="dueTime">New due time in milliseconds</param>
|
||||
/// <param name="period">New period in milliseconds, or -1 for one-shot</param>
|
||||
/// <returns>True if successful</returns>
|
||||
public bool Reset(long dueTime, long period)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (_disposed || _timer == null) return false;
|
||||
|
||||
TimeToFire = period;
|
||||
var dueTimeInt = dueTime > int.MaxValue ? Timeout.Infinite : (int)dueTime;
|
||||
var periodInt = period > int.MaxValue || period < 0 ? Timeout.Infinite : (int)period;
|
||||
|
||||
try
|
||||
{
|
||||
_timer.Change(dueTimeInt, periodInt);
|
||||
Running = dueTime != Timeout.Infinite;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops the timer</summary>
|
||||
/// <returns>True if successful</returns>
|
||||
public bool Stop()
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (_disposed || _timer == null) return false;
|
||||
|
||||
try
|
||||
{
|
||||
_timer.Change(Timeout.Infinite, Timeout.Infinite);
|
||||
Running = false;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
/// <summary>Internal timer callback</summary>
|
||||
/// <param name="state">Timer state (unused)</param>
|
||||
private void TimerCallback(object? state)
|
||||
{
|
||||
try
|
||||
{
|
||||
_callback?.Invoke(_userObject);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Suppress exceptions in callback to prevent timer from stopping
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Implementation
|
||||
|
||||
/// <summary>Disposes the timer and releases resources</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>Protected dispose method</summary>
|
||||
/// <param name="disposing">True if disposing managed resources</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
Running = false;
|
||||
}
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
119
src/CrestronMock/Console.cs
Normal file
119
src/CrestronMock/Console.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
public static class ErrorLog
|
||||
{
|
||||
public static void Error(string message, params object[] args)
|
||||
{
|
||||
Console.WriteLine($"[ERROR] {string.Format(message, args)}");
|
||||
}
|
||||
|
||||
public static void Notice(string message, params object[] args)
|
||||
{
|
||||
Console.WriteLine($"[NOTICE] {string.Format(message, args)}");
|
||||
}
|
||||
|
||||
public static void Warn(string message, params object[] args)
|
||||
{
|
||||
Console.WriteLine($"[WARN] {string.Format(message, args)}");
|
||||
}
|
||||
|
||||
public static void Info(string message, params object[] args)
|
||||
{
|
||||
Console.WriteLine($"[INFO] {string.Format(message, args)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronDataStore
|
||||
{
|
||||
public static class CrestronDataStoreStatic
|
||||
{
|
||||
public static CDS_ERROR SetLocalStringValue(string key, string value)
|
||||
{
|
||||
return CDS_ERROR.CDS_SUCCESS;
|
||||
}
|
||||
|
||||
public static CDS_ERROR GetLocalStringValue(string key, out string value)
|
||||
{
|
||||
value = "";
|
||||
return CDS_ERROR.CDS_SUCCESS;
|
||||
}
|
||||
|
||||
/// <summary>Initialize the Crestron data store</summary>
|
||||
/// <returns>0 on success, negative on error</returns>
|
||||
public static int InitCrestronDataStore()
|
||||
{
|
||||
// Mock implementation
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Get a boolean value from local storage</summary>
|
||||
/// <param name="key">The key to retrieve</param>
|
||||
/// <param name="value">The retrieved value</param>
|
||||
/// <returns>0 on success, negative on error</returns>
|
||||
public static int GetLocalBoolValue(string key, out bool value)
|
||||
{
|
||||
// Mock implementation - always return false for now
|
||||
value = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Set a boolean value in local storage</summary>
|
||||
/// <param name="key">The key to set</param>
|
||||
/// <param name="value">The value to set</param>
|
||||
/// <returns>0 on success, negative on error</returns>
|
||||
public static int SetLocalBoolValue(string key, bool value)
|
||||
{
|
||||
// Mock implementation
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Get an integer value from local storage</summary>
|
||||
/// <param name="key">The key to retrieve</param>
|
||||
/// <param name="value">The retrieved value</param>
|
||||
/// <returns>0 on success, negative on error</returns>
|
||||
public static int GetLocalIntValue(string key, out int value)
|
||||
{
|
||||
// Mock implementation - always return 0 for now
|
||||
value = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Set an integer value in local storage</summary>
|
||||
/// <param name="key">The key to set</param>
|
||||
/// <param name="value">The value to set</param>
|
||||
/// <returns>0 on success, negative on error</returns>
|
||||
public static int SetLocalIntValue(string key, int value)
|
||||
{
|
||||
// Mock implementation
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Set an unsigned integer value in local storage</summary>
|
||||
/// <param name="key">The key to set</param>
|
||||
/// <param name="value">The value to set</param>
|
||||
/// <returns>0 on success, negative on error</returns>
|
||||
public static int SetLocalUintValue(string key, uint value)
|
||||
{
|
||||
// Mock implementation
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public enum CDS_ERROR
|
||||
{
|
||||
CDS_SUCCESS = 0,
|
||||
CDS_ERROR = -1
|
||||
}
|
||||
|
||||
/// <summary>Mock CrestronDataStore for local data storage</summary>
|
||||
public static class CrestronDataStore
|
||||
{
|
||||
/// <summary>Error constant for CDS operations</summary>
|
||||
public static readonly int CDS_ERROR = -1;
|
||||
}
|
||||
}
|
||||
27
src/CrestronMock/ConsoleTypes.cs
Normal file
27
src/CrestronMock/ConsoleTypes.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
/// <summary>Mock console command response utility</summary>
|
||||
public static class ConsoleCommandResponseUtility
|
||||
{
|
||||
/// <summary>Send console command response with response code</summary>
|
||||
/// <param name="response">The response text</param>
|
||||
/// <param name="responseCode">The response code</param>
|
||||
public static void ConsoleCommandResponse(string response, int responseCode = 0)
|
||||
{
|
||||
// Mock implementation - just log to console or ignore
|
||||
Console.WriteLine($"Console Response ({responseCode}): {response}");
|
||||
}
|
||||
|
||||
/// <summary>Send console command response with additional parameter</summary>
|
||||
/// <param name="response">The response text</param>
|
||||
/// <param name="param1">First parameter</param>
|
||||
/// <param name="param2">Second parameter</param>
|
||||
public static void ConsoleCommandResponse(string response, object param1, object param2)
|
||||
{
|
||||
// Mock implementation
|
||||
Console.WriteLine($"Console Response: {response} - {param1}, {param2}");
|
||||
}
|
||||
}
|
||||
}
|
||||
266
src/CrestronMock/CrestronControlSystem.cs
Normal file
266
src/CrestronMock/CrestronControlSystem.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace CrestronMock;
|
||||
|
||||
/// <summary>Mock Crestron signal base class</summary>
|
||||
public class Sig { }
|
||||
|
||||
/// <summary>Mock UShort input signal</summary>
|
||||
public class UShortInputSig { }
|
||||
|
||||
/// <summary>Mock UShort output signal</summary>
|
||||
public class UShortOutputSig { }
|
||||
|
||||
/// <summary>Mock Boolean input signal</summary>
|
||||
public class BoolInputSig { }
|
||||
|
||||
/// <summary>Mock String input signal</summary>
|
||||
public class StringInputSig { }
|
||||
|
||||
/// <summary>Mock Boolean output signal</summary>
|
||||
public class BoolOutputSig { }
|
||||
|
||||
/// <summary>Mock String output signal</summary>
|
||||
public class StringOutputSig { }
|
||||
|
||||
/// <summary>Mock signal group</summary>
|
||||
public class SigGroup { }
|
||||
|
||||
/// <summary>Mock COM port</summary>
|
||||
public class ComPort { }
|
||||
|
||||
/// <summary>Mock relay</summary>
|
||||
public class Relay { }
|
||||
|
||||
/// <summary>Mock IR output port</summary>
|
||||
public class IROutputPort { }
|
||||
|
||||
/// <summary>Mock IO port</summary>
|
||||
public class IOPort { }
|
||||
|
||||
/// <summary>Mock VersiPort</summary>
|
||||
public class VersiPort { }
|
||||
|
||||
/// <summary>Mock IR input port</summary>
|
||||
public class IRInputPort { }
|
||||
|
||||
/// <summary>Signal type enumeration</summary>
|
||||
public enum eSigType
|
||||
{
|
||||
Bool,
|
||||
UShort,
|
||||
String
|
||||
}
|
||||
|
||||
/// <summary>Mock read-only collection</summary>
|
||||
public class ReadOnlyCollection<TKey, TValue> : Dictionary<TKey, TValue> where TKey : notnull
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Mock COM ports interface</summary>
|
||||
public interface IComPorts
|
||||
{
|
||||
ComPort[] ComPorts { get; }
|
||||
}
|
||||
|
||||
/// <summary>Mock relay ports interface</summary>
|
||||
public interface IRelayPorts
|
||||
{
|
||||
Relay[] RelayPorts { get; }
|
||||
}
|
||||
|
||||
/// <summary>Mock IR output ports interface</summary>
|
||||
public interface IIROutputPorts
|
||||
{
|
||||
IROutputPort[] IROutputPorts { get; }
|
||||
}
|
||||
|
||||
/// <summary>Mock IO ports interface</summary>
|
||||
public interface IIOPorts
|
||||
{
|
||||
IOPort[] IOPorts { get; }
|
||||
}
|
||||
|
||||
/// <summary>Mock digital input ports interface</summary>
|
||||
public interface IDigitalInputPorts
|
||||
{
|
||||
VersiPort[] DigitalInputPorts { get; }
|
||||
}
|
||||
|
||||
/// <summary>Mock IR input port interface</summary>
|
||||
public interface IIRInputPort
|
||||
{
|
||||
IRInputPort IRInputPort { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mock implementation of CrestronControlSystem for testing purposes
|
||||
/// Base class for the CrestronControlSystem The Customer application is derived over this class
|
||||
/// </summary>
|
||||
public class CrestronControlSystem : IComPorts, IRelayPorts, IIROutputPorts, IIOPorts, IDigitalInputPorts, IIRInputPort
|
||||
{
|
||||
// Static fields
|
||||
public static Sig NullCue { get; set; } = new Sig();
|
||||
public static UShortInputSig NullUShortInputSig { get; set; } = new UShortInputSig();
|
||||
public static UShortOutputSig NullUShortOutputSig { get; set; } = new UShortOutputSig();
|
||||
public static BoolInputSig NullBoolInputSig { get; set; } = new BoolInputSig();
|
||||
public static StringInputSig NullStringInputSig { get; set; } = new StringInputSig();
|
||||
public static BoolOutputSig NullBoolOutputSig { get; set; } = new BoolOutputSig();
|
||||
public static StringOutputSig NullStringOutputSig { get; set; } = new StringOutputSig();
|
||||
public static ReadOnlyCollection<int, SigGroup> SigGroups { get; set; } = new ReadOnlyCollection<int, SigGroup>();
|
||||
public static int MaxNumberOfEventsInQueue { get; set; } = 1000;
|
||||
|
||||
// Constructor
|
||||
public CrestronControlSystem()
|
||||
{
|
||||
// Initialize collections and properties
|
||||
ComPorts = Array.Empty<ComPort>();
|
||||
RelayPorts = Array.Empty<Relay>();
|
||||
IROutputPorts = Array.Empty<IROutputPort>();
|
||||
IOPorts = Array.Empty<IOPort>();
|
||||
DigitalInputPorts = Array.Empty<VersiPort>();
|
||||
IRInputPort = new IRInputPort();
|
||||
}
|
||||
|
||||
// Virtual methods that can be overridden
|
||||
public virtual void InitializeSystem()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void SavePreset()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void RecallPreset()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void BassFlat()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void TrebleFlat()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void LimiterEnable()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void LimiterDisable()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void LimiterSoftKneeOn()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void LimiterSoftKneeOff()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void MasterMuteOn()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void MasterMuteOff()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void MicMasterMuteOn()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void MicMasterMuteOff()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void SourceMuteOn()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
public virtual void SourceMuteOff()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
// Non-virtual methods
|
||||
public void MicMuteOn(uint MicNumber)
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
public void MicMuteOff(uint MicNumber)
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
public void MonoOutput()
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
public void StereoOutput()
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
// Static methods for SigGroup management
|
||||
public static SigGroup CreateSigGroup(int groupID, params BoolInputSig[] boolInputSigs)
|
||||
{
|
||||
return new SigGroup();
|
||||
}
|
||||
|
||||
public static SigGroup CreateSigGroup(int groupID, params UShortInputSig[] ushortInputSigs)
|
||||
{
|
||||
return new SigGroup();
|
||||
}
|
||||
|
||||
public static SigGroup CreateSigGroup(int groupID, eSigType type)
|
||||
{
|
||||
return new SigGroup();
|
||||
}
|
||||
|
||||
public static SigGroup CreateSigGroup(int groupID, params StringInputSig[] stringInputSigs)
|
||||
{
|
||||
return new SigGroup();
|
||||
}
|
||||
|
||||
public static void RemoveSigGroup(int groupID)
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
public static void RemoveSigGroup(SigGroup sigGroupToRemove)
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
public static void ClearSigGroups()
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
// Interface implementations
|
||||
public ComPort[] ComPorts { get; set; }
|
||||
public Relay[] RelayPorts { get; set; }
|
||||
public IROutputPort[] IROutputPorts { get; set; }
|
||||
public IOPort[] IOPorts { get; set; }
|
||||
public VersiPort[] DigitalInputPorts { get; set; }
|
||||
public IRInputPort IRInputPort { get; set; }
|
||||
}
|
||||
277
src/CrestronMock/CrestronEnvironment.cs
Normal file
277
src/CrestronMock/CrestronEnvironment.cs
Normal file
@@ -0,0 +1,277 @@
|
||||
using System;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
// Console and logging types needed by CrestronConsole and CrestronLogger
|
||||
public delegate string ConsoleCommandFunction(string parameters);
|
||||
|
||||
public enum ConsoleAccessLevelEnum
|
||||
{
|
||||
AccessOperator = 0,
|
||||
AccessProgrammer = 1,
|
||||
AccessAdministrator = 2
|
||||
}
|
||||
|
||||
public class ConsoleCommandParameterSpecClass
|
||||
{
|
||||
// Mock implementation
|
||||
}
|
||||
|
||||
/// <summary>Ethernet event handler delegate</summary>
|
||||
public delegate void EthernetEventHandler(EthernetEventArgs args);
|
||||
|
||||
/// <summary>Mock CrestronEnvironment for system event handling</summary>
|
||||
public static class CrestronEnvironment
|
||||
{
|
||||
/// <summary>Event fired when program status changes</summary>
|
||||
public static event ProgramStatusEventHandler? ProgramStatusEventHandler;
|
||||
|
||||
/// <summary>Event fired when ethernet status changes</summary>
|
||||
public static event EthernetEventHandler? EthernetEventHandler;
|
||||
|
||||
/// <summary>Gets the device platform</summary>
|
||||
public static eDevicePlatform DevicePlatform => eDevicePlatform.Appliance;
|
||||
|
||||
/// <summary>Gets the runtime environment</summary>
|
||||
public static eRuntimeEnvironment RuntimeEnvironment => eRuntimeEnvironment.SimplSharpPro;
|
||||
|
||||
/// <summary>Gets system information</summary>
|
||||
public static string SystemInfo => "Mock System v1.0";
|
||||
|
||||
/// <summary>Gets OS version</summary>
|
||||
public static string OSVersion => "Mock OS 1.0.0";
|
||||
|
||||
/// <summary>Gets new line character sequence</summary>
|
||||
public static string NewLine => Environment.NewLine;
|
||||
|
||||
/// <summary>Gets program compatibility level</summary>
|
||||
public static eProgramCompatibility ProgramCompatibility => eProgramCompatibility.Series3And4;
|
||||
|
||||
/// <summary>Sleep for specified milliseconds</summary>
|
||||
/// <param name="milliseconds">Sleep duration</param>
|
||||
public static void Sleep(int milliseconds)
|
||||
{
|
||||
System.Threading.Thread.Sleep(milliseconds);
|
||||
}
|
||||
|
||||
/// <summary>Gets the time zone</summary>
|
||||
/// <returns>Time zone string</returns>
|
||||
public static string GetTimeZone()
|
||||
{
|
||||
return TimeZoneInfo.Local.Id;
|
||||
}
|
||||
|
||||
/// <summary>Triggers a program status event (for testing)</summary>
|
||||
/// <param name="eventType">Event type</param>
|
||||
public static void TriggerProgramStatusEvent(eProgramStatusEventType eventType)
|
||||
{
|
||||
ProgramStatusEventHandler?.Invoke(eventType);
|
||||
}
|
||||
|
||||
/// <summary>Triggers an ethernet event (for testing)</summary>
|
||||
/// <param name="args">Event arguments</param>
|
||||
public static void TriggerEthernetEvent(EthernetEventArgs args)
|
||||
{
|
||||
EthernetEventHandler?.Invoke(args);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock ethernet event type enumeration</summary>
|
||||
public enum eEthernetEventType
|
||||
{
|
||||
/// <summary>Link down</summary>
|
||||
LinkDown = 0,
|
||||
/// <summary>Link up</summary>
|
||||
LinkUp = 1
|
||||
}
|
||||
|
||||
/// <summary>Mock CrestronConsole for console output</summary>
|
||||
public static class CrestronConsole
|
||||
{
|
||||
/// <summary>Prints a line to the console</summary>
|
||||
/// <param name="message">Message to print</param>
|
||||
public static void PrintLine(string message)
|
||||
{
|
||||
// Mock implementation - could write to System.Console in test environment
|
||||
Console.WriteLine($"[CrestronConsole] {message}");
|
||||
}
|
||||
|
||||
/// <summary>Prints formatted text to the console</summary>
|
||||
/// <param name="format">Format string</param>
|
||||
/// <param name="args">Arguments</param>
|
||||
public static void PrintLine(string format, params object[] args)
|
||||
{
|
||||
Console.WriteLine($"[CrestronConsole] {string.Format(format, args)}");
|
||||
}
|
||||
|
||||
/// <summary>Prints text to the console without a newline</summary>
|
||||
/// <param name="message">Message to print</param>
|
||||
public static void Print(string message)
|
||||
{
|
||||
Console.Write($"[CrestronConsole] {message}");
|
||||
}
|
||||
|
||||
/// <summary>Console command response</summary>
|
||||
/// <param name="command">Command to execute</param>
|
||||
/// <returns>Response string</returns>
|
||||
public static string ConsoleCommandResponse(string command)
|
||||
{
|
||||
return $"Mock response for command: {command}";
|
||||
}
|
||||
|
||||
/// <summary>Add new console command</summary>
|
||||
/// <param name="function">Command function</param>
|
||||
/// <param name="command">Command name</param>
|
||||
/// <param name="help">Help text</param>
|
||||
/// <param name="accessLevel">Access level</param>
|
||||
/// <returns>0 for success</returns>
|
||||
public static int AddNewConsoleCommand(ConsoleCommandFunction function, string command, string help, ConsoleAccessLevelEnum accessLevel)
|
||||
{
|
||||
return 0; // Mock success
|
||||
}
|
||||
|
||||
/// <summary>Add new console command with parameter spec</summary>
|
||||
/// <param name="function">Command function</param>
|
||||
/// <param name="command">Command name</param>
|
||||
/// <param name="help">Help text</param>
|
||||
/// <param name="accessLevel">Access level</param>
|
||||
/// <param name="spec">Parameter specification</param>
|
||||
/// <returns>0 for success</returns>
|
||||
public static int AddNewConsoleCommand(ConsoleCommandFunction function, string command, string help, ConsoleAccessLevelEnum accessLevel, ConsoleCommandParameterSpecClass spec)
|
||||
{
|
||||
return 0; // Mock success
|
||||
}
|
||||
|
||||
/// <summary>Send control system command</summary>
|
||||
/// <param name="command">Command to send</param>
|
||||
/// <param name="programNumber">Program number</param>
|
||||
public static void SendControlSystemCommand(string command, uint programNumber)
|
||||
{
|
||||
// Mock implementation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronIO
|
||||
{
|
||||
/// <summary>Mock File class for basic file operations</summary>
|
||||
public static class File
|
||||
{
|
||||
/// <summary>Checks if a file exists</summary>
|
||||
/// <param name="path">File path</param>
|
||||
/// <returns>True if file exists</returns>
|
||||
public static bool Exists(string path)
|
||||
{
|
||||
// Mock implementation - use System.IO.File for actual file operations
|
||||
return System.IO.File.Exists(path);
|
||||
}
|
||||
|
||||
/// <summary>Reads all text from a file</summary>
|
||||
/// <param name="path">File path</param>
|
||||
/// <returns>File contents</returns>
|
||||
public static string ReadToEnd(string path)
|
||||
{
|
||||
return System.IO.File.ReadAllText(path);
|
||||
}
|
||||
|
||||
/// <summary>Reads all text from a file with specified encoding</summary>
|
||||
/// <param name="path">File path</param>
|
||||
/// <param name="encoding">Text encoding</param>
|
||||
/// <returns>File contents</returns>
|
||||
public static string ReadToEnd(string path, System.Text.Encoding encoding)
|
||||
{
|
||||
return System.IO.File.ReadAllText(path, encoding);
|
||||
}
|
||||
|
||||
/// <summary>Writes text to a file</summary>
|
||||
/// <param name="path">File path</param>
|
||||
/// <param name="contents">Contents to write</param>
|
||||
public static void WriteAllText(string path, string contents)
|
||||
{
|
||||
System.IO.File.WriteAllText(path, contents);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a file</summary>
|
||||
/// <param name="path">File path</param>
|
||||
public static void Delete(string path)
|
||||
{
|
||||
if (System.IO.File.Exists(path))
|
||||
System.IO.File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock Directory class for basic directory operations</summary>
|
||||
public static class Directory
|
||||
{
|
||||
/// <summary>Gets the application directory path</summary>
|
||||
/// <returns>Application directory path</returns>
|
||||
public static string GetApplicationDirectory()
|
||||
{
|
||||
// Mock implementation - return current directory or a typical Crestron path
|
||||
return System.IO.Directory.GetCurrentDirectory();
|
||||
}
|
||||
|
||||
/// <summary>Gets the application root directory path</summary>
|
||||
/// <returns>Application root directory path</returns>
|
||||
public static string GetApplicationRootDirectory()
|
||||
{
|
||||
// Mock implementation - return current directory or a typical Crestron path
|
||||
return System.IO.Directory.GetCurrentDirectory();
|
||||
}
|
||||
|
||||
/// <summary>Checks if a directory exists</summary>
|
||||
/// <param name="path">Directory path</param>
|
||||
/// <returns>True if directory exists</returns>
|
||||
public static bool Exists(string path)
|
||||
{
|
||||
return System.IO.Directory.Exists(path);
|
||||
}
|
||||
|
||||
/// <summary>Creates a directory</summary>
|
||||
/// <param name="path">Directory path</param>
|
||||
public static void CreateDirectory(string path)
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock Path class for path operations</summary>
|
||||
public static class Path
|
||||
{
|
||||
/// <summary>Directory separator character</summary>
|
||||
public static readonly char DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar;
|
||||
|
||||
/// <summary>Combines path strings</summary>
|
||||
/// <param name="path1">First path</param>
|
||||
/// <param name="path2">Second path</param>
|
||||
/// <returns>Combined path</returns>
|
||||
public static string Combine(string path1, string path2)
|
||||
{
|
||||
return System.IO.Path.Combine(path1, path2);
|
||||
}
|
||||
|
||||
/// <summary>Gets the file name from a path</summary>
|
||||
/// <param name="path">Full path</param>
|
||||
/// <returns>File name</returns>
|
||||
public static string GetFileName(string path)
|
||||
{
|
||||
return System.IO.Path.GetFileName(path);
|
||||
}
|
||||
|
||||
/// <summary>Gets the directory name from a path</summary>
|
||||
/// <param name="path">Full path</param>
|
||||
/// <returns>Directory name</returns>
|
||||
public static string GetDirectoryName(string path)
|
||||
{
|
||||
return System.IO.Path.GetDirectoryName(path) ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Gets the file extension from a path</summary>
|
||||
/// <param name="path">Full path</param>
|
||||
/// <returns>File extension</returns>
|
||||
public static string GetExtension(string path)
|
||||
{
|
||||
return System.IO.Path.GetExtension(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
61
src/CrestronMock/CrestronLogger.cs
Normal file
61
src/CrestronMock/CrestronLogger.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronLogger
|
||||
{
|
||||
/// <summary>Mock CrestronLogger for .NET 8 compatibility</summary>
|
||||
public static class CrestronLogger
|
||||
{
|
||||
/// <summary>Write to log</summary>
|
||||
/// <param name="logName">Log name</param>
|
||||
/// <param name="message">Message</param>
|
||||
/// <param name="mode">Logger mode</param>
|
||||
public static void WriteToLog(string logName, string message, LoggerModeEnum mode)
|
||||
{
|
||||
Console.WriteLine($"[{logName}] {message}");
|
||||
}
|
||||
|
||||
/// <summary>Write to log with level</summary>
|
||||
/// <param name="message">Message</param>
|
||||
/// <param name="level">Log level</param>
|
||||
public static void WriteToLog(string message, uint level)
|
||||
{
|
||||
Console.WriteLine($"[Level {level}] {message}");
|
||||
}
|
||||
|
||||
/// <summary>Initialize logger</summary>
|
||||
/// <param name="bufferSize">Buffer size</param>
|
||||
/// <param name="mode">Logger mode</param>
|
||||
public static void Initialize(int bufferSize, LoggerModeEnum mode)
|
||||
{
|
||||
// Mock implementation
|
||||
}
|
||||
|
||||
/// <summary>Print the log</summary>
|
||||
/// <param name="includeAll">Include all log entries</param>
|
||||
/// <returns>Log entries as string list</returns>
|
||||
public static List<string> PrintTheLog(bool includeAll = false)
|
||||
{
|
||||
return new List<string> { "Mock log entry" };
|
||||
}
|
||||
|
||||
/// <summary>Clear the log</summary>
|
||||
/// <param name="clearAll">Clear all entries</param>
|
||||
/// <returns>Success message</returns>
|
||||
public static string Clear(bool clearAll)
|
||||
{
|
||||
return "Log cleared (mock)";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Logger mode enumeration</summary>
|
||||
public enum LoggerModeEnum
|
||||
{
|
||||
/// <summary>Append mode</summary>
|
||||
LoggingModeAppend = 0,
|
||||
/// <summary>Overwrite mode</summary>
|
||||
LoggingModeOverwrite = 1,
|
||||
/// <summary>RM mode</summary>
|
||||
RM = 2
|
||||
}
|
||||
}
|
||||
10
src/CrestronMock/CrestronMock.csproj
Normal file
10
src/CrestronMock/CrestronMock.csproj
Normal file
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Configurations>Debug;Release;Test</Configurations>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
245
src/CrestronMock/CrestronQueue.cs
Normal file
245
src/CrestronMock/CrestronQueue.cs
Normal file
@@ -0,0 +1,245 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Mock implementation of Crestron CrestronQueue for testing purposes
|
||||
/// Provides the same public API surface as the real CrestronQueue
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of items in the queue</typeparam>
|
||||
public class CrestronQueue<T> : IDisposable
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private readonly Queue<T> _queue = new Queue<T>();
|
||||
private readonly object _lockObject = new object();
|
||||
private readonly ManualResetEventSlim _dataAvailableEvent = new ManualResetEventSlim(false);
|
||||
private bool _disposed = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>Gets the number of items in the queue</summary>
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _queue.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets whether the queue is empty</summary>
|
||||
public bool IsEmpty
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _queue.Count == 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Constructor
|
||||
|
||||
/// <summary>Initializes a new instance of the CrestronQueue class</summary>
|
||||
public CrestronQueue()
|
||||
{
|
||||
// Mock implementation
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of the CrestronQueue class with specified capacity</summary>
|
||||
/// <param name="capacity">The initial capacity of the queue</param>
|
||||
public CrestronQueue(int capacity)
|
||||
{
|
||||
// Mock implementation - capacity is ignored in this mock
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>Adds an item to the end of the queue</summary>
|
||||
/// <param name="item">Item to add</param>
|
||||
public void Enqueue(T item)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CrestronQueue<T>));
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
_queue.Enqueue(item);
|
||||
_dataAvailableEvent.Set();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes and returns the item at the beginning of the queue</summary>
|
||||
/// <returns>The item that was removed from the queue</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown when the queue is empty</exception>
|
||||
public T Dequeue()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CrestronQueue<T>));
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (_queue.Count == 0)
|
||||
throw new InvalidOperationException("Queue is empty");
|
||||
|
||||
var item = _queue.Dequeue();
|
||||
|
||||
if (_queue.Count == 0)
|
||||
_dataAvailableEvent.Reset();
|
||||
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tries to remove and return the item at the beginning of the queue</summary>
|
||||
/// <param name="item">When successful, contains the dequeued item</param>
|
||||
/// <returns>True if an item was successfully dequeued</returns>
|
||||
public bool TryDequeue(out T item)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
item = default(T)!;
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (_queue.Count == 0)
|
||||
{
|
||||
item = default(T)!;
|
||||
return false;
|
||||
}
|
||||
|
||||
item = _queue.Dequeue();
|
||||
|
||||
if (_queue.Count == 0)
|
||||
_dataAvailableEvent.Reset();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns the item at the beginning of the queue without removing it</summary>
|
||||
/// <returns>The item at the beginning of the queue</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown when the queue is empty</exception>
|
||||
public T Peek()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CrestronQueue<T>));
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (_queue.Count == 0)
|
||||
throw new InvalidOperationException("Queue is empty");
|
||||
|
||||
return _queue.Peek();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tries to return the item at the beginning of the queue without removing it</summary>
|
||||
/// <param name="item">When successful, contains the item at the beginning of the queue</param>
|
||||
/// <returns>True if an item was found</returns>
|
||||
public bool TryPeek(out T item)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
item = default(T)!;
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (_queue.Count == 0)
|
||||
{
|
||||
item = default(T)!;
|
||||
return false;
|
||||
}
|
||||
|
||||
item = _queue.Peek();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes all items from the queue</summary>
|
||||
public void Clear()
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
_queue.Clear();
|
||||
_dataAvailableEvent.Reset();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for data to become available in the queue</summary>
|
||||
/// <param name="timeout">Timeout in milliseconds</param>
|
||||
/// <returns>True if data became available within the timeout</returns>
|
||||
public bool WaitForData(int timeout)
|
||||
{
|
||||
if (_disposed) return false;
|
||||
|
||||
return _dataAvailableEvent.Wait(timeout);
|
||||
}
|
||||
|
||||
/// <summary>Waits for data to become available in the queue</summary>
|
||||
/// <returns>True when data becomes available</returns>
|
||||
public bool WaitForData()
|
||||
{
|
||||
if (_disposed) return false;
|
||||
|
||||
_dataAvailableEvent.Wait();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Copies the queue elements to an array</summary>
|
||||
/// <returns>Array containing the queue elements</returns>
|
||||
public T[] ToArray()
|
||||
{
|
||||
if (_disposed) return new T[0];
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _queue.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Implementation
|
||||
|
||||
/// <summary>Disposes the queue and releases resources</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>Protected dispose method</summary>
|
||||
/// <param name="disposing">True if disposing managed resources</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_dataAvailableEvent?.Dispose();
|
||||
Clear();
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
131
src/CrestronMock/EventTypes.cs
Normal file
131
src/CrestronMock/EventTypes.cs
Normal file
@@ -0,0 +1,131 @@
|
||||
using System;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
/// <summary>Mock eProgramStatusEventType enumeration</summary>
|
||||
public enum eProgramStatusEventType
|
||||
{
|
||||
/// <summary>Program stopping</summary>
|
||||
Stopping = 0,
|
||||
/// <summary>Program started</summary>
|
||||
Starting = 1,
|
||||
/// <summary>Program running</summary>
|
||||
Running = 2,
|
||||
/// <summary>Program paused</summary>
|
||||
Paused = 3
|
||||
}
|
||||
|
||||
/// <summary>Mock EthernetEventArgs class</summary>
|
||||
public class EthernetEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>Gets the Ethernet adapter that triggered the event</summary>
|
||||
public int EthernetAdapter { get; private set; }
|
||||
|
||||
/// <summary>Gets the link status</summary>
|
||||
public bool LinkUp { get; private set; }
|
||||
|
||||
/// <summary>Gets the speed in Mbps</summary>
|
||||
public int Speed { get; private set; }
|
||||
|
||||
/// <summary>Gets whether it's full duplex</summary>
|
||||
public bool FullDuplex { get; private set; }
|
||||
|
||||
/// <summary>Gets the ethernet event type</summary>
|
||||
public eEthernetEventType EthernetEventType { get; private set; }
|
||||
|
||||
/// <summary>Initializes a new instance of EthernetEventArgs</summary>
|
||||
/// <param name="adapter">Ethernet adapter number</param>
|
||||
/// <param name="linkUp">Link status</param>
|
||||
/// <param name="speed">Speed in Mbps</param>
|
||||
/// <param name="fullDuplex">Full duplex status</param>
|
||||
public EthernetEventArgs(int adapter, bool linkUp, int speed, bool fullDuplex)
|
||||
{
|
||||
EthernetAdapter = adapter;
|
||||
LinkUp = linkUp;
|
||||
Speed = speed;
|
||||
FullDuplex = fullDuplex;
|
||||
EthernetEventType = linkUp ? eEthernetEventType.LinkUp : eEthernetEventType.LinkDown;
|
||||
}
|
||||
|
||||
/// <summary>Default constructor</summary>
|
||||
public EthernetEventArgs() : this(0, false, 0, false)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronIO
|
||||
{
|
||||
/// <summary>Mock FileInfo class for basic file operations</summary>
|
||||
public class FileInfo
|
||||
{
|
||||
/// <summary>Gets the full path of the file</summary>
|
||||
public string FullName { get; private set; }
|
||||
|
||||
/// <summary>Gets the name of the file</summary>
|
||||
public string Name { get; private set; }
|
||||
|
||||
/// <summary>Gets the directory name</summary>
|
||||
public string? DirectoryName { get; private set; }
|
||||
|
||||
/// <summary>Gets whether the file exists</summary>
|
||||
public bool Exists { get; private set; }
|
||||
|
||||
/// <summary>Gets the length of the file in bytes</summary>
|
||||
public long Length { get; private set; }
|
||||
|
||||
/// <summary>Gets the creation time</summary>
|
||||
public DateTime CreationTime { get; private set; }
|
||||
|
||||
/// <summary>Gets the last write time</summary>
|
||||
public DateTime LastWriteTime { get; private set; }
|
||||
|
||||
/// <summary>Gets the last access time</summary>
|
||||
public DateTime LastAccessTime { get; private set; }
|
||||
|
||||
/// <summary>Initializes a new instance of FileInfo</summary>
|
||||
/// <param name="fileName">Path to the file</param>
|
||||
public FileInfo(string fileName)
|
||||
{
|
||||
FullName = fileName ?? string.Empty;
|
||||
Name = System.IO.Path.GetFileName(fileName) ?? string.Empty;
|
||||
DirectoryName = System.IO.Path.GetDirectoryName(fileName);
|
||||
|
||||
// Mock file properties
|
||||
Exists = !string.IsNullOrEmpty(fileName);
|
||||
Length = 0;
|
||||
CreationTime = DateTime.Now;
|
||||
LastWriteTime = DateTime.Now;
|
||||
LastAccessTime = DateTime.Now;
|
||||
}
|
||||
|
||||
/// <summary>Deletes the file</summary>
|
||||
public void Delete()
|
||||
{
|
||||
// Mock implementation - just mark as not existing
|
||||
Exists = false;
|
||||
}
|
||||
|
||||
/// <summary>Creates a text file or opens an existing one for writing</summary>
|
||||
/// <returns>A mock StreamWriter</returns>
|
||||
public System.IO.StreamWriter CreateText()
|
||||
{
|
||||
var stream = new System.IO.MemoryStream();
|
||||
return new System.IO.StreamWriter(stream);
|
||||
}
|
||||
|
||||
/// <summary>Opens an existing file for reading</summary>
|
||||
/// <returns>A mock FileStream</returns>
|
||||
public System.IO.FileStream OpenRead()
|
||||
{
|
||||
// Mock implementation - return a memory stream wrapped as FileStream
|
||||
return new System.IO.FileStream(FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
|
||||
}
|
||||
}
|
||||
|
||||
// Event handler delegates
|
||||
/// <summary>Ethernet event handler delegate</summary>
|
||||
public delegate void EthernetEventHandler(EthernetEventArgs args);
|
||||
}
|
||||
|
||||
|
||||
112
src/CrestronMock/Extensions.cs
Normal file
112
src/CrestronMock/Extensions.cs
Normal file
@@ -0,0 +1,112 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threa case ETHERNET_PARAMETER_TO_GET.ETHERNET_HOSTNAME:
|
||||
return "mock-hostname";
|
||||
case ETHERNET_PARAMETER_TO_GET.ETHERNET_MAC_ADDRESS:
|
||||
return "00:11:22:33:44:55";
|
||||
case ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME:
|
||||
return "mock-domain.local";
|
||||
default:
|
||||
return string.Empty; asks;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
public static class CrestronInvoke
|
||||
{
|
||||
public static void BeginInvoke(Func<object> func, object? state = null)
|
||||
{
|
||||
Task.Run(func);
|
||||
}
|
||||
|
||||
public static void BeginInvoke(Action action)
|
||||
{
|
||||
Task.Run(action);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CrestronEthernetHelper
|
||||
{
|
||||
/// <summary>Ethernet parameter enumeration</summary>
|
||||
public enum ETHERNET_PARAMETER_TO_GET
|
||||
{
|
||||
ETHERNET_HOSTNAME = 0,
|
||||
ETHERNET_DOMAIN_NAME = 1,
|
||||
ETHERNET_IP_ADDRESS = 2,
|
||||
ETHERNET_SUBNET_MASK = 3,
|
||||
ETHERNET_GATEWAY = 4,
|
||||
ETHERNET_DNS_SERVER = 5,
|
||||
ETHERNET_MAC_ADDRESS = 6,
|
||||
ETHERNET_DHCP_STATUS = 7,
|
||||
GET_CURRENT_DHCP_STATE = 8,
|
||||
GET_CURRENT_IP_ADDRESS = 9,
|
||||
GET_CURRENT_IP_MASK = 10,
|
||||
GET_CURRENT_ROUTER = 11,
|
||||
GET_HOSTNAME = 12,
|
||||
GET_LINK_STATUS = 13,
|
||||
GET_DOMAIN_NAME = 14
|
||||
}
|
||||
|
||||
public static List<string> GetEthernetAdaptersInfo()
|
||||
{
|
||||
return new List<string> { "MockAdapter" };
|
||||
}
|
||||
|
||||
public static string GetEthernetParameter(string adapter, string parameter)
|
||||
{
|
||||
return "MockValue";
|
||||
}
|
||||
|
||||
/// <summary>Get ethernet parameter as string</summary>
|
||||
/// <param name="parameter">The parameter to get</param>
|
||||
/// <param name="adapterType">The adapter type</param>
|
||||
/// <returns>The parameter value as string</returns>
|
||||
public static string GetEthernetParameter(ETHERNET_PARAMETER_TO_GET parameter, EthernetAdapterType adapterType)
|
||||
{
|
||||
// Mock implementation
|
||||
switch (parameter)
|
||||
{
|
||||
case ETHERNET_PARAMETER_TO_GET.ETHERNET_IP_ADDRESS:
|
||||
return "192.168.1.100";
|
||||
case ETHERNET_PARAMETER_TO_GET.ETHERNET_SUBNET_MASK:
|
||||
return "255.255.255.0";
|
||||
case ETHERNET_PARAMETER_TO_GET.ETHERNET_GATEWAY:
|
||||
return "192.168.1.1";
|
||||
case ETHERNET_PARAMETER_TO_GET.ETHERNET_HOSTNAME:
|
||||
return "MockHost";
|
||||
case ETHERNET_PARAMETER_TO_GET.ETHERNET_MAC_ADDRESS:
|
||||
return "00:11:22:33:44:55";
|
||||
default:
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Get adapter ID for specified adapter type</summary>
|
||||
/// <param name="adapterType">The adapter type</param>
|
||||
/// <returns>The adapter ID</returns>
|
||||
public static int GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType adapterType)
|
||||
{
|
||||
// Mock implementation
|
||||
return (int)adapterType;
|
||||
}
|
||||
|
||||
/// <summary>Check if control subnet is in automatic mode</summary>
|
||||
/// <param name="adapterId">The adapter ID</param>
|
||||
/// <returns>True if in automatic mode</returns>
|
||||
public static bool IsControlSubnetInAutomaticMode(int adapterId)
|
||||
{
|
||||
// Mock implementation
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock EthernetAdapterType enumeration</summary>
|
||||
public enum EthernetAdapterType
|
||||
{
|
||||
/// <summary>Ethernet LAN adapter</summary>
|
||||
EthernetLANAdapter = 0,
|
||||
/// <summary>Control subnet adapter</summary>
|
||||
ControlSubnet = 1,
|
||||
/// <summary>Auto-detect adapter</summary>
|
||||
EthernetAdapterAuto = 2
|
||||
}
|
||||
}
|
||||
407
src/CrestronMock/HttpCwsServer.cs
Normal file
407
src/CrestronMock/HttpCwsServer.cs
Normal file
@@ -0,0 +1,407 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Crestron.SimplSharp.WebScripting
|
||||
{
|
||||
/// <summary>Mock HttpCwsServer class for HTTP web server functionality</summary>
|
||||
public class HttpCwsServer : IDisposable
|
||||
{
|
||||
private HttpListener? _httpListener;
|
||||
private bool _listening;
|
||||
private readonly Dictionary<string, IHttpCwsHandler> _routes = new Dictionary<string, IHttpCwsHandler>();
|
||||
|
||||
/// <summary>Gets or sets the port number</summary>
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>Gets whether the server is listening</summary>
|
||||
public bool Listening => _listening;
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsServer</summary>
|
||||
public HttpCwsServer()
|
||||
{
|
||||
Port = 80;
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsServer</summary>
|
||||
/// <param name="port">Port number to listen on</param>
|
||||
public HttpCwsServer(int port)
|
||||
{
|
||||
Port = port;
|
||||
}
|
||||
|
||||
/// <summary>Starts the HTTP server</summary>
|
||||
/// <returns>True if started successfully</returns>
|
||||
public bool Start()
|
||||
{
|
||||
if (_listening)
|
||||
return true;
|
||||
|
||||
try
|
||||
{
|
||||
_httpListener = new HttpListener();
|
||||
_httpListener.Prefixes.Add($"http://+:{Port}/");
|
||||
_httpListener.Start();
|
||||
_listening = true;
|
||||
|
||||
_ = Task.Run(ProcessRequestsAsync);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops the HTTP server</summary>
|
||||
/// <returns>True if stopped successfully</returns>
|
||||
public bool Stop()
|
||||
{
|
||||
if (!_listening)
|
||||
return true;
|
||||
|
||||
try
|
||||
{
|
||||
_listening = false;
|
||||
_httpListener?.Stop();
|
||||
_httpListener?.Close();
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds a route handler</summary>
|
||||
/// <param name="route">Route path</param>
|
||||
/// <param name="handler">Handler for the route</param>
|
||||
public void AddRoute(string route, IHttpCwsHandler handler)
|
||||
{
|
||||
_routes[route.ToLowerInvariant()] = handler;
|
||||
}
|
||||
|
||||
/// <summary>Removes a route handler</summary>
|
||||
/// <param name="route">Route path to remove</param>
|
||||
public void RemoveRoute(string route)
|
||||
{
|
||||
_routes.Remove(route.ToLowerInvariant());
|
||||
}
|
||||
|
||||
/// <summary>Unregisters a route handler</summary>
|
||||
/// <param name="route">Route path to unregister</param>
|
||||
public void Unregister(string route)
|
||||
{
|
||||
RemoveRoute(route);
|
||||
}
|
||||
|
||||
private async Task ProcessRequestsAsync()
|
||||
{
|
||||
while (_listening && _httpListener != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var context = await _httpListener.GetContextAsync();
|
||||
_ = Task.Run(() => HandleRequest(context));
|
||||
}
|
||||
catch (HttpListenerException)
|
||||
{
|
||||
// Listener was stopped
|
||||
break;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// Listener was disposed
|
||||
break;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Handle other exceptions
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleRequest(HttpListenerContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = context.Request;
|
||||
var response = context.Response;
|
||||
|
||||
var path = request.Url?.AbsolutePath?.ToLowerInvariant() ?? "/";
|
||||
|
||||
var cwsContext = new HttpCwsContext(context);
|
||||
|
||||
if (_routes.TryGetValue(path, out var handler))
|
||||
{
|
||||
handler.ProcessRequest(cwsContext);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Default 404 response
|
||||
response.StatusCode = 404;
|
||||
var buffer = Encoding.UTF8.GetBytes("Not Found");
|
||||
response.ContentLength64 = buffer.Length;
|
||||
response.OutputStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
response.Close();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Handle request processing errors
|
||||
try
|
||||
{
|
||||
context.Response.StatusCode = 500;
|
||||
context.Response.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore errors when closing response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Disposes the HttpCwsServer</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_httpListener?.Close();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HttpCwsContext class representing an HTTP request/response context</summary>
|
||||
public class HttpCwsContext
|
||||
{
|
||||
private readonly HttpListenerContext _context;
|
||||
|
||||
/// <summary>Gets the HTTP request</summary>
|
||||
public HttpCwsRequest Request { get; }
|
||||
|
||||
/// <summary>Gets the HTTP response</summary>
|
||||
public HttpCwsResponse Response { get; }
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsContext</summary>
|
||||
/// <param name="context">Underlying HttpListenerContext</param>
|
||||
public HttpCwsContext(HttpListenerContext context)
|
||||
{
|
||||
_context = context;
|
||||
Request = new HttpCwsRequest(context.Request);
|
||||
Response = new HttpCwsResponse(context.Response);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HttpCwsRequest class representing an HTTP request</summary>
|
||||
public class HttpCwsRequest
|
||||
{
|
||||
private readonly HttpListenerRequest _request;
|
||||
|
||||
/// <summary>Gets the HTTP method</summary>
|
||||
public string HttpMethod => _request.HttpMethod;
|
||||
|
||||
/// <summary>Gets the request URL</summary>
|
||||
public Uri? Url => _request.Url;
|
||||
|
||||
/// <summary>Gets the request headers</summary>
|
||||
public System.Collections.Specialized.NameValueCollection Headers => _request.Headers;
|
||||
|
||||
/// <summary>Gets the query string</summary>
|
||||
public System.Collections.Specialized.NameValueCollection QueryString => _request.QueryString;
|
||||
|
||||
/// <summary>Gets the content type</summary>
|
||||
public string? ContentType => _request.ContentType;
|
||||
|
||||
/// <summary>Gets the content length</summary>
|
||||
public long ContentLength => _request.ContentLength64;
|
||||
|
||||
/// <summary>Gets the input stream</summary>
|
||||
public Stream InputStream => _request.InputStream;
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsRequest</summary>
|
||||
/// <param name="request">Underlying HttpListenerRequest</param>
|
||||
public HttpCwsRequest(HttpListenerRequest request)
|
||||
{
|
||||
_request = request;
|
||||
}
|
||||
|
||||
/// <summary>Gets the request body as a string</summary>
|
||||
/// <returns>Request body content</returns>
|
||||
public string GetRequestBodyAsString()
|
||||
{
|
||||
using var reader = new StreamReader(InputStream, Encoding.UTF8);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HttpCwsResponse class representing an HTTP response</summary>
|
||||
public class HttpCwsResponse
|
||||
{
|
||||
private readonly HttpListenerResponse _response;
|
||||
|
||||
/// <summary>Gets or sets the status code</summary>
|
||||
public int StatusCode
|
||||
{
|
||||
get => _response.StatusCode;
|
||||
set => _response.StatusCode = value;
|
||||
}
|
||||
|
||||
/// <summary>Gets or sets the status description</summary>
|
||||
public string StatusDescription
|
||||
{
|
||||
get => _response.StatusDescription;
|
||||
set => _response.StatusDescription = value;
|
||||
}
|
||||
|
||||
/// <summary>Gets or sets the content type</summary>
|
||||
public string? ContentType
|
||||
{
|
||||
get => _response.ContentType;
|
||||
set => _response.ContentType = value;
|
||||
}
|
||||
|
||||
/// <summary>Gets or sets the content length</summary>
|
||||
public long ContentLength
|
||||
{
|
||||
get => _response.ContentLength64;
|
||||
set => _response.ContentLength64 = value;
|
||||
}
|
||||
|
||||
/// <summary>Gets the response headers</summary>
|
||||
public WebHeaderCollection Headers => _response.Headers;
|
||||
|
||||
/// <summary>Gets the output stream</summary>
|
||||
public Stream OutputStream => _response.OutputStream;
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsResponse</summary>
|
||||
/// <param name="response">Underlying HttpListenerResponse</param>
|
||||
public HttpCwsResponse(HttpListenerResponse response)
|
||||
{
|
||||
_response = response;
|
||||
}
|
||||
|
||||
/// <summary>Writes a string to the response</summary>
|
||||
/// <param name="content">Content to write</param>
|
||||
public void Write(string content)
|
||||
{
|
||||
var buffer = Encoding.UTF8.GetBytes(content);
|
||||
ContentLength = buffer.Length;
|
||||
OutputStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
/// <summary>Writes bytes to the response</summary>
|
||||
/// <param name="buffer">Buffer to write</param>
|
||||
/// <param name="offset">Offset in buffer</param>
|
||||
/// <param name="count">Number of bytes to write</param>
|
||||
public void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
OutputStream.Write(buffer, offset, count);
|
||||
}
|
||||
|
||||
/// <summary>Ends the response</summary>
|
||||
public void End()
|
||||
{
|
||||
try
|
||||
{
|
||||
_response.Close();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Ignore exceptions during close
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Interface for HTTP request handlers</summary>
|
||||
public interface IHttpCwsHandler
|
||||
{
|
||||
/// <summary>Processes an HTTP request</summary>
|
||||
/// <param name="context">HTTP context</param>
|
||||
void ProcessRequest(HttpCwsContext context);
|
||||
}
|
||||
|
||||
/// <summary>Mock HttpCwsRoute class for route management</summary>
|
||||
public class HttpCwsRoute
|
||||
{
|
||||
/// <summary>Gets or sets the route path</summary>
|
||||
public string Path { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets or sets the HTTP method</summary>
|
||||
public string Method { get; set; } = "GET";
|
||||
|
||||
/// <summary>Gets or sets the route handler</summary>
|
||||
public IHttpCwsHandler? Handler { get; set; }
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsRoute</summary>
|
||||
public HttpCwsRoute()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsRoute</summary>
|
||||
/// <param name="path">Route path</param>
|
||||
/// <param name="handler">Route handler</param>
|
||||
public HttpCwsRoute(string path, IHttpCwsHandler handler)
|
||||
{
|
||||
Path = path;
|
||||
Handler = handler;
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of HttpCwsRoute</summary>
|
||||
/// <param name="path">Route path</param>
|
||||
/// <param name="method">HTTP method</param>
|
||||
/// <param name="handler">Route handler</param>
|
||||
public HttpCwsRoute(string path, string method, IHttpCwsHandler handler)
|
||||
{
|
||||
Path = path;
|
||||
Method = method;
|
||||
Handler = handler;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTP CWS route collection</summary>
|
||||
public class HttpCwsRouteCollection
|
||||
{
|
||||
private readonly List<HttpCwsRoute> _routes = new List<HttpCwsRoute>();
|
||||
|
||||
/// <summary>Adds a route</summary>
|
||||
/// <param name="route">Route to add</param>
|
||||
public void Add(HttpCwsRoute route)
|
||||
{
|
||||
_routes.Add(route);
|
||||
}
|
||||
|
||||
/// <summary>Removes a route</summary>
|
||||
/// <param name="route">Route to remove</param>
|
||||
public void Remove(HttpCwsRoute route)
|
||||
{
|
||||
_routes.Remove(route);
|
||||
}
|
||||
|
||||
/// <summary>Clears all routes</summary>
|
||||
public void Clear()
|
||||
{
|
||||
_routes.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Gets route count</summary>
|
||||
public int Count => _routes.Count;
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTP CWS request event args</summary>
|
||||
public class HttpCwsRequestEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>Gets the HTTP context</summary>
|
||||
public HttpCwsContext Context { get; private set; }
|
||||
|
||||
/// <summary>Initializes new instance</summary>
|
||||
/// <param name="context">HTTP context</param>
|
||||
public HttpCwsRequestEventArgs(HttpCwsContext context)
|
||||
{
|
||||
Context = context;
|
||||
}
|
||||
}
|
||||
}
|
||||
41
src/CrestronMock/NetworkingExtensions.cs
Normal file
41
src/CrestronMock/NetworkingExtensions.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronSockets
|
||||
{
|
||||
// Additional types needed for networking compatibility
|
||||
|
||||
/// <summary>IP address extensions and utilities</summary>
|
||||
public static class IPAddress
|
||||
{
|
||||
/// <summary>Parse IP address string</summary>
|
||||
public static System.Net.IPAddress Parse(string ipString)
|
||||
{
|
||||
return System.Net.IPAddress.Parse(ipString);
|
||||
}
|
||||
|
||||
/// <summary>Any IP address</summary>
|
||||
public static System.Net.IPAddress Any => System.Net.IPAddress.Any;
|
||||
}
|
||||
}
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
/// <summary>Extensions for CrestronQueue</summary>
|
||||
public static class CrestronQueueExtensions
|
||||
{
|
||||
/// <summary>Try to enqueue item</summary>
|
||||
public static bool TryToEnqueue<T>(this CrestronQueue<T> queue, T item)
|
||||
{
|
||||
try
|
||||
{
|
||||
queue.Enqueue(item);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
src/CrestronMock/SecureTCPClient.cs
Normal file
31
src/CrestronMock/SecureTCPClient.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronSockets
|
||||
{
|
||||
/// <summary>Mock implementation of Crestron SecureTCPClient for testing purposes</summary>
|
||||
public class SecureTCPClient : TCPClient
|
||||
{
|
||||
/// <summary>Initializes a new instance of the SecureTCPClient class</summary>
|
||||
/// <param name="addressToConnectTo">IP address to connect to</param>
|
||||
/// <param name="portNumber">Port number to connect to</param>
|
||||
/// <param name="bufferSize">Size of the receive buffer</param>
|
||||
public SecureTCPClient(string addressToConnectTo, int portNumber, int bufferSize)
|
||||
: base(addressToConnectTo, portNumber, bufferSize)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Gets or sets whether to verify the host certificate</summary>
|
||||
public bool HostVerification { get; set; } = true;
|
||||
|
||||
/// <summary>Gets or sets whether to verify the peer certificate</summary>
|
||||
public bool PeerVerification { get; set; } = true;
|
||||
|
||||
/// <summary>Resets the client connection</summary>
|
||||
/// <param name="connectionFlag">Connection flag</param>
|
||||
public void Reset(int connectionFlag)
|
||||
{
|
||||
// Mock implementation
|
||||
DisconnectFromServer();
|
||||
}
|
||||
}
|
||||
}
|
||||
74
src/CrestronMock/SocketTypes.cs
Normal file
74
src/CrestronMock/SocketTypes.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronSockets
|
||||
{
|
||||
/// <summary>Mock EthernetAdapterType enumeration</summary>
|
||||
public enum EthernetAdapterType
|
||||
{
|
||||
/// <summary>Ethernet adapter 1</summary>
|
||||
EthernetLANAdapter = 0,
|
||||
/// <summary>Ethernet adapter 2</summary>
|
||||
EthernetAdapter2 = 1,
|
||||
/// <summary>Auto-detect adapter</summary>
|
||||
EthernetAdapterAuto = 2
|
||||
}
|
||||
|
||||
/// <summary>Mock SocketErrorCodes enumeration</summary>
|
||||
public enum SocketErrorCodes
|
||||
{
|
||||
/// <summary>Operation completed successfully</summary>
|
||||
SOCKET_OK = 0,
|
||||
/// <summary>Socket operation pending</summary>
|
||||
SOCKET_OPERATION_PENDING = 1,
|
||||
/// <summary>Socket not connected</summary>
|
||||
SOCKET_NOT_CONNECTED = 2,
|
||||
/// <summary>Connection failed</summary>
|
||||
SOCKET_CONNECTION_FAILED = 3,
|
||||
/// <summary>Invalid client index</summary>
|
||||
SOCKET_INVALID_CLIENT_INDEX = 4,
|
||||
/// <summary>DNS lookup failed</summary>
|
||||
SOCKET_DNS_LOOKUP_FAILED = 5,
|
||||
/// <summary>Invalid address</summary>
|
||||
SOCKET_INVALID_ADDRESS = 6,
|
||||
/// <summary>Connection timed out</summary>
|
||||
SOCKET_CONNECTION_TIMEOUT = 7,
|
||||
/// <summary>Send data failed</summary>
|
||||
SOCKET_SEND_DATA_FAILED = 8,
|
||||
/// <summary>Receive data failed</summary>
|
||||
SOCKET_RECEIVE_DATA_FAILED = 9,
|
||||
/// <summary>Socket closed</summary>
|
||||
SOCKET_CLOSED = 10,
|
||||
/// <summary>Socket disconnected</summary>
|
||||
SOCKET_DISCONNECTED = 11,
|
||||
/// <summary>Max connections reached</summary>
|
||||
SOCKET_MAX_CONNECTIONS_REACHED = 12,
|
||||
/// <summary>Permission denied</summary>
|
||||
SOCKET_PERMISSION_DENIED = 13,
|
||||
/// <summary>Address already in use</summary>
|
||||
SOCKET_ADDRESS_IN_USE = 14,
|
||||
/// <summary>Invalid parameter</summary>
|
||||
SOCKET_INVALID_PARAMETER = 15,
|
||||
/// <summary>Connection in progress</summary>
|
||||
SOCKET_CONNECTION_IN_PROGRESS = 16
|
||||
}
|
||||
|
||||
/// <summary>Mock socket exception</summary>
|
||||
public class SocketException : Exception
|
||||
{
|
||||
/// <summary>Error code</summary>
|
||||
public int ErrorCode { get; }
|
||||
|
||||
/// <summary>Constructor with error code</summary>
|
||||
public SocketException(int errorCode, string message) : base(message)
|
||||
{
|
||||
ErrorCode = errorCode;
|
||||
}
|
||||
|
||||
/// <summary>Constructor with message only</summary>
|
||||
public SocketException(string message) : base(message)
|
||||
{
|
||||
ErrorCode = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
61
src/CrestronMock/SystemTypes.cs
Normal file
61
src/CrestronMock/SystemTypes.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Crestron.SimplSharp
|
||||
{
|
||||
public delegate void ProgramStatusEventHandler(eProgramStatusEventType eventType);
|
||||
|
||||
public class InitialParametersClass
|
||||
{
|
||||
public static string ApplicationDirectory { get; set; } = "/User/";
|
||||
public static string ProgramIDTag { get; set; } = "MockProgram";
|
||||
public static string ApplicationName { get; set; } = "MockApplication";
|
||||
public static string FirmwareVersion { get; set; } = "1.0.0.0";
|
||||
public static uint ProgramNumber { get; set; } = 1;
|
||||
public static eDevicePlatform DevicePlatform { get; set; } = eDevicePlatform.Appliance;
|
||||
public static eCrestronSeries ControllerSeries { get; set; } = eCrestronSeries.FourSeries;
|
||||
|
||||
// Additional properties needed by PepperDash.Core
|
||||
public static string RoomId { get; set; } = "Room001";
|
||||
public static string RoomName { get; set; } = "Conference Room";
|
||||
public static uint ApplicationNumber { get; set; } = 1;
|
||||
public static string ControllerPromptName { get; set; } = "TestController";
|
||||
public static string ProgramDirectory { get; set; } = "/User/";
|
||||
}
|
||||
|
||||
public enum eDevicePlatform
|
||||
{
|
||||
Appliance = 0,
|
||||
Server = 1,
|
||||
ControlSystem = 2
|
||||
}
|
||||
|
||||
public enum eCrestronSeries
|
||||
{
|
||||
TwoSeries = 2,
|
||||
ThreeSeries = 3,
|
||||
FourSeries = 4,
|
||||
// Alias names used in some contexts
|
||||
Series2 = 2,
|
||||
Series3 = 3,
|
||||
Series4 = 4
|
||||
}
|
||||
|
||||
public enum eRuntimeEnvironment
|
||||
{
|
||||
SimplSharpPro = 0,
|
||||
SimplSharp = 1
|
||||
}
|
||||
|
||||
public enum eProgramCompatibility
|
||||
{
|
||||
Series3And4 = 0,
|
||||
Series3Only = 1,
|
||||
Series4Only = 2
|
||||
}
|
||||
|
||||
public static class Timeout
|
||||
{
|
||||
public const int Infinite = -1;
|
||||
}
|
||||
}
|
||||
360
src/CrestronMock/TCPClient.cs
Normal file
360
src/CrestronMock/TCPClient.cs
Normal file
@@ -0,0 +1,360 @@
|
||||
using System;
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronSockets
|
||||
{
|
||||
/// <summary>Mock SocketStatus enumeration</summary>
|
||||
public enum SocketStatus
|
||||
{
|
||||
/// <summary>Socket is connecting</summary>
|
||||
SOCKET_STATUS_WAITING = 1,
|
||||
/// <summary>Socket is connected</summary>
|
||||
SOCKET_STATUS_CONNECTED = 2,
|
||||
/// <summary>Socket is not connected</summary>
|
||||
SOCKET_STATUS_NOT_CONNECTED = 3,
|
||||
/// <summary>Connection broken</summary>
|
||||
SOCKET_STATUS_BROKEN_REMOTELY = 4,
|
||||
/// <summary>Connection broken locally</summary>
|
||||
SOCKET_STATUS_BROKEN_LOCALLY = 5,
|
||||
/// <summary>DNS resolution failed</summary>
|
||||
SOCKET_STATUS_DNS_RESOLUTION_FAILED = 6,
|
||||
/// <summary>Connection failed</summary>
|
||||
SOCKET_STATUS_CONNECT_FAILED = 7,
|
||||
/// <summary>Socket error</summary>
|
||||
SOCKET_STATUS_SOCKET_ERROR = 8,
|
||||
/// <summary>Secure connection failed</summary>
|
||||
SOCKET_STATUS_SSL_FAILED = 9,
|
||||
/// <summary>No connection available</summary>
|
||||
SOCKET_STATUS_NO_CONNECT = 10
|
||||
}
|
||||
|
||||
/// <summary>Mock ServerState enumeration</summary>
|
||||
public enum ServerState
|
||||
{
|
||||
/// <summary>Server is not listening</summary>
|
||||
SERVER_NOT_LISTENING = 0,
|
||||
/// <summary>Server is listening</summary>
|
||||
SERVER_LISTENING = 1,
|
||||
/// <summary>Server is connected</summary>
|
||||
SERVER_CONNECTED = 2
|
||||
}
|
||||
|
||||
/// <summary>Mock event handler for TCP client status changes</summary>
|
||||
/// <param name="client">The TCP client</param>
|
||||
/// <param name="clientSocketStatus">The socket status</param>
|
||||
public delegate void TCPClientSocketStatusChangeEventHandler(TCPClient client, SocketStatus clientSocketStatus);
|
||||
|
||||
/// <summary>Delegate for TCP client connect callback</summary>
|
||||
/// <param name="client">TCP client instance</param>
|
||||
public delegate void TCPClientConnectCallback(TCPClient client);
|
||||
|
||||
/// <summary>Delegate for TCP client send callback</summary>
|
||||
/// <param name="client">TCP client instance</param>
|
||||
/// <param name="numberOfBytesSent">Number of bytes sent</param>
|
||||
public delegate void TCPClientSendCallback(TCPClient client, int numberOfBytesSent);
|
||||
|
||||
/// <summary>Delegate for TCP client receive callback</summary>
|
||||
/// <param name="client">TCP client instance</param>
|
||||
/// <param name="numberOfBytesReceived">Number of bytes received</param>
|
||||
public delegate void TCPClientReceiveCallback(TCPClient client, int numberOfBytesReceived);
|
||||
|
||||
/// <summary>Mock event handler for receiving TCP client data</summary>
|
||||
/// <param name="client">The TCP client</param>
|
||||
/// <param name="numberOfBytesReceived">Number of bytes received</param>
|
||||
public delegate void TCPClientReceiveEventHandler(TCPClient client, int numberOfBytesReceived);
|
||||
|
||||
/// <summary>
|
||||
/// Mock implementation of Crestron TCPClient for testing purposes
|
||||
/// Provides the same public API surface as the real TCPClient
|
||||
/// </summary>
|
||||
public class TCPClient : IDisposable
|
||||
{
|
||||
#region Events
|
||||
|
||||
/// <summary>Event fired when socket status changes</summary>
|
||||
public event TCPClientSocketStatusChangeEventHandler? SocketStatusChange;
|
||||
|
||||
/// <summary>Event fired when data is received</summary>
|
||||
public event TCPClientReceiveEventHandler? DataReceived;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>Gets the client socket status</summary>
|
||||
public SocketStatus ClientStatus { get; private set; } = SocketStatus.SOCKET_STATUS_NOT_CONNECTED;
|
||||
|
||||
/// <summary>Gets or sets the address to connect to</summary>
|
||||
public string AddressToConnectTo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets or sets the port number to connect to</summary>
|
||||
public int PortNumber { get; set; } = 0;
|
||||
|
||||
/// <summary>Gets the number of bytes received in the incoming data buffer</summary>
|
||||
public int IncomingDataBufferSize { get; private set; } = 0;
|
||||
|
||||
/// <summary>Gets or sets the socket send timeout in milliseconds</summary>
|
||||
public int SocketSendTimeout { get; set; } = 30000;
|
||||
|
||||
/// <summary>Gets or sets the socket receive timeout in milliseconds</summary>
|
||||
public int SocketReceiveTimeout { get; set; } = 30000;
|
||||
|
||||
/// <summary>Gets or sets whether to keep the connection alive</summary>
|
||||
public bool KeepAlive { get; set; } = false;
|
||||
|
||||
/// <summary>Gets or sets whether Nagle algorithm is enabled</summary>
|
||||
public bool EnableNagle { get; set; } = true;
|
||||
|
||||
/// <summary>Gets the number of bytes available to read</summary>
|
||||
public int BytesAvailable => IncomingDataBufferSize;
|
||||
|
||||
/// <summary>Gets or sets the socket send or receive timeout in milliseconds</summary>
|
||||
public int SocketSendOrReceiveTimeOutInMs
|
||||
{
|
||||
get => SocketSendTimeout;
|
||||
set => SocketSendTimeout = SocketReceiveTimeout = value;
|
||||
}
|
||||
|
||||
/// <summary>Gets the address the client is connected to</summary>
|
||||
public string AddressClientConnectedTo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets the local port number of the client</summary>
|
||||
public uint LocalPortNumberOfClient { get; private set; } = 0;
|
||||
|
||||
/// <summary>Gets the incoming data buffer</summary>
|
||||
public byte[] IncomingDataBuffer { get; private set; } = new byte[0];
|
||||
|
||||
#endregion
|
||||
|
||||
#region Constructor
|
||||
|
||||
/// <summary>Initializes a new instance of the TCPClient class</summary>
|
||||
/// <param name="addressToConnectTo">IP address to connect to</param>
|
||||
/// <param name="portNumber">Port number to connect to</param>
|
||||
/// <param name="bufferSize">Size of the receive buffer</param>
|
||||
public TCPClient(string addressToConnectTo, int portNumber, int bufferSize)
|
||||
{
|
||||
AddressToConnectTo = addressToConnectTo;
|
||||
PortNumber = portNumber;
|
||||
_bufferSize = bufferSize;
|
||||
_receiveBuffer = new byte[bufferSize];
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of the TCPClient class</summary>
|
||||
/// <param name="addressToConnectTo">IP address to connect to</param>
|
||||
/// <param name="portNumber">Port number to connect to</param>
|
||||
/// <param name="bufferSize">Size of the receive buffer</param>
|
||||
/// <param name="ethernetAdapterToBindTo">Ethernet adapter to bind to</param>
|
||||
public TCPClient(string addressToConnectTo, int portNumber, int bufferSize, EthernetAdapterType ethernetAdapterToBindTo)
|
||||
{
|
||||
AddressToConnectTo = addressToConnectTo;
|
||||
PortNumber = portNumber;
|
||||
_bufferSize = bufferSize;
|
||||
_receiveBuffer = new byte[bufferSize];
|
||||
// Note: EthernetAdapterType is ignored in mock implementation
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Fields
|
||||
|
||||
private readonly int _bufferSize;
|
||||
private readonly byte[] _receiveBuffer;
|
||||
private bool _disposed = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>Connects to the remote endpoint asynchronously</summary>
|
||||
/// <returns>Status of the connection attempt</returns>
|
||||
public SocketStatus ConnectToServerAsync()
|
||||
{
|
||||
if (_disposed) return SocketStatus.SOCKET_STATUS_SOCKET_ERROR;
|
||||
|
||||
// Mock connection - simulate successful connection
|
||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
||||
AddressClientConnectedTo = AddressToConnectTo;
|
||||
SocketStatusChange?.Invoke(this, ClientStatus);
|
||||
return ClientStatus;
|
||||
}
|
||||
|
||||
/// <summary>Connects to the remote endpoint asynchronously with callback</summary>
|
||||
/// <param name="callback">Callback to invoke when connection completes</param>
|
||||
/// <returns>Status of the connection attempt</returns>
|
||||
public SocketStatus ConnectToServerAsync(TCPClientConnectCallback callback)
|
||||
{
|
||||
var status = ConnectToServerAsync();
|
||||
callback?.Invoke(this);
|
||||
return status;
|
||||
}
|
||||
|
||||
/// <summary>Connects to the remote endpoint</summary>
|
||||
/// <returns>Status of the connection attempt</returns>
|
||||
public SocketStatus ConnectToServer()
|
||||
{
|
||||
return ConnectToServerAsync();
|
||||
}
|
||||
|
||||
/// <summary>Disconnects from the remote endpoint</summary>
|
||||
/// <returns>Status of the disconnection</returns>
|
||||
public SocketStatus DisconnectFromServer()
|
||||
{
|
||||
if (_disposed) return SocketStatus.SOCKET_STATUS_SOCKET_ERROR;
|
||||
|
||||
ClientStatus = SocketStatus.SOCKET_STATUS_NOT_CONNECTED;
|
||||
SocketStatusChange?.Invoke(this, ClientStatus);
|
||||
return ClientStatus;
|
||||
}
|
||||
|
||||
/// <summary>Sends data to the connected server</summary>
|
||||
/// <param name="dataToSend">Data to send as a string</param>
|
||||
/// <returns>Number of bytes sent, or -1 on error</returns>
|
||||
public int SendData(string dataToSend)
|
||||
{
|
||||
if (_disposed || string.IsNullOrEmpty(dataToSend)) return -1;
|
||||
if (ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) return -1;
|
||||
|
||||
// Mock send - return the length of the string as bytes sent
|
||||
return System.Text.Encoding.UTF8.GetByteCount(dataToSend);
|
||||
}
|
||||
|
||||
/// <summary>Sends data to the connected server</summary>
|
||||
/// <param name="dataToSend">Data to send as byte array</param>
|
||||
/// <param name="lengthToSend">Number of bytes to send</param>
|
||||
/// <returns>Number of bytes sent, or -1 on error</returns>
|
||||
public int SendData(byte[] dataToSend, int lengthToSend)
|
||||
{
|
||||
if (_disposed || dataToSend == null || lengthToSend <= 0) return -1;
|
||||
if (ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) return -1;
|
||||
if (lengthToSend > dataToSend.Length) return -1;
|
||||
|
||||
// Mock send - return the requested length
|
||||
return lengthToSend;
|
||||
}
|
||||
|
||||
/// <summary>Receives data from the server</summary>
|
||||
/// <param name="buffer">Buffer to receive data into</param>
|
||||
/// <param name="bufferIndex">Starting index in the buffer</param>
|
||||
/// <param name="lengthToReceive">Maximum number of bytes to receive</param>
|
||||
/// <returns>Number of bytes received, or -1 on error</returns>
|
||||
public int ReceiveData(byte[] buffer, int bufferIndex, int lengthToReceive)
|
||||
{
|
||||
if (_disposed || buffer == null || bufferIndex < 0 || lengthToReceive <= 0) return -1;
|
||||
if (ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) return -1;
|
||||
if (bufferIndex + lengthToReceive > buffer.Length) return -1;
|
||||
|
||||
// Mock receive - simulate no data available for now
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Receives data from the server as a string</summary>
|
||||
/// <param name="numberOfBytesToReceive">Maximum number of bytes to receive</param>
|
||||
/// <returns>Received data as string, or empty string on error</returns>
|
||||
public string ReceiveData(int numberOfBytesToReceive)
|
||||
{
|
||||
if (_disposed || numberOfBytesToReceive <= 0) return string.Empty;
|
||||
if (ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) return string.Empty;
|
||||
|
||||
// Mock receive - return empty string (no data available)
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Sends data to the connected server asynchronously</summary>
|
||||
/// <param name="dataToSend">Data to send as byte array</param>
|
||||
/// <param name="lengthToSend">Number of bytes to send</param>
|
||||
/// <returns>Number of bytes sent, or -1 on error</returns>
|
||||
public int SendDataAsync(byte[] dataToSend, int lengthToSend)
|
||||
{
|
||||
return SendData(dataToSend, lengthToSend);
|
||||
}
|
||||
|
||||
/// <summary>Sends data to the connected server asynchronously with callback</summary>
|
||||
/// <param name="dataToSend">Data to send as byte array</param>
|
||||
/// <param name="lengthToSend">Number of bytes to send</param>
|
||||
/// <param name="callback">Callback to invoke when send completes</param>
|
||||
/// <returns>Number of bytes sent, or -1 on error</returns>
|
||||
public int SendDataAsync(byte[] dataToSend, int lengthToSend, TCPClientSendCallback callback)
|
||||
{
|
||||
var result = SendData(dataToSend, lengthToSend);
|
||||
callback?.Invoke(this, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Receives data from the server asynchronously</summary>
|
||||
/// <returns>Number of bytes received, or -1 on error</returns>
|
||||
public int ReceiveDataAsync()
|
||||
{
|
||||
if (_disposed) return -1;
|
||||
if (ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) return -1;
|
||||
|
||||
// Mock receive - simulate no data available
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Receives data from the server asynchronously with callback</summary>
|
||||
/// <param name="callback">Callback to invoke when data is received</param>
|
||||
/// <returns>Number of bytes received, or -1 on error</returns>
|
||||
public int ReceiveDataAsync(TCPClientReceiveCallback callback)
|
||||
{
|
||||
var result = ReceiveDataAsync();
|
||||
callback?.Invoke(this, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Simulates receiving data (for testing purposes)</summary>
|
||||
/// <param name="data">Data to simulate receiving</param>
|
||||
public void SimulateDataReceived(string data)
|
||||
{
|
||||
if (_disposed || string.IsNullOrEmpty(data)) return;
|
||||
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(data);
|
||||
var bytesToCopy = Math.Min(bytes.Length, _receiveBuffer.Length);
|
||||
Array.Copy(bytes, _receiveBuffer, bytesToCopy);
|
||||
IncomingDataBufferSize = bytesToCopy;
|
||||
|
||||
DataReceived?.Invoke(this, bytesToCopy);
|
||||
}
|
||||
|
||||
/// <summary>Simulates a socket status change (for testing purposes)</summary>
|
||||
/// <param name="newStatus">New socket status</param>
|
||||
public void SimulateStatusChange(SocketStatus newStatus)
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
||||
ClientStatus = newStatus;
|
||||
SocketStatusChange?.Invoke(this, newStatus);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Implementation
|
||||
|
||||
/// <summary>Disposes the TCP client and releases resources</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>Protected dispose method</summary>
|
||||
/// <param name="disposing">True if disposing managed resources</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
// Disconnect if still connected
|
||||
if (ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
DisconnectFromServer();
|
||||
}
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
552
src/CrestronMock/TCPServer.cs
Normal file
552
src/CrestronMock/TCPServer.cs
Normal file
@@ -0,0 +1,552 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronSockets
|
||||
{
|
||||
/// <summary>Mock TCPServer class for server-side TCP operations</summary>
|
||||
public class TCPServer : IDisposable
|
||||
{
|
||||
private TcpListener? _listener;
|
||||
private readonly List<TCPClientConnection> _clients = new List<TCPClientConnection>();
|
||||
private bool _listening;
|
||||
private readonly object _lockObject = new object();
|
||||
private int _bufferSize = 4096;
|
||||
private CancellationTokenSource? _cancellationTokenSource;
|
||||
|
||||
/// <summary>Event fired when waiting for connections</summary>
|
||||
public event TCPServerWaitingForConnectionsEventHandler? WaitingForConnections;
|
||||
|
||||
/// <summary>Event fired when a client connects</summary>
|
||||
public event TCPServerClientConnectEventHandler? ClientConnected;
|
||||
|
||||
/// <summary>Event fired when a client disconnects</summary>
|
||||
public event TCPServerClientDisconnectEventHandler? ClientDisconnected;
|
||||
|
||||
/// <summary>Event fired when data is received from a client</summary>
|
||||
public event TCPServerReceiveDataEventHandler? ReceivedData;
|
||||
|
||||
/// <summary>Event fired when socket status changes</summary>
|
||||
public event TCPServerWaitingForConnectionsEventHandler? SocketStatusChange;
|
||||
|
||||
/// <summary>Gets the server state</summary>
|
||||
public ServerState State { get; private set; } = ServerState.SERVER_NOT_LISTENING;
|
||||
|
||||
/// <summary>Gets or sets the port number</summary>
|
||||
public int PortNumber { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the socket send or receive timeout in milliseconds</summary>
|
||||
public int SocketSendOrReceiveTimeOutInMs { get; set; } = 30000;
|
||||
|
||||
/// <summary>Gets the server socket status based on current state</summary>
|
||||
public SocketStatus ServerSocketStatus => State == ServerState.SERVER_LISTENING ? SocketStatus.SOCKET_STATUS_CONNECTED : SocketStatus.SOCKET_STATUS_NOT_CONNECTED; /// <summary>Gets the maximum number of clients</summary>
|
||||
public int MaxNumberOfClientSupported { get; private set; }
|
||||
|
||||
/// <summary>Gets the number of connected clients</summary>
|
||||
public int NumberOfClientsConnected
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _clients.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Creates a TCP server with IP address binding</summary>
|
||||
/// <param name="ipAddress">IP address to bind to</param>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="bufferSize">Buffer size for incoming data</param>
|
||||
/// <param name="ethernetAdapterToBindTo">Ethernet adapter to bind to</param>
|
||||
/// <param name="maxNumberOfClientSupported">Maximum number of clients</param>
|
||||
public TCPServer(string ipAddress, int portNumber, int bufferSize, EthernetAdapterType ethernetAdapterToBindTo, int maxNumberOfClientSupported)
|
||||
{
|
||||
PortNumber = portNumber;
|
||||
MaxNumberOfClientSupported = maxNumberOfClientSupported;
|
||||
_bufferSize = bufferSize;
|
||||
}
|
||||
|
||||
/// <summary>Creates a TCP server</summary>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="bufferSize">Buffer size for incoming data</param>
|
||||
/// <param name="maxNumberOfClientSupported">Maximum number of clients</param>
|
||||
public TCPServer(int portNumber, int bufferSize, int maxNumberOfClientSupported)
|
||||
{
|
||||
PortNumber = portNumber;
|
||||
MaxNumberOfClientSupported = maxNumberOfClientSupported;
|
||||
_bufferSize = bufferSize;
|
||||
}
|
||||
|
||||
/// <summary>Creates a TCP server with just port and max clients</summary>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="maxNumberOfClientSupported">Maximum number of clients</param>
|
||||
public TCPServer(int portNumber, int maxNumberOfClientSupported)
|
||||
{
|
||||
PortNumber = portNumber;
|
||||
MaxNumberOfClientSupported = maxNumberOfClientSupported;
|
||||
_bufferSize = 4096; // Default buffer size
|
||||
}
|
||||
|
||||
/// <summary>Starts listening for client connections</summary>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes WaitForConnectionAsync()
|
||||
{
|
||||
if (_listening)
|
||||
return SocketErrorCodes.SOCKET_OPERATION_PENDING;
|
||||
|
||||
try
|
||||
{
|
||||
_listener = new TcpListener(IPAddress.Any, PortNumber);
|
||||
_listener.Start();
|
||||
_listening = true;
|
||||
State = ServerState.SERVER_LISTENING;
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
// Start accepting clients in background
|
||||
_ = Task.Run(() => AcceptClientsAsync());
|
||||
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
State = ServerState.SERVER_NOT_LISTENING;
|
||||
return SocketErrorCodes.SOCKET_CONNECTION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Starts listening for connections asynchronously with callback</summary>
|
||||
/// <param name="ipAddress">IP address to listen on</param>
|
||||
/// <param name="callback">Callback for connection events</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes WaitForConnectionAsync(string ipAddress, TCPServerWaitingForConnectionsEventHandler callback)
|
||||
{
|
||||
SocketStatusChange += callback;
|
||||
return WaitForConnectionAsync();
|
||||
}
|
||||
|
||||
/// <summary>Stops listening for connections</summary>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes Stop()
|
||||
{
|
||||
if (!_listening)
|
||||
return SocketErrorCodes.SOCKET_NOT_CONNECTED;
|
||||
|
||||
try
|
||||
{
|
||||
_listening = false;
|
||||
_listener?.Stop();
|
||||
State = ServerState.SERVER_NOT_LISTENING;
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
foreach (var client in _clients)
|
||||
{
|
||||
client.Disconnect();
|
||||
}
|
||||
_clients.Clear();
|
||||
}
|
||||
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return SocketErrorCodes.SOCKET_CONNECTION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends data to a specific client</summary>
|
||||
/// <param name="data">Data to send</param>
|
||||
/// <param name="dataLength">Length of data</param>
|
||||
/// <param name="clientIndex">Index of client to send to</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes SendData(byte[] data, int dataLength, uint clientIndex)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (clientIndex >= _clients.Count)
|
||||
return SocketErrorCodes.SOCKET_INVALID_CLIENT_INDEX;
|
||||
|
||||
return _clients[(int)clientIndex].SendData(data, dataLength);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends data to all connected clients</summary>
|
||||
/// <param name="data">Data to send</param>
|
||||
/// <param name="dataLength">Length of data</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes SendDataToAll(byte[] data, int dataLength)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
var result = SocketErrorCodes.SOCKET_OK;
|
||||
foreach (var client in _clients)
|
||||
{
|
||||
var sendResult = client.SendData(data, dataLength);
|
||||
if (sendResult != SocketErrorCodes.SOCKET_OK)
|
||||
result = sendResult;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Disconnects a specific client</summary>
|
||||
/// <param name="clientIndex">Index of client to disconnect</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes Disconnect(uint clientIndex)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (clientIndex >= _clients.Count)
|
||||
return SocketErrorCodes.SOCKET_INVALID_CLIENT_INDEX;
|
||||
|
||||
var client = _clients[(int)clientIndex];
|
||||
client.Disconnect();
|
||||
_clients.RemoveAt((int)clientIndex);
|
||||
|
||||
ClientDisconnected?.Invoke(this, new TCPServerClientDisconnectEventArgs((uint)clientIndex));
|
||||
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets the IP address of a connected client</summary>
|
||||
/// <param name="clientIndex">Index of client</param>
|
||||
/// <returns>IP address as string</returns>
|
||||
public string GetAddressServerAcceptedConnectionFromForSpecificClient(uint clientIndex)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (clientIndex >= _clients.Count)
|
||||
return string.Empty;
|
||||
|
||||
return _clients[(int)clientIndex].ClientIPAddress;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets the socket status for a specific client</summary>
|
||||
/// <param name="clientIndex">Index of client</param>
|
||||
/// <returns>Socket status</returns>
|
||||
public SocketStatus GetServerSocketStatusForSpecificClient(uint clientIndex)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (clientIndex >= _clients.Count)
|
||||
return SocketStatus.SOCKET_STATUS_NOT_CONNECTED;
|
||||
|
||||
return _clients[(int)clientIndex].IsConnected ?
|
||||
SocketStatus.SOCKET_STATUS_CONNECTED :
|
||||
SocketStatus.SOCKET_STATUS_NOT_CONNECTED;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets the port number the server accepted connection from for a specific client</summary>
|
||||
/// <param name="clientIndex">Index of client</param>
|
||||
/// <returns>Port number</returns>
|
||||
public int GetPortNumberServerAcceptedConnectionFromForSpecificClient(uint clientIndex)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (clientIndex >= _clients.Count)
|
||||
return 0;
|
||||
|
||||
return _clients[(int)clientIndex].ClientPort;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets the local address the server accepted connection from for a specific client</summary>
|
||||
/// <param name="clientIndex">Index of client</param>
|
||||
/// <returns>Local address</returns>
|
||||
public string GetLocalAddressServerAcceptedConnectionFromForSpecificClient(uint clientIndex)
|
||||
{
|
||||
return "127.0.0.1"; // Mock local address
|
||||
}
|
||||
|
||||
/// <summary>Gets the incoming data buffer for a specific client</summary>
|
||||
/// <param name="clientIndex">Index of client</param>
|
||||
/// <returns>Incoming data buffer</returns>
|
||||
public byte[] GetIncomingDataBufferForSpecificClient(uint clientIndex)
|
||||
{
|
||||
return new byte[0]; // Mock empty buffer
|
||||
}
|
||||
|
||||
/// <summary>Sends data to a specific client asynchronously</summary>
|
||||
/// <param name="data">Data to send</param>
|
||||
/// <param name="dataLength">Length of data to send</param>
|
||||
/// <param name="clientIndex">Index of client</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes SendDataAsync(byte[] data, int dataLength, uint clientIndex)
|
||||
{
|
||||
return SendData(data, dataLength, clientIndex);
|
||||
}
|
||||
|
||||
/// <summary>Receives data from a specific client asynchronously</summary>
|
||||
/// <param name="clientIndex">Index of client</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes ReceiveDataAsync(uint clientIndex)
|
||||
{
|
||||
// Mock implementation - no data to receive
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
|
||||
private async Task AcceptClientsAsync()
|
||||
{
|
||||
while (_listening && _listener != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tcpClient = await _listener.AcceptTcpClientAsync();
|
||||
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (_clients.Count >= MaxNumberOfClientSupported)
|
||||
{
|
||||
tcpClient.Close();
|
||||
continue;
|
||||
}
|
||||
|
||||
var clientConnection = new TCPClientConnection(tcpClient, (uint)_clients.Count);
|
||||
clientConnection.DataReceived += OnClientDataReceived;
|
||||
clientConnection.Disconnected += OnClientDisconnected;
|
||||
_clients.Add(clientConnection);
|
||||
|
||||
ClientConnected?.Invoke(this, new TCPServerClientConnectEventArgs((uint)(_clients.Count - 1)));
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// Server was stopped
|
||||
break;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Handle other exceptions
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnClientDataReceived(object? sender, TCPClientDataEventArgs e)
|
||||
{
|
||||
if (sender is TCPClientConnection client)
|
||||
{
|
||||
var args = new TCPServerReceiveDataEventArgs(e.Data, e.DataLength, client.ClientIndex);
|
||||
ReceivedData?.Invoke(this, args);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnClientDisconnected(object? sender, EventArgs e)
|
||||
{
|
||||
if (sender is TCPClientConnection client)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
var index = _clients.IndexOf(client);
|
||||
if (index >= 0)
|
||||
{
|
||||
_clients.RemoveAt(index);
|
||||
ClientDisconnected?.Invoke(this, new TCPServerClientDisconnectEventArgs(client.ClientIndex));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Disposes the TCPServer</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_listener?.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock SecureTCPServer class for secure server-side TCP operations</summary>
|
||||
public class SecureTCPServer : TCPServer
|
||||
{
|
||||
/// <summary>Initializes a new instance of SecureTCPServer</summary>
|
||||
/// <param name="ipAddress">IP address to bind to</param>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="bufferSize">Buffer size for data reception</param>
|
||||
/// <param name="ethernetAdapterToBindTo">Ethernet adapter to bind to</param>
|
||||
/// <param name="maxNumberOfClientSupported">Maximum number of clients</param>
|
||||
public SecureTCPServer(string ipAddress, int portNumber, int bufferSize, EthernetAdapterType ethernetAdapterToBindTo, int maxNumberOfClientSupported)
|
||||
: base(ipAddress, portNumber, bufferSize, ethernetAdapterToBindTo, maxNumberOfClientSupported)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of SecureTCPServer</summary>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="bufferSize">Buffer size for data reception</param>
|
||||
/// <param name="maxNumberOfClientSupported">Maximum number of clients</param>
|
||||
public SecureTCPServer(int portNumber, int bufferSize, int maxNumberOfClientSupported)
|
||||
: base(portNumber, bufferSize, maxNumberOfClientSupported)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of SecureTCPServer</summary>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="maxNumberOfClientSupported">Maximum number of clients</param>
|
||||
public SecureTCPServer(int portNumber, int maxNumberOfClientSupported)
|
||||
: base(portNumber, 4096, maxNumberOfClientSupported) // Default buffer size
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Gets or sets the handshake timeout in seconds</summary>
|
||||
public int HandshakeTimeout { get; set; } = 30;
|
||||
|
||||
/// <summary>Event raised when socket status changes with client details</summary>
|
||||
public event SecureTCPServerSocketStatusEventHandler? SocketStatusChangeWithClientDetails;
|
||||
}
|
||||
|
||||
/// <summary>Internal class representing a client connection</summary>
|
||||
internal class TCPClientConnection
|
||||
{
|
||||
private readonly TcpClient _tcpClient;
|
||||
private readonly NetworkStream _stream;
|
||||
private readonly byte[] _buffer = new byte[4096];
|
||||
private bool _connected = true;
|
||||
|
||||
public uint ClientIndex { get; }
|
||||
public string ClientIPAddress { get; }
|
||||
public bool IsConnected => _connected;
|
||||
public int ClientPort { get; }
|
||||
|
||||
public event EventHandler<TCPClientDataEventArgs>? DataReceived;
|
||||
public event EventHandler? Disconnected;
|
||||
|
||||
public TCPClientConnection(TcpClient tcpClient, uint clientIndex)
|
||||
{
|
||||
_tcpClient = tcpClient;
|
||||
ClientIndex = clientIndex;
|
||||
_stream = tcpClient.GetStream();
|
||||
|
||||
var endpoint = tcpClient.Client.RemoteEndPoint as IPEndPoint;
|
||||
ClientIPAddress = endpoint?.Address.ToString() ?? "Unknown";
|
||||
ClientPort = endpoint?.Port ?? 0;
|
||||
|
||||
_ = Task.Run(ReceiveDataAsync);
|
||||
}
|
||||
|
||||
public SocketErrorCodes SendData(byte[] data, int dataLength)
|
||||
{
|
||||
if (!_connected)
|
||||
return SocketErrorCodes.SOCKET_NOT_CONNECTED;
|
||||
|
||||
try
|
||||
{
|
||||
_stream.Write(data, 0, dataLength);
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Disconnect();
|
||||
return SocketErrorCodes.SOCKET_CONNECTION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
public void Disconnect()
|
||||
{
|
||||
if (!_connected)
|
||||
return;
|
||||
|
||||
_connected = false;
|
||||
_stream?.Close();
|
||||
_tcpClient?.Close();
|
||||
Disconnected?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
private async Task ReceiveDataAsync()
|
||||
{
|
||||
while (_connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytesRead = await _stream.ReadAsync(_buffer, 0, _buffer.Length);
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
Disconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
var data = new byte[bytesRead];
|
||||
Array.Copy(_buffer, data, bytesRead);
|
||||
DataReceived?.Invoke(this, new TCPClientDataEventArgs(data, bytesRead));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Disconnect();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Event args for TCP client data</summary>
|
||||
internal class TCPClientDataEventArgs : EventArgs
|
||||
{
|
||||
public byte[] Data { get; }
|
||||
public int DataLength { get; }
|
||||
|
||||
public TCPClientDataEventArgs(byte[] data, int dataLength)
|
||||
{
|
||||
Data = data;
|
||||
DataLength = dataLength;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Server state enumeration</summary>
|
||||
public enum SocketServerState
|
||||
{
|
||||
/// <summary>Server is not listening</summary>
|
||||
SERVER_NOT_LISTENING = 0,
|
||||
/// <summary>Server is listening for connections</summary>
|
||||
SERVER_LISTENING = 1,
|
||||
/// <summary>Server is connected</summary>
|
||||
SERVER_CONNECTED = 2
|
||||
}
|
||||
|
||||
// Event handler delegates
|
||||
public delegate void TCPServerWaitingForConnectionsEventHandler(TCPServer server, TCPServerWaitingForConnectionsEventArgs args);
|
||||
public delegate void TCPServerClientConnectEventHandler(TCPServer server, TCPServerClientConnectEventArgs args);
|
||||
public delegate void TCPServerClientDisconnectEventHandler(TCPServer server, TCPServerClientDisconnectEventArgs args);
|
||||
public delegate void TCPServerReceiveDataEventHandler(TCPServer server, TCPServerReceiveDataEventArgs args);
|
||||
public delegate void SecureTCPServerSocketStatusChangeEventHandler(SecureTCPServer server, TCPServerWaitingForConnectionsEventArgs args);
|
||||
/// <summary>Delegate for secure TCP server socket status changes with client details</summary>
|
||||
public delegate void SecureTCPServerSocketStatusEventHandler(SecureTCPServer server, uint clientIndex, SocketStatus serverSocketStatus);
|
||||
|
||||
// Event argument classes
|
||||
public class TCPServerWaitingForConnectionsEventArgs : EventArgs
|
||||
{
|
||||
public int ErrorCode { get; }
|
||||
public TCPServerWaitingForConnectionsEventArgs(int errorCode) { ErrorCode = errorCode; }
|
||||
}
|
||||
|
||||
public class TCPServerClientConnectEventArgs : EventArgs
|
||||
{
|
||||
public uint ClientIndex { get; }
|
||||
public TCPServerClientConnectEventArgs(uint clientIndex) { ClientIndex = clientIndex; }
|
||||
}
|
||||
|
||||
public class TCPServerClientDisconnectEventArgs : EventArgs
|
||||
{
|
||||
public uint ClientIndex { get; }
|
||||
public TCPServerClientDisconnectEventArgs(uint clientIndex) { ClientIndex = clientIndex; }
|
||||
}
|
||||
|
||||
public class TCPServerReceiveDataEventArgs : EventArgs
|
||||
{
|
||||
public byte[] Data { get; }
|
||||
public int DataLength { get; }
|
||||
public uint ClientIndex { get; }
|
||||
|
||||
public TCPServerReceiveDataEventArgs(byte[] data, int dataLength, uint clientIndex)
|
||||
{
|
||||
Data = data;
|
||||
DataLength = dataLength;
|
||||
ClientIndex = clientIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
270
src/CrestronMock/UDPServer.cs
Normal file
270
src/CrestronMock/UDPServer.cs
Normal file
@@ -0,0 +1,270 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Crestron.SimplSharp.CrestronSockets
|
||||
{
|
||||
/// <summary>Mock UDPServer class for UDP communication</summary>
|
||||
public class UDPServer : IDisposable
|
||||
{
|
||||
private UdpClient? _udpClient;
|
||||
private bool _listening;
|
||||
private readonly object _lockObject = new object();
|
||||
private CancellationTokenSource? _cancellationTokenSource;
|
||||
|
||||
/// <summary>Event fired when data is received</summary>
|
||||
public event UDPServerReceiveDataEventHandler? ReceivedData;
|
||||
|
||||
/// <summary>Gets the server state</summary>
|
||||
public SocketServerState State { get; private set; } = SocketServerState.SERVER_NOT_LISTENING;
|
||||
|
||||
/// <summary>Gets the server status (alias for State)</summary>
|
||||
public SocketServerState ServerStatus => State;
|
||||
|
||||
/// <summary>Gets the client status as SocketStatus</summary>
|
||||
public SocketStatus ClientStatus => State == SocketServerState.SERVER_LISTENING ? SocketStatus.SOCKET_STATUS_CONNECTED : SocketStatus.SOCKET_STATUS_NOT_CONNECTED;
|
||||
|
||||
/// <summary>Gets or sets the port number</summary>
|
||||
public int PortNumber { get; set; }
|
||||
|
||||
/// <summary>Gets the buffer size</summary>
|
||||
public int BufferSize { get; private set; }
|
||||
|
||||
/// <summary>Gets the IP address of the last message received from</summary>
|
||||
public string IPAddressLastMessageReceivedFrom { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets the IP port of the last message received from</summary>
|
||||
public int IPPortLastMessageReceivedFrom { get; private set; }
|
||||
|
||||
/// <summary>Gets the incoming data buffer</summary>
|
||||
public byte[] IncomingDataBuffer { get; private set; } = new byte[0];
|
||||
|
||||
/// <summary>Initializes a new instance of UDPServer</summary>
|
||||
public UDPServer()
|
||||
{
|
||||
PortNumber = 0;
|
||||
BufferSize = 1024;
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of UDPServer</summary>
|
||||
/// <param name="ipAddress">IP address to bind to</param>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="bufferSize">Buffer size for data reception</param>
|
||||
/// <param name="ethernetAdapterToBindTo">Ethernet adapter to bind to</param>
|
||||
public UDPServer(string ipAddress, int portNumber, int bufferSize, EthernetAdapterType ethernetAdapterToBindTo)
|
||||
{
|
||||
PortNumber = portNumber;
|
||||
BufferSize = bufferSize;
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of UDPServer</summary>
|
||||
/// <param name="portNumber">Port number to listen on</param>
|
||||
/// <param name="bufferSize">Buffer size for data reception</param>
|
||||
public UDPServer(int portNumber, int bufferSize)
|
||||
{
|
||||
PortNumber = portNumber;
|
||||
BufferSize = bufferSize;
|
||||
}
|
||||
|
||||
/// <summary>Starts listening for UDP packets</summary>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes EnableUDPServer()
|
||||
{
|
||||
if (_listening)
|
||||
return SocketErrorCodes.SOCKET_OPERATION_PENDING;
|
||||
|
||||
try
|
||||
{
|
||||
_udpClient = new UdpClient(PortNumber);
|
||||
_listening = true;
|
||||
State = SocketServerState.SERVER_LISTENING;
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
_ = Task.Run(() => ReceiveDataAsync(_cancellationTokenSource.Token));
|
||||
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
State = SocketServerState.SERVER_NOT_LISTENING;
|
||||
return SocketErrorCodes.SOCKET_CONNECTION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Starts listening for UDP packets on specified hostname and port</summary>
|
||||
/// <param name="hostname">Hostname to bind to</param>
|
||||
/// <param name="port">Port number to listen on</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes EnableUDPServer(string hostname, int port)
|
||||
{
|
||||
PortNumber = port;
|
||||
return EnableUDPServer();
|
||||
}
|
||||
|
||||
/// <summary>Stops listening for UDP packets</summary>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes DisableUDPServer()
|
||||
{
|
||||
if (!_listening)
|
||||
return SocketErrorCodes.SOCKET_NOT_CONNECTED;
|
||||
|
||||
try
|
||||
{
|
||||
_listening = false;
|
||||
_cancellationTokenSource?.Cancel();
|
||||
_udpClient?.Close();
|
||||
State = SocketServerState.SERVER_NOT_LISTENING;
|
||||
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return SocketErrorCodes.SOCKET_CONNECTION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends data to a specific endpoint</summary>
|
||||
/// <param name="data">Data to send</param>
|
||||
/// <param name="dataLength">Length of data</param>
|
||||
/// <param name="ipAddress">Target IP address</param>
|
||||
/// <param name="portNumber">Target port number</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes SendData(byte[] data, int dataLength, string ipAddress, int portNumber)
|
||||
{
|
||||
if (!_listening || _udpClient == null)
|
||||
return SocketErrorCodes.SOCKET_NOT_CONNECTED;
|
||||
|
||||
try
|
||||
{
|
||||
var endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), portNumber);
|
||||
_udpClient.Send(data, dataLength, endpoint);
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return SocketErrorCodes.SOCKET_CONNECTION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends data to the last received endpoint</summary>
|
||||
/// <param name="data">Data to send</param>
|
||||
/// <param name="dataLength">Length of data</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes SendData(byte[] data, int dataLength)
|
||||
{
|
||||
return SendData(data, dataLength, IPAddressLastMessageReceivedFrom, IPPortLastMessageReceivedFrom);
|
||||
}
|
||||
|
||||
/// <summary>Receives data asynchronously</summary>
|
||||
/// <param name="callback">Callback to invoke when data is received</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes ReceiveDataAsync(UDPServerReceiveDataEventHandler callback)
|
||||
{
|
||||
ReceivedData += callback;
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
|
||||
/// <summary>Receives data asynchronously with simple callback</summary>
|
||||
/// <param name="callback">Simple callback to invoke when data is received</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes ReceiveDataAsync(UDPServerReceiveDataSimpleEventHandler callback)
|
||||
{
|
||||
// Convert simple callback to full event handler and subscribe
|
||||
ReceivedData += (server, args) => callback(server, args.DataLength);
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
|
||||
/// <summary>Sends data to a specific endpoint</summary>
|
||||
/// <param name="data">Data to send</param>
|
||||
/// <param name="dataLength">Length of data</param>
|
||||
/// <param name="endpoint">Target endpoint</param>
|
||||
/// <returns>SocketErrorCodes indicating success or failure</returns>
|
||||
public SocketErrorCodes SendData(byte[] data, int dataLength, IPEndPoint endpoint)
|
||||
{
|
||||
if (!_listening || _udpClient == null)
|
||||
return SocketErrorCodes.SOCKET_NOT_CONNECTED;
|
||||
|
||||
try
|
||||
{
|
||||
_udpClient.Send(data, dataLength, endpoint);
|
||||
return SocketErrorCodes.SOCKET_OK;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return SocketErrorCodes.SOCKET_CONNECTION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceiveDataAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (_listening && _udpClient != null && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _udpClient.ReceiveAsync();
|
||||
|
||||
var args = new UDPServerReceiveDataEventArgs(
|
||||
result.Buffer,
|
||||
result.Buffer.Length,
|
||||
result.RemoteEndPoint.Address.ToString(),
|
||||
result.RemoteEndPoint.Port);
|
||||
|
||||
ReceivedData?.Invoke(this, args);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// UDP client was disposed
|
||||
break;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Handle other exceptions
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Disposes the UDPServer</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
DisableUDPServer();
|
||||
_cancellationTokenSource?.Dispose();
|
||||
_udpClient?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Event handler delegates for UDP
|
||||
public delegate void UDPServerReceiveDataEventHandler(UDPServer server, UDPServerReceiveDataEventArgs args);
|
||||
public delegate void UDPServerReceiveDataSimpleEventHandler(UDPServer server, int numBytes);
|
||||
|
||||
// Event argument classes for UDP
|
||||
public class UDPServerReceiveDataEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>Gets the received data</summary>
|
||||
public byte[] Data { get; }
|
||||
|
||||
/// <summary>Gets the length of received data</summary>
|
||||
public int DataLength { get; }
|
||||
|
||||
/// <summary>Gets the sender's IP address</summary>
|
||||
public string IPAddress { get; }
|
||||
|
||||
/// <summary>Gets the sender's port number</summary>
|
||||
public int Port { get; }
|
||||
|
||||
/// <summary>Initializes a new instance of UDPServerReceiveDataEventArgs</summary>
|
||||
/// <param name="data">Received data</param>
|
||||
/// <param name="dataLength">Length of received data</param>
|
||||
/// <param name="ipAddress">Sender's IP address</param>
|
||||
/// <param name="port">Sender's port number</param>
|
||||
public UDPServerReceiveDataEventArgs(byte[] data, int dataLength, string ipAddress, int port)
|
||||
{
|
||||
Data = data;
|
||||
DataLength = dataLength;
|
||||
IPAddress = ipAddress;
|
||||
Port = port;
|
||||
}
|
||||
}
|
||||
}
|
||||
45
src/CrestronMock/UrlParserTypes.cs
Normal file
45
src/CrestronMock/UrlParserTypes.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
|
||||
namespace Crestron.SimplSharp.Net.Http
|
||||
{
|
||||
/// <summary>Mock UrlParser for HTTP</summary>
|
||||
public static class UrlParser
|
||||
{
|
||||
/// <summary>Parse a URL string</summary>
|
||||
/// <param name="url">URL to parse</param>
|
||||
/// <returns>Parsed URL components</returns>
|
||||
public static UrlParserResult Parse(string url)
|
||||
{
|
||||
return new UrlParserResult { Url = url };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>URL parser result</summary>
|
||||
public class UrlParserResult
|
||||
{
|
||||
/// <summary>Original URL</summary>
|
||||
public string Url { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
namespace Crestron.SimplSharp.Net.Https
|
||||
{
|
||||
/// <summary>Mock UrlParser for HTTPS - different from HTTP version</summary>
|
||||
public static class UrlParser
|
||||
{
|
||||
/// <summary>Parse a URL string</summary>
|
||||
/// <param name="url">URL to parse</param>
|
||||
/// <returns>Parsed URL components</returns>
|
||||
public static UrlParserResult Parse(string url)
|
||||
{
|
||||
return new UrlParserResult { Url = url };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>HTTPS URL parser result</summary>
|
||||
public class UrlParserResult
|
||||
{
|
||||
/// <summary>Original URL</summary>
|
||||
public string Url { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
295
src/CrestronMock/WebAndNetworking.cs
Normal file
295
src/CrestronMock/WebAndNetworking.cs
Normal file
@@ -0,0 +1,295 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Crestron.SimplSharp.Net.Http
|
||||
{
|
||||
/// <summary>HTTP request types</summary>
|
||||
public enum RequestType
|
||||
{
|
||||
/// <summary>GET request</summary>
|
||||
Get = 0,
|
||||
/// <summary>POST request</summary>
|
||||
Post = 1,
|
||||
/// <summary>PUT request</summary>
|
||||
Put = 2,
|
||||
/// <summary>DELETE request</summary>
|
||||
Delete = 3,
|
||||
/// <summary>HEAD request</summary>
|
||||
Head = 4,
|
||||
/// <summary>OPTIONS request</summary>
|
||||
Options = 5,
|
||||
/// <summary>PATCH request</summary>
|
||||
Patch = 6
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTP client</summary>
|
||||
public class HttpClient
|
||||
{
|
||||
/// <summary>Gets or sets the keep-alive setting</summary>
|
||||
public bool KeepAlive { get; set; } = false;
|
||||
|
||||
/// <summary>Gets or sets the port number</summary>
|
||||
public int Port { get; set; } = 80;
|
||||
|
||||
/// <summary>Dispatch HTTP request</summary>
|
||||
/// <param name="request">HTTP request</param>
|
||||
/// <param name="callback">Callback for response</param>
|
||||
public void Dispatch(HttpClientRequest request, Action<HttpClientResponse> callback)
|
||||
{
|
||||
// Mock implementation - invoke callback with empty response
|
||||
var response = new HttpClientResponse();
|
||||
callback?.Invoke(response);
|
||||
}
|
||||
|
||||
/// <summary>Dispatches HTTP request synchronously</summary>
|
||||
/// <param name="request">HTTP request</param>
|
||||
/// <returns>HTTP response</returns>
|
||||
public HttpClientResponse Dispatch(HttpClientRequest request)
|
||||
{
|
||||
// Mock implementation - return empty response
|
||||
return new HttpClientResponse();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTP client request</summary>
|
||||
public class HttpClientRequest
|
||||
{
|
||||
/// <summary>Gets or sets the URL parser</summary>
|
||||
public Crestron.SimplSharp.Net.Http.UrlParserResult Url { get; set; } = new Crestron.SimplSharp.Net.Http.UrlParserResult();
|
||||
|
||||
/// <summary>Gets or sets the HTTP method</summary>
|
||||
public RequestType RequestType { get; set; } = RequestType.Get;
|
||||
|
||||
/// <summary>Gets or sets the content data</summary>
|
||||
public string ContentString { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets the headers collection</summary>
|
||||
public HttpHeaderCollection Header { get; } = new HttpHeaderCollection();
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTP client response</summary>
|
||||
public class HttpClientResponse
|
||||
{
|
||||
/// <summary>Gets the response code</summary>
|
||||
public int Code { get; set; } = 200;
|
||||
|
||||
/// <summary>Gets the response content</summary>
|
||||
public string ContentString { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets the response data as bytes</summary>
|
||||
public byte[] ContentBytes { get; set; } = Array.Empty<byte>();
|
||||
|
||||
/// <summary>Gets the headers collection</summary>
|
||||
public HttpHeaderCollection Header { get; } = new HttpHeaderCollection();
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTP header collection</summary>
|
||||
public class HttpHeaderCollection
|
||||
{
|
||||
private readonly Dictionary<string, string> _headers = new Dictionary<string, string>();
|
||||
|
||||
/// <summary>Gets or sets the content type</summary>
|
||||
public string ContentType
|
||||
{
|
||||
get => _headers.TryGetValue("Content-Type", out var value) ? value : string.Empty;
|
||||
set => _headers["Content-Type"] = value;
|
||||
}
|
||||
|
||||
/// <summary>Sets a header value</summary>
|
||||
/// <param name="name">Header name</param>
|
||||
/// <param name="value">Header value</param>
|
||||
public void SetHeaderValue(string name, string value)
|
||||
{
|
||||
_headers[name] = value;
|
||||
}
|
||||
|
||||
/// <summary>Gets a header value</summary>
|
||||
/// <param name="name">Header name</param>
|
||||
/// <returns>Header value or empty string if not found</returns>
|
||||
public string GetHeaderValue(string name)
|
||||
{
|
||||
return _headers.TryGetValue(name, out var value) ? value : string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
namespace Crestron.SimplSharp.Net.Https
|
||||
{
|
||||
/// <summary>HTTPS request types</summary>
|
||||
public enum RequestType
|
||||
{
|
||||
/// <summary>GET request</summary>
|
||||
Get = 0,
|
||||
/// <summary>POST request</summary>
|
||||
Post = 1,
|
||||
/// <summary>PUT request</summary>
|
||||
Put = 2,
|
||||
/// <summary>DELETE request</summary>
|
||||
Delete = 3,
|
||||
/// <summary>HEAD request</summary>
|
||||
Head = 4,
|
||||
/// <summary>OPTIONS request</summary>
|
||||
Options = 5,
|
||||
/// <summary>PATCH request</summary>
|
||||
Patch = 6
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTPS client</summary>
|
||||
public class HttpsClient
|
||||
{
|
||||
/// <summary>Gets or sets the keep-alive setting</summary>
|
||||
public bool KeepAlive { get; set; } = false;
|
||||
|
||||
/// <summary>Gets or sets the host verification setting</summary>
|
||||
public bool HostVerification { get; set; } = false;
|
||||
|
||||
/// <summary>Gets or sets the peer verification setting</summary>
|
||||
public bool PeerVerification { get; set; } = false;
|
||||
|
||||
/// <summary>Dispatch HTTPS request</summary>
|
||||
/// <param name="request">HTTPS request</param>
|
||||
/// <param name="callback">Callback for response</param>
|
||||
public void Dispatch(HttpsClientRequest request, Action<HttpsClientResponse> callback)
|
||||
{
|
||||
// Mock implementation - invoke callback with empty response
|
||||
var response = new HttpsClientResponse();
|
||||
callback?.Invoke(response);
|
||||
}
|
||||
|
||||
/// <summary>Dispatches HTTPS request synchronously</summary>
|
||||
/// <param name="request">HTTPS request</param>
|
||||
/// <returns>HTTPS response</returns>
|
||||
public HttpsClientResponse Dispatch(HttpsClientRequest request)
|
||||
{
|
||||
// Mock implementation - return empty response
|
||||
return new HttpsClientResponse();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTPS client request</summary>
|
||||
public class HttpsClientRequest
|
||||
{
|
||||
/// <summary>Gets or sets the URL parser</summary>
|
||||
public Crestron.SimplSharp.Net.Https.UrlParserResult Url { get; set; } = new Crestron.SimplSharp.Net.Https.UrlParserResult();
|
||||
|
||||
/// <summary>Gets or sets the HTTP method</summary>
|
||||
public RequestType RequestType { get; set; } = RequestType.Get;
|
||||
|
||||
/// <summary>Gets or sets the content data</summary>
|
||||
public string ContentString { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets the headers collection</summary>
|
||||
public HttpsHeaderCollection Header { get; } = new HttpsHeaderCollection();
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTPS client response</summary>
|
||||
public class HttpsClientResponse
|
||||
{
|
||||
/// <summary>Gets the response code</summary>
|
||||
public int Code { get; set; } = 200;
|
||||
|
||||
/// <summary>Gets the response content</summary>
|
||||
public string ContentString { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets the response data as bytes</summary>
|
||||
public byte[] ContentBytes { get; set; } = Array.Empty<byte>();
|
||||
|
||||
/// <summary>Gets the headers collection</summary>
|
||||
public HttpsHeaderCollection Header { get; } = new HttpsHeaderCollection();
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTPS header collection</summary>
|
||||
public class HttpsHeaderCollection
|
||||
{
|
||||
private readonly Dictionary<string, string> _headers = new Dictionary<string, string>();
|
||||
|
||||
/// <summary>Gets or sets the content type</summary>
|
||||
public string ContentType
|
||||
{
|
||||
get => _headers.TryGetValue("Content-Type", out var value) ? value : string.Empty;
|
||||
set => _headers["Content-Type"] = value;
|
||||
}
|
||||
|
||||
/// <summary>Sets a header value</summary>
|
||||
/// <param name="name">Header name</param>
|
||||
/// <param name="value">Header value</param>
|
||||
public void SetHeaderValue(string name, string value)
|
||||
{
|
||||
_headers[name] = value;
|
||||
}
|
||||
|
||||
/// <summary>Adds a header</summary>
|
||||
/// <param name="header">Header to add</param>
|
||||
public void AddHeader(HttpsHeader header)
|
||||
{
|
||||
_headers[header.Name] = header.Value;
|
||||
}
|
||||
|
||||
/// <summary>Gets a header value</summary>
|
||||
/// <param name="name">Header name</param>
|
||||
/// <returns>Header value or empty string if not found</returns>
|
||||
public string GetHeaderValue(string name)
|
||||
{
|
||||
return _headers.TryGetValue(name, out var value) ? value : string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTPS header</summary>
|
||||
public class HttpsHeader
|
||||
{
|
||||
/// <summary>Gets the header name</summary>
|
||||
public string Name { get; private set; }
|
||||
|
||||
/// <summary>Gets the header value</summary>
|
||||
public string Value { get; private set; }
|
||||
|
||||
/// <summary>Initializes a new instance of HttpsHeader</summary>
|
||||
/// <param name="name">Header name</param>
|
||||
/// <param name="value">Header value</param>
|
||||
public HttpsHeader(string name, string value)
|
||||
{
|
||||
Name = name ?? string.Empty;
|
||||
Value = value ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock HTTP exception</summary>
|
||||
public class HttpException : Exception
|
||||
{
|
||||
/// <summary>Gets the HTTP response</summary>
|
||||
public HttpsClientResponse Response { get; }
|
||||
|
||||
/// <summary>Initializes a new instance of HttpException</summary>
|
||||
public HttpException() : base()
|
||||
{
|
||||
Response = new HttpsClientResponse();
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of HttpException</summary>
|
||||
/// <param name="message">Exception message</param>
|
||||
public HttpException(string message) : base(message)
|
||||
{
|
||||
Response = new HttpsClientResponse();
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of HttpException</summary>
|
||||
/// <param name="message">Exception message</param>
|
||||
/// <param name="innerException">Inner exception</param>
|
||||
public HttpException(string message, Exception innerException) : base(message, innerException)
|
||||
{
|
||||
Response = new HttpsClientResponse();
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance of HttpException</summary>
|
||||
/// <param name="message">Exception message</param>
|
||||
/// <param name="response">HTTP response</param>
|
||||
public HttpException(string message, HttpsClientResponse response) : base(message)
|
||||
{
|
||||
Response = response ?? new HttpsClientResponse();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>2.4.0-local</Version>
|
||||
<Version>3.0.0-local</Version>
|
||||
<InformationalVersion>$(Version)</InformationalVersion>
|
||||
<Authors>PepperDash Technology</Authors>
|
||||
<Company>PepperDash Technology</Company>
|
||||
|
||||
@@ -8,8 +8,8 @@ using Crestron.SimplSharp;
|
||||
using PepperDash.Core;
|
||||
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the string event handler for line events on the gather
|
||||
/// </summary>
|
||||
@@ -30,7 +30,7 @@ namespace PepperDash.Core
|
||||
/// <summary>
|
||||
/// The communication port that this gathers on
|
||||
/// </summary>
|
||||
public ICommunicationReceiver Port { get; private set; }
|
||||
public ICommunicationReceiver Port { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default false. If true, the delimiter will be included in the line output
|
||||
@@ -67,22 +67,22 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="delimiter"></param>
|
||||
public CommunicationGather(ICommunicationReceiver port, string delimiter)
|
||||
:this(port, new string[] { delimiter} )
|
||||
public CommunicationGather(ICommunicationReceiver port, string delimiter)
|
||||
:this(port, new string[] { delimiter} )
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for using an array of string delimiters
|
||||
/// </summary>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="delimiters"></param>
|
||||
public CommunicationGather(ICommunicationReceiver port, string[] delimiters)
|
||||
{
|
||||
Port = port;
|
||||
StringDelimiters = delimiters;
|
||||
port.TextReceived += Port_TextReceivedStringDelimiter;
|
||||
}
|
||||
/// <summary>
|
||||
/// Constructor for using an array of string delimiters
|
||||
/// </summary>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="delimiters"></param>
|
||||
public CommunicationGather(ICommunicationReceiver port, string[] delimiters)
|
||||
{
|
||||
Port = port;
|
||||
StringDelimiters = delimiters;
|
||||
port.TextReceived += Port_TextReceivedStringDelimiter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnects this gather from the Port's TextReceived event. This will not fire LineReceived
|
||||
@@ -136,35 +136,35 @@ namespace PepperDash.Core
|
||||
ReceiveBuffer.Append(args.Text);
|
||||
var str = ReceiveBuffer.ToString();
|
||||
|
||||
// Case: Receiving DEVICE get version\x0d\0x0a+OK "value":"1234"\x0d\x0a
|
||||
// Case: Receiving DEVICE get version\x0d\0x0a+OK "value":"1234"\x0d\x0a
|
||||
|
||||
// RX: DEV
|
||||
// Split: (1) "DEV"
|
||||
// RX: I
|
||||
// Split: (1) "DEVI"
|
||||
// RX: CE get version
|
||||
// Split: (1) "DEVICE get version"
|
||||
// RX: \x0d\x0a+OK "value":"1234"\x0d\x0a
|
||||
// Split: (2) DEVICE get version, +OK "value":"1234"
|
||||
// RX: DEV
|
||||
// Split: (1) "DEV"
|
||||
// RX: I
|
||||
// Split: (1) "DEVI"
|
||||
// RX: CE get version
|
||||
// Split: (1) "DEVICE get version"
|
||||
// RX: \x0d\x0a+OK "value":"1234"\x0d\x0a
|
||||
// Split: (2) DEVICE get version, +OK "value":"1234"
|
||||
|
||||
// Iterate the delimiters and fire an event for any matching delimiter
|
||||
foreach (var delimiter in StringDelimiters)
|
||||
// Iterate the delimiters and fire an event for any matching delimiter
|
||||
foreach (var delimiter in StringDelimiters)
|
||||
{
|
||||
var lines = Regex.Split(str, delimiter);
|
||||
if (lines.Length == 1)
|
||||
continue;
|
||||
|
||||
for (int i = 0; i < lines.Length - 1; i++)
|
||||
{
|
||||
var lines = Regex.Split(str, delimiter);
|
||||
if (lines.Length == 1)
|
||||
continue;
|
||||
|
||||
for (int i = 0; i < lines.Length - 1; i++)
|
||||
{
|
||||
string strToSend = null;
|
||||
if (IncludeDelimiter)
|
||||
strToSend = lines[i] + delimiter;
|
||||
else
|
||||
strToSend = lines[i];
|
||||
handler(this, new GenericCommMethodReceiveTextArgs(strToSend, delimiter));
|
||||
}
|
||||
ReceiveBuffer = new StringBuilder(lines[lines.Length - 1]);
|
||||
string strToSend = null;
|
||||
if (IncludeDelimiter)
|
||||
strToSend = lines[i] + delimiter;
|
||||
else
|
||||
strToSend = lines[i];
|
||||
handler(this, new GenericCommMethodReceiveTextArgs(strToSend, delimiter));
|
||||
}
|
||||
ReceiveBuffer = new StringBuilder(lines[lines.Length - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,5 +175,4 @@ namespace PepperDash.Core
|
||||
{
|
||||
Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,173 +5,172 @@ using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
using PepperDash.Core;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Controls the ability to disable/enable debugging of TX/RX data sent to/from a device with a built in timer to disable
|
||||
/// </summary>
|
||||
public class CommunicationStreamDebugging
|
||||
{
|
||||
/// <summary>
|
||||
/// Controls the ability to disable/enable debugging of TX/RX data sent to/from a device with a built in timer to disable
|
||||
/// Device Key that this instance configures
|
||||
/// </summary>
|
||||
public class CommunicationStreamDebugging
|
||||
public string ParentDeviceKey { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Timer to disable automatically if not manually disabled
|
||||
/// </summary>
|
||||
private CTimer DebugExpiryPeriod;
|
||||
|
||||
/// <summary>
|
||||
/// The current debug setting
|
||||
/// </summary>
|
||||
public eStreamDebuggingSetting DebugSetting { get; private set; }
|
||||
|
||||
private uint _DebugTimeoutInMs;
|
||||
private const uint _DefaultDebugTimeoutMin = 30;
|
||||
|
||||
/// <summary>
|
||||
/// Timeout in Minutes
|
||||
/// </summary>
|
||||
public uint DebugTimeoutMinutes
|
||||
{
|
||||
/// <summary>
|
||||
/// Device Key that this instance configures
|
||||
/// </summary>
|
||||
public string ParentDeviceKey { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Timer to disable automatically if not manually disabled
|
||||
/// </summary>
|
||||
private CTimer DebugExpiryPeriod;
|
||||
|
||||
/// <summary>
|
||||
/// The current debug setting
|
||||
/// </summary>
|
||||
public eStreamDebuggingSetting DebugSetting { get; private set; }
|
||||
|
||||
private uint _DebugTimeoutInMs;
|
||||
private const uint _DefaultDebugTimeoutMin = 30;
|
||||
|
||||
/// <summary>
|
||||
/// Timeout in Minutes
|
||||
/// </summary>
|
||||
public uint DebugTimeoutMinutes
|
||||
get
|
||||
{
|
||||
get
|
||||
{
|
||||
return _DebugTimeoutInMs/60000;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that receive stream debugging is enabled
|
||||
/// </summary>
|
||||
public bool RxStreamDebuggingIsEnabled{ get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that transmit stream debugging is enabled
|
||||
/// </summary>
|
||||
public bool TxStreamDebuggingIsEnabled { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="parentDeviceKey"></param>
|
||||
public CommunicationStreamDebugging(string parentDeviceKey)
|
||||
{
|
||||
ParentDeviceKey = parentDeviceKey;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets the debugging setting and if not setting to off, assumes the default of 30 mintues
|
||||
/// </summary>
|
||||
/// <param name="setting"></param>
|
||||
public void SetDebuggingWithDefaultTimeout(eStreamDebuggingSetting setting)
|
||||
{
|
||||
if (setting == eStreamDebuggingSetting.Off)
|
||||
{
|
||||
DisableDebugging();
|
||||
return;
|
||||
}
|
||||
|
||||
SetDebuggingWithSpecificTimeout(setting, _DefaultDebugTimeoutMin);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the debugging setting for the specified number of minutes
|
||||
/// </summary>
|
||||
/// <param name="setting"></param>
|
||||
/// <param name="minutes"></param>
|
||||
public void SetDebuggingWithSpecificTimeout(eStreamDebuggingSetting setting, uint minutes)
|
||||
{
|
||||
if (setting == eStreamDebuggingSetting.Off)
|
||||
{
|
||||
DisableDebugging();
|
||||
return;
|
||||
}
|
||||
|
||||
_DebugTimeoutInMs = minutes * 60000;
|
||||
|
||||
StopDebugTimer();
|
||||
|
||||
DebugExpiryPeriod = new CTimer((o) => DisableDebugging(), _DebugTimeoutInMs);
|
||||
|
||||
if ((setting & eStreamDebuggingSetting.Rx) == eStreamDebuggingSetting.Rx)
|
||||
RxStreamDebuggingIsEnabled = true;
|
||||
|
||||
if ((setting & eStreamDebuggingSetting.Tx) == eStreamDebuggingSetting.Tx)
|
||||
TxStreamDebuggingIsEnabled = true;
|
||||
|
||||
Debug.SetDeviceDebugSettings(ParentDeviceKey, setting);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disabled debugging
|
||||
/// </summary>
|
||||
private void DisableDebugging()
|
||||
{
|
||||
StopDebugTimer();
|
||||
|
||||
Debug.SetDeviceDebugSettings(ParentDeviceKey, eStreamDebuggingSetting.Off);
|
||||
}
|
||||
|
||||
private void StopDebugTimer()
|
||||
{
|
||||
RxStreamDebuggingIsEnabled = false;
|
||||
TxStreamDebuggingIsEnabled = false;
|
||||
|
||||
if (DebugExpiryPeriod == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DebugExpiryPeriod.Stop();
|
||||
DebugExpiryPeriod.Dispose();
|
||||
DebugExpiryPeriod = null;
|
||||
return _DebugTimeoutInMs/60000;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The available settings for stream debugging
|
||||
/// Indicates that receive stream debugging is enabled
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum eStreamDebuggingSetting
|
||||
public bool RxStreamDebuggingIsEnabled{ get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that transmit stream debugging is enabled
|
||||
/// </summary>
|
||||
public bool TxStreamDebuggingIsEnabled { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="parentDeviceKey"></param>
|
||||
public CommunicationStreamDebugging(string parentDeviceKey)
|
||||
{
|
||||
/// <summary>
|
||||
/// Debug off
|
||||
/// </summary>
|
||||
Off = 0,
|
||||
/// <summary>
|
||||
/// Debug received data
|
||||
/// </summary>
|
||||
Rx = 1,
|
||||
/// <summary>
|
||||
/// Debug transmitted data
|
||||
/// </summary>
|
||||
Tx = 2,
|
||||
/// <summary>
|
||||
/// Debug both received and transmitted data
|
||||
/// </summary>
|
||||
Both = Rx | Tx
|
||||
ParentDeviceKey = parentDeviceKey;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets the debugging setting and if not setting to off, assumes the default of 30 mintues
|
||||
/// </summary>
|
||||
/// <param name="setting"></param>
|
||||
public void SetDebuggingWithDefaultTimeout(eStreamDebuggingSetting setting)
|
||||
{
|
||||
if (setting == eStreamDebuggingSetting.Off)
|
||||
{
|
||||
DisableDebugging();
|
||||
return;
|
||||
}
|
||||
|
||||
SetDebuggingWithSpecificTimeout(setting, _DefaultDebugTimeoutMin);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The available settings for stream debugging response types
|
||||
/// Sets the debugging setting for the specified number of minutes
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum eStreamDebuggingDataTypeSettings
|
||||
/// <param name="setting"></param>
|
||||
/// <param name="minutes"></param>
|
||||
public void SetDebuggingWithSpecificTimeout(eStreamDebuggingSetting setting, uint minutes)
|
||||
{
|
||||
/// <summary>
|
||||
/// Debug data in byte format
|
||||
/// </summary>
|
||||
Bytes = 0,
|
||||
/// <summary>
|
||||
/// Debug data in text format
|
||||
/// </summary>
|
||||
Text = 1,
|
||||
/// <summary>
|
||||
/// Debug data in both byte and text formats
|
||||
/// </summary>
|
||||
Both = Bytes | Text,
|
||||
if (setting == eStreamDebuggingSetting.Off)
|
||||
{
|
||||
DisableDebugging();
|
||||
return;
|
||||
}
|
||||
|
||||
_DebugTimeoutInMs = minutes * 60000;
|
||||
|
||||
StopDebugTimer();
|
||||
|
||||
DebugExpiryPeriod = new CTimer((o) => DisableDebugging(), _DebugTimeoutInMs);
|
||||
|
||||
if ((setting & eStreamDebuggingSetting.Rx) == eStreamDebuggingSetting.Rx)
|
||||
RxStreamDebuggingIsEnabled = true;
|
||||
|
||||
if ((setting & eStreamDebuggingSetting.Tx) == eStreamDebuggingSetting.Tx)
|
||||
TxStreamDebuggingIsEnabled = true;
|
||||
|
||||
Debug.SetDeviceDebugSettings(ParentDeviceKey, setting);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disabled debugging
|
||||
/// </summary>
|
||||
private void DisableDebugging()
|
||||
{
|
||||
StopDebugTimer();
|
||||
|
||||
Debug.SetDeviceDebugSettings(ParentDeviceKey, eStreamDebuggingSetting.Off);
|
||||
}
|
||||
|
||||
private void StopDebugTimer()
|
||||
{
|
||||
RxStreamDebuggingIsEnabled = false;
|
||||
TxStreamDebuggingIsEnabled = false;
|
||||
|
||||
if (DebugExpiryPeriod == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DebugExpiryPeriod.Stop();
|
||||
DebugExpiryPeriod.Dispose();
|
||||
DebugExpiryPeriod = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The available settings for stream debugging
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum eStreamDebuggingSetting
|
||||
{
|
||||
/// <summary>
|
||||
/// Debug off
|
||||
/// </summary>
|
||||
Off = 0,
|
||||
/// <summary>
|
||||
/// Debug received data
|
||||
/// </summary>
|
||||
Rx = 1,
|
||||
/// <summary>
|
||||
/// Debug transmitted data
|
||||
/// </summary>
|
||||
Tx = 2,
|
||||
/// <summary>
|
||||
/// Debug both received and transmitted data
|
||||
/// </summary>
|
||||
Both = Rx | Tx
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The available settings for stream debugging response types
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum eStreamDebuggingDataTypeSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Debug data in byte format
|
||||
/// </summary>
|
||||
Bytes = 0,
|
||||
/// <summary>
|
||||
/// Debug data in text format
|
||||
/// </summary>
|
||||
Text = 1,
|
||||
/// <summary>
|
||||
/// Debug data in both byte and text formats
|
||||
/// </summary>
|
||||
Both = Bytes | Text,
|
||||
}
|
||||
|
||||
@@ -3,91 +3,90 @@ using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Config properties that indicate how to communicate with a device for control
|
||||
/// </summary>
|
||||
public class ControlPropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// Config properties that indicate how to communicate with a device for control
|
||||
/// The method of control
|
||||
/// </summary>
|
||||
public class ControlPropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// The method of control
|
||||
/// </summary>
|
||||
[JsonProperty("method")]
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
public eControlMethod Method { get; set; }
|
||||
[JsonProperty("method")]
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
public eControlMethod Method { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The key of the device that contains the control port
|
||||
/// </summary>
|
||||
[JsonProperty("controlPortDevKey", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string ControlPortDevKey { get; set; }
|
||||
/// <summary>
|
||||
/// The key of the device that contains the control port
|
||||
/// </summary>
|
||||
[JsonProperty("controlPortDevKey", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string ControlPortDevKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The number of the control port on the device specified by ControlPortDevKey
|
||||
/// </summary>
|
||||
[JsonProperty("controlPortNumber", NullValueHandling = NullValueHandling.Ignore)] // In case "null" is present in config on this value
|
||||
public uint? ControlPortNumber { get; set; }
|
||||
/// <summary>
|
||||
/// The number of the control port on the device specified by ControlPortDevKey
|
||||
/// </summary>
|
||||
[JsonProperty("controlPortNumber", NullValueHandling = NullValueHandling.Ignore)] // In case "null" is present in config on this value
|
||||
public uint? ControlPortNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The name of the control port on the device specified by ControlPortDevKey
|
||||
/// </summary>
|
||||
[JsonProperty("controlPortName", NullValueHandling = NullValueHandling.Ignore)] // In case "null" is present in config on this value
|
||||
public string ControlPortName { get; set; }
|
||||
/// <summary>
|
||||
/// The name of the control port on the device specified by ControlPortDevKey
|
||||
/// </summary>
|
||||
[JsonProperty("controlPortName", NullValueHandling = NullValueHandling.Ignore)] // In case "null" is present in config on this value
|
||||
public string ControlPortName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Properties for ethernet based communications
|
||||
/// </summary>
|
||||
[JsonProperty("tcpSshProperties", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public TcpSshPropertiesConfig TcpSshProperties { get; set; }
|
||||
/// <summary>
|
||||
/// Properties for ethernet based communications
|
||||
/// </summary>
|
||||
[JsonProperty("tcpSshProperties", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public TcpSshPropertiesConfig TcpSshProperties { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The filename and path for the IR file
|
||||
/// </summary>
|
||||
[JsonProperty("irFile", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string IrFile { get; set; }
|
||||
/// <summary>
|
||||
/// The filename and path for the IR file
|
||||
/// </summary>
|
||||
[JsonProperty("irFile", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string IrFile { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The IpId of a Crestron device
|
||||
/// </summary>
|
||||
[JsonProperty("ipId", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string IpId { get; set; }
|
||||
/// <summary>
|
||||
/// The IpId of a Crestron device
|
||||
/// </summary>
|
||||
[JsonProperty("ipId", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string IpId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Readonly uint representation of the IpId
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public uint IpIdInt { get { return Convert.ToUInt32(IpId, 16); } }
|
||||
/// <summary>
|
||||
/// Readonly uint representation of the IpId
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public uint IpIdInt { get { return Convert.ToUInt32(IpId, 16); } }
|
||||
|
||||
/// <summary>
|
||||
/// Char indicating end of line
|
||||
/// </summary>
|
||||
[JsonProperty("endOfLineChar", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public char EndOfLineChar { get; set; }
|
||||
/// <summary>
|
||||
/// Char indicating end of line
|
||||
/// </summary>
|
||||
[JsonProperty("endOfLineChar", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public char EndOfLineChar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to Environment.NewLine;
|
||||
/// </summary>
|
||||
[JsonProperty("endOfLineString", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string EndOfLineString { get; set; }
|
||||
/// <summary>
|
||||
/// Defaults to Environment.NewLine;
|
||||
/// </summary>
|
||||
[JsonProperty("endOfLineString", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string EndOfLineString { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates
|
||||
/// </summary>
|
||||
[JsonProperty("deviceReadyResponsePattern", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string DeviceReadyResponsePattern { get; set; }
|
||||
/// <summary>
|
||||
/// Indicates
|
||||
/// </summary>
|
||||
[JsonProperty("deviceReadyResponsePattern", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string DeviceReadyResponsePattern { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Used when communcating to programs running in VC-4
|
||||
/// </summary>
|
||||
[JsonProperty("roomId", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string RoomId { get; set; }
|
||||
/// <summary>
|
||||
/// Used when communcating to programs running in VC-4
|
||||
/// </summary>
|
||||
[JsonProperty("roomId", NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string RoomId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public ControlPropertiesConfig()
|
||||
{
|
||||
}
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public ControlPropertiesConfig()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -16,28 +16,28 @@ using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Delegate for notifying of socket status changes
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
public delegate void GenericSocketStatusChangeEventDelegate(ISocketStatus client);
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs class for socket status changes
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Delegate for notifying of socket status changes
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
public delegate void GenericSocketStatusChangeEventDelegate(ISocketStatus client);
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs class for socket status changes
|
||||
/// </summary>
|
||||
public class GenericSocketStatusChageEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ISocketStatus Client { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
public GenericSocketStatusChageEventArgs(ISocketStatus client)
|
||||
{
|
||||
Client = client;
|
||||
@@ -46,105 +46,105 @@ namespace PepperDash.Core
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericSocketStatusChageEventArgs() { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delegate for notifying of TCP Server state changes
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
public delegate void GenericTcpServerStateChangedEventDelegate(ServerState state);
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs class for TCP Server state changes
|
||||
/// </summary>
|
||||
public class GenericTcpServerStateChangedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ServerState State { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Delegate for notifying of TCP Server state changes
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
public delegate void GenericTcpServerStateChangedEventDelegate(ServerState state);
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs class for TCP Server state changes
|
||||
/// </summary>
|
||||
public class GenericTcpServerStateChangedEventArgs : EventArgs
|
||||
public GenericTcpServerStateChangedEventArgs(ServerState state)
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ServerState State { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
public GenericTcpServerStateChangedEventArgs(ServerState state)
|
||||
{
|
||||
State = state;
|
||||
}
|
||||
State = state;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerStateChangedEventArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delegate for TCP Server socket status changes
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <param name="clientIndex"></param>
|
||||
/// <param name="clientStatus"></param>
|
||||
public delegate void GenericTcpServerSocketStatusChangeEventDelegate(object socket, uint clientIndex, SocketStatus clientStatus);
|
||||
/// <summary>
|
||||
/// EventArgs for TCP server socket status changes
|
||||
/// </summary>
|
||||
public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public object Socket { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public uint ReceivedFromClientIndex { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <param name="clientStatus"></param>
|
||||
public GenericTcpServerSocketStatusChangeEventArgs(object socket, SocketStatus clientStatus)
|
||||
{
|
||||
Socket = socket;
|
||||
ClientStatus = clientStatus;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delegate for TCP Server socket status changes
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <param name="clientIndex"></param>
|
||||
/// <param name="clientStatus"></param>
|
||||
public delegate void GenericTcpServerSocketStatusChangeEventDelegate(object socket, uint clientIndex, SocketStatus clientStatus);
|
||||
/// <summary>
|
||||
/// EventArgs for TCP server socket status changes
|
||||
/// </summary>
|
||||
public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs
|
||||
public GenericTcpServerSocketStatusChangeEventArgs(object socket, uint clientIndex, SocketStatus clientStatus)
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public object Socket { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public uint ReceivedFromClientIndex { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <param name="clientStatus"></param>
|
||||
public GenericTcpServerSocketStatusChangeEventArgs(object socket, SocketStatus clientStatus)
|
||||
{
|
||||
Socket = socket;
|
||||
ClientStatus = clientStatus;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <param name="clientIndex"></param>
|
||||
/// <param name="clientStatus"></param>
|
||||
public GenericTcpServerSocketStatusChangeEventArgs(object socket, uint clientIndex, SocketStatus clientStatus)
|
||||
{
|
||||
Socket = socket;
|
||||
ReceivedFromClientIndex = clientIndex;
|
||||
ClientStatus = clientStatus;
|
||||
}
|
||||
Socket = socket;
|
||||
ReceivedFromClientIndex = clientIndex;
|
||||
ClientStatus = clientStatus;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerSocketStatusChangeEventArgs() { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs for TCP server com method receive text
|
||||
/// </summary>
|
||||
public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public uint ReceivedFromClientIndex { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs for TCP server com method receive text
|
||||
///
|
||||
/// </summary>
|
||||
public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public uint ReceivedFromClientIndex { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort ReceivedFromClientIndexShort
|
||||
{
|
||||
get
|
||||
@@ -153,99 +153,96 @@ namespace PepperDash.Core
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Text { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Text { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs(string text)
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs(string text)
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <param name="clientIndex"></param>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs(string text, uint clientIndex)
|
||||
{
|
||||
Text = text;
|
||||
ReceivedFromClientIndex = clientIndex;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <param name="clientIndex"></param>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs(string text, uint clientIndex)
|
||||
{
|
||||
Text = text;
|
||||
ReceivedFromClientIndex = clientIndex;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs() { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs for TCP server client ready for communication
|
||||
/// </summary>
|
||||
public class GenericTcpServerClientReadyForcommunicationsEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool IsReady;
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs for TCP server client ready for communication
|
||||
///
|
||||
/// </summary>
|
||||
public class GenericTcpServerClientReadyForcommunicationsEventArgs : EventArgs
|
||||
/// <param name="isReady"></param>
|
||||
public GenericTcpServerClientReadyForcommunicationsEventArgs(bool isReady)
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool IsReady;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="isReady"></param>
|
||||
public GenericTcpServerClientReadyForcommunicationsEventArgs(bool isReady)
|
||||
{
|
||||
IsReady = isReady;
|
||||
}
|
||||
IsReady = isReady;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs for UDP connected
|
||||
/// </summary>
|
||||
public class GenericUdpConnectedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort UConnected;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool Connected;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public GenericUdpConnectedEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="uconnected"></param>
|
||||
public GenericUdpConnectedEventArgs(ushort uconnected)
|
||||
{
|
||||
UConnected = uconnected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs for UDP connected
|
||||
///
|
||||
/// </summary>
|
||||
public class GenericUdpConnectedEventArgs : EventArgs
|
||||
/// <param name="connected"></param>
|
||||
public GenericUdpConnectedEventArgs(bool connected)
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort UConnected;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool Connected;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public GenericUdpConnectedEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="uconnected"></param>
|
||||
public GenericUdpConnectedEventArgs(ushort uconnected)
|
||||
{
|
||||
UConnected = uconnected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="connected"></param>
|
||||
public GenericUdpConnectedEventArgs(bool connected)
|
||||
{
|
||||
Connected = connected;
|
||||
}
|
||||
|
||||
Connected = connected;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -8,145 +8,145 @@ using PepperDash.Core.Logging;
|
||||
using Renci.SshNet;
|
||||
using Renci.SshNet.Common;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
||||
{
|
||||
private const string SPlusKey = "Uninitialized SshClient";
|
||||
/// <summary>
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Event that fires when data is received. Delivers args with byte array
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Event that fires when data is received. Delivered as text.
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Event when the connection status changes.
|
||||
/// </summary>
|
||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||
|
||||
///// <summary>
|
||||
/////
|
||||
///// </summary>
|
||||
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
|
||||
|
||||
/// <summary>
|
||||
/// Address of server
|
||||
/// </summary>
|
||||
public string Hostname { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Username for server
|
||||
/// </summary>
|
||||
public string Username { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// And... Password for server. That was worth documenting!
|
||||
/// </summary>
|
||||
public string Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True when the server is connected - when status == 2.
|
||||
/// </summary>
|
||||
public bool IsConnected
|
||||
{
|
||||
// returns false if no client or not connected
|
||||
get { return Client != null && ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper for IsConnected
|
||||
/// </summary>
|
||||
public ushort UIsConnected
|
||||
{
|
||||
get { return (ushort)(IsConnected ? 1 : 0); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
||||
public SocketStatus ClientStatus
|
||||
{
|
||||
private const string SPlusKey = "Uninitialized SshClient";
|
||||
/// <summary>
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Event that fires when data is received. Delivers args with byte array
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Event that fires when data is received. Delivered as text.
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Event when the connection status changes.
|
||||
/// </summary>
|
||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||
|
||||
///// <summary>
|
||||
/////
|
||||
///// </summary>
|
||||
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
|
||||
|
||||
/// <summary>
|
||||
/// Address of server
|
||||
/// </summary>
|
||||
public string Hostname { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Username for server
|
||||
/// </summary>
|
||||
public string Username { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// And... Password for server. That was worth documenting!
|
||||
/// </summary>
|
||||
public string Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True when the server is connected - when status == 2.
|
||||
/// </summary>
|
||||
public bool IsConnected
|
||||
get { return _ClientStatus; }
|
||||
private set
|
||||
{
|
||||
// returns false if no client or not connected
|
||||
get { return Client != null && ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
if (_ClientStatus == value)
|
||||
return;
|
||||
_ClientStatus = value;
|
||||
OnConnectionChange();
|
||||
}
|
||||
}
|
||||
SocketStatus _ClientStatus;
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper for IsConnected
|
||||
/// </summary>
|
||||
public ushort UIsConnected
|
||||
{
|
||||
get { return (ushort)(IsConnected ? 1 : 0); }
|
||||
}
|
||||
/// <summary>
|
||||
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
|
||||
/// and IsConnected with be true when this == 2.
|
||||
/// </summary>
|
||||
public ushort UStatus
|
||||
{
|
||||
get { return (ushort)_ClientStatus; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus
|
||||
{
|
||||
get { return _ClientStatus; }
|
||||
private set
|
||||
{
|
||||
if (_ClientStatus == value)
|
||||
return;
|
||||
_ClientStatus = value;
|
||||
OnConnectionChange();
|
||||
}
|
||||
}
|
||||
SocketStatus _ClientStatus;
|
||||
/// <summary>
|
||||
/// Determines whether client will attempt reconnection on failure. Default is true
|
||||
/// </summary>
|
||||
public bool AutoReconnect { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
|
||||
/// and IsConnected with be true when this == 2.
|
||||
/// </summary>
|
||||
public ushort UStatus
|
||||
{
|
||||
get { return (ushort)_ClientStatus; }
|
||||
}
|
||||
/// <summary>
|
||||
/// Will be set and unset by connect and disconnect only
|
||||
/// </summary>
|
||||
public bool ConnectEnabled { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether client will attempt reconnection on failure. Default is true
|
||||
/// </summary>
|
||||
public bool AutoReconnect { get; set; }
|
||||
/// <summary>
|
||||
/// S+ helper for AutoReconnect
|
||||
/// </summary>
|
||||
public ushort UAutoReconnect
|
||||
{
|
||||
get { return (ushort)(AutoReconnect ? 1 : 0); }
|
||||
set { AutoReconnect = value == 1; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Will be set and unset by connect and disconnect only
|
||||
/// </summary>
|
||||
public bool ConnectEnabled { get; private set; }
|
||||
/// <summary>
|
||||
/// Millisecond value, determines the timeout period in between reconnect attempts.
|
||||
/// Set to 5000 by default
|
||||
/// </summary>
|
||||
public int AutoReconnectIntervalMs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper for AutoReconnect
|
||||
/// </summary>
|
||||
public ushort UAutoReconnect
|
||||
{
|
||||
get { return (ushort)(AutoReconnect ? 1 : 0); }
|
||||
set { AutoReconnect = value == 1; }
|
||||
}
|
||||
SshClient Client;
|
||||
|
||||
/// <summary>
|
||||
/// Millisecond value, determines the timeout period in between reconnect attempts.
|
||||
/// Set to 5000 by default
|
||||
/// </summary>
|
||||
public int AutoReconnectIntervalMs { get; set; }
|
||||
ShellStream TheStream;
|
||||
|
||||
SshClient Client;
|
||||
CTimer ReconnectTimer;
|
||||
|
||||
ShellStream TheStream;
|
||||
//Lock object to prevent simulatneous connect/disconnect operations
|
||||
//private CCriticalSection connectLock = new CCriticalSection();
|
||||
private SemaphoreSlim connectLock = new SemaphoreSlim(1);
|
||||
|
||||
CTimer ReconnectTimer;
|
||||
private bool DisconnectLogged = false;
|
||||
|
||||
//Lock object to prevent simulatneous connect/disconnect operations
|
||||
//private CCriticalSection connectLock = new CCriticalSection();
|
||||
private SemaphoreSlim connectLock = new SemaphoreSlim(1);
|
||||
|
||||
private bool DisconnectLogged = false;
|
||||
|
||||
/// <summary>
|
||||
/// Typical constructor.
|
||||
/// </summary>
|
||||
public GenericSshClient(string key, string hostname, int port, string username, string password) :
|
||||
base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
/// <summary>
|
||||
/// Typical constructor.
|
||||
/// </summary>
|
||||
public GenericSshClient(string key, string hostname, int port, string username, string password) :
|
||||
base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
Key = key;
|
||||
Hostname = hostname;
|
||||
@@ -155,12 +155,12 @@ namespace PepperDash.Core
|
||||
Password = password;
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
|
||||
ReconnectTimer = new CTimer(o =>
|
||||
ReconnectTimer = new CTimer(o =>
|
||||
{
|
||||
if (ConnectEnabled)
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
if (ConnectEnabled)
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
}, System.Threading.Timeout.Infinite);
|
||||
}
|
||||
|
||||
@@ -173,13 +173,13 @@ namespace PepperDash.Core
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
|
||||
ReconnectTimer = new CTimer(o =>
|
||||
ReconnectTimer = new CTimer(o =>
|
||||
{
|
||||
if (ConnectEnabled)
|
||||
{
|
||||
if (ConnectEnabled)
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
}, System.Threading.Timeout.Infinite);
|
||||
Connect();
|
||||
}
|
||||
}, System.Threading.Timeout.Infinite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -192,137 +192,137 @@ namespace PepperDash.Core
|
||||
if (Client != null)
|
||||
{
|
||||
this.LogDebug("Program stopping. Closing connection");
|
||||
Disconnect();
|
||||
}
|
||||
Disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connect to the server, using the provided properties.
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
/// <summary>
|
||||
/// Connect to the server, using the provided properties.
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
// Don't go unless everything is here
|
||||
if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535
|
||||
|| Username == null || Password == null)
|
||||
{
|
||||
// Don't go unless everything is here
|
||||
if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535
|
||||
|| Username == null || Password == null)
|
||||
this.LogError("Connect failed. Check hostname, port, username and password are set or not null");
|
||||
return;
|
||||
}
|
||||
|
||||
ConnectEnabled = true;
|
||||
|
||||
try
|
||||
{
|
||||
connectLock.Wait();
|
||||
if (IsConnected)
|
||||
{
|
||||
this.LogError("Connect failed. Check hostname, port, username and password are set or not null");
|
||||
return;
|
||||
this.LogDebug("Connection already connected. Exiting Connect");
|
||||
}
|
||||
|
||||
ConnectEnabled = true;
|
||||
|
||||
try
|
||||
else
|
||||
{
|
||||
connectLock.Wait();
|
||||
if (IsConnected)
|
||||
{
|
||||
this.LogDebug("Connection already connected. Exiting Connect");
|
||||
}
|
||||
else
|
||||
{
|
||||
this.LogDebug("Attempting connect");
|
||||
this.LogDebug("Attempting connect");
|
||||
|
||||
// Cancel reconnect if running.
|
||||
// Cancel reconnect if running.
|
||||
if (ReconnectTimer != null)
|
||||
{
|
||||
ReconnectTimer.Stop();
|
||||
}
|
||||
|
||||
// Cleanup the old client if it already exists
|
||||
if (Client != null)
|
||||
// Cleanup the old client if it already exists
|
||||
if (Client != null)
|
||||
{
|
||||
this.LogDebug("Cleaning up disconnected client");
|
||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||
}
|
||||
|
||||
// This handles both password and keyboard-interactive (like on OS-X, 'nixes)
|
||||
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
|
||||
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(kauth_AuthenticationPrompt);
|
||||
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
|
||||
|
||||
this.LogDebug("Creating new SshClient");
|
||||
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, Port, Username, pauth, kauth);
|
||||
Client = new SshClient(connectionInfo);
|
||||
Client.ErrorOccurred += Client_ErrorOccurred;
|
||||
|
||||
//Attempt to connect
|
||||
ClientStatus = SocketStatus.SOCKET_STATUS_WAITING;
|
||||
try
|
||||
{
|
||||
Client.Connect();
|
||||
TheStream = Client.CreateShellStream("PDTShell", 0, 0, 0, 0, 65534);
|
||||
if (TheStream.DataAvailable)
|
||||
{
|
||||
this.LogDebug("Cleaning up disconnected client");
|
||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||
// empty the buffer if there is data
|
||||
string str = TheStream.Read();
|
||||
}
|
||||
TheStream.DataReceived += Stream_DataReceived;
|
||||
this.LogInformation("Connected");
|
||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
||||
DisconnectLogged = false;
|
||||
}
|
||||
catch (SshConnectionException e)
|
||||
{
|
||||
var ie = e.InnerException; // The details are inside!!
|
||||
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
||||
|
||||
if (ie is SocketException)
|
||||
{
|
||||
this.LogException(ie, "CONNECTION failure: Cannot reach host");
|
||||
}
|
||||
|
||||
// This handles both password and keyboard-interactive (like on OS-X, 'nixes)
|
||||
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
|
||||
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(kauth_AuthenticationPrompt);
|
||||
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
|
||||
|
||||
this.LogDebug("Creating new SshClient");
|
||||
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, Port, Username, pauth, kauth);
|
||||
Client = new SshClient(connectionInfo);
|
||||
Client.ErrorOccurred += Client_ErrorOccurred;
|
||||
|
||||
//Attempt to connect
|
||||
ClientStatus = SocketStatus.SOCKET_STATUS_WAITING;
|
||||
try
|
||||
if (ie is System.Net.Sockets.SocketException socketException)
|
||||
{
|
||||
Client.Connect();
|
||||
TheStream = Client.CreateShellStream("PDTShell", 0, 0, 0, 0, 65534);
|
||||
if (TheStream.DataAvailable)
|
||||
{
|
||||
// empty the buffer if there is data
|
||||
string str = TheStream.Read();
|
||||
}
|
||||
TheStream.DataReceived += Stream_DataReceived;
|
||||
this.LogInformation("Connected");
|
||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
||||
DisconnectLogged = false;
|
||||
this.LogException(ie, "Connection failure: Cannot reach {host} on {port}",
|
||||
Hostname, Port);
|
||||
}
|
||||
catch (SshConnectionException e)
|
||||
if (ie is SshAuthenticationException)
|
||||
{
|
||||
var ie = e.InnerException; // The details are inside!!
|
||||
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
||||
|
||||
if (ie is SocketException)
|
||||
{
|
||||
this.LogException(ie, "CONNECTION failure: Cannot reach host");
|
||||
}
|
||||
|
||||
if (ie is System.Net.Sockets.SocketException socketException)
|
||||
{
|
||||
this.LogException(ie, "Connection failure: Cannot reach {host} on {port}",
|
||||
Hostname, Port);
|
||||
}
|
||||
if (ie is SshAuthenticationException)
|
||||
{
|
||||
this.LogException(ie, "Authentication failure for username {userName}", Username);
|
||||
}
|
||||
else
|
||||
this.LogException(ie, "Error on connect");
|
||||
|
||||
DisconnectLogged = true;
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
if (AutoReconnect)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {autoReconnect}, {autoReconnectInterval}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
this.LogException(ie, "Authentication failure for username {userName}", Username);
|
||||
}
|
||||
catch(SshOperationTimeoutException ex)
|
||||
{
|
||||
this.LogWarning("Connection attempt timed out: {message}", ex.Message);
|
||||
else
|
||||
this.LogException(ie, "Error on connect");
|
||||
|
||||
DisconnectLogged = true;
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
if (AutoReconnect)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
DisconnectLogged = true;
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
if (AutoReconnect)
|
||||
{
|
||||
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
||||
this.LogException(e, "Unhandled exception on connect");
|
||||
DisconnectLogged = true;
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
if (AutoReconnect)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
this.LogDebug("Checking autoreconnect: {autoReconnect}, {autoReconnectInterval}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);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
|
||||
this.LogException(e, "Unhandled exception on connect");
|
||||
DisconnectLogged = true;
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
if (AutoReconnect)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Release();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnect the clients and put away it's resources.
|
||||
@@ -337,54 +337,54 @@ namespace PepperDash.Core
|
||||
// ReconnectTimer = null;
|
||||
}
|
||||
|
||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||
}
|
||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kills the stream, cleans up the client and sets it to null
|
||||
/// </summary>
|
||||
private void KillClient(SocketStatus status)
|
||||
/// <summary>
|
||||
/// Kills the stream, cleans up the client and sets it to null
|
||||
/// </summary>
|
||||
private void KillClient(SocketStatus status)
|
||||
{
|
||||
KillStream();
|
||||
|
||||
try
|
||||
{
|
||||
KillStream();
|
||||
|
||||
try
|
||||
if (Client != null)
|
||||
{
|
||||
if (Client != null)
|
||||
{
|
||||
Client.ErrorOccurred -= Client_ErrorOccurred;
|
||||
Client.Disconnect();
|
||||
Client.Dispose();
|
||||
Client = null;
|
||||
ClientStatus = status;
|
||||
this.LogDebug("Disconnected");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex,"Exception in Kill Client");
|
||||
Client.ErrorOccurred -= Client_ErrorOccurred;
|
||||
Client.Disconnect();
|
||||
Client.Dispose();
|
||||
Client = null;
|
||||
ClientStatus = status;
|
||||
this.LogDebug("Disconnected");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex,"Exception in Kill Client");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kills the stream
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Kills the stream
|
||||
/// </summary>
|
||||
void KillStream()
|
||||
{
|
||||
try
|
||||
try
|
||||
{
|
||||
if (TheStream != null)
|
||||
{
|
||||
if (TheStream != null)
|
||||
{
|
||||
TheStream.DataReceived -= Stream_DataReceived;
|
||||
TheStream.Close();
|
||||
TheStream.Dispose();
|
||||
TheStream = null;
|
||||
this.LogDebug("Disconnected stream");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex, "Exception in Kill Stream:{0}");
|
||||
TheStream.DataReceived -= Stream_DataReceived;
|
||||
TheStream.Close();
|
||||
TheStream.Dispose();
|
||||
TheStream = null;
|
||||
this.LogDebug("Disconnected stream");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex, "Exception in Kill Stream:{0}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -402,32 +402,32 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
void Stream_DataReceived(object sender, ShellDataEventArgs e)
|
||||
{
|
||||
if (((ShellStream)sender).Length <= 0L)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var response = ((ShellStream)sender).Read();
|
||||
|
||||
if (((ShellStream)sender).Length <= 0L)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var response = ((ShellStream)sender).Read();
|
||||
|
||||
var bytesHandler = BytesReceived;
|
||||
|
||||
|
||||
if (bytesHandler != null)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(response);
|
||||
var bytes = Encoding.UTF8.GetBytes(response);
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
this.LogInformation("Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
}
|
||||
|
||||
var textHandler = TextReceived;
|
||||
if (textHandler != null)
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
this.LogInformation("Received: '{0}'", ComTextHelper.GetDebugText(response));
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
this.LogInformation("Received: '{0}'", ComTextHelper.GetDebugText(response));
|
||||
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(response));
|
||||
}
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(response));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -438,39 +438,39 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
void Client_ErrorOccurred(object sender, ExceptionEventArgs e)
|
||||
{
|
||||
CrestronInvoke.BeginInvoke(o =>
|
||||
{
|
||||
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
|
||||
this.LogError("Disconnected by remote");
|
||||
else
|
||||
this.LogException(e.Exception, "Unhandled SSH client error");
|
||||
try
|
||||
{
|
||||
connectLock.Wait();
|
||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Release();
|
||||
}
|
||||
if (AutoReconnect && ConnectEnabled)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper for ConnectionChange event
|
||||
/// </summary>
|
||||
void OnConnectionChange()
|
||||
CrestronInvoke.BeginInvoke(o =>
|
||||
{
|
||||
if (ConnectionChange != null)
|
||||
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
|
||||
}
|
||||
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
|
||||
this.LogError("Disconnected by remote");
|
||||
else
|
||||
this.LogException(e.Exception, "Unhandled SSH client error");
|
||||
try
|
||||
{
|
||||
connectLock.Wait();
|
||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Release();
|
||||
}
|
||||
if (AutoReconnect && ConnectEnabled)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#region IBasicCommunication Members
|
||||
/// <summary>
|
||||
/// Helper for ConnectionChange event
|
||||
/// </summary>
|
||||
void OnConnectionChange()
|
||||
{
|
||||
if (ConnectionChange != null)
|
||||
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
|
||||
}
|
||||
|
||||
#region IBasicCommunication Members
|
||||
|
||||
/// <summary>
|
||||
/// Sends text to the server
|
||||
@@ -497,52 +497,52 @@ namespace PepperDash.Core
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
this.LogError("ObjectDisposedException sending '{message}'. Restarting connection...", text.Trim());
|
||||
{
|
||||
this.LogError("ObjectDisposedException sending '{message}'. Restarting connection...", text.Trim());
|
||||
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
ReconnectTimer.Reset();
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
ReconnectTimer.Reset();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex, "Exception sending text: '{message}'", text);
|
||||
this.LogException(ex, "Exception sending text: '{message}'", text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends Bytes to the server
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
/// <summary>
|
||||
/// Sends Bytes to the server
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
try
|
||||
try
|
||||
{
|
||||
if (Client != null && TheStream != null && IsConnected)
|
||||
{
|
||||
if (Client != null && TheStream != null && IsConnected)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
this.LogInformation("Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
this.LogInformation("Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
|
||||
TheStream.Write(bytes, 0, bytes.Length);
|
||||
TheStream.Flush();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.LogDebug("Client is null or disconnected. Cannot Send Bytes");
|
||||
}
|
||||
TheStream.Write(bytes, 0, bytes.Length);
|
||||
TheStream.Flush();
|
||||
}
|
||||
catch (ObjectDisposedException ex)
|
||||
else
|
||||
{
|
||||
this.LogException(ex, "ObjectDisposedException sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||
this.LogDebug("Client is null or disconnected. Cannot Send Bytes");
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException ex)
|
||||
{
|
||||
this.LogException(ex, "ObjectDisposedException sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
ReconnectTimer.Reset();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex, "Exception sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||
}
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
ReconnectTimer.Reset();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex, "Exception sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
@@ -553,40 +553,39 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public class SshConnectionChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Connection State
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Connection State
|
||||
/// </summary>
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Connection Status represented as a ushort
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Connection Status represented as a ushort
|
||||
/// </summary>
|
||||
public ushort UIsConnected { get { return (ushort)(Client.IsConnected ? 1 : 0); } }
|
||||
|
||||
/// <summary>
|
||||
/// The client
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// The client
|
||||
/// </summary>
|
||||
public GenericSshClient Client { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Socket Status as represented by
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Socket Status as represented by
|
||||
/// </summary>
|
||||
public ushort Status { get { return Client.UStatus; } }
|
||||
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public SshConnectionChangeEventArgs() { }
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public SshConnectionChangeEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs class
|
||||
/// </summary>
|
||||
/// <param name="isConnected">Connection State</param>
|
||||
/// <param name="client">The Client</param>
|
||||
/// <summary>
|
||||
/// EventArgs class
|
||||
/// </summary>
|
||||
/// <param name="isConnected">Connection State</param>
|
||||
/// <param name="client">The Client</param>
|
||||
public SshConnectionChangeEventArgs(bool isConnected, GenericSshClient client)
|
||||
{
|
||||
IsConnected = isConnected;
|
||||
Client = client;
|
||||
}
|
||||
{
|
||||
IsConnected = isConnected;
|
||||
Client = client;
|
||||
}
|
||||
}
|
||||
@@ -6,18 +6,18 @@ using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// A class to handle basic TCP/IP communications with a server
|
||||
/// </summary>
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// A class to handle basic TCP/IP communications with a server
|
||||
/// </summary>
|
||||
public class GenericTcpIpClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
||||
{
|
||||
private const string SplusKey = "Uninitialized TcpIpClient";
|
||||
/// <summary>
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||
{
|
||||
private const string SplusKey = "Uninitialized TcpIpClient";
|
||||
/// <summary>
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Fires when data is received from the server and returns it as a Byte array
|
||||
@@ -38,11 +38,11 @@ namespace PepperDash.Core
|
||||
|
||||
private string _hostname;
|
||||
|
||||
/// <summary>
|
||||
/// Address of server
|
||||
/// </summary>
|
||||
public string Hostname
|
||||
{
|
||||
/// <summary>
|
||||
/// Address of server
|
||||
/// </summary>
|
||||
public string Hostname
|
||||
{
|
||||
get
|
||||
{
|
||||
return _hostname;
|
||||
@@ -58,25 +58,25 @@ namespace PepperDash.Core
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Another damn S+ helper because S+ seems to treat large port nums as signed ints
|
||||
/// which screws up things
|
||||
/// </summary>
|
||||
public ushort UPort
|
||||
{
|
||||
get { return Convert.ToUInt16(Port); }
|
||||
set { Port = Convert.ToInt32(value); }
|
||||
}
|
||||
/// <summary>
|
||||
/// Another damn S+ helper because S+ seems to treat large port nums as signed ints
|
||||
/// which screws up things
|
||||
/// </summary>
|
||||
public ushort UPort
|
||||
{
|
||||
get { return Convert.ToUInt16(Port); }
|
||||
set { Port = Convert.ToInt32(value); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to 2000
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
/// <summary>
|
||||
/// Defaults to 2000
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The actual client class
|
||||
@@ -87,47 +87,47 @@ namespace PepperDash.Core
|
||||
/// Bool showing if socket is connected
|
||||
/// </summary>
|
||||
public bool IsConnected
|
||||
{
|
||||
get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper for IsConnected
|
||||
/// </summary>
|
||||
public ushort UIsConnected
|
||||
{
|
||||
get { return (ushort)(IsConnected ? 1 : 0); }
|
||||
}
|
||||
{
|
||||
get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper for IsConnected
|
||||
/// </summary>
|
||||
public ushort UIsConnected
|
||||
{
|
||||
get { return (ushort)(IsConnected ? 1 : 0); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// _client socket status Read only
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus
|
||||
{
|
||||
get
|
||||
{
|
||||
return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
|
||||
/// and IsConnected would be true when this == 2.
|
||||
/// </summary>
|
||||
public ushort UStatus
|
||||
{
|
||||
get
|
||||
{
|
||||
get { return (ushort)ClientStatus; }
|
||||
}
|
||||
return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
|
||||
/// and IsConnected would be true when this == 2.
|
||||
/// </summary>
|
||||
public ushort UStatus
|
||||
{
|
||||
get { return (ushort)ClientStatus; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Status text shows the message associated with socket status
|
||||
/// Status text shows the message associated with socket status
|
||||
/// </summary>
|
||||
public string ClientStatusText { get { return ClientStatus.ToString(); } }
|
||||
|
||||
/// <summary>
|
||||
/// Ushort representation of client status
|
||||
/// </summary>
|
||||
[Obsolete]
|
||||
[Obsolete]
|
||||
public ushort UClientStatus { get { return (ushort)ClientStatus; } }
|
||||
|
||||
/// <summary>
|
||||
@@ -140,14 +140,14 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public bool AutoReconnect { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper for AutoReconnect
|
||||
/// </summary>
|
||||
public ushort UAutoReconnect
|
||||
{
|
||||
get { return (ushort)(AutoReconnect ? 1 : 0); }
|
||||
set { AutoReconnect = value == 1; }
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ helper for AutoReconnect
|
||||
/// </summary>
|
||||
public ushort UAutoReconnect
|
||||
{
|
||||
get { return (ushort)(AutoReconnect ? 1 : 0); }
|
||||
set { AutoReconnect = value == 1; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Milliseconds to wait before attempting to reconnect. Defaults to 5000
|
||||
@@ -167,283 +167,283 @@ namespace PepperDash.Core
|
||||
get { return _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
}
|
||||
|
||||
//Lock object to prevent simulatneous connect/disconnect operations
|
||||
private CCriticalSection connectLock = new CCriticalSection();
|
||||
//Lock object to prevent simulatneous connect/disconnect operations
|
||||
private CCriticalSection connectLock = new CCriticalSection();
|
||||
|
||||
// private Timer for auto reconnect
|
||||
// private Timer for auto reconnect
|
||||
private CTimer RetryTimer;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="key">unique string to differentiate between instances</param>
|
||||
/// <param name="address"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="bufferSize"></param>
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="key">unique string to differentiate between instances</param>
|
||||
/// <param name="address"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="bufferSize"></param>
|
||||
public GenericTcpIpClient(string key, string address, int port, int bufferSize)
|
||||
: base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
Hostname = address;
|
||||
Port = port;
|
||||
BufferSize = bufferSize;
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
Hostname = address;
|
||||
Port = port;
|
||||
BufferSize = bufferSize;
|
||||
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
public GenericTcpIpClient(string key)
|
||||
: base(key)
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
BufferSize = 2000;
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
}
|
||||
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
}
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
public GenericTcpIpClient(string key)
|
||||
: base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
BufferSize = 2000;
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor for S+
|
||||
/// </summary>
|
||||
public GenericTcpIpClient()
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor for S+
|
||||
/// </summary>
|
||||
public GenericTcpIpClient()
|
||||
: base(SplusKey)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(SplusKey);
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(SplusKey);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
BufferSize = 2000;
|
||||
BufferSize = 2000;
|
||||
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Just to help S+ set the key
|
||||
/// </summary>
|
||||
public void Initialize(string key)
|
||||
{
|
||||
Key = key;
|
||||
}
|
||||
/// <summary>
|
||||
/// 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)
|
||||
/// <summary>
|
||||
/// Handles closing this up when the program shuts down
|
||||
/// </summary>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
Debug.Console(1, this, "Program stopping. Closing connection");
|
||||
Deactivate();
|
||||
}
|
||||
Debug.Console(1, this, "Program stopping. Closing connection");
|
||||
Deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override bool Deactivate()
|
||||
{
|
||||
RetryTimer.Stop();
|
||||
RetryTimer.Dispose();
|
||||
if (_client != null)
|
||||
{
|
||||
_client.SocketStatusChange -= this.Client_SocketStatusChange;
|
||||
DisconnectClient();
|
||||
}
|
||||
RetryTimer.Stop();
|
||||
RetryTimer.Dispose();
|
||||
if (_client != null)
|
||||
{
|
||||
_client.SocketStatusChange -= this.Client_SocketStatusChange;
|
||||
DisconnectClient();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to connect to the server
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Attempts to connect to the server
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': No address set", Key);
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': Invalid port", Key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
connectLock.Enter();
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(1, this, "Connection already connected. Exiting Connect()");
|
||||
}
|
||||
else
|
||||
{
|
||||
//Stop retry timer if running
|
||||
RetryTimer.Stop();
|
||||
_client = new TCPClient(Hostname, Port, BufferSize);
|
||||
_client.SocketStatusChange -= Client_SocketStatusChange;
|
||||
_client.SocketStatusChange += Client_SocketStatusChange;
|
||||
DisconnectCalledByUser = false;
|
||||
_client.ConnectToServerAsync(ConnectToServerCallback);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
private void Reconnect()
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': No address set", Key);
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
if (_client == null)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': Invalid port", Key);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
connectLock.Enter();
|
||||
if (IsConnected || DisconnectCalledByUser == true)
|
||||
{
|
||||
Debug.Console(1, this, "Reconnect no longer needed. Exiting Reconnect()");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Attempting reconnect now");
|
||||
_client.ConnectToServerAsync(ConnectToServerCallback);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to disconnect the client
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
connectLock.Enter();
|
||||
DisconnectCalledByUser = true;
|
||||
|
||||
// Stop trying reconnects, if we are
|
||||
RetryTimer.Stop();
|
||||
DisconnectClient();
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Does the actual disconnect business
|
||||
/// </summary>
|
||||
public void DisconnectClient()
|
||||
try
|
||||
{
|
||||
if (_client != null)
|
||||
connectLock.Enter();
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(1, this, "Disconnecting client");
|
||||
if (IsConnected)
|
||||
_client.DisconnectFromServer();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback method for connection attempt
|
||||
/// </summary>
|
||||
/// <param name="c"></param>
|
||||
void ConnectToServerCallback(TCPClient c)
|
||||
{
|
||||
if (c.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(0, this, "Server connection result: {0}", c.ClientStatus);
|
||||
WaitAndTryReconnect();
|
||||
Debug.Console(1, this, "Connection already connected. Exiting Connect()");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Server connection result: {0}", c.ClientStatus);
|
||||
//Stop retry timer if running
|
||||
RetryTimer.Stop();
|
||||
_client = new TCPClient(Hostname, Port, BufferSize);
|
||||
_client.SocketStatusChange -= Client_SocketStatusChange;
|
||||
_client.SocketStatusChange += Client_SocketStatusChange;
|
||||
DisconnectCalledByUser = false;
|
||||
_client.ConnectToServerAsync(ConnectToServerCallback);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnects, waits and attemtps to connect again
|
||||
/// </summary>
|
||||
private void Reconnect()
|
||||
{
|
||||
if (_client == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
connectLock.Enter();
|
||||
if (IsConnected || DisconnectCalledByUser == true)
|
||||
{
|
||||
Debug.Console(1, this, "Reconnect no longer needed. Exiting Reconnect()");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Attempting reconnect now");
|
||||
_client.ConnectToServerAsync(ConnectToServerCallback);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to disconnect the client
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
connectLock.Enter();
|
||||
DisconnectCalledByUser = true;
|
||||
|
||||
// Stop trying reconnects, if we are
|
||||
RetryTimer.Stop();
|
||||
DisconnectClient();
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Does the actual disconnect business
|
||||
/// </summary>
|
||||
public void DisconnectClient()
|
||||
{
|
||||
if (_client != null)
|
||||
{
|
||||
Debug.Console(1, this, "Disconnecting client");
|
||||
if (IsConnected)
|
||||
_client.DisconnectFromServer();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback method for connection attempt
|
||||
/// </summary>
|
||||
/// <param name="c"></param>
|
||||
void ConnectToServerCallback(TCPClient c)
|
||||
{
|
||||
if (c.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(0, this, "Server connection result: {0}", c.ClientStatus);
|
||||
WaitAndTryReconnect();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Server connection result: {0}", c.ClientStatus);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnects, waits and attemtps to connect again
|
||||
/// </summary>
|
||||
void WaitAndTryReconnect()
|
||||
{
|
||||
CrestronInvoke.BeginInvoke(o =>
|
||||
CrestronInvoke.BeginInvoke(o =>
|
||||
{
|
||||
try
|
||||
{
|
||||
try
|
||||
connectLock.Enter();
|
||||
if (!IsConnected && AutoReconnect && !DisconnectCalledByUser && _client != null)
|
||||
{
|
||||
connectLock.Enter();
|
||||
if (!IsConnected && AutoReconnect && !DisconnectCalledByUser && _client != null)
|
||||
{
|
||||
DisconnectClient();
|
||||
Debug.Console(1, this, "Attempting reconnect, status={0}", _client.ClientStatus);
|
||||
RetryTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
DisconnectClient();
|
||||
Debug.Console(1, this, "Attempting reconnect, status={0}", _client.ClientStatus);
|
||||
RetryTimer.Reset(AutoReconnectIntervalMs);
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recieves incoming data
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="numBytes"></param>
|
||||
/// <summary>
|
||||
/// Recieves incoming data
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="numBytes"></param>
|
||||
void Receive(TCPClient client, int numBytes)
|
||||
{
|
||||
if (client != null)
|
||||
if (client != null)
|
||||
{
|
||||
if (numBytes > 0)
|
||||
{
|
||||
if (numBytes > 0)
|
||||
var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray();
|
||||
var bytesHandler = BytesReceived;
|
||||
if (bytesHandler != null)
|
||||
{
|
||||
var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray();
|
||||
var bytesHandler = BytesReceived;
|
||||
if (bytesHandler != null)
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
var textHandler = TextReceived;
|
||||
if (textHandler != null)
|
||||
{
|
||||
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
||||
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
}
|
||||
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
}
|
||||
client.ReceiveDataAsync(Receive);
|
||||
var textHandler = TextReceived;
|
||||
if (textHandler != null)
|
||||
{
|
||||
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
||||
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
}
|
||||
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
|
||||
}
|
||||
}
|
||||
client.ReceiveDataAsync(Receive);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -453,9 +453,9 @@ namespace PepperDash.Core
|
||||
{
|
||||
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
|
||||
// Check debug level before processing byte array
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
||||
if (_client != null)
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
||||
if (_client != null)
|
||||
_client.SendData(bytes, bytes.Length);
|
||||
}
|
||||
|
||||
@@ -472,35 +472,35 @@ namespace PepperDash.Core
|
||||
SendText(unescapedText);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends Bytes to the server
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
/// <summary>
|
||||
/// Sends Bytes to the server
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
if (_client != null)
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
if (_client != null)
|
||||
_client.SendData(bytes, bytes.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Socket Status Change Handler
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="clientSocketStatus"></param>
|
||||
/// <summary>
|
||||
/// Socket Status Change Handler
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="clientSocketStatus"></param>
|
||||
void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus)
|
||||
{
|
||||
if (clientSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(0, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
WaitAndTryReconnect();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
if (clientSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(0, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
WaitAndTryReconnect();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
_client.ReceiveDataAsync(Receive);
|
||||
}
|
||||
}
|
||||
|
||||
var handler = ConnectionChange;
|
||||
if (handler != null)
|
||||
@@ -508,30 +508,30 @@ namespace PepperDash.Core
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configuration properties for TCP/SSH Connections
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Configuration properties for TCP/SSH Connections
|
||||
/// </summary>
|
||||
public class TcpSshPropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// Address to connect to
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Address to connect to
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Address { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Port to connect to
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Port to connect to
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Username credential
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Username credential
|
||||
/// </summary>
|
||||
public string Username { get; set; }
|
||||
/// <summary>
|
||||
/// Passord credential
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Passord credential
|
||||
/// </summary>
|
||||
public string Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -549,18 +549,16 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public int AutoReconnectIntervalMs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Default constructor
|
||||
/// </summary>
|
||||
public TcpSshPropertiesConfig()
|
||||
{
|
||||
BufferSize = 32768;
|
||||
AutoReconnect = true;
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
Username = "";
|
||||
Password = "";
|
||||
Username = "";
|
||||
Password = "";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -8,389 +8,388 @@ using Crestron.SimplSharp.CrestronSockets;
|
||||
using Newtonsoft.Json;
|
||||
using PepperDash.Core.Logging;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Generic UDP Server device
|
||||
/// </summary>
|
||||
public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
{
|
||||
private const string SplusKey = "Uninitialized Udp Server";
|
||||
/// <summary>
|
||||
/// Generic UDP Server device
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
|
||||
/// <summary>
|
||||
/// This event will fire when a message is dequeued that includes the source IP and Port info if needed to determine the source of the received data.
|
||||
/// </summary>
|
||||
public event EventHandler<GenericUdpReceiveTextExtraArgs> DataRecievedExtra;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericUdpConnectedEventArgs> UpdateConnectionStatus;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus
|
||||
{
|
||||
private const string SplusKey = "Uninitialized Udp Server";
|
||||
/// <summary>
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
|
||||
/// <summary>
|
||||
/// This event will fire when a message is dequeued that includes the source IP and Port info if needed to determine the source of the received data.
|
||||
/// </summary>
|
||||
public event EventHandler<GenericUdpReceiveTextExtraArgs> DataRecievedExtra;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public event EventHandler<GenericUdpConnectedEventArgs> UpdateConnectionStatus;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus
|
||||
get
|
||||
{
|
||||
return Server.ClientStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort UStatus
|
||||
{
|
||||
get { return (ushort)Server.ServerStatus; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Address of server
|
||||
/// </summary>
|
||||
public string Hostname { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Another damn S+ helper because S+ seems to treat large port nums as signed ints
|
||||
/// which screws up things
|
||||
/// </summary>
|
||||
public ushort UPort
|
||||
{
|
||||
get { return Convert.ToUInt16(Port); }
|
||||
set { Port = Convert.ToInt32(value); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that the UDP Server is enabled
|
||||
/// </summary>
|
||||
public bool IsConnected
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Numeric value indicating
|
||||
/// </summary>
|
||||
public ushort UIsConnected
|
||||
{
|
||||
get { return IsConnected ? (ushort)1 : (ushort)0; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to 2000
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The server
|
||||
/// </summary>
|
||||
public UDPServer Server { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for S+. Make sure to set key, address, port, and buffersize using init method
|
||||
/// </summary>
|
||||
public GenericUdpServer()
|
||||
: base(SplusKey)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(SplusKey);
|
||||
BufferSize = 5000;
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
CrestronEnvironment.EthernetEventHandler += new EthernetEventHandler(CrestronEnvironment_EthernetEventHandler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="address"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="buffefSize"></param>
|
||||
public GenericUdpServer(string key, string address, int port, int buffefSize)
|
||||
: base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
Hostname = address;
|
||||
Port = port;
|
||||
BufferSize = buffefSize;
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
CrestronEnvironment.EthernetEventHandler += new EthernetEventHandler(CrestronEnvironment_EthernetEventHandler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call from S+ to initialize values
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="address"></param>
|
||||
/// <param name="port"></param>
|
||||
public void Initialize(string key, string address, ushort port)
|
||||
{
|
||||
Key = key;
|
||||
Hostname = address;
|
||||
UPort = port;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </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
|
||||
&& IsConnected)
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="programEventType"></param>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType != eProgramStatusEventType.Stopping)
|
||||
return;
|
||||
|
||||
Debug.Console(1, this, "Program stopping. Disabling Server");
|
||||
Disconnect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enables the UDP Server
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
if (Server == null)
|
||||
{
|
||||
Server = new UDPServer();
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericUdpServer '{0}': No address set", Key);
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
get
|
||||
{
|
||||
return Server.ServerStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort UStatus
|
||||
{
|
||||
get { return (ushort)Server.ServerStatus; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Address of server
|
||||
/// </summary>
|
||||
public string Hostname { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Another damn S+ helper because S+ seems to treat large port nums as signed ints
|
||||
/// which screws up things
|
||||
/// </summary>
|
||||
public ushort UPort
|
||||
{
|
||||
get { return Convert.ToUInt16(Port); }
|
||||
set { Port = Convert.ToInt32(value); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that the UDP Server is enabled
|
||||
/// </summary>
|
||||
public bool IsConnected
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Numeric value indicating
|
||||
/// </summary>
|
||||
public ushort UIsConnected
|
||||
{
|
||||
get { return IsConnected ? (ushort)1 : (ushort)0; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to 2000
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The server
|
||||
/// </summary>
|
||||
public UDPServer Server { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for S+. Make sure to set key, address, port, and buffersize using init method
|
||||
/// </summary>
|
||||
public GenericUdpServer()
|
||||
: base(SplusKey)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(SplusKey);
|
||||
BufferSize = 5000;
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
CrestronEnvironment.EthernetEventHandler += new EthernetEventHandler(CrestronEnvironment_EthernetEventHandler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="address"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="buffefSize"></param>
|
||||
public GenericUdpServer(string key, string address, int port, int buffefSize)
|
||||
: base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
Hostname = address;
|
||||
Port = port;
|
||||
BufferSize = buffefSize;
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
CrestronEnvironment.EthernetEventHandler += new EthernetEventHandler(CrestronEnvironment_EthernetEventHandler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call from S+ to initialize values
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="address"></param>
|
||||
/// <param name="port"></param>
|
||||
public void Initialize(string key, string address, ushort port)
|
||||
{
|
||||
Key = key;
|
||||
Hostname = address;
|
||||
UPort = port;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </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
|
||||
&& IsConnected)
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="programEventType"></param>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType != eProgramStatusEventType.Stopping)
|
||||
return;
|
||||
|
||||
Debug.Console(1, this, "Program stopping. Disabling Server");
|
||||
Disconnect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enables the UDP Server
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
if (Server == null)
|
||||
{
|
||||
Server = new UDPServer();
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericUdpServer '{0}': No address set", Key);
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericUdpServer '{0}': Invalid port", Key);
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericUdpServer '{0}': Invalid port", Key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var status = Server.EnableUDPServer(Hostname, Port);
|
||||
|
||||
Debug.Console(2, this, "SocketErrorCode: {0}", status);
|
||||
if (status == SocketErrorCodes.SOCKET_OK)
|
||||
IsConnected = true;
|
||||
|
||||
var handler = UpdateConnectionStatus;
|
||||
if (handler != null)
|
||||
handler(this, new GenericUdpConnectedEventArgs(UIsConnected));
|
||||
|
||||
// Start receiving data
|
||||
Server.ReceiveDataAsync(Receive);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disabled the UDP Server
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
var status = Server.EnableUDPServer(Hostname, Port);
|
||||
|
||||
Debug.Console(2, this, "SocketErrorCode: {0}", status);
|
||||
if (status == SocketErrorCodes.SOCKET_OK)
|
||||
IsConnected = true;
|
||||
|
||||
var handler = UpdateConnectionStatus;
|
||||
if (handler != null)
|
||||
handler(this, new GenericUdpConnectedEventArgs(UIsConnected));
|
||||
|
||||
// Start receiving data
|
||||
Server.ReceiveDataAsync(Receive);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disabled the UDP Server
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
if (Server != null)
|
||||
Server.DisableUDPServer();
|
||||
|
||||
IsConnected = false;
|
||||
|
||||
var handler = UpdateConnectionStatus;
|
||||
if (handler != null)
|
||||
handler(this, new GenericUdpConnectedEventArgs(UIsConnected));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Recursive method to receive data
|
||||
/// </summary>
|
||||
/// <param name="server"></param>
|
||||
/// <param name="numBytes"></param>
|
||||
void Receive(UDPServer server, int numBytes)
|
||||
{
|
||||
Debug.Console(2, this, "Received {0} bytes", numBytes);
|
||||
|
||||
try
|
||||
{
|
||||
if(Server != null)
|
||||
Server.DisableUDPServer();
|
||||
if (numBytes <= 0)
|
||||
return;
|
||||
|
||||
IsConnected = false;
|
||||
var sourceIp = Server.IPAddressLastMessageReceivedFrom;
|
||||
var sourcePort = Server.IPPortLastMessageReceivedFrom;
|
||||
var bytes = server.IncomingDataBuffer.Take(numBytes).ToArray();
|
||||
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
||||
|
||||
var handler = UpdateConnectionStatus;
|
||||
if (handler != null)
|
||||
handler(this, new GenericUdpConnectedEventArgs(UIsConnected));
|
||||
}
|
||||
var dataRecivedExtra = DataRecievedExtra;
|
||||
if (dataRecivedExtra != null)
|
||||
dataRecivedExtra(this, new GenericUdpReceiveTextExtraArgs(str, sourceIp, sourcePort, bytes));
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Recursive method to receive data
|
||||
/// </summary>
|
||||
/// <param name="server"></param>
|
||||
/// <param name="numBytes"></param>
|
||||
void Receive(UDPServer server, int numBytes)
|
||||
{
|
||||
Debug.Console(2, this, "Received {0} bytes", numBytes);
|
||||
|
||||
try
|
||||
Debug.Console(2, this, "Bytes: {0}", bytes.ToString());
|
||||
var bytesHandler = BytesReceived;
|
||||
if (bytesHandler != null)
|
||||
{
|
||||
if (numBytes <= 0)
|
||||
return;
|
||||
|
||||
var sourceIp = Server.IPAddressLastMessageReceivedFrom;
|
||||
var sourcePort = Server.IPPortLastMessageReceivedFrom;
|
||||
var bytes = server.IncomingDataBuffer.Take(numBytes).ToArray();
|
||||
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
||||
|
||||
var dataRecivedExtra = DataRecievedExtra;
|
||||
if (dataRecivedExtra != null)
|
||||
dataRecivedExtra(this, new GenericUdpReceiveTextExtraArgs(str, sourceIp, sourcePort, bytes));
|
||||
|
||||
Debug.Console(2, this, "Bytes: {0}", bytes.ToString());
|
||||
var bytesHandler = BytesReceived;
|
||||
if (bytesHandler != null)
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
}
|
||||
var textHandler = TextReceived;
|
||||
if (textHandler != null)
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
|
||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
}
|
||||
catch (Exception ex)
|
||||
var textHandler = TextReceived;
|
||||
if (textHandler != null)
|
||||
{
|
||||
this.LogException(ex, "GenericUdpServer Receive error");
|
||||
}
|
||||
finally
|
||||
{
|
||||
server.ReceiveDataAsync(Receive);
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// General send method
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public void SendText(string text)
|
||||
catch (Exception ex)
|
||||
{
|
||||
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
|
||||
|
||||
if (IsConnected && Server != null)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
||||
|
||||
Server.SendData(bytes, bytes.Length);
|
||||
}
|
||||
this.LogException(ex, "GenericUdpServer Receive error");
|
||||
}
|
||||
finally
|
||||
{
|
||||
server.ReceiveDataAsync(Receive);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
public void SendBytes(byte[] bytes)
|
||||
/// <summary>
|
||||
/// General send method
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public void SendText(string text)
|
||||
{
|
||||
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
|
||||
|
||||
if (IsConnected && Server != null)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
||||
|
||||
if (IsConnected && Server != null)
|
||||
Server.SendData(bytes, bytes.Length);
|
||||
Server.SendData(bytes, bytes.Length);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class GenericUdpReceiveTextExtraArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Text { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string IpAddress { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int Port { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public byte[] Bytes { get; private set; }
|
||||
/// <param name="bytes"></param>
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <param name="ipAddress"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="bytes"></param>
|
||||
public GenericUdpReceiveTextExtraArgs(string text, string ipAddress, int port, byte[] bytes)
|
||||
{
|
||||
Text = text;
|
||||
IpAddress = ipAddress;
|
||||
Port = port;
|
||||
Bytes = bytes;
|
||||
}
|
||||
if (IsConnected && Server != null)
|
||||
Server.SendData(bytes, bytes.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stupid S+ Constructor
|
||||
/// </summary>
|
||||
public GenericUdpReceiveTextExtraArgs() { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class GenericUdpReceiveTextExtraArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Text { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string IpAddress { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int Port { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public byte[] Bytes { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class UdpServerPropertiesConfig
|
||||
/// <param name="text"></param>
|
||||
/// <param name="ipAddress"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="bytes"></param>
|
||||
public GenericUdpReceiveTextExtraArgs(string text, string ipAddress, int port, byte[] bytes)
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Address { get; set; }
|
||||
Text = text;
|
||||
IpAddress = ipAddress;
|
||||
Port = port;
|
||||
Bytes = bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public int Port { get; set; }
|
||||
/// <summary>
|
||||
/// Stupid S+ Constructor
|
||||
/// </summary>
|
||||
public GenericUdpReceiveTextExtraArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to 32768
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class UdpServerPropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Address { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public UdpServerPropertiesConfig()
|
||||
{
|
||||
BufferSize = 32768;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to 32768
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public UdpServerPropertiesConfig()
|
||||
{
|
||||
BufferSize = 32768;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,58 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Client config object for TCP client with server that inherits from TcpSshPropertiesConfig and adds properties for shared key and heartbeat
|
||||
/// </summary>
|
||||
public class TcpClientConfigObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Client config object for TCP client with server that inherits from TcpSshPropertiesConfig and adds properties for shared key and heartbeat
|
||||
/// TcpSsh Properties
|
||||
/// </summary>
|
||||
public class TcpClientConfigObject
|
||||
{
|
||||
/// <summary>
|
||||
/// TcpSsh Properties
|
||||
/// </summary>
|
||||
[JsonProperty("control")]
|
||||
public ControlPropertiesConfig Control { get; set; }
|
||||
[JsonProperty("control")]
|
||||
public ControlPropertiesConfig Control { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Bool value for secure. Currently not implemented in TCP sockets as they are not dynamic
|
||||
/// </summary>
|
||||
[JsonProperty("secure")]
|
||||
public bool Secure { get; set; }
|
||||
/// <summary>
|
||||
/// Bool value for secure. Currently not implemented in TCP sockets as they are not dynamic
|
||||
/// </summary>
|
||||
[JsonProperty("secure")]
|
||||
public bool Secure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Require a shared key that both server and client negotiate. If negotiation fails server disconnects the client
|
||||
/// </summary>
|
||||
[JsonProperty("sharedKeyRequired")]
|
||||
public bool SharedKeyRequired { get; set; }
|
||||
/// <summary>
|
||||
/// Require a shared key that both server and client negotiate. If negotiation fails server disconnects the client
|
||||
/// </summary>
|
||||
[JsonProperty("sharedKeyRequired")]
|
||||
public bool SharedKeyRequired { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The shared key that must match on the server and client
|
||||
/// </summary>
|
||||
[JsonProperty("sharedKey")]
|
||||
public string SharedKey { get; set; }
|
||||
/// <summary>
|
||||
/// The shared key that must match on the server and client
|
||||
/// </summary>
|
||||
[JsonProperty("sharedKey")]
|
||||
public string SharedKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Require a heartbeat on the client/server connection that will cause the server/client to disconnect if the heartbeat is not received.
|
||||
/// heartbeats do not raise received events.
|
||||
/// </summary>
|
||||
[JsonProperty("heartbeatRequired")]
|
||||
public bool HeartbeatRequired { get; set; }
|
||||
/// <summary>
|
||||
/// Require a heartbeat on the client/server connection that will cause the server/client to disconnect if the heartbeat is not received.
|
||||
/// heartbeats do not raise received events.
|
||||
/// </summary>
|
||||
[JsonProperty("heartbeatRequired")]
|
||||
public bool HeartbeatRequired { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The interval in seconds for the heartbeat from the client. If not received client is disconnected
|
||||
/// </summary>
|
||||
[JsonProperty("heartbeatRequiredIntervalInSeconds")]
|
||||
public ushort HeartbeatRequiredIntervalInSeconds { get; set; }
|
||||
/// <summary>
|
||||
/// The interval in seconds for the heartbeat from the client. If not received client is disconnected
|
||||
/// </summary>
|
||||
[JsonProperty("heartbeatRequiredIntervalInSeconds")]
|
||||
public ushort HeartbeatRequiredIntervalInSeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// HeartbeatString that will be checked against the message received. defaults to heartbeat if no string is provided.
|
||||
/// </summary>
|
||||
[JsonProperty("heartbeatStringToMatch")]
|
||||
public string HeartbeatStringToMatch { get; set; }
|
||||
/// <summary>
|
||||
/// HeartbeatString that will be checked against the message received. defaults to heartbeat if no string is provided.
|
||||
/// </summary>
|
||||
[JsonProperty("heartbeatStringToMatch")]
|
||||
public string HeartbeatStringToMatch { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Receive Queue size must be greater than 20 or defaults to 20
|
||||
/// </summary>
|
||||
[JsonProperty("receiveQueueSize")]
|
||||
public int ReceiveQueueSize { get; set; }
|
||||
}
|
||||
/// <summary>
|
||||
/// Receive Queue size must be greater than 20 or defaults to 20
|
||||
/// </summary>
|
||||
[JsonProperty("receiveQueueSize")]
|
||||
public int ReceiveQueueSize { get; set; }
|
||||
}
|
||||
@@ -4,57 +4,56 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Tcp Server Config object with properties for a tcp server with shared key and heartbeat capabilities
|
||||
/// </summary>
|
||||
public class TcpServerConfigObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Tcp Server Config object with properties for a tcp server with shared key and heartbeat capabilities
|
||||
/// Uique key
|
||||
/// </summary>
|
||||
public class TcpServerConfigObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Uique key
|
||||
/// </summary>
|
||||
public string Key { get; set; }
|
||||
/// <summary>
|
||||
/// Max Clients that the server will allow to connect.
|
||||
/// </summary>
|
||||
public ushort MaxClients { get; set; }
|
||||
/// <summary>
|
||||
/// Bool value for secure. Currently not implemented in TCP sockets as they are not dynamic
|
||||
/// </summary>
|
||||
public bool Secure { get; set; }
|
||||
/// <summary>
|
||||
/// Port for the server to listen on
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
/// <summary>
|
||||
/// Require a shared key that both server and client negotiate. If negotiation fails server disconnects the client
|
||||
/// </summary>
|
||||
public bool SharedKeyRequired { get; set; }
|
||||
/// <summary>
|
||||
/// The shared key that must match on the server and client
|
||||
/// </summary>
|
||||
public string SharedKey { get; set; }
|
||||
/// <summary>
|
||||
/// Require a heartbeat on the client/server connection that will cause the server/client to disconnect if the heartbeat is not received.
|
||||
/// heartbeats do not raise received events.
|
||||
/// </summary>
|
||||
public bool HeartbeatRequired { get; set; }
|
||||
/// <summary>
|
||||
/// The interval in seconds for the heartbeat from the client. If not received client is disconnected
|
||||
/// </summary>
|
||||
public ushort HeartbeatRequiredIntervalInSeconds { get; set; }
|
||||
/// <summary>
|
||||
/// HeartbeatString that will be checked against the message received. defaults to heartbeat if no string is provided.
|
||||
/// </summary>
|
||||
public string HeartbeatStringToMatch { get; set; }
|
||||
/// <summary>
|
||||
/// Client buffer size. See Crestron help. defaults to 2000 if not greater than 2000
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
/// <summary>
|
||||
/// Receive Queue size must be greater than 20 or defaults to 20
|
||||
/// </summary>
|
||||
public int ReceiveQueueSize { get; set; }
|
||||
}
|
||||
public string Key { get; set; }
|
||||
/// <summary>
|
||||
/// Max Clients that the server will allow to connect.
|
||||
/// </summary>
|
||||
public ushort MaxClients { get; set; }
|
||||
/// <summary>
|
||||
/// Bool value for secure. Currently not implemented in TCP sockets as they are not dynamic
|
||||
/// </summary>
|
||||
public bool Secure { get; set; }
|
||||
/// <summary>
|
||||
/// Port for the server to listen on
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
/// <summary>
|
||||
/// Require a shared key that both server and client negotiate. If negotiation fails server disconnects the client
|
||||
/// </summary>
|
||||
public bool SharedKeyRequired { get; set; }
|
||||
/// <summary>
|
||||
/// The shared key that must match on the server and client
|
||||
/// </summary>
|
||||
public string SharedKey { get; set; }
|
||||
/// <summary>
|
||||
/// Require a heartbeat on the client/server connection that will cause the server/client to disconnect if the heartbeat is not received.
|
||||
/// heartbeats do not raise received events.
|
||||
/// </summary>
|
||||
public bool HeartbeatRequired { get; set; }
|
||||
/// <summary>
|
||||
/// The interval in seconds for the heartbeat from the client. If not received client is disconnected
|
||||
/// </summary>
|
||||
public ushort HeartbeatRequiredIntervalInSeconds { get; set; }
|
||||
/// <summary>
|
||||
/// HeartbeatString that will be checked against the message received. defaults to heartbeat if no string is provided.
|
||||
/// </summary>
|
||||
public string HeartbeatStringToMatch { get; set; }
|
||||
/// <summary>
|
||||
/// Client buffer size. See Crestron help. defaults to 2000 if not greater than 2000
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
/// <summary>
|
||||
/// Receive Queue size must be greater than 20 or defaults to 20
|
||||
/// </summary>
|
||||
public int ReceiveQueueSize { get; set; }
|
||||
}
|
||||
@@ -4,76 +4,75 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Crestron Control Methods for a comm object
|
||||
/// </summary>
|
||||
public enum eControlMethod
|
||||
{
|
||||
/// <summary>
|
||||
/// Crestron Control Methods for a comm object
|
||||
///
|
||||
/// </summary>
|
||||
public enum eControlMethod
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// RS232/422/485
|
||||
/// </summary>
|
||||
Com,
|
||||
/// <summary>
|
||||
/// Crestron IpId (most Crestron ethernet devices)
|
||||
/// </summary>
|
||||
IpId,
|
||||
/// <summary>
|
||||
/// Crestron IpIdTcp (HD-MD series, etc.)
|
||||
/// </summary>
|
||||
IpidTcp,
|
||||
/// <summary>
|
||||
/// Crestron IR control
|
||||
/// </summary>
|
||||
IR,
|
||||
/// <summary>
|
||||
/// SSH client
|
||||
/// </summary>
|
||||
Ssh,
|
||||
/// <summary>
|
||||
/// TCP/IP client
|
||||
/// </summary>
|
||||
Tcpip,
|
||||
/// <summary>
|
||||
/// Telnet
|
||||
/// </summary>
|
||||
Telnet,
|
||||
/// <summary>
|
||||
/// Crestnet device
|
||||
/// </summary>
|
||||
Cresnet,
|
||||
/// <summary>
|
||||
/// CEC Control, via a DM HDMI port
|
||||
/// </summary>
|
||||
Cec,
|
||||
/// <summary>
|
||||
/// UDP Server
|
||||
/// </summary>
|
||||
Udp,
|
||||
/// <summary>
|
||||
/// HTTP client
|
||||
/// </summary>
|
||||
Http,
|
||||
/// <summary>
|
||||
/// HTTPS client
|
||||
/// </summary>
|
||||
Https,
|
||||
/// <summary>
|
||||
/// Websocket client
|
||||
/// </summary>
|
||||
Ws,
|
||||
/// <summary>
|
||||
/// Secure Websocket client
|
||||
/// </summary>
|
||||
Wss,
|
||||
/// <summary>
|
||||
/// Secure TCP/IP
|
||||
/// </summary>
|
||||
SecureTcpIp
|
||||
}
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// RS232/422/485
|
||||
/// </summary>
|
||||
Com,
|
||||
/// <summary>
|
||||
/// Crestron IpId (most Crestron ethernet devices)
|
||||
/// </summary>
|
||||
IpId,
|
||||
/// <summary>
|
||||
/// Crestron IpIdTcp (HD-MD series, etc.)
|
||||
/// </summary>
|
||||
IpidTcp,
|
||||
/// <summary>
|
||||
/// Crestron IR control
|
||||
/// </summary>
|
||||
IR,
|
||||
/// <summary>
|
||||
/// SSH client
|
||||
/// </summary>
|
||||
Ssh,
|
||||
/// <summary>
|
||||
/// TCP/IP client
|
||||
/// </summary>
|
||||
Tcpip,
|
||||
/// <summary>
|
||||
/// Telnet
|
||||
/// </summary>
|
||||
Telnet,
|
||||
/// <summary>
|
||||
/// Crestnet device
|
||||
/// </summary>
|
||||
Cresnet,
|
||||
/// <summary>
|
||||
/// CEC Control, via a DM HDMI port
|
||||
/// </summary>
|
||||
Cec,
|
||||
/// <summary>
|
||||
/// UDP Server
|
||||
/// </summary>
|
||||
Udp,
|
||||
/// <summary>
|
||||
/// HTTP client
|
||||
/// </summary>
|
||||
Http,
|
||||
/// <summary>
|
||||
/// HTTPS client
|
||||
/// </summary>
|
||||
Https,
|
||||
/// <summary>
|
||||
/// Websocket client
|
||||
/// </summary>
|
||||
Ws,
|
||||
/// <summary>
|
||||
/// Secure Websocket client
|
||||
/// </summary>
|
||||
Wss,
|
||||
/// <summary>
|
||||
/// Secure TCP/IP
|
||||
/// </summary>
|
||||
SecureTcpIp
|
||||
}
|
||||
@@ -7,74 +7,74 @@ using Crestron.SimplSharp.CrestronSockets;
|
||||
using System.Text.RegularExpressions;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// An incoming communication stream
|
||||
/// </summary>
|
||||
public interface ICommunicationReceiver : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// An incoming communication stream
|
||||
/// Notifies of bytes received
|
||||
/// </summary>
|
||||
public interface ICommunicationReceiver : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Notifies of bytes received
|
||||
/// </summary>
|
||||
event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
/// <summary>
|
||||
/// Notifies of text received
|
||||
/// </summary>
|
||||
event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
/// <summary>
|
||||
/// Notifies of text received
|
||||
/// </summary>
|
||||
event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Indicates connection status
|
||||
/// </summary>
|
||||
[JsonProperty("isConnected")]
|
||||
bool IsConnected { get; }
|
||||
/// <summary>
|
||||
/// Connect to the device
|
||||
/// </summary>
|
||||
void Connect();
|
||||
/// <summary>
|
||||
/// Disconnect from the device
|
||||
/// </summary>
|
||||
void Disconnect();
|
||||
}
|
||||
/// <summary>
|
||||
/// Indicates connection status
|
||||
/// </summary>
|
||||
[JsonProperty("isConnected")]
|
||||
bool IsConnected { get; }
|
||||
/// <summary>
|
||||
/// Connect to the device
|
||||
/// </summary>
|
||||
void Connect();
|
||||
/// <summary>
|
||||
/// Disconnect from the device
|
||||
/// </summary>
|
||||
void Disconnect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a device that uses basic connection
|
||||
/// </summary>
|
||||
public interface IBasicCommunication : ICommunicationReceiver
|
||||
public interface IBasicCommunication : ICommunicationReceiver
|
||||
{
|
||||
/// <summary>
|
||||
/// Send text to the device
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <summary>
|
||||
/// Send text to the device
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
void SendText(string text);
|
||||
|
||||
/// <summary>
|
||||
/// Send bytes to the device
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
/// <summary>
|
||||
/// Send bytes to the device
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
void SendBytes(byte[] bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a device that implements IBasicCommunication and IStreamDebugging
|
||||
/// </summary>
|
||||
public interface IBasicCommunicationWithStreamDebugging : IBasicCommunication, IStreamDebugging
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a device that implements IBasicCommunication and IStreamDebugging
|
||||
/// </summary>
|
||||
public interface IBasicCommunicationWithStreamDebugging : IBasicCommunication, IStreamDebugging
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a device with stream debugging capablities
|
||||
/// </summary>
|
||||
public interface IStreamDebugging
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a device with stream debugging capablities
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
public interface IStreamDebugging
|
||||
{
|
||||
/// <summary>
|
||||
/// Object to enable stream debugging
|
||||
/// </summary>
|
||||
[JsonProperty("streamDebugging")]
|
||||
CommunicationStreamDebugging StreamDebugging { get; }
|
||||
}
|
||||
[JsonProperty("streamDebugging")]
|
||||
CommunicationStreamDebugging StreamDebugging { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For IBasicCommunication classes that have SocketStatus. GenericSshClient,
|
||||
@@ -82,41 +82,41 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public interface ISocketStatus : IBasicCommunication
|
||||
{
|
||||
/// <summary>
|
||||
/// Notifies of socket status changes
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of socket status changes
|
||||
/// </summary>
|
||||
event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||
|
||||
/// <summary>
|
||||
/// The current socket status of the client
|
||||
/// </summary>
|
||||
[JsonProperty("clientStatus")]
|
||||
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
|
||||
SocketStatus ClientStatus { get; }
|
||||
/// <summary>
|
||||
/// The current socket status of the client
|
||||
/// </summary>
|
||||
[JsonProperty("clientStatus")]
|
||||
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
|
||||
SocketStatus ClientStatus { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes a device that implements ISocketStatus and IStreamDebugging
|
||||
/// </summary>
|
||||
public interface ISocketStatusWithStreamDebugging : ISocketStatus, IStreamDebugging
|
||||
{
|
||||
/// <summary>
|
||||
/// Describes a device that implements ISocketStatus and IStreamDebugging
|
||||
/// </summary>
|
||||
public interface ISocketStatusWithStreamDebugging : ISocketStatus, IStreamDebugging
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes a device that can automatically attempt to reconnect
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Describes a device that can automatically attempt to reconnect
|
||||
/// </summary>
|
||||
public interface IAutoReconnect
|
||||
{
|
||||
/// <summary>
|
||||
/// Enable automatic recconnect
|
||||
/// </summary>
|
||||
[JsonProperty("autoReconnect")]
|
||||
/// <summary>
|
||||
/// Enable automatic recconnect
|
||||
/// </summary>
|
||||
[JsonProperty("autoReconnect")]
|
||||
bool AutoReconnect { get; set; }
|
||||
/// <summary>
|
||||
/// Interval in ms to attempt automatic recconnections
|
||||
/// </summary>
|
||||
[JsonProperty("autoReconnectIntervalMs")]
|
||||
/// <summary>
|
||||
/// Interval in ms to attempt automatic recconnections
|
||||
/// </summary>
|
||||
[JsonProperty("autoReconnectIntervalMs")]
|
||||
int AutoReconnectIntervalMs { get; set; }
|
||||
}
|
||||
|
||||
@@ -125,14 +125,14 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public enum eGenericCommMethodStatusChangeType
|
||||
{
|
||||
/// <summary>
|
||||
/// Connected
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Connected
|
||||
/// </summary>
|
||||
Connected,
|
||||
/// <summary>
|
||||
/// Disconnected
|
||||
/// </summary>
|
||||
Disconnected
|
||||
/// <summary>
|
||||
/// Disconnected
|
||||
/// </summary>
|
||||
Disconnected
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -147,15 +147,15 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public class GenericCommMethodReceiveBytesArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public byte[] Bytes { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
public GenericCommMethodReceiveBytesArgs(byte[] bytes)
|
||||
{
|
||||
Bytes = bytes;
|
||||
@@ -172,33 +172,33 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public class GenericCommMethodReceiveTextArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Text { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Delimiter { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Delimiter { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public GenericCommMethodReceiveTextArgs(string text)
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <param name="delimiter"></param>
|
||||
public GenericCommMethodReceiveTextArgs(string text, string delimiter)
|
||||
:this(text)
|
||||
{
|
||||
Delimiter = delimiter;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <param name="delimiter"></param>
|
||||
public GenericCommMethodReceiveTextArgs(string text, string delimiter)
|
||||
:this(text)
|
||||
{
|
||||
Delimiter = delimiter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
@@ -213,35 +213,34 @@ namespace PepperDash.Core
|
||||
/// </summary>
|
||||
public class ComTextHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets escaped text for a byte array
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// Gets escaped text for a byte array
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetEscapedText(byte[] bytes)
|
||||
{
|
||||
return String.Concat(bytes.Select(b => string.Format(@"[{0:X2}]", (int)b)).ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets escaped text for a string
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// Gets escaped text for a string
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetEscapedText(string text)
|
||||
{
|
||||
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
|
||||
return String.Concat(bytes.Select(b => string.Format(@"[{0:X2}]", (int)b)).ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets debug text for a string
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetDebugText(string text)
|
||||
{
|
||||
return Regex.Replace(text, @"[^\u0020-\u007E]", a => GetEscapedText(a.Value));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets debug text for a string
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetDebugText(string text)
|
||||
{
|
||||
return Regex.Replace(text, @"[^\u0020-\u007E]", a => GetEscapedText(a.Value));
|
||||
}
|
||||
}
|
||||
@@ -1,235 +1,234 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using PepperDash.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core.Config
|
||||
namespace PepperDash.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// Reads a Portal formatted config file
|
||||
/// </summary>
|
||||
public class PortalConfigReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads a Portal formatted config file
|
||||
/// </summary>
|
||||
public class PortalConfigReader
|
||||
/// <summary>
|
||||
/// Reads the config file, checks if it needs a merge, merges and saves, then returns the merged Object.
|
||||
/// </summary>
|
||||
/// <returns>JObject of config file</returns>
|
||||
public static void ReadAndMergeFileIfNecessary(string filePath, string savePath)
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the config file, checks if it needs a merge, merges and saves, then returns the merged Object.
|
||||
/// </summary>
|
||||
/// <returns>JObject of config file</returns>
|
||||
public static void ReadAndMergeFileIfNecessary(string filePath, string savePath)
|
||||
try
|
||||
{
|
||||
try
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Error,
|
||||
"ERROR: Configuration file not present. Please load file to {0} and reset program", filePath);
|
||||
}
|
||||
|
||||
using (StreamReader fs = new StreamReader(filePath))
|
||||
{
|
||||
var jsonObj = JObject.Parse(fs.ReadToEnd());
|
||||
if (jsonObj["template"] != null && jsonObj["system"] != null)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Error,
|
||||
"ERROR: Configuration file not present. Please load file to {0} and reset program", filePath);
|
||||
// it's a double-config, merge it.
|
||||
var merged = MergeConfigs(jsonObj);
|
||||
if (jsonObj["system_url"] != null)
|
||||
{
|
||||
merged["systemUrl"] = jsonObj["system_url"].Value<string>();
|
||||
}
|
||||
|
||||
if (jsonObj["template_url"] != null)
|
||||
{
|
||||
merged["templateUrl"] = jsonObj["template_url"].Value<string>();
|
||||
}
|
||||
|
||||
jsonObj = merged;
|
||||
}
|
||||
|
||||
using (StreamReader fs = new StreamReader(filePath))
|
||||
using (StreamWriter fw = new StreamWriter(savePath))
|
||||
{
|
||||
var jsonObj = JObject.Parse(fs.ReadToEnd());
|
||||
if(jsonObj["template"] != null && jsonObj["system"] != null)
|
||||
{
|
||||
// it's a double-config, merge it.
|
||||
var merged = MergeConfigs(jsonObj);
|
||||
if (jsonObj["system_url"] != null)
|
||||
{
|
||||
merged["systemUrl"] = jsonObj["system_url"].Value<string>();
|
||||
}
|
||||
|
||||
if (jsonObj["template_url"] != null)
|
||||
{
|
||||
merged["templateUrl"] = jsonObj["template_url"].Value<string>();
|
||||
}
|
||||
|
||||
jsonObj = merged;
|
||||
}
|
||||
|
||||
using (StreamWriter fw = new StreamWriter(savePath))
|
||||
{
|
||||
fw.Write(jsonObj.ToString(Formatting.Indented));
|
||||
Debug.LogMessage(LogEventLevel.Debug, "JSON config merged and saved to {0}", savePath);
|
||||
}
|
||||
|
||||
fw.Write(jsonObj.ToString(Formatting.Indented));
|
||||
Debug.LogMessage(LogEventLevel.Debug, "JSON config merged and saved to {0}", savePath);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogMessage(e, "ERROR: Config load failed");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="doubleConfig"></param>
|
||||
/// <returns></returns>
|
||||
public static JObject MergeConfigs(JObject doubleConfig)
|
||||
catch (Exception e)
|
||||
{
|
||||
var system = JObject.FromObject(doubleConfig["system"]);
|
||||
var template = JObject.FromObject(doubleConfig["template"]);
|
||||
var merged = new JObject();
|
||||
|
||||
// Put together top-level objects
|
||||
if (system["info"] != null)
|
||||
merged.Add("info", Merge(template["info"], system["info"], "infO"));
|
||||
else
|
||||
merged.Add("info", template["info"]);
|
||||
|
||||
merged.Add("devices", MergeArraysOnTopLevelProperty(template["devices"] as JArray,
|
||||
system["devices"] as JArray, "key", "devices"));
|
||||
|
||||
if (system["rooms"] == null)
|
||||
merged.Add("rooms", template["rooms"]);
|
||||
else
|
||||
merged.Add("rooms", MergeArraysOnTopLevelProperty(template["rooms"] as JArray,
|
||||
system["rooms"] as JArray, "key", "rooms"));
|
||||
|
||||
if (system["sourceLists"] == null)
|
||||
merged.Add("sourceLists", template["sourceLists"]);
|
||||
else
|
||||
merged.Add("sourceLists", Merge(template["sourceLists"], system["sourceLists"], "sourceLists"));
|
||||
|
||||
if (system["destinationLists"] == null)
|
||||
merged.Add("destinationLists", template["destinationLists"]);
|
||||
else
|
||||
merged.Add("destinationLists",
|
||||
Merge(template["destinationLists"], system["destinationLists"], "destinationLists"));
|
||||
|
||||
|
||||
if (system["cameraLists"] == null)
|
||||
merged.Add("cameraLists", template["cameraLists"]);
|
||||
else
|
||||
merged.Add("cameraLists", Merge(template["cameraLists"], system["cameraLists"], "cameraLists"));
|
||||
|
||||
if (system["audioControlPointLists"] == null)
|
||||
merged.Add("audioControlPointLists", template["audioControlPointLists"]);
|
||||
else
|
||||
merged.Add("audioControlPointLists",
|
||||
Merge(template["audioControlPointLists"], system["audioControlPointLists"], "audioControlPointLists"));
|
||||
|
||||
|
||||
// Template tie lines take precedence. Config tool doesn't do them at system
|
||||
// level anyway...
|
||||
if (template["tieLines"] != null)
|
||||
merged.Add("tieLines", template["tieLines"]);
|
||||
else if (system["tieLines"] != null)
|
||||
merged.Add("tieLines", system["tieLines"]);
|
||||
else
|
||||
merged.Add("tieLines", new JArray());
|
||||
|
||||
if (template["joinMaps"] != null)
|
||||
merged.Add("joinMaps", template["joinMaps"]);
|
||||
else
|
||||
merged.Add("joinMaps", new JObject());
|
||||
|
||||
if (system["global"] != null)
|
||||
merged.Add("global", Merge(template["global"], system["global"], "global"));
|
||||
else
|
||||
merged.Add("global", template["global"]);
|
||||
|
||||
//Debug.Console(2, "MERGED CONFIG RESULT: \x0d\x0a{0}", merged);
|
||||
return merged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merges the contents of a base and a delta array, matching the entries on a top-level property
|
||||
/// given by propertyName. Returns a merge of them. Items in the delta array that do not have
|
||||
/// a matched item in base array will not be merged. Non keyed system items will replace the template items.
|
||||
/// </summary>
|
||||
static JArray MergeArraysOnTopLevelProperty(JArray a1, JArray a2, string propertyName, string path)
|
||||
{
|
||||
var result = new JArray();
|
||||
if (a2 == null || a2.Count == 0) // If the system array is null or empty, return the template array
|
||||
return a1;
|
||||
else if (a1 != null)
|
||||
{
|
||||
if (a2[0]["key"] == null) // If the first item in the system array has no key, overwrite the template array
|
||||
{ // with the system array
|
||||
return a2;
|
||||
}
|
||||
else // The arrays are keyed, merge them by key
|
||||
{
|
||||
for (int i = 0; i < a1.Count(); i++)
|
||||
{
|
||||
var a1Dev = a1[i];
|
||||
// Try to get a system device and if found, merge it onto template
|
||||
var a2Match = a2.FirstOrDefault(t => t[propertyName].Equals(a1Dev[propertyName]));// t.Value<int>("uid") == tmplDev.Value<int>("uid"));
|
||||
if (a2Match != null)
|
||||
{
|
||||
var mergedItem = Merge(a1Dev, a2Match, string.Format("{0}[{1}].", path, i));// Merge(JObject.FromObject(a1Dev), JObject.FromObject(a2Match));
|
||||
result.Add(mergedItem);
|
||||
}
|
||||
else
|
||||
result.Add(a1Dev);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Helper for using with JTokens. Converts to JObject
|
||||
/// </summary>
|
||||
static JObject Merge(JToken t1, JToken t2, string path)
|
||||
{
|
||||
return Merge(JObject.FromObject(t1), JObject.FromObject(t2), path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merge o2 onto o1
|
||||
/// </summary>
|
||||
/// <param name="o1"></param>
|
||||
/// <param name="o2"></param>
|
||||
/// <param name="path"></param>
|
||||
static JObject Merge(JObject o1, JObject o2, string path)
|
||||
{
|
||||
foreach (var o2Prop in o2)
|
||||
{
|
||||
var propKey = o2Prop.Key;
|
||||
var o1Value = o1[propKey];
|
||||
var o2Value = o2[propKey];
|
||||
|
||||
// if the property doesn't exist on o1, then add it.
|
||||
if (o1Value == null)
|
||||
{
|
||||
o1.Add(propKey, o2Value);
|
||||
}
|
||||
// otherwise merge them
|
||||
else
|
||||
{
|
||||
// Drill down
|
||||
var propPath = String.Format("{0}.{1}", path, propKey);
|
||||
try
|
||||
{
|
||||
|
||||
if (o1Value is JArray)
|
||||
{
|
||||
if (o2Value is JArray)
|
||||
{
|
||||
o1Value.Replace(MergeArraysOnTopLevelProperty(o1Value as JArray, o2Value as JArray, "key", propPath));
|
||||
}
|
||||
}
|
||||
else if (o2Prop.Value.HasValues && o1Value.HasValues)
|
||||
{
|
||||
o1Value.Replace(Merge(JObject.FromObject(o1Value), JObject.FromObject(o2Value), propPath));
|
||||
}
|
||||
else
|
||||
{
|
||||
o1Value.Replace(o2Prop.Value);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Cannot merge items at path {0}: \r{1}", propPath, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return o1;
|
||||
Debug.LogMessage(e, "ERROR: Config load failed");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="doubleConfig"></param>
|
||||
/// <returns></returns>
|
||||
public static JObject MergeConfigs(JObject doubleConfig)
|
||||
{
|
||||
var system = JObject.FromObject(doubleConfig["system"]);
|
||||
var template = JObject.FromObject(doubleConfig["template"]);
|
||||
var merged = new JObject();
|
||||
|
||||
// Put together top-level objects
|
||||
if (system["info"] != null)
|
||||
merged.Add("info", Merge(template["info"], system["info"], "infO"));
|
||||
else
|
||||
merged.Add("info", template["info"]);
|
||||
|
||||
merged.Add("devices", MergeArraysOnTopLevelProperty(template["devices"] as JArray,
|
||||
system["devices"] as JArray, "key", "devices"));
|
||||
|
||||
if (system["rooms"] == null)
|
||||
merged.Add("rooms", template["rooms"]);
|
||||
else
|
||||
merged.Add("rooms", MergeArraysOnTopLevelProperty(template["rooms"] as JArray,
|
||||
system["rooms"] as JArray, "key", "rooms"));
|
||||
|
||||
if (system["sourceLists"] == null)
|
||||
merged.Add("sourceLists", template["sourceLists"]);
|
||||
else
|
||||
merged.Add("sourceLists", Merge(template["sourceLists"], system["sourceLists"], "sourceLists"));
|
||||
|
||||
if (system["destinationLists"] == null)
|
||||
merged.Add("destinationLists", template["destinationLists"]);
|
||||
else
|
||||
merged.Add("destinationLists",
|
||||
Merge(template["destinationLists"], system["destinationLists"], "destinationLists"));
|
||||
|
||||
|
||||
if (system["cameraLists"] == null)
|
||||
merged.Add("cameraLists", template["cameraLists"]);
|
||||
else
|
||||
merged.Add("cameraLists", Merge(template["cameraLists"], system["cameraLists"], "cameraLists"));
|
||||
|
||||
if (system["audioControlPointLists"] == null)
|
||||
merged.Add("audioControlPointLists", template["audioControlPointLists"]);
|
||||
else
|
||||
merged.Add("audioControlPointLists",
|
||||
Merge(template["audioControlPointLists"], system["audioControlPointLists"], "audioControlPointLists"));
|
||||
|
||||
|
||||
// Template tie lines take precedence. Config tool doesn't do them at system
|
||||
// level anyway...
|
||||
if (template["tieLines"] != null)
|
||||
merged.Add("tieLines", template["tieLines"]);
|
||||
else if (system["tieLines"] != null)
|
||||
merged.Add("tieLines", system["tieLines"]);
|
||||
else
|
||||
merged.Add("tieLines", new JArray());
|
||||
|
||||
if (template["joinMaps"] != null)
|
||||
merged.Add("joinMaps", template["joinMaps"]);
|
||||
else
|
||||
merged.Add("joinMaps", new JObject());
|
||||
|
||||
if (system["global"] != null)
|
||||
merged.Add("global", Merge(template["global"], system["global"], "global"));
|
||||
else
|
||||
merged.Add("global", template["global"]);
|
||||
|
||||
//Debug.Console(2, "MERGED CONFIG RESULT: \x0d\x0a{0}", merged);
|
||||
return merged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merges the contents of a base and a delta array, matching the entries on a top-level property
|
||||
/// given by propertyName. Returns a merge of them. Items in the delta array that do not have
|
||||
/// a matched item in base array will not be merged. Non keyed system items will replace the template items.
|
||||
/// </summary>
|
||||
static JArray MergeArraysOnTopLevelProperty(JArray a1, JArray a2, string propertyName, string path)
|
||||
{
|
||||
var result = new JArray();
|
||||
if (a2 == null || a2.Count == 0) // If the system array is null or empty, return the template array
|
||||
return a1;
|
||||
else if (a1 != null)
|
||||
{
|
||||
if (a2[0]["key"] == null) // If the first item in the system array has no key, overwrite the template array
|
||||
{ // with the system array
|
||||
return a2;
|
||||
}
|
||||
else // The arrays are keyed, merge them by key
|
||||
{
|
||||
for (int i = 0; i < a1.Count(); i++)
|
||||
{
|
||||
var a1Dev = a1[i];
|
||||
// Try to get a system device and if found, merge it onto template
|
||||
var a2Match = a2.FirstOrDefault(t => t[propertyName].Equals(a1Dev[propertyName]));// t.Value<int>("uid") == tmplDev.Value<int>("uid"));
|
||||
if (a2Match != null)
|
||||
{
|
||||
var mergedItem = Merge(a1Dev, a2Match, string.Format("{0}[{1}].", path, i));// Merge(JObject.FromObject(a1Dev), JObject.FromObject(a2Match));
|
||||
result.Add(mergedItem);
|
||||
}
|
||||
else
|
||||
result.Add(a1Dev);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Helper for using with JTokens. Converts to JObject
|
||||
/// </summary>
|
||||
static JObject Merge(JToken t1, JToken t2, string path)
|
||||
{
|
||||
return Merge(JObject.FromObject(t1), JObject.FromObject(t2), path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merge o2 onto o1
|
||||
/// </summary>
|
||||
/// <param name="o1"></param>
|
||||
/// <param name="o2"></param>
|
||||
/// <param name="path"></param>
|
||||
static JObject Merge(JObject o1, JObject o2, string path)
|
||||
{
|
||||
foreach (var o2Prop in o2)
|
||||
{
|
||||
var propKey = o2Prop.Key;
|
||||
var o1Value = o1[propKey];
|
||||
var o2Value = o2[propKey];
|
||||
|
||||
// if the property doesn't exist on o1, then add it.
|
||||
if (o1Value == null)
|
||||
{
|
||||
o1.Add(propKey, o2Value);
|
||||
}
|
||||
// otherwise merge them
|
||||
else
|
||||
{
|
||||
// Drill down
|
||||
var propPath = String.Format("{0}.{1}", path, propKey);
|
||||
try
|
||||
{
|
||||
|
||||
if (o1Value is JArray)
|
||||
{
|
||||
if (o2Value is JArray)
|
||||
{
|
||||
o1Value.Replace(MergeArraysOnTopLevelProperty(o1Value as JArray, o2Value as JArray, "key", propPath));
|
||||
}
|
||||
}
|
||||
else if (o2Prop.Value.HasValues && o1Value.HasValues)
|
||||
{
|
||||
o1Value.Replace(Merge(JObject.FromObject(o1Value), JObject.FromObject(o2Value), propPath));
|
||||
}
|
||||
else
|
||||
{
|
||||
o1Value.Replace(o2Prop.Value);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Cannot merge items at path {0}: \r{1}", propPath, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return o1;
|
||||
}
|
||||
}
|
||||
@@ -4,19 +4,18 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
public class EncodingHelper
|
||||
{
|
||||
public class EncodingHelper
|
||||
public static string ConvertUtf8ToAscii(string utf8String)
|
||||
{
|
||||
public static string ConvertUtf8ToAscii(string utf8String)
|
||||
{
|
||||
return Encoding.ASCII.GetString(Encoding.UTF8.GetBytes(utf8String), 0, utf8String.Length);
|
||||
}
|
||||
|
||||
public static string ConvertUtf8ToUtf16(string utf8String)
|
||||
{
|
||||
return Encoding.Unicode.GetString(Encoding.UTF8.GetBytes(utf8String), 0, utf8String.Length);
|
||||
}
|
||||
|
||||
return Encoding.ASCII.GetString(Encoding.UTF8.GetBytes(utf8String), 0, utf8String.Length);
|
||||
}
|
||||
|
||||
public static string ConvertUtf8ToUtf16(string utf8String)
|
||||
{
|
||||
return Encoding.Unicode.GetString(Encoding.UTF8.GetBytes(utf8String), 0, utf8String.Length);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,30 +6,28 @@ using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
using Serilog;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Unique key interface to require a unique key for the class
|
||||
/// </summary>
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Unique key interface to require a unique key for the class
|
||||
/// </summary>
|
||||
public interface IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Unique Key
|
||||
/// </summary>
|
||||
[JsonProperty("key")]
|
||||
string Key { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Named Keyed device interface. Forces the device to have a Unique Key and a name.
|
||||
/// <summary>
|
||||
/// Gets the unique key associated with the object.
|
||||
/// </summary>
|
||||
public interface IKeyName : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Isn't it obvious :)
|
||||
/// </summary>
|
||||
[JsonProperty("name")]
|
||||
string Name { get; }
|
||||
}
|
||||
[JsonProperty("key")]
|
||||
string Key { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Named Keyed device interface. Forces the device to have a Unique Key and a name.
|
||||
/// </summary>
|
||||
public interface IKeyName : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the name associated with the current object.
|
||||
/// </summary>
|
||||
[JsonProperty("name")]
|
||||
string Name { get; }
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
using System.Collections.Generic;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
namespace PepperDash.Core;
|
||||
|
||||
//*********************************************************************************************************
|
||||
/// <summary>
|
||||
/// The core event and status-bearing class that most if not all device and connectors can derive from.
|
||||
@@ -11,35 +11,35 @@ namespace PepperDash.Core
|
||||
public class Device : IKeyName
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Unique Key
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Unique Key
|
||||
/// </summary>
|
||||
public string Key { get; protected set; }
|
||||
/// <summary>
|
||||
/// Name of the devie
|
||||
/// </summary>
|
||||
public string Name { get; protected set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Name { get; protected set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool Enabled { get; protected set; }
|
||||
|
||||
///// <summary>
|
||||
///// A place to store reference to the original config object, if any. These values should
|
||||
///// NOT be used as properties on the device as they are all publicly-settable values.
|
||||
///// </summary>
|
||||
//public DeviceConfig Config { get; private set; }
|
||||
///// <summary>
|
||||
///// Helper method to check if Config exists
|
||||
///// </summary>
|
||||
//public bool HasConfig { get { return Config != null; } }
|
||||
///// <summary>
|
||||
///// A place to store reference to the original config object, if any. These values should
|
||||
///// NOT be used as properties on the device as they are all publicly-settable values.
|
||||
///// </summary>
|
||||
//public DeviceConfig Config { get; private set; }
|
||||
///// <summary>
|
||||
///// Helper method to check if Config exists
|
||||
///// </summary>
|
||||
//public bool HasConfig { get { return Config != null; } }
|
||||
|
||||
List<Action> _PreActivationActions;
|
||||
List<Action> _PostActivationActions;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static Device DefaultDevice { get { return _DefaultDevice; } }
|
||||
static Device _DefaultDevice = new Device("Default", "Default");
|
||||
|
||||
@@ -54,27 +54,27 @@ namespace PepperDash.Core
|
||||
Name = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor with key and name
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="name"></param>
|
||||
/// <summary>
|
||||
/// Constructor with key and name
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="name"></param>
|
||||
public Device(string key, string name) : this(key)
|
||||
{
|
||||
Name = name;
|
||||
|
||||
}
|
||||
|
||||
//public Device(DeviceConfig config)
|
||||
// : this(config.Key, config.Name)
|
||||
//{
|
||||
// Config = config;
|
||||
//}
|
||||
//public Device(DeviceConfig config)
|
||||
// : this(config.Key, config.Name)
|
||||
//{
|
||||
// Config = config;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a pre activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
/// <summary>
|
||||
/// Adds a pre activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
public void AddPreActivationAction(Action act)
|
||||
{
|
||||
if (_PreActivationActions == null)
|
||||
@@ -82,10 +82,10 @@ namespace PepperDash.Core
|
||||
_PreActivationActions.Add(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a post activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
/// <summary>
|
||||
/// Adds a post activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
public void AddPostActivationAction(Action act)
|
||||
{
|
||||
if (_PostActivationActions == null)
|
||||
@@ -93,55 +93,58 @@ namespace PepperDash.Core
|
||||
_PostActivationActions.Add(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the preactivation actions
|
||||
/// </summary>
|
||||
public void PreActivate()
|
||||
{
|
||||
if (_PreActivationActions != null)
|
||||
_PreActivationActions.ForEach(a => {
|
||||
/// <summary>
|
||||
/// Executes the preactivation actions
|
||||
/// </summary>
|
||||
public void PreActivate()
|
||||
{
|
||||
if (_PreActivationActions != null)
|
||||
_PreActivationActions.ForEach(a =>
|
||||
{
|
||||
try
|
||||
{
|
||||
a.Invoke();
|
||||
} catch (Exception e)
|
||||
{
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogMessage(e, "Error in PreActivationAction: " + e.Message, this);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets this device ready to be used in the system. Runs any added pre-activation items, and
|
||||
/// all post-activation at end. Classes needing additional logic to
|
||||
/// run should override CustomActivate()
|
||||
/// </summary>
|
||||
public bool Activate()
|
||||
public bool Activate()
|
||||
{
|
||||
//if (_PreActivationActions != null)
|
||||
// _PreActivationActions.ForEach(a => a.Invoke());
|
||||
//if (_PreActivationActions != null)
|
||||
// _PreActivationActions.ForEach(a => a.Invoke());
|
||||
var result = CustomActivate();
|
||||
//if(result && _PostActivationActions != null)
|
||||
// _PostActivationActions.ForEach(a => a.Invoke());
|
||||
return result;
|
||||
//if(result && _PostActivationActions != null)
|
||||
// _PostActivationActions.ForEach(a => a.Invoke());
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the postactivation actions
|
||||
/// </summary>
|
||||
public void PostActivate()
|
||||
{
|
||||
if (_PostActivationActions != null)
|
||||
_PostActivationActions.ForEach(a => {
|
||||
try
|
||||
{
|
||||
a.Invoke();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogMessage(e, "Error in PostActivationAction: " + e.Message, this);
|
||||
}
|
||||
});
|
||||
}
|
||||
/// <summary>
|
||||
/// Executes the postactivation actions
|
||||
/// </summary>
|
||||
public void PostActivate()
|
||||
{
|
||||
if (_PostActivationActions != null)
|
||||
_PostActivationActions.ForEach(a =>
|
||||
{
|
||||
try
|
||||
{
|
||||
a.Invoke();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogMessage(e, "Error in PostActivationAction: " + e.Message, this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called in between Pre and PostActivationActions when Activate() is called.
|
||||
@@ -158,14 +161,14 @@ namespace PepperDash.Core
|
||||
/// <returns></returns>
|
||||
public virtual bool Deactivate() { return true; }
|
||||
|
||||
/// <summary>
|
||||
/// Call this method to start communications with a device. Overriding classes do not need to call base.Initialize()
|
||||
/// </summary>
|
||||
public virtual void Initialize()
|
||||
{
|
||||
}
|
||||
/// <summary>
|
||||
/// Call this method to start communications with a device. Overriding classes do not need to call base.Initialize()
|
||||
/// </summary>
|
||||
public virtual void Initialize()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <summary>
|
||||
/// Helper method to check object for bool value false and fire an Action method
|
||||
/// </summary>
|
||||
/// <param name="o">Should be of type bool, others will be ignored</param>
|
||||
@@ -175,5 +178,14 @@ namespace PepperDash.Core
|
||||
if (o is bool && !(bool)o) a();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Returns a string representation of the object, including its key and name.
|
||||
/// </summary>
|
||||
/// <remarks>The returned string is formatted as "{Key} - {Name}". If the <c>Name</c> property is
|
||||
/// null or empty, "---" is used in place of the name.</remarks>
|
||||
/// <returns>A string that represents the object, containing the key and name in the format "{Key} - {Name}".</returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return string.Format("{0} - {1}", Key, string.IsNullOrEmpty(Name) ? "---" : Name);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
using Newtonsoft.Json;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to help with accessing values from the CrestronEthernetHelper class
|
||||
/// </summary>
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Class to help with accessing values from the CrestronEthernetHelper class
|
||||
/// </summary>
|
||||
public class EthernetHelper
|
||||
{
|
||||
/// <summary>
|
||||
@@ -113,5 +113,4 @@ namespace PepperDash.Core
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Bool change event args
|
||||
/// </summary>
|
||||
@@ -168,5 +168,4 @@ namespace PepperDash.Core
|
||||
Type = type;
|
||||
Index = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,13 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.GenericRESTfulCommunications
|
||||
{
|
||||
namespace PepperDash.Core.GenericRESTfulCommunications;
|
||||
|
||||
/// <summary>
|
||||
/// Constants
|
||||
/// </summary>
|
||||
public class GenericRESTfulConstants
|
||||
{
|
||||
public class GenericRESTfulConstants
|
||||
{
|
||||
/// <summary>
|
||||
/// Generic boolean change
|
||||
/// </summary>
|
||||
@@ -35,5 +35,4 @@ namespace PepperDash.Core.GenericRESTfulCommunications
|
||||
/// Error string change
|
||||
/// </summary>
|
||||
public const ushort ErrorStringChange = 203;
|
||||
}
|
||||
}
|
||||
@@ -6,251 +6,250 @@ using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.Net.Http;
|
||||
using Crestron.SimplSharp.Net.Https;
|
||||
|
||||
namespace PepperDash.Core.GenericRESTfulCommunications
|
||||
namespace PepperDash.Core.GenericRESTfulCommunications;
|
||||
|
||||
/// <summary>
|
||||
/// Generic RESTful communication class
|
||||
/// </summary>
|
||||
public class GenericRESTfulClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Generic RESTful communication class
|
||||
/// Boolean event handler
|
||||
/// </summary>
|
||||
public class GenericRESTfulClient
|
||||
public event EventHandler<BoolChangeEventArgs> BoolChange;
|
||||
/// <summary>
|
||||
/// Ushort event handler
|
||||
/// </summary>
|
||||
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
|
||||
/// <summary>
|
||||
/// String event handler
|
||||
/// </summary>
|
||||
public event EventHandler<StringChangeEventArgs> StringChange;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public GenericRESTfulClient()
|
||||
{
|
||||
/// <summary>
|
||||
/// Boolean event handler
|
||||
/// </summary>
|
||||
public event EventHandler<BoolChangeEventArgs> BoolChange;
|
||||
/// <summary>
|
||||
/// Ushort event handler
|
||||
/// </summary>
|
||||
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
|
||||
/// <summary>
|
||||
/// String event handler
|
||||
/// </summary>
|
||||
public event EventHandler<StringChangeEventArgs> StringChange;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public GenericRESTfulClient()
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic RESTful submit request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="requestType"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <param name="contentType"></param>
|
||||
public void SubmitRequest(string url, ushort port, ushort requestType, string contentType, string username, string password)
|
||||
{
|
||||
if (url.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
|
||||
SubmitRequestHttps(url, port, requestType, contentType, username, password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic RESTful submit request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="requestType"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <param name="contentType"></param>
|
||||
public void SubmitRequest(string url, ushort port, ushort requestType, string contentType, string username, string password)
|
||||
else if (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (url.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
SubmitRequestHttps(url, port, requestType, contentType, username, password);
|
||||
}
|
||||
else if (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
SubmitRequestHttp(url, port, requestType, contentType, username, password);
|
||||
}
|
||||
SubmitRequestHttp(url, port, requestType, contentType, username, password);
|
||||
}
|
||||
else
|
||||
{
|
||||
OnStringChange(string.Format("Invalid URL {0}", url), 0, GenericRESTfulConstants.ErrorStringChange);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private HTTP submit request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="requestType"></param>
|
||||
/// <param name="contentType"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
private void SubmitRequestHttp(string url, ushort port, ushort requestType, string contentType, string username, string password)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpClient client = new HttpClient();
|
||||
HttpClientRequest request = new HttpClientRequest();
|
||||
HttpClientResponse response;
|
||||
|
||||
client.KeepAlive = false;
|
||||
|
||||
if (port >= 1 || port <= 65535)
|
||||
client.Port = port;
|
||||
else
|
||||
{
|
||||
OnStringChange(string.Format("Invalid URL {0}", url), 0, GenericRESTfulConstants.ErrorStringChange);
|
||||
}
|
||||
}
|
||||
client.Port = 80;
|
||||
|
||||
/// <summary>
|
||||
/// Private HTTP submit request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="requestType"></param>
|
||||
/// <param name="contentType"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
private void SubmitRequestHttp(string url, ushort port, ushort requestType, string contentType, string username, string password)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpClient client = new HttpClient();
|
||||
HttpClientRequest request = new HttpClientRequest();
|
||||
HttpClientResponse response;
|
||||
|
||||
client.KeepAlive = false;
|
||||
|
||||
if(port >= 1 || port <= 65535)
|
||||
client.Port = port;
|
||||
else
|
||||
client.Port = 80;
|
||||
|
||||
var authorization = "";
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
authorization = EncodeBase64(username, password);
|
||||
|
||||
if (!string.IsNullOrEmpty(authorization))
|
||||
request.Header.SetHeaderValue("Authorization", authorization);
|
||||
|
||||
if (!string.IsNullOrEmpty(contentType))
|
||||
request.Header.ContentType = contentType;
|
||||
|
||||
request.Url.Parse(url);
|
||||
request.RequestType = (Crestron.SimplSharp.Net.Http.RequestType)requestType;
|
||||
|
||||
response = client.Dispatch(request);
|
||||
|
||||
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
|
||||
|
||||
if (!string.IsNullOrEmpty(response.ContentString.ToString()))
|
||||
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
|
||||
|
||||
if (response.Code > 0)
|
||||
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//var msg = string.Format("SubmitRequestHttp({0}, {1}, {2}) failed:{3}", url, port, requestType, e.Message);
|
||||
//CrestronConsole.PrintLine(msg);
|
||||
//ErrorLog.Error(msg);
|
||||
|
||||
CrestronConsole.PrintLine(e.Message);
|
||||
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private HTTPS submit request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="requestType"></param>
|
||||
/// <param name="contentType"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
private void SubmitRequestHttps(string url, ushort port, ushort requestType, string contentType, string username, string password)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpsClient client = new HttpsClient();
|
||||
HttpsClientRequest request = new HttpsClientRequest();
|
||||
HttpsClientResponse response;
|
||||
|
||||
client.KeepAlive = false;
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
|
||||
var authorization = "";
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
authorization = EncodeBase64(username, password);
|
||||
|
||||
if (!string.IsNullOrEmpty(authorization))
|
||||
request.Header.SetHeaderValue("Authorization", authorization);
|
||||
|
||||
if (!string.IsNullOrEmpty(contentType))
|
||||
request.Header.ContentType = contentType;
|
||||
|
||||
request.Url.Parse(url);
|
||||
request.RequestType = (Crestron.SimplSharp.Net.Https.RequestType)requestType;
|
||||
|
||||
response = client.Dispatch(request);
|
||||
|
||||
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
|
||||
|
||||
if(!string.IsNullOrEmpty(response.ContentString.ToString()))
|
||||
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
|
||||
|
||||
if(response.Code > 0)
|
||||
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//var msg = string.Format("SubmitRequestHttps({0}, {1}, {2}, {3}, {4}) failed:{5}", url, port, requestType, username, password, e.Message);
|
||||
//CrestronConsole.PrintLine(msg);
|
||||
//ErrorLog.Error(msg);
|
||||
|
||||
CrestronConsole.PrintLine(e.Message);
|
||||
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private method to encode username and password to Base64 string
|
||||
/// </summary>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <returns>authorization</returns>
|
||||
private string EncodeBase64(string username, string password)
|
||||
{
|
||||
var authorization = "";
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
authorization = EncodeBase64(username, password);
|
||||
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
{
|
||||
string base64String = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", username, password)));
|
||||
authorization = string.Format("Basic {0}", base64String);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var msg = string.Format("EncodeBase64({0}, {1}) failed:\r{2}", username, password, e);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
return "" ;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(authorization))
|
||||
request.Header.SetHeaderValue("Authorization", authorization);
|
||||
|
||||
return authorization;
|
||||
if (!string.IsNullOrEmpty(contentType))
|
||||
request.Header.ContentType = contentType;
|
||||
|
||||
request.Url = Crestron.SimplSharp.Net.Http.UrlParser.Parse(url);
|
||||
request.RequestType = (Crestron.SimplSharp.Net.Http.RequestType)requestType;
|
||||
|
||||
response = client.Dispatch(request);
|
||||
|
||||
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
|
||||
|
||||
if (!string.IsNullOrEmpty(response.ContentString.ToString()))
|
||||
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
|
||||
|
||||
if (response.Code > 0)
|
||||
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected method to handle boolean change events
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnBoolChange(bool state, ushort index, ushort type)
|
||||
catch (Exception e)
|
||||
{
|
||||
var handler = BoolChange;
|
||||
if (handler != null)
|
||||
//var msg = string.Format("SubmitRequestHttp({0}, {1}, {2}) failed:{3}", url, port, requestType, e.Message);
|
||||
//CrestronConsole.PrintLine(msg);
|
||||
//ErrorLog.Error(msg);
|
||||
|
||||
CrestronConsole.PrintLine(e.Message);
|
||||
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private HTTPS submit request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="requestType"></param>
|
||||
/// <param name="contentType"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
private void SubmitRequestHttps(string url, ushort port, ushort requestType, string contentType, string username, string password)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpsClient client = new HttpsClient();
|
||||
HttpsClientRequest request = new HttpsClientRequest();
|
||||
HttpsClientResponse response;
|
||||
|
||||
client.KeepAlive = false;
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
|
||||
var authorization = "";
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
authorization = EncodeBase64(username, password);
|
||||
|
||||
if (!string.IsNullOrEmpty(authorization))
|
||||
request.Header.SetHeaderValue("Authorization", authorization);
|
||||
|
||||
if (!string.IsNullOrEmpty(contentType))
|
||||
request.Header.ContentType = contentType;
|
||||
|
||||
request.Url = Crestron.SimplSharp.Net.Https.UrlParser.Parse(url);
|
||||
request.RequestType = (Crestron.SimplSharp.Net.Https.RequestType)requestType;
|
||||
|
||||
response = client.Dispatch(request);
|
||||
|
||||
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
|
||||
|
||||
if (!string.IsNullOrEmpty(response.ContentString.ToString()))
|
||||
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
|
||||
|
||||
if (response.Code > 0)
|
||||
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
//var msg = string.Format("SubmitRequestHttps({0}, {1}, {2}, {3}, {4}) failed:{5}", url, port, requestType, username, password, e.Message);
|
||||
//CrestronConsole.PrintLine(msg);
|
||||
//ErrorLog.Error(msg);
|
||||
|
||||
CrestronConsole.PrintLine(e.Message);
|
||||
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private method to encode username and password to Base64 string
|
||||
/// </summary>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <returns>authorization</returns>
|
||||
private string EncodeBase64(string username, string password)
|
||||
{
|
||||
var authorization = "";
|
||||
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
{
|
||||
var args = new BoolChangeEventArgs(state, type);
|
||||
args.Index = index;
|
||||
BoolChange(this, args);
|
||||
string base64String = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", username, password)));
|
||||
authorization = string.Format("Basic {0}", base64String);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected mehtod to handle ushort change events
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnUshrtChange(ushort value, ushort index, ushort type)
|
||||
catch (Exception e)
|
||||
{
|
||||
var handler = UshrtChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new UshrtChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
UshrtChange(this, args);
|
||||
}
|
||||
var msg = string.Format("EncodeBase64({0}, {1}) failed:\r{2}", username, password, e);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected method to handle string change events
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnStringChange(string value, ushort index, ushort type)
|
||||
return authorization;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected method to handle boolean change events
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnBoolChange(bool state, ushort index, ushort type)
|
||||
{
|
||||
var handler = BoolChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var handler = StringChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new StringChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
StringChange(this, args);
|
||||
}
|
||||
var args = new BoolChangeEventArgs(state, type);
|
||||
args.Index = index;
|
||||
BoolChange(this, args);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected mehtod to handle ushort change events
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnUshrtChange(ushort value, ushort index, ushort type)
|
||||
{
|
||||
var handler = UshrtChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new UshrtChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
UshrtChange(this, args);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected method to handle string change events
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnStringChange(string value, ushort index, ushort type)
|
||||
{
|
||||
var handler = StringChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new StringChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
StringChange(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.JsonStandardObjects
|
||||
{
|
||||
namespace PepperDash.Core.JsonStandardObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Constants for simpl modules
|
||||
/// </summary>
|
||||
@@ -73,5 +73,4 @@ namespace PepperDash.Core.JsonStandardObjects
|
||||
Type = type;
|
||||
Index = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using Crestron.SimplSharp;
|
||||
using PepperDash.Core.JsonToSimpl;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core.JsonStandardObjects
|
||||
{
|
||||
namespace PepperDash.Core.JsonStandardObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Device class
|
||||
/// </summary>
|
||||
@@ -179,5 +179,4 @@ namespace PepperDash.Core.JsonStandardObjects
|
||||
}
|
||||
|
||||
#endregion EventHandler Helpers
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.JsonStandardObjects
|
||||
{
|
||||
namespace PepperDash.Core.JsonStandardObjects;
|
||||
|
||||
/*
|
||||
Convert JSON snippt to C#: http://json2csharp.com/#
|
||||
|
||||
@@ -52,55 +52,55 @@ namespace PepperDash.Core.JsonStandardObjects
|
||||
/// </summary>
|
||||
public class ComParamsConfig
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int baudRate { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int dataBits { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int stopBits { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string parity { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string protocol { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string hardwareHandshake { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string softwareHandshake { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int pacing { get; set; }
|
||||
|
||||
// convert properties for simpl
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplDataBits { get { return Convert.ToUInt16(dataBits); } }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplStopBits { get { return Convert.ToUInt16(stopBits); } }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplPacing { get { return Convert.ToUInt16(pacing); } }
|
||||
|
||||
/// <summary>
|
||||
@@ -117,43 +117,43 @@ namespace PepperDash.Core.JsonStandardObjects
|
||||
/// </summary>
|
||||
public class TcpSshPropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string address { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int port { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string username { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string password { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool autoReconnect { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int autoReconnectIntervalMs { get; set; }
|
||||
|
||||
// convert properties for simpl
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplPort { get { return Convert.ToUInt16(port); } }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplAutoReconnect { get { return (ushort)(autoReconnect ? 1 : 0); } }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplAutoReconnectIntervalMs { get { return Convert.ToUInt16(autoReconnectIntervalMs); } }
|
||||
|
||||
/// <summary>
|
||||
@@ -170,31 +170,31 @@ namespace PepperDash.Core.JsonStandardObjects
|
||||
/// </summary>
|
||||
public class ControlConfig
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string method { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string controlPortDevKey { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int controlPortNumber { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ComParamsConfig comParams { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public TcpSshPropertiesConfig tcpSshProperties { get; set; }
|
||||
|
||||
// convert properties for simpl
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } }
|
||||
|
||||
/// <summary>
|
||||
@@ -212,27 +212,27 @@ namespace PepperDash.Core.JsonStandardObjects
|
||||
/// </summary>
|
||||
public class PropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int deviceId { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool enabled { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ControlConfig control { get; set; }
|
||||
|
||||
// convert properties for simpl
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort simplEnabled { get { return (ushort)(enabled ? 1 : 0); } }
|
||||
|
||||
/// <summary>
|
||||
@@ -249,9 +249,8 @@ namespace PepperDash.Core.JsonStandardObjects
|
||||
/// </summary>
|
||||
public class RootObject
|
||||
{
|
||||
/// <summary>
|
||||
/// The collection of devices
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// The collection of devices
|
||||
/// </summary>
|
||||
public List<DeviceConfig> devices { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,78 +4,78 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// Constants for Simpl modules
|
||||
/// </summary>
|
||||
public class JsonToSimplConstants
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort BoolValueChange = 1;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort JsonIsValidBoolChange = 2;
|
||||
|
||||
/// <summary>
|
||||
/// Reports the if the device is 3-series compatible
|
||||
/// </summary>
|
||||
public const ushort ProgramCompatibility3SeriesChange = 3;
|
||||
/// <summary>
|
||||
/// Reports the if the device is 3-series compatible
|
||||
/// </summary>
|
||||
public const ushort ProgramCompatibility3SeriesChange = 3;
|
||||
|
||||
/// <summary>
|
||||
/// Reports the if the device is 4-series compatible
|
||||
/// </summary>
|
||||
public const ushort ProgramCompatibility4SeriesChange = 4;
|
||||
/// <summary>
|
||||
/// Reports the if the device is 4-series compatible
|
||||
/// </summary>
|
||||
public const ushort ProgramCompatibility4SeriesChange = 4;
|
||||
|
||||
/// <summary>
|
||||
/// Reports the device platform enum value
|
||||
/// </summary>
|
||||
public const ushort DevicePlatformValueChange = 5;
|
||||
/// <summary>
|
||||
/// Reports the device platform enum value
|
||||
/// </summary>
|
||||
public const ushort DevicePlatformValueChange = 5;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort UshortValueChange = 101;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort StringValueChange = 201;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort FullPathToArrayChange = 202;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ActualFilePathChange = 203;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort FilenameResolvedChange = 204;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort FilePathResolvedChange = 205;
|
||||
|
||||
/// <summary>
|
||||
/// Reports the root directory change
|
||||
/// </summary>
|
||||
public const ushort RootDirectoryChange = 206;
|
||||
/// <summary>
|
||||
/// Reports the root directory change
|
||||
/// </summary>
|
||||
public const ushort RootDirectoryChange = 206;
|
||||
|
||||
/// <summary>
|
||||
/// Reports the room ID change
|
||||
/// </summary>
|
||||
public const ushort RoomIdChange = 207;
|
||||
/// <summary>
|
||||
/// Reports the room ID change
|
||||
/// </summary>
|
||||
public const ushort RoomIdChange = 207;
|
||||
|
||||
/// <summary>
|
||||
/// Reports the room name change
|
||||
/// </summary>
|
||||
public const ushort RoomNameChange = 208;
|
||||
/// <summary>
|
||||
/// Reports the room name change
|
||||
/// </summary>
|
||||
public const ushort RoomNameChange = 208;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -88,33 +88,33 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
/// </summary>
|
||||
public class SPlusValueWrapper
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public SPlusType ValueType { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Index { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort BoolUShortValue { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string StringValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public SPlusValueWrapper() {}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="index"></param>
|
||||
public SPlusValueWrapper(SPlusType type, ushort index)
|
||||
{
|
||||
ValueType = type;
|
||||
@@ -127,17 +127,16 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
/// </summary>
|
||||
public enum SPlusType
|
||||
{
|
||||
/// <summary>
|
||||
/// Digital
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Digital
|
||||
/// </summary>
|
||||
Digital,
|
||||
/// <summary>
|
||||
/// Analog
|
||||
/// </summary>
|
||||
Analog,
|
||||
/// <summary>
|
||||
/// String
|
||||
/// </summary>
|
||||
String
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Analog
|
||||
/// </summary>
|
||||
Analog,
|
||||
/// <summary>
|
||||
/// String
|
||||
/// </summary>
|
||||
String
|
||||
}
|
||||
@@ -7,11 +7,11 @@ using Serilog.Events;
|
||||
|
||||
//using PepperDash.Core;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
/// <summary>
|
||||
/// The global class to manage all the instances of JsonToSimplMaster
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// The global class to manage all the instances of JsonToSimplMaster
|
||||
/// </summary>
|
||||
public class J2SGlobal
|
||||
{
|
||||
static List<JsonToSimplMaster> Masters = new List<JsonToSimplMaster>();
|
||||
@@ -22,7 +22,7 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
/// master, this will fail
|
||||
/// </summary>
|
||||
/// <param name="master">New master to add</param>
|
||||
///
|
||||
///
|
||||
public static void AddMaster(JsonToSimplMaster master)
|
||||
{
|
||||
if (master == null)
|
||||
@@ -56,5 +56,4 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
return Masters.FirstOrDefault(m => m.UniqueID.Equals(file, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,20 @@ using System.Linq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to interact with an array of values with the S+ modules
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// Used to interact with an array of values with the S+ modules
|
||||
/// </summary>
|
||||
public class JsonToSimplArrayLookupChild : JsonToSimplChildObjectBase
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string SearchPropertyName { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string SearchPropertyValue { get; set; }
|
||||
|
||||
int ArrayIndex;
|
||||
@@ -76,9 +76,9 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
PathSuffix == null ? "" : PathSuffix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Process all values
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Process all values
|
||||
/// </summary>
|
||||
public override void ProcessAll()
|
||||
{
|
||||
if (FindInArray())
|
||||
@@ -158,5 +158,4 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,29 +3,29 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
/// <summary>
|
||||
/// Base class for JSON objects
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for JSON objects
|
||||
/// </summary>
|
||||
public abstract class JsonToSimplChildObjectBase : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Notifies of bool change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of bool change
|
||||
/// </summary>
|
||||
public event EventHandler<BoolChangeEventArgs> BoolChange;
|
||||
/// <summary>
|
||||
/// Notifies of ushort change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of ushort change
|
||||
/// </summary>
|
||||
public event EventHandler<UshrtChangeEventArgs> UShortChange;
|
||||
/// <summary>
|
||||
/// Notifies of string change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of string change
|
||||
/// </summary>
|
||||
public event EventHandler<StringChangeEventArgs> StringChange;
|
||||
|
||||
/// <summary>
|
||||
/// Delegate to get all values
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Delegate to get all values
|
||||
/// </summary>
|
||||
public SPlusValuesDelegate GetAllValuesDelegate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -33,9 +33,9 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
/// </summary>
|
||||
public SPlusValuesDelegate SetAllPathsDelegate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Unique identifier for instance
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Unique identifier for instance
|
||||
/// </summary>
|
||||
public string Key { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -49,33 +49,33 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
/// </summary>
|
||||
public string PathSuffix { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates if the instance is linked to an object
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Indicates if the instance is linked to an object
|
||||
/// </summary>
|
||||
public bool LinkedToObject { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Reference to Master instance
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Reference to Master instance
|
||||
/// </summary>
|
||||
protected JsonToSimplMaster Master;
|
||||
|
||||
/// <summary>
|
||||
/// Paths to boolean values in JSON structure
|
||||
/// </summary>
|
||||
protected Dictionary<ushort, string> BoolPaths = new Dictionary<ushort, string>();
|
||||
/// <summary>
|
||||
/// Paths to numeric values in JSON structure
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Paths to boolean values in JSON structure
|
||||
/// </summary>
|
||||
protected Dictionary<ushort, string> BoolPaths = new Dictionary<ushort, string>();
|
||||
/// <summary>
|
||||
/// Paths to numeric values in JSON structure
|
||||
/// </summary>
|
||||
protected Dictionary<ushort, string> UshortPaths = new Dictionary<ushort, string>();
|
||||
/// <summary>
|
||||
/// Paths to string values in JSON structure
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Paths to string values in JSON structure
|
||||
/// </summary>
|
||||
protected Dictionary<ushort, string> StringPaths = new Dictionary<ushort, string>();
|
||||
|
||||
/// <summary>
|
||||
/// Call this before doing anything else
|
||||
/// </summary>
|
||||
/// <param name="masterUniqueId"></param>
|
||||
/// <param name="masterUniqueId"></param>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pathPrefix"></param>
|
||||
/// <param name="pathSuffix"></param>
|
||||
@@ -92,10 +92,10 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
Debug.Console(1, "JSON Child [{0}] cannot link to master {1}", key, masterUniqueId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the path prefix for the object
|
||||
/// </summary>
|
||||
/// <param name="pathPrefix"></param>
|
||||
/// <summary>
|
||||
/// Sets the path prefix for the object
|
||||
/// </summary>
|
||||
/// <param name="pathPrefix"></param>
|
||||
public void SetPathPrefix(string pathPrefix)
|
||||
{
|
||||
PathPrefix = pathPrefix;
|
||||
@@ -170,18 +170,18 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
}
|
||||
|
||||
// Processes the path to a ushort, converting to ushort if able, twos complement if necessary, firing off UshrtChange event
|
||||
void ProcessUshortPath(ushort index) {
|
||||
string response;
|
||||
if (Process(UshortPaths[index], out response)) {
|
||||
ushort val;
|
||||
try { val = Convert.ToInt32(response) < 0 ? (ushort)(Convert.ToInt16(response) + 65536) : Convert.ToUInt16(response); }
|
||||
catch { val = 0; }
|
||||
void ProcessUshortPath(ushort index) {
|
||||
string response;
|
||||
if (Process(UshortPaths[index], out response)) {
|
||||
ushort val;
|
||||
try { val = Convert.ToInt32(response) < 0 ? (ushort)(Convert.ToInt16(response) + 65536) : Convert.ToUInt16(response); }
|
||||
catch { val = 0; }
|
||||
|
||||
OnUShortChange(val, index, JsonToSimplConstants.UshortValueChange);
|
||||
}
|
||||
else { }
|
||||
// OnUShortChange(0, index, JsonToSimplConstants.UshortValueChange);
|
||||
OnUShortChange(val, index, JsonToSimplConstants.UshortValueChange);
|
||||
}
|
||||
else { }
|
||||
// OnUShortChange(0, index, JsonToSimplConstants.UshortValueChange);
|
||||
}
|
||||
|
||||
// Processes the path to a string property and fires of a StringChange event.
|
||||
void ProcessStringPath(ushort index)
|
||||
@@ -272,54 +272,54 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
GetAllValuesDelegate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
public void USetBoolValue(ushort key, ushort theValue)
|
||||
{
|
||||
SetBoolValue(key, theValue == 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
public void SetBoolValue(ushort key, bool theValue)
|
||||
{
|
||||
if (BoolPaths.ContainsKey(key))
|
||||
SetValueOnMaster(BoolPaths[key], new JValue(theValue));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
public void SetUShortValue(ushort key, ushort theValue)
|
||||
{
|
||||
if (UshortPaths.ContainsKey(key))
|
||||
SetValueOnMaster(UshortPaths[key], new JValue(theValue));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="theValue"></param>
|
||||
public void SetStringValue(ushort key, string theValue)
|
||||
{
|
||||
if (StringPaths.ContainsKey(key))
|
||||
SetValueOnMaster(StringPaths[key], new JValue(theValue));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="keyPath"></param>
|
||||
/// <param name="valueToSave"></param>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="keyPath"></param>
|
||||
/// <param name="valueToSave"></param>
|
||||
public void SetValueOnMaster(string keyPath, JValue valueToSave)
|
||||
{
|
||||
var path = GetFullPath(keyPath);
|
||||
@@ -349,12 +349,12 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
|
||||
// Helpers for events
|
||||
//******************************************************************************************
|
||||
/// <summary>
|
||||
/// Event helper
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <summary>
|
||||
/// Event helper
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnBoolChange(bool state, ushort index, ushort type)
|
||||
{
|
||||
var handler = BoolChange;
|
||||
@@ -367,12 +367,12 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
}
|
||||
|
||||
//******************************************************************************************
|
||||
/// <summary>
|
||||
/// Event helper
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <summary>
|
||||
/// Event helper
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnUShortChange(ushort state, ushort index, ushort type)
|
||||
{
|
||||
var handler = UShortChange;
|
||||
@@ -384,12 +384,12 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event helper
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <summary>
|
||||
/// Event helper
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnStringChange(string value, ushort index, ushort type)
|
||||
{
|
||||
var handler = StringChange;
|
||||
@@ -400,5 +400,4 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
StringChange(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,287 +1,286 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a JSON file that can be read and written to
|
||||
/// </summary>
|
||||
public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a JSON file that can be read and written to
|
||||
/// Sets the filepath as well as registers this with the Global.Masters list
|
||||
/// </summary>
|
||||
public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
public string Filepath { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Filepath to the actual file that will be read (Portal or local)
|
||||
/// </summary>
|
||||
public string ActualFilePath { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Filename { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string FilePathName { get; private set; }
|
||||
|
||||
/*****************************************************************************************/
|
||||
/** Privates **/
|
||||
|
||||
|
||||
// The JSON file in JObject form
|
||||
// For gathering the incoming data
|
||||
object StringBuilderLock = new object();
|
||||
// To prevent multiple same-file access
|
||||
static object FileLock = new object();
|
||||
|
||||
/*****************************************************************************************/
|
||||
|
||||
/// <summary>
|
||||
/// SIMPL+ default constructor.
|
||||
/// </summary>
|
||||
public JsonToSimplFileMaster()
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets the filepath as well as registers this with the Global.Masters list
|
||||
/// </summary>
|
||||
public string Filepath { get; private set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filepath to the actual file that will be read (Portal or local)
|
||||
/// </summary>
|
||||
public string ActualFilePath { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Filename { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string FilePathName { get; private set; }
|
||||
|
||||
/*****************************************************************************************/
|
||||
/** Privates **/
|
||||
|
||||
|
||||
// The JSON file in JObject form
|
||||
// For gathering the incoming data
|
||||
object StringBuilderLock = new object();
|
||||
// To prevent multiple same-file access
|
||||
static object FileLock = new object();
|
||||
|
||||
/*****************************************************************************************/
|
||||
|
||||
/// <summary>
|
||||
/// SIMPL+ default constructor.
|
||||
/// </summary>
|
||||
public JsonToSimplFileMaster()
|
||||
/// <summary>
|
||||
/// Read, evaluate and udpate status
|
||||
/// </summary>
|
||||
public void EvaluateFile(string filepath)
|
||||
{
|
||||
try
|
||||
{
|
||||
}
|
||||
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
|
||||
/// <summary>
|
||||
/// Read, evaluate and udpate status
|
||||
/// </summary>
|
||||
public void EvaluateFile(string filepath)
|
||||
{
|
||||
try
|
||||
var dirSeparator = Path.DirectorySeparatorChar;
|
||||
var dirSeparatorAlt = Path.AltDirectorySeparatorChar;
|
||||
|
||||
var series = CrestronEnvironment.ProgramCompatibility;
|
||||
|
||||
var is3Series = (eCrestronSeries.Series3 == (series & eCrestronSeries.Series3));
|
||||
OnBoolChange(is3Series, 0,
|
||||
JsonToSimplConstants.ProgramCompatibility3SeriesChange);
|
||||
|
||||
var is4Series = (eCrestronSeries.Series4 == (series & eCrestronSeries.Series4));
|
||||
OnBoolChange(is4Series, 0,
|
||||
JsonToSimplConstants.ProgramCompatibility4SeriesChange);
|
||||
|
||||
var isServer = CrestronEnvironment.DevicePlatform == eDevicePlatform.Server;
|
||||
OnBoolChange(isServer, 0,
|
||||
JsonToSimplConstants.DevicePlatformValueChange);
|
||||
|
||||
// get the roomID
|
||||
var roomId = Crestron.SimplSharp.InitialParametersClass.RoomId;
|
||||
if (!string.IsNullOrEmpty(roomId))
|
||||
{
|
||||
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
OnStringChange(roomId, 0, JsonToSimplConstants.RoomIdChange);
|
||||
}
|
||||
|
||||
var dirSeparator = Path.DirectorySeparatorChar;
|
||||
var dirSeparatorAlt = Path.AltDirectorySeparatorChar;
|
||||
// get the roomName
|
||||
var roomName = Crestron.SimplSharp.InitialParametersClass.RoomName;
|
||||
if (!string.IsNullOrEmpty(roomName))
|
||||
{
|
||||
OnStringChange(roomName, 0, JsonToSimplConstants.RoomNameChange);
|
||||
}
|
||||
|
||||
var series = CrestronEnvironment.ProgramCompatibility;
|
||||
var rootDirectory = Directory.GetCurrentDirectory();
|
||||
OnStringChange(rootDirectory, 0, JsonToSimplConstants.RootDirectoryChange);
|
||||
|
||||
var is3Series = (eCrestronSeries.Series3 == (series & eCrestronSeries.Series3));
|
||||
OnBoolChange(is3Series, 0,
|
||||
JsonToSimplConstants.ProgramCompatibility3SeriesChange);
|
||||
var splusPath = string.Empty;
|
||||
if (Regex.IsMatch(filepath, @"user", RegexOptions.IgnoreCase))
|
||||
{
|
||||
if (is4Series)
|
||||
splusPath = Regex.Replace(filepath, "user", "user", RegexOptions.IgnoreCase);
|
||||
else if (isServer)
|
||||
splusPath = Regex.Replace(filepath, "user", "User", RegexOptions.IgnoreCase);
|
||||
else
|
||||
splusPath = filepath;
|
||||
}
|
||||
|
||||
var is4Series = (eCrestronSeries.Series4 == (series & eCrestronSeries.Series4));
|
||||
OnBoolChange(is4Series, 0,
|
||||
JsonToSimplConstants.ProgramCompatibility4SeriesChange);
|
||||
filepath = splusPath.Replace(dirSeparatorAlt, dirSeparator);
|
||||
|
||||
var isServer = CrestronEnvironment.DevicePlatform == eDevicePlatform.Server;
|
||||
OnBoolChange(isServer, 0,
|
||||
JsonToSimplConstants.DevicePlatformValueChange);
|
||||
Filepath = string.Format("{1}{0}{2}", dirSeparator, rootDirectory,
|
||||
filepath.TrimStart(dirSeparator, dirSeparatorAlt));
|
||||
|
||||
// get the roomID
|
||||
var roomId = Crestron.SimplSharp.InitialParametersClass.RoomId;
|
||||
if (!string.IsNullOrEmpty(roomId))
|
||||
OnStringChange(string.Format("Attempting to evaluate {0}", Filepath), 0, JsonToSimplConstants.StringValueChange);
|
||||
|
||||
if (string.IsNullOrEmpty(Filepath))
|
||||
{
|
||||
OnStringChange(string.Format("Cannot evaluate file. JSON file path not set"), 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set");
|
||||
return;
|
||||
}
|
||||
|
||||
// get file directory and name to search
|
||||
var fileDirectory = Path.GetDirectoryName(Filepath);
|
||||
var fileName = Path.GetFileName(Filepath);
|
||||
|
||||
OnStringChange(string.Format("Checking '{0}' for '{1}'", fileDirectory, fileName), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "Checking '{0}' for '{1}'", fileDirectory, fileName);
|
||||
|
||||
if (Directory.Exists(fileDirectory))
|
||||
{
|
||||
// get the directory info
|
||||
var directoryInfo = new DirectoryInfo(fileDirectory);
|
||||
|
||||
// get the file to be read
|
||||
var actualFile = directoryInfo.GetFiles(fileName).FirstOrDefault();
|
||||
if (actualFile == null)
|
||||
{
|
||||
OnStringChange(roomId, 0, JsonToSimplConstants.RoomIdChange);
|
||||
}
|
||||
|
||||
// get the roomName
|
||||
var roomName = Crestron.SimplSharp.InitialParametersClass.RoomName;
|
||||
if (!string.IsNullOrEmpty(roomName))
|
||||
{
|
||||
OnStringChange(roomName, 0, JsonToSimplConstants.RoomNameChange);
|
||||
}
|
||||
|
||||
var rootDirectory = Directory.GetApplicationRootDirectory();
|
||||
OnStringChange(rootDirectory, 0, JsonToSimplConstants.RootDirectoryChange);
|
||||
|
||||
var splusPath = string.Empty;
|
||||
if (Regex.IsMatch(filepath, @"user", RegexOptions.IgnoreCase))
|
||||
{
|
||||
if (is4Series)
|
||||
splusPath = Regex.Replace(filepath, "user", "user", RegexOptions.IgnoreCase);
|
||||
else if (isServer)
|
||||
splusPath = Regex.Replace(filepath, "user", "User", RegexOptions.IgnoreCase);
|
||||
else
|
||||
splusPath = filepath;
|
||||
}
|
||||
|
||||
filepath = splusPath.Replace(dirSeparatorAlt, dirSeparator);
|
||||
|
||||
Filepath = string.Format("{1}{0}{2}", dirSeparator, rootDirectory,
|
||||
filepath.TrimStart(dirSeparator, dirSeparatorAlt));
|
||||
|
||||
OnStringChange(string.Format("Attempting to evaluate {0}", Filepath), 0, JsonToSimplConstants.StringValueChange);
|
||||
|
||||
if (string.IsNullOrEmpty(Filepath))
|
||||
{
|
||||
OnStringChange(string.Format("Cannot evaluate file. JSON file path not set"), 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set");
|
||||
var msg = string.Format("JSON file not found: {0}", Filepath);
|
||||
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
return;
|
||||
}
|
||||
|
||||
// get file directory and name to search
|
||||
var fileDirectory = Path.GetDirectoryName(Filepath);
|
||||
var fileName = Path.GetFileName(Filepath);
|
||||
// \xSE\xR\PDT000-Template_Main_Config-Combined_DSP_v00.02.json
|
||||
// \USER\PDT000-Template_Main_Config-Combined_DSP_v00.02.json
|
||||
ActualFilePath = actualFile.FullName;
|
||||
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
|
||||
OnStringChange(string.Format("Actual JSON file is {0}", ActualFilePath), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "Actual JSON file is {0}", ActualFilePath);
|
||||
|
||||
OnStringChange(string.Format("Checking '{0}' for '{1}'", fileDirectory, fileName), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "Checking '{0}' for '{1}'", fileDirectory, fileName);
|
||||
|
||||
if (Directory.Exists(fileDirectory))
|
||||
{
|
||||
// get the directory info
|
||||
var directoryInfo = new DirectoryInfo(fileDirectory);
|
||||
|
||||
// get the file to be read
|
||||
var actualFile = directoryInfo.GetFiles(fileName).FirstOrDefault();
|
||||
if (actualFile == null)
|
||||
{
|
||||
var msg = string.Format("JSON file not found: {0}", Filepath);
|
||||
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
return;
|
||||
}
|
||||
|
||||
// \xSE\xR\PDT000-Template_Main_Config-Combined_DSP_v00.02.json
|
||||
// \USER\PDT000-Template_Main_Config-Combined_DSP_v00.02.json
|
||||
ActualFilePath = actualFile.FullName;
|
||||
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
|
||||
OnStringChange(string.Format("Actual JSON file is {0}", ActualFilePath), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "Actual JSON file is {0}", ActualFilePath);
|
||||
|
||||
Filename = actualFile.Name;
|
||||
OnStringChange(Filename, 0, JsonToSimplConstants.FilenameResolvedChange);
|
||||
OnStringChange(string.Format("JSON Filename is {0}", Filename), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "JSON Filename is {0}", Filename);
|
||||
Filename = actualFile.Name;
|
||||
OnStringChange(Filename, 0, JsonToSimplConstants.FilenameResolvedChange);
|
||||
OnStringChange(string.Format("JSON Filename is {0}", Filename), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "JSON Filename is {0}", Filename);
|
||||
|
||||
|
||||
FilePathName = string.Format(@"{0}{1}", actualFile.DirectoryName, dirSeparator);
|
||||
OnStringChange(string.Format(@"{0}", actualFile.DirectoryName), 0, JsonToSimplConstants.FilePathResolvedChange);
|
||||
OnStringChange(string.Format(@"JSON File Path is {0}", actualFile.DirectoryName), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "JSON File Path is {0}", FilePathName);
|
||||
FilePathName = string.Format(@"{0}{1}", actualFile.DirectoryName, dirSeparator);
|
||||
OnStringChange(string.Format(@"{0}", actualFile.DirectoryName), 0, JsonToSimplConstants.FilePathResolvedChange);
|
||||
OnStringChange(string.Format(@"JSON File Path is {0}", actualFile.DirectoryName), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "JSON File Path is {0}", FilePathName);
|
||||
|
||||
var json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);
|
||||
var json = File.ReadAllText(ActualFilePath, System.Text.Encoding.ASCII);
|
||||
|
||||
JsonObject = JObject.Parse(json);
|
||||
foreach (var child in Children)
|
||||
child.ProcessAll();
|
||||
JsonObject = JObject.Parse(json);
|
||||
foreach (var child in Children)
|
||||
child.ProcessAll();
|
||||
|
||||
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
}
|
||||
else
|
||||
{
|
||||
OnStringChange(string.Format("'{0}' not found", fileDirectory), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "'{0}' not found", fileDirectory);
|
||||
}
|
||||
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
}
|
||||
catch (Exception e)
|
||||
else
|
||||
{
|
||||
var msg = string.Format("EvaluateFile Exception: Message\r{0}", e.Message);
|
||||
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
|
||||
var stackTrace = string.Format("EvaluateFile: Stack Trace\r{0}", e.StackTrace);
|
||||
OnStringChange(stackTrace, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(stackTrace);
|
||||
ErrorLog.Error(stackTrace);
|
||||
OnStringChange(string.Format("'{0}' not found", fileDirectory), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "'{0}' not found", fileDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets the debug level
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
public void setDebugLevel(uint level)
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.SetDebugLevel(level);
|
||||
var msg = string.Format("EvaluateFile Exception: Message\r{0}", e.Message);
|
||||
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
|
||||
var stackTrace = string.Format("EvaluateFile: Stack Trace\r{0}", e.StackTrace);
|
||||
OnStringChange(stackTrace, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(stackTrace);
|
||||
ErrorLog.Error(stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets the debug level
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
public void setDebugLevel(uint level)
|
||||
{
|
||||
Debug.SetDebugLevel(level);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the values to the file
|
||||
/// </summary>
|
||||
public override void Save()
|
||||
{
|
||||
// this code is duplicated in the other masters!!!!!!!!!!!!!
|
||||
UnsavedValues = new Dictionary<string, JValue>();
|
||||
// Make each child update their values into master object
|
||||
foreach (var child in Children)
|
||||
{
|
||||
Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key);
|
||||
child.UpdateInputsForMaster();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the values to the file
|
||||
/// </summary>
|
||||
public override void Save()
|
||||
if (UnsavedValues == null || UnsavedValues.Count == 0)
|
||||
{
|
||||
// this code is duplicated in the other masters!!!!!!!!!!!!!
|
||||
UnsavedValues = new Dictionary<string, JValue>();
|
||||
// Make each child update their values into master object
|
||||
foreach (var child in Children)
|
||||
Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID);
|
||||
return;
|
||||
}
|
||||
lock (FileLock)
|
||||
{
|
||||
Debug.Console(1, "Saving");
|
||||
foreach (var path in UnsavedValues.Keys)
|
||||
{
|
||||
Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key);
|
||||
child.UpdateInputsForMaster();
|
||||
}
|
||||
|
||||
if (UnsavedValues == null || UnsavedValues.Count == 0)
|
||||
{
|
||||
Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID);
|
||||
return;
|
||||
}
|
||||
lock (FileLock)
|
||||
{
|
||||
Debug.Console(1, "Saving");
|
||||
foreach (var path in UnsavedValues.Keys)
|
||||
{
|
||||
var tokenToReplace = JsonObject.SelectToken(path);
|
||||
if (tokenToReplace != null)
|
||||
{// It's found
|
||||
tokenToReplace.Replace(UnsavedValues[path]);
|
||||
Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path);
|
||||
}
|
||||
else // No token. Let's make one
|
||||
{
|
||||
//http://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net
|
||||
Debug.Console(1, "JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
|
||||
|
||||
// JContainer jpart = JsonObject;
|
||||
// // walk down the path and find where it goes
|
||||
//#warning Does not handle arrays.
|
||||
// foreach (var part in path.Split('.'))
|
||||
// {
|
||||
|
||||
// var openPos = part.IndexOf('[');
|
||||
// if (openPos > -1)
|
||||
// {
|
||||
// openPos++; // move to number
|
||||
// var closePos = part.IndexOf(']');
|
||||
// var arrayName = part.Substring(0, openPos - 1); // get the name
|
||||
// var index = Convert.ToInt32(part.Substring(openPos, closePos - openPos));
|
||||
|
||||
// // Check if the array itself exists and add the item if so
|
||||
// if (jpart[arrayName] != null)
|
||||
// {
|
||||
// var arrayObj = jpart[arrayName] as JArray;
|
||||
// var item = arrayObj[index];
|
||||
// if (item == null)
|
||||
// arrayObj.Add(new JObject());
|
||||
// }
|
||||
|
||||
// Debug.Console(0, "IGNORING MISSING ARRAY VALUE FOR NOW");
|
||||
// continue;
|
||||
// }
|
||||
// // Build the
|
||||
// if (jpart[part] == null)
|
||||
// jpart.Add(new JProperty(part, new JObject()));
|
||||
// jpart = jpart[part] as JContainer;
|
||||
// }
|
||||
// jpart.Replace(UnsavedValues[path]);
|
||||
}
|
||||
var tokenToReplace = JsonObject.SelectToken(path);
|
||||
if (tokenToReplace != null)
|
||||
{// It's found
|
||||
tokenToReplace.Replace(UnsavedValues[path]);
|
||||
Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path);
|
||||
}
|
||||
using (StreamWriter sw = new StreamWriter(ActualFilePath))
|
||||
else // No token. Let's make one
|
||||
{
|
||||
try
|
||||
{
|
||||
sw.Write(JsonObject.ToString());
|
||||
sw.Flush();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string err = string.Format("Error writing JSON file:\r{0}", e);
|
||||
Debug.Console(0, err);
|
||||
ErrorLog.Warn(err);
|
||||
return;
|
||||
}
|
||||
//http://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net
|
||||
Debug.Console(1, "JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
|
||||
|
||||
// JContainer jpart = JsonObject;
|
||||
// // walk down the path and find where it goes
|
||||
//#warning Does not handle arrays.
|
||||
// foreach (var part in path.Split('.'))
|
||||
// {
|
||||
|
||||
// var openPos = part.IndexOf('[');
|
||||
// if (openPos > -1)
|
||||
// {
|
||||
// openPos++; // move to number
|
||||
// var closePos = part.IndexOf(']');
|
||||
// var arrayName = part.Substring(0, openPos - 1); // get the name
|
||||
// var index = Convert.ToInt32(part.Substring(openPos, closePos - openPos));
|
||||
|
||||
// // Check if the array itself exists and add the item if so
|
||||
// if (jpart[arrayName] != null)
|
||||
// {
|
||||
// var arrayObj = jpart[arrayName] as JArray;
|
||||
// var item = arrayObj[index];
|
||||
// if (item == null)
|
||||
// arrayObj.Add(new JObject());
|
||||
// }
|
||||
|
||||
// Debug.Console(0, "IGNORING MISSING ARRAY VALUE FOR NOW");
|
||||
// continue;
|
||||
// }
|
||||
// // Build the
|
||||
// if (jpart[part] == null)
|
||||
// jpart.Add(new JProperty(part, new JObject()));
|
||||
// jpart = jpart[part] as JContainer;
|
||||
// }
|
||||
// jpart.Replace(UnsavedValues[path]);
|
||||
}
|
||||
}
|
||||
using (StreamWriter sw = new StreamWriter(ActualFilePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
sw.Write(JsonObject.ToString());
|
||||
sw.Flush();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string err = string.Format("Error writing JSON file:\r{0}", e);
|
||||
Debug.Console(0, err);
|
||||
ErrorLog.Warn(err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class JsonToSimplFixedPathObject : JsonToSimplChildObjectBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public JsonToSimplFixedPathObject()
|
||||
{
|
||||
this.LinkedToObject = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,35 +3,35 @@ using System.Collections.Generic;
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
/// <summary>
|
||||
/// Generic Master
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// Generic Master
|
||||
/// </summary>
|
||||
public class JsonToSimplGenericMaster : JsonToSimplMaster
|
||||
{
|
||||
{
|
||||
/*****************************************************************************************/
|
||||
/** Privates **/
|
||||
|
||||
|
||||
|
||||
// The JSON file in JObject form
|
||||
// For gathering the incoming data
|
||||
object StringBuilderLock = new object();
|
||||
// To prevent multiple same-file access
|
||||
static object WriteLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Callback action for saving
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Callback action for saving
|
||||
/// </summary>
|
||||
public Action<string> SaveCallback { get; set; }
|
||||
|
||||
/*****************************************************************************************/
|
||||
|
||||
/// <summary>
|
||||
/// SIMPL+ default constructor.
|
||||
/// </summary>
|
||||
/// SIMPL+ default constructor.
|
||||
/// </summary>
|
||||
public JsonToSimplGenericMaster()
|
||||
{
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -78,7 +78,7 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
public override void Save()
|
||||
{
|
||||
// this code is duplicated in the other masters!!!!!!!!!!!!!
|
||||
UnsavedValues = new Dictionary<string, JValue>();
|
||||
UnsavedValues = new Dictionary<string, JValue>();
|
||||
// Make each child update their values into master object
|
||||
foreach (var child in Children)
|
||||
{
|
||||
@@ -114,5 +114,4 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
else
|
||||
Debug.Console(0, this, "WARNING: No save callback defined.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,33 +2,32 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
{
|
||||
/// <summary>
|
||||
/// Abstract base class for JsonToSimpl interactions
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// Abstract base class for JsonToSimpl interactions
|
||||
/// </summary>
|
||||
public abstract class JsonToSimplMaster : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Notifies of bool change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of bool change
|
||||
/// </summary>
|
||||
public event EventHandler<BoolChangeEventArgs> BoolChange;
|
||||
/// <summary>
|
||||
/// Notifies of ushort change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of ushort change
|
||||
/// </summary>
|
||||
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
|
||||
/// <summary>
|
||||
/// Notifies of string change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of string change
|
||||
/// </summary>
|
||||
public event EventHandler<StringChangeEventArgs> StringChange;
|
||||
|
||||
/// <summary>
|
||||
/// A collection of associated child modules
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// A collection of associated child modules
|
||||
/// </summary>
|
||||
protected List<JsonToSimplChildObjectBase> Children = new List<JsonToSimplChildObjectBase>();
|
||||
|
||||
/*****************************************************************************************/
|
||||
@@ -38,9 +37,9 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
/// </summary>
|
||||
public string Key { get { return UniqueID; } }
|
||||
|
||||
/// <summary>
|
||||
/// A unique ID
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// A unique ID
|
||||
/// </summary>
|
||||
public string UniqueID { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -83,9 +82,9 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public JObject JsonObject { get; protected set; }
|
||||
|
||||
/*****************************************************************************************/
|
||||
@@ -142,9 +141,9 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
//Debug.Console(0, "Master[{0}] Unsaved size={1}", UniqueID, UnsavedValues.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the file
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Saves the file
|
||||
/// </summary>
|
||||
public abstract void Save();
|
||||
|
||||
|
||||
@@ -153,18 +152,14 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
/// </summary>
|
||||
public static class JsonFixes
|
||||
{
|
||||
/// <summary>
|
||||
/// Deserializes a string into a JObject
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// Deserializes a string into a JObject
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
/// <returns></returns>
|
||||
public static JObject ParseObject(string 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
|
||||
using (var reader = new JsonTextReader(new StringReader(json)))
|
||||
{
|
||||
var startDepth = reader.Depth;
|
||||
var obj = JObject.Load(reader);
|
||||
@@ -174,18 +169,15 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes a string into a JArray
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// Deserializes a string into a JArray
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
/// <returns></returns>
|
||||
public static JArray ParseArray(string 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
|
||||
|
||||
using (var reader = new JsonTextReader(new StringReader(json)))
|
||||
{
|
||||
var startDepth = reader.Depth;
|
||||
var obj = JArray.Load(reader);
|
||||
@@ -228,12 +220,12 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper event
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <summary>
|
||||
/// Helper event
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnStringChange(string value, ushort index, ushort type)
|
||||
{
|
||||
if (StringChange != null)
|
||||
@@ -244,4 +236,3 @@ namespace PepperDash.Core.JsonToSimpl
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,189 +1,188 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using PepperDash.Core.Config;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
/// <summary>
|
||||
/// Portal File Master
|
||||
/// </summary>
|
||||
public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Portal File Master
|
||||
/// </summary>
|
||||
public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets the filepath as well as registers this with the Global.Masters list
|
||||
/// </summary>
|
||||
public string PortalFilepath { get; private set; }
|
||||
/// <summary>
|
||||
/// Sets the filepath as well as registers this with the Global.Masters list
|
||||
/// </summary>
|
||||
public string PortalFilepath { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// File path of the actual file being read (Portal or local)
|
||||
/// </summary>
|
||||
public string ActualFilePath { get; private set; }
|
||||
/// <summary>
|
||||
/// File path of the actual file being read (Portal or local)
|
||||
/// </summary>
|
||||
public string ActualFilePath { get; private set; }
|
||||
|
||||
/*****************************************************************************************/
|
||||
/** Privates **/
|
||||
/*****************************************************************************************/
|
||||
/** Privates **/
|
||||
|
||||
// To prevent multiple same-file access
|
||||
object StringBuilderLock = new object();
|
||||
static object FileLock = new object();
|
||||
// To prevent multiple same-file access
|
||||
object StringBuilderLock = new object();
|
||||
static object FileLock = new object();
|
||||
|
||||
/*****************************************************************************************/
|
||||
/*****************************************************************************************/
|
||||
|
||||
/// <summary>
|
||||
/// SIMPL+ default constructor.
|
||||
/// </summary>
|
||||
public JsonToSimplPortalFileMaster()
|
||||
{
|
||||
/// <summary>
|
||||
/// SIMPL+ default constructor.
|
||||
/// </summary>
|
||||
public JsonToSimplPortalFileMaster()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read, evaluate and udpate status
|
||||
/// </summary>
|
||||
public void EvaluateFile(string portalFilepath)
|
||||
{
|
||||
PortalFilepath = portalFilepath;
|
||||
|
||||
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
if (string.IsNullOrEmpty(PortalFilepath))
|
||||
{
|
||||
CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set");
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read, evaluate and udpate status
|
||||
/// </summary>
|
||||
public void EvaluateFile(string portalFilepath)
|
||||
// Resolve possible wildcarded filename
|
||||
|
||||
// If the portal file is xyz.json, then
|
||||
// the file we want to check for first will be called xyz.local.json
|
||||
var localFilepath = Path.ChangeExtension(PortalFilepath, "local.json");
|
||||
Debug.Console(0, this, "Checking for local file {0}", localFilepath);
|
||||
var actualLocalFile = GetActualFileInfoFromPath(localFilepath);
|
||||
|
||||
if (actualLocalFile != null)
|
||||
{
|
||||
PortalFilepath = portalFilepath;
|
||||
|
||||
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
if (string.IsNullOrEmpty(PortalFilepath))
|
||||
ActualFilePath = actualLocalFile.FullName;
|
||||
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
|
||||
}
|
||||
// If the local file does not exist, then read the portal file xyz.json
|
||||
// and create the local.
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Local JSON file not found {0}\rLoading portal JSON file", localFilepath);
|
||||
var actualPortalFile = GetActualFileInfoFromPath(portalFilepath);
|
||||
if (actualPortalFile != null)
|
||||
{
|
||||
CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set");
|
||||
return;
|
||||
var newLocalPath = Path.ChangeExtension(actualPortalFile.FullName, "local.json");
|
||||
// got the portal file, hand off to the merge / save method
|
||||
PortalConfigReader.ReadAndMergeFileIfNecessary(actualPortalFile.FullName, newLocalPath);
|
||||
ActualFilePath = newLocalPath;
|
||||
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
|
||||
}
|
||||
|
||||
// Resolve possible wildcarded filename
|
||||
|
||||
// If the portal file is xyz.json, then
|
||||
// the file we want to check for first will be called xyz.local.json
|
||||
var localFilepath = Path.ChangeExtension(PortalFilepath, "local.json");
|
||||
Debug.Console(0, this, "Checking for local file {0}", localFilepath);
|
||||
var actualLocalFile = GetActualFileInfoFromPath(localFilepath);
|
||||
|
||||
if (actualLocalFile != null)
|
||||
{
|
||||
ActualFilePath = actualLocalFile.FullName;
|
||||
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
|
||||
}
|
||||
// If the local file does not exist, then read the portal file xyz.json
|
||||
// and create the local.
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Local JSON file not found {0}\rLoading portal JSON file", localFilepath);
|
||||
var actualPortalFile = GetActualFileInfoFromPath(portalFilepath);
|
||||
if (actualPortalFile != null)
|
||||
{
|
||||
var newLocalPath = Path.ChangeExtension(actualPortalFile.FullName, "local.json");
|
||||
// got the portal file, hand off to the merge / save method
|
||||
PortalConfigReader.ReadAndMergeFileIfNecessary(actualPortalFile.FullName, newLocalPath);
|
||||
ActualFilePath = newLocalPath;
|
||||
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
|
||||
}
|
||||
else
|
||||
{
|
||||
var msg = string.Format("Portal JSON file not found: {0}", PortalFilepath);
|
||||
Debug.Console(1, this, msg);
|
||||
ErrorLog.Error(msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// At this point we should have a local file. Do it.
|
||||
Debug.Console(1, "Reading local JSON file {0}", ActualFilePath);
|
||||
|
||||
string json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);
|
||||
|
||||
try
|
||||
{
|
||||
JsonObject = JObject.Parse(json);
|
||||
foreach (var child in Children)
|
||||
child.ProcessAll();
|
||||
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var msg = string.Format("JSON parsing failed:\r{0}", e);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
var msg = string.Format("Portal JSON file not found: {0}", PortalFilepath);
|
||||
Debug.Console(1, this, msg);
|
||||
ErrorLog.Error(msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the FileInfo object for a given path, with possible wildcards
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
FileInfo GetActualFileInfoFromPath(string path)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(path);
|
||||
var localFilename = Path.GetFileName(path);
|
||||
var directory = new DirectoryInfo(dir);
|
||||
// search the directory for the file w/ wildcards
|
||||
return directory.GetFiles(localFilename).FirstOrDefault();
|
||||
}
|
||||
// At this point we should have a local file. Do it.
|
||||
Debug.Console(1, "Reading local JSON file {0}", ActualFilePath);
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
public void setDebugLevel(uint level)
|
||||
{
|
||||
Debug.SetDebugLevel(level);
|
||||
}
|
||||
string json = File.ReadAllText(ActualFilePath, System.Text.Encoding.ASCII);
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override void Save()
|
||||
try
|
||||
{
|
||||
// this code is duplicated in the other masters!!!!!!!!!!!!!
|
||||
UnsavedValues = new Dictionary<string, JValue>();
|
||||
// Make each child update their values into master object
|
||||
JsonObject = JObject.Parse(json);
|
||||
foreach (var child in Children)
|
||||
{
|
||||
Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key);
|
||||
child.UpdateInputsForMaster();
|
||||
}
|
||||
child.ProcessAll();
|
||||
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var msg = string.Format("JSON parsing failed:\r{0}", e);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (UnsavedValues == null || UnsavedValues.Count == 0)
|
||||
/// <summary>
|
||||
/// Returns the FileInfo object for a given path, with possible wildcards
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
FileInfo GetActualFileInfoFromPath(string path)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(path);
|
||||
var localFilename = Path.GetFileName(path);
|
||||
var directory = new DirectoryInfo(dir);
|
||||
// search the directory for the file w/ wildcards
|
||||
return directory.GetFiles(localFilename).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
public void setDebugLevel(uint level)
|
||||
{
|
||||
Debug.SetDebugLevel(level);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override void Save()
|
||||
{
|
||||
// this code is duplicated in the other masters!!!!!!!!!!!!!
|
||||
UnsavedValues = new Dictionary<string, JValue>();
|
||||
// Make each child update their values into master object
|
||||
foreach (var child in Children)
|
||||
{
|
||||
Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key);
|
||||
child.UpdateInputsForMaster();
|
||||
}
|
||||
|
||||
if (UnsavedValues == null || UnsavedValues.Count == 0)
|
||||
{
|
||||
Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID);
|
||||
return;
|
||||
}
|
||||
lock (FileLock)
|
||||
{
|
||||
Debug.Console(1, "Saving");
|
||||
foreach (var path in UnsavedValues.Keys)
|
||||
{
|
||||
Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID);
|
||||
return;
|
||||
}
|
||||
lock (FileLock)
|
||||
{
|
||||
Debug.Console(1, "Saving");
|
||||
foreach (var path in UnsavedValues.Keys)
|
||||
{
|
||||
var tokenToReplace = JsonObject.SelectToken(path);
|
||||
if (tokenToReplace != null)
|
||||
{// It's found
|
||||
tokenToReplace.Replace(UnsavedValues[path]);
|
||||
Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path);
|
||||
}
|
||||
else // No token. Let's make one
|
||||
{
|
||||
//http://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net
|
||||
Debug.Console(1, "JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
|
||||
|
||||
}
|
||||
var tokenToReplace = JsonObject.SelectToken(path);
|
||||
if (tokenToReplace != null)
|
||||
{// It's found
|
||||
tokenToReplace.Replace(UnsavedValues[path]);
|
||||
Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path);
|
||||
}
|
||||
using (StreamWriter sw = new StreamWriter(ActualFilePath))
|
||||
else // No token. Let's make one
|
||||
{
|
||||
try
|
||||
{
|
||||
sw.Write(JsonObject.ToString());
|
||||
sw.Flush();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string err = string.Format("Error writing JSON file:\r{0}", e);
|
||||
Debug.Console(0, err);
|
||||
ErrorLog.Warn(err);
|
||||
return;
|
||||
}
|
||||
//http://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net
|
||||
Debug.Console(1, "JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
|
||||
|
||||
}
|
||||
}
|
||||
using (StreamWriter sw = new StreamWriter(ActualFilePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
sw.Write(JsonObject.ToString());
|
||||
sw.Flush();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string err = string.Format("Error writing JSON file:\r{0}", e);
|
||||
Debug.Console(0, err);
|
||||
ErrorLog.Warn(err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,31 +7,30 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PepperDash.Core.Logging
|
||||
namespace PepperDash.Core.Logging;
|
||||
|
||||
public class CrestronEnricher : ILogEventEnricher
|
||||
{
|
||||
public class CrestronEnricher : ILogEventEnricher
|
||||
static readonly string _appName;
|
||||
|
||||
static CrestronEnricher()
|
||||
{
|
||||
static readonly string _appName;
|
||||
|
||||
static CrestronEnricher()
|
||||
switch (CrestronEnvironment.DevicePlatform)
|
||||
{
|
||||
switch (CrestronEnvironment.DevicePlatform)
|
||||
{
|
||||
case eDevicePlatform.Appliance:
|
||||
_appName = $"App {InitialParametersClass.ApplicationNumber}";
|
||||
break;
|
||||
case eDevicePlatform.Server:
|
||||
_appName = $"{InitialParametersClass.RoomId}";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
|
||||
{
|
||||
var property = propertyFactory.CreateProperty("App", _appName);
|
||||
|
||||
logEvent.AddOrUpdateProperty(property);
|
||||
case eDevicePlatform.Appliance:
|
||||
_appName = $"App {InitialParametersClass.ApplicationNumber}";
|
||||
break;
|
||||
case eDevicePlatform.Server:
|
||||
_appName = $"{InitialParametersClass.RoomId}";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
|
||||
{
|
||||
var property = propertyFactory.CreateProperty("App", _appName);
|
||||
|
||||
logEvent.AddOrUpdateProperty(property);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,47 +9,45 @@ using System.IO;
|
||||
using System.Text;
|
||||
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
public class DebugConsoleSink : ILogEventSink
|
||||
{
|
||||
public class DebugConsoleSink : ILogEventSink
|
||||
private readonly ITextFormatter _textFormatter;
|
||||
|
||||
public void Emit(LogEvent logEvent)
|
||||
{
|
||||
private readonly ITextFormatter _textFormatter;
|
||||
if (!Debug.IsRunningOnAppliance) return;
|
||||
|
||||
public void Emit(LogEvent logEvent)
|
||||
/*string message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}]{logEvent.RenderMessage()}";
|
||||
|
||||
if(logEvent.Properties.TryGetValue("Key",out var value) && value is ScalarValue sv && sv.Value is string rawValue)
|
||||
{
|
||||
if (!Debug.IsRunningOnAppliance) return;
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}][{rawValue,3}]: {logEvent.RenderMessage()}";
|
||||
}*/
|
||||
|
||||
/*string message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}]{logEvent.RenderMessage()}";
|
||||
var buffer = new StringWriter(new StringBuilder(256));
|
||||
|
||||
if(logEvent.Properties.TryGetValue("Key",out var value) && value is ScalarValue sv && sv.Value is string rawValue)
|
||||
{
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}][{rawValue,3}]: {logEvent.RenderMessage()}";
|
||||
}*/
|
||||
_textFormatter.Format(logEvent, buffer);
|
||||
|
||||
var buffer = new StringWriter(new StringBuilder(256));
|
||||
|
||||
_textFormatter.Format(logEvent, buffer);
|
||||
|
||||
var message = buffer.ToString();
|
||||
|
||||
CrestronConsole.PrintLine(message);
|
||||
}
|
||||
|
||||
public DebugConsoleSink(ITextFormatter formatProvider )
|
||||
{
|
||||
_textFormatter = formatProvider ?? new JsonFormatter();
|
||||
}
|
||||
var message = buffer.ToString();
|
||||
|
||||
CrestronConsole.PrintLine(message);
|
||||
}
|
||||
|
||||
public static class DebugConsoleSinkExtensions
|
||||
public DebugConsoleSink(ITextFormatter formatProvider )
|
||||
{
|
||||
public static LoggerConfiguration DebugConsoleSink(
|
||||
this LoggerSinkConfiguration loggerConfiguration,
|
||||
ITextFormatter formatProvider = null)
|
||||
{
|
||||
return loggerConfiguration.Sink(new DebugConsoleSink(formatProvider));
|
||||
}
|
||||
_textFormatter = formatProvider ?? new JsonFormatter();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class DebugConsoleSinkExtensions
|
||||
{
|
||||
public static LoggerConfiguration DebugConsoleSink(
|
||||
this LoggerSinkConfiguration loggerConfiguration,
|
||||
ITextFormatter formatProvider = null)
|
||||
{
|
||||
return loggerConfiguration.Sink(new DebugConsoleSink(formatProvider));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,281 +1,280 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a debugging context
|
||||
/// </summary>
|
||||
public class DebugContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a debugging context
|
||||
/// Describes the folder location where a given program stores it's debug level memory. By default, the
|
||||
/// file written will be named appNdebug where N is 1-10.
|
||||
/// </summary>
|
||||
public class DebugContext
|
||||
public string Key { get; private set; }
|
||||
|
||||
///// <summary>
|
||||
///// The name of the file containing the current debug settings.
|
||||
///// </summary>
|
||||
//string FileName = string.Format(@"\nvram\debug\app{0}Debug.json", InitialParametersClass.ApplicationNumber);
|
||||
|
||||
DebugContextSaveData SaveData;
|
||||
|
||||
int SaveTimeoutMs = 30000;
|
||||
|
||||
CTimer SaveTimer;
|
||||
|
||||
|
||||
static List<DebugContext> Contexts = new List<DebugContext>();
|
||||
|
||||
/// <summary>
|
||||
/// Creates or gets a debug context
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static DebugContext GetDebugContext(string key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Describes the folder location where a given program stores it's debug level memory. By default, the
|
||||
/// file written will be named appNdebug where N is 1-10.
|
||||
/// </summary>
|
||||
public string Key { get; private set; }
|
||||
|
||||
///// <summary>
|
||||
///// The name of the file containing the current debug settings.
|
||||
///// </summary>
|
||||
//string FileName = string.Format(@"\nvram\debug\app{0}Debug.json", InitialParametersClass.ApplicationNumber);
|
||||
|
||||
DebugContextSaveData SaveData;
|
||||
|
||||
int SaveTimeoutMs = 30000;
|
||||
|
||||
CTimer SaveTimer;
|
||||
|
||||
|
||||
static List<DebugContext> Contexts = new List<DebugContext>();
|
||||
|
||||
/// <summary>
|
||||
/// Creates or gets a debug context
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static DebugContext GetDebugContext(string key)
|
||||
var context = Contexts.FirstOrDefault(c => c.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||||
if (context == null)
|
||||
{
|
||||
var context = Contexts.FirstOrDefault(c => c.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||||
if (context == null)
|
||||
{
|
||||
context = new DebugContext(key);
|
||||
Contexts.Add(context);
|
||||
}
|
||||
return context;
|
||||
context = new DebugContext(key);
|
||||
Contexts.Add(context);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Do not use. For S+ access.
|
||||
/// </summary>
|
||||
public DebugContext() { }
|
||||
|
||||
DebugContext(string key)
|
||||
{
|
||||
Key = key;
|
||||
if (CrestronEnvironment.RuntimeEnvironment == eRuntimeEnvironment.SimplSharpPro)
|
||||
{
|
||||
// Add command to console
|
||||
CrestronConsole.AddNewConsoleCommand(SetDebugFromConsole, "appdebug",
|
||||
"appdebug:P [0-2]: Sets the application's console debug message level",
|
||||
ConsoleAccessLevelEnum.AccessOperator);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Do not use. For S+ access.
|
||||
/// </summary>
|
||||
public DebugContext() { }
|
||||
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
|
||||
|
||||
DebugContext(string key)
|
||||
LoadMemory();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to save memory when shutting down
|
||||
/// </summary>
|
||||
/// <param name="programEventType"></param>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
Key = key;
|
||||
if (CrestronEnvironment.RuntimeEnvironment == eRuntimeEnvironment.SimplSharpPro)
|
||||
if (SaveTimer != null)
|
||||
{
|
||||
// Add command to console
|
||||
CrestronConsole.AddNewConsoleCommand(SetDebugFromConsole, "appdebug",
|
||||
"appdebug:P [0-2]: Sets the application's console debug message level",
|
||||
ConsoleAccessLevelEnum.AccessOperator);
|
||||
SaveTimer.Stop();
|
||||
SaveTimer = null;
|
||||
}
|
||||
Console(0, "Saving debug settings");
|
||||
SaveMemory();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback for console command
|
||||
/// </summary>
|
||||
/// <param name="levelString"></param>
|
||||
public void SetDebugFromConsole(string levelString)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(levelString.Trim()))
|
||||
{
|
||||
CrestronConsole.ConsoleCommandResponse("AppDebug level = {0}", SaveData.Level);
|
||||
return;
|
||||
}
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
|
||||
|
||||
LoadMemory();
|
||||
SetDebugLevel(Convert.ToInt32(levelString));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to save memory when shutting down
|
||||
/// </summary>
|
||||
/// <param name="programEventType"></param>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
catch
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
if (SaveTimer != null)
|
||||
{
|
||||
SaveTimer.Stop();
|
||||
SaveTimer = null;
|
||||
}
|
||||
Console(0, "Saving debug settings");
|
||||
SaveMemory();
|
||||
}
|
||||
CrestronConsole.PrintLine("Usage: appdebug:P [0-2]");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback for console command
|
||||
/// </summary>
|
||||
/// <param name="levelString"></param>
|
||||
public void SetDebugFromConsole(string levelString)
|
||||
/// <summary>
|
||||
/// Sets the debug level
|
||||
/// </summary>
|
||||
/// <param name="level"> Valid values 0 (no debug), 1 (critical), 2 (all messages)</param>
|
||||
public void SetDebugLevel(int level)
|
||||
{
|
||||
if (level <= 2)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(levelString.Trim()))
|
||||
{
|
||||
CrestronConsole.ConsoleCommandResponse("AppDebug level = {0}", SaveData.Level);
|
||||
return;
|
||||
}
|
||||
SaveData.Level = level;
|
||||
SaveMemoryOnTimeout();
|
||||
|
||||
SetDebugLevel(Convert.ToInt32(levelString));
|
||||
}
|
||||
catch
|
||||
{
|
||||
CrestronConsole.PrintLine("Usage: appdebug:P [0-2]");
|
||||
}
|
||||
CrestronConsole.PrintLine("[Application {0}], Debug level set to {1}",
|
||||
InitialParametersClass.ApplicationNumber, SaveData.Level);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the debug level
|
||||
/// </summary>
|
||||
/// <param name="level"> Valid values 0 (no debug), 1 (critical), 2 (all messages)</param>
|
||||
public void SetDebugLevel(int level)
|
||||
/// <summary>
|
||||
/// Prints message to console if current debug level is equal to or higher than the level of this message.
|
||||
/// Uses CrestronConsole.PrintLine.
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
/// <param name="format">Console format string</param>
|
||||
/// <param name="items">Object parameters</param>
|
||||
public void Console(uint level, string format, params object[] items)
|
||||
{
|
||||
if (SaveData.Level >= level)
|
||||
CrestronConsole.PrintLine("App {0}:{1}", InitialParametersClass.ApplicationNumber,
|
||||
string.Format(format, items));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends a device Key to the beginning of a message
|
||||
/// </summary>
|
||||
public void Console(uint level, IKeyed dev, string format, params object[] items)
|
||||
{
|
||||
if (SaveData.Level >= level)
|
||||
Console(level, "[{0}] {1}", dev.Key, string.Format(format, items));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
/// <param name="dev"></param>
|
||||
/// <param name="errorLogLevel"></param>
|
||||
/// <param name="format"></param>
|
||||
/// <param name="items"></param>
|
||||
public void Console(uint level, IKeyed dev, Debug.ErrorLogLevel errorLogLevel,
|
||||
string format, params object[] items)
|
||||
{
|
||||
if (SaveData.Level >= level)
|
||||
{
|
||||
if (level <= 2)
|
||||
{
|
||||
SaveData.Level = level;
|
||||
SaveMemoryOnTimeout();
|
||||
|
||||
CrestronConsole.PrintLine("[Application {0}], Debug level set to {1}",
|
||||
InitialParametersClass.ApplicationNumber, SaveData.Level);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prints message to console if current debug level is equal to or higher than the level of this message.
|
||||
/// Uses CrestronConsole.PrintLine.
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
/// <param name="format">Console format string</param>
|
||||
/// <param name="items">Object parameters</param>
|
||||
public void Console(uint level, string format, params object[] items)
|
||||
{
|
||||
if (SaveData.Level >= level)
|
||||
CrestronConsole.PrintLine("App {0}:{1}", InitialParametersClass.ApplicationNumber,
|
||||
string.Format(format, items));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends a device Key to the beginning of a message
|
||||
/// </summary>
|
||||
public void Console(uint level, IKeyed dev, string format, params object[] items)
|
||||
{
|
||||
if (SaveData.Level >= level)
|
||||
Console(level, "[{0}] {1}", dev.Key, string.Format(format, items));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
/// <param name="dev"></param>
|
||||
/// <param name="errorLogLevel"></param>
|
||||
/// <param name="format"></param>
|
||||
/// <param name="items"></param>
|
||||
public void Console(uint level, IKeyed dev, Debug.ErrorLogLevel errorLogLevel,
|
||||
string format, params object[] items)
|
||||
{
|
||||
if (SaveData.Level >= level)
|
||||
{
|
||||
var str = string.Format("[{0}] {1}", dev.Key, string.Format(format, items));
|
||||
Console(level, str);
|
||||
LogError(errorLogLevel, str);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
/// <param name="errorLogLevel"></param>
|
||||
/// <param name="format"></param>
|
||||
/// <param name="items"></param>
|
||||
public void Console(uint level, Debug.ErrorLogLevel errorLogLevel,
|
||||
string format, params object[] items)
|
||||
{
|
||||
if (SaveData.Level >= level)
|
||||
{
|
||||
var str = string.Format(format, items);
|
||||
Console(level, str);
|
||||
LogError(errorLogLevel, str);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="errorLogLevel"></param>
|
||||
/// <param name="str"></param>
|
||||
public void LogError(Debug.ErrorLogLevel errorLogLevel, string str)
|
||||
{
|
||||
string msg = string.Format("App {0}:{1}", InitialParametersClass.ApplicationNumber, str);
|
||||
switch (errorLogLevel)
|
||||
{
|
||||
case Debug.ErrorLogLevel.Error:
|
||||
ErrorLog.Error(msg);
|
||||
break;
|
||||
case Debug.ErrorLogLevel.Warning:
|
||||
ErrorLog.Warn(msg);
|
||||
break;
|
||||
case Debug.ErrorLogLevel.Notice:
|
||||
ErrorLog.Notice(msg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the memory object after timeout
|
||||
/// </summary>
|
||||
void SaveMemoryOnTimeout()
|
||||
{
|
||||
if (SaveTimer == null)
|
||||
SaveTimer = new CTimer(o =>
|
||||
{
|
||||
SaveTimer = null;
|
||||
SaveMemory();
|
||||
}, SaveTimeoutMs);
|
||||
else
|
||||
SaveTimer.Reset(SaveTimeoutMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the memory - use SaveMemoryOnTimeout
|
||||
/// </summary>
|
||||
void SaveMemory()
|
||||
{
|
||||
using (StreamWriter sw = new StreamWriter(GetMemoryFileName()))
|
||||
{
|
||||
var json = JsonConvert.SerializeObject(SaveData);
|
||||
sw.Write(json);
|
||||
sw.Flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
void LoadMemory()
|
||||
{
|
||||
var file = GetMemoryFileName();
|
||||
if (File.Exists(file))
|
||||
{
|
||||
using (StreamReader sr = new StreamReader(file))
|
||||
{
|
||||
var data = JsonConvert.DeserializeObject<DebugContextSaveData>(sr.ReadToEnd());
|
||||
if (data != null)
|
||||
{
|
||||
SaveData = data;
|
||||
Debug.Console(1, "Debug memory restored from file");
|
||||
return;
|
||||
}
|
||||
else
|
||||
SaveData = new DebugContextSaveData();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper to get the file path for this app's debug memory
|
||||
/// </summary>
|
||||
string GetMemoryFileName()
|
||||
{
|
||||
return string.Format(@"\NVRAM\debugSettings\program{0}-{1}", InitialParametersClass.ApplicationNumber, Key);
|
||||
var str = string.Format("[{0}] {1}", dev.Key, string.Format(format, items));
|
||||
Console(level, str);
|
||||
LogError(errorLogLevel, str);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class DebugContextSaveData
|
||||
/// <param name="level"></param>
|
||||
/// <param name="errorLogLevel"></param>
|
||||
/// <param name="format"></param>
|
||||
/// <param name="items"></param>
|
||||
public void Console(uint level, Debug.ErrorLogLevel errorLogLevel,
|
||||
string format, params object[] items)
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int Level { get; set; }
|
||||
if (SaveData.Level >= level)
|
||||
{
|
||||
var str = string.Format(format, items);
|
||||
Console(level, str);
|
||||
LogError(errorLogLevel, str);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="errorLogLevel"></param>
|
||||
/// <param name="str"></param>
|
||||
public void LogError(Debug.ErrorLogLevel errorLogLevel, string str)
|
||||
{
|
||||
string msg = string.Format("App {0}:{1}", InitialParametersClass.ApplicationNumber, str);
|
||||
switch (errorLogLevel)
|
||||
{
|
||||
case Debug.ErrorLogLevel.Error:
|
||||
ErrorLog.Error(msg);
|
||||
break;
|
||||
case Debug.ErrorLogLevel.Warning:
|
||||
ErrorLog.Warn(msg);
|
||||
break;
|
||||
case Debug.ErrorLogLevel.Notice:
|
||||
ErrorLog.Notice(msg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the memory object after timeout
|
||||
/// </summary>
|
||||
void SaveMemoryOnTimeout()
|
||||
{
|
||||
if (SaveTimer == null)
|
||||
SaveTimer = new CTimer(o =>
|
||||
{
|
||||
SaveTimer = null;
|
||||
SaveMemory();
|
||||
}, SaveTimeoutMs);
|
||||
else
|
||||
SaveTimer.Reset(SaveTimeoutMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the memory - use SaveMemoryOnTimeout
|
||||
/// </summary>
|
||||
void SaveMemory()
|
||||
{
|
||||
using (StreamWriter sw = new StreamWriter(GetMemoryFileName()))
|
||||
{
|
||||
var json = JsonConvert.SerializeObject(SaveData);
|
||||
sw.Write(json);
|
||||
sw.Flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
void LoadMemory()
|
||||
{
|
||||
var file = GetMemoryFileName();
|
||||
if (File.Exists(file))
|
||||
{
|
||||
using (StreamReader sr = new StreamReader(file))
|
||||
{
|
||||
var data = JsonConvert.DeserializeObject<DebugContextSaveData>(sr.ReadToEnd());
|
||||
if (data != null)
|
||||
{
|
||||
SaveData = data;
|
||||
Debug.Console(1, "Debug memory restored from file");
|
||||
return;
|
||||
}
|
||||
else
|
||||
SaveData = new DebugContextSaveData();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper to get the file path for this app's debug memory
|
||||
/// </summary>
|
||||
string GetMemoryFileName()
|
||||
{
|
||||
return string.Format(@"\NVRAM\debugSettings\program{0}-{1}", InitialParametersClass.ApplicationNumber, Key);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class DebugContextSaveData
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int Level { get; set; }
|
||||
}
|
||||
@@ -3,27 +3,26 @@ using Crestron.SimplSharp.CrestronLogger;
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core.Logging
|
||||
namespace PepperDash.Core.Logging;
|
||||
|
||||
public class DebugCrestronLoggerSink : ILogEventSink
|
||||
{
|
||||
public class DebugCrestronLoggerSink : ILogEventSink
|
||||
public void Emit(LogEvent logEvent)
|
||||
{
|
||||
public void Emit(LogEvent logEvent)
|
||||
if (!Debug.IsRunningOnAppliance) return;
|
||||
|
||||
string message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}]{logEvent.RenderMessage()}";
|
||||
|
||||
if (logEvent.Properties.TryGetValue("Key", out var value) && value is ScalarValue sv && sv.Value is string rawValue)
|
||||
{
|
||||
if (!Debug.IsRunningOnAppliance) return;
|
||||
|
||||
string message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}]{logEvent.RenderMessage()}";
|
||||
|
||||
if (logEvent.Properties.TryGetValue("Key", out var value) && value is ScalarValue sv && sv.Value is string rawValue)
|
||||
{
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}][{rawValue}]: {logEvent.RenderMessage()}";
|
||||
}
|
||||
|
||||
CrestronLogger.WriteToLog(message, (uint)logEvent.Level);
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][App {InitialParametersClass.ApplicationNumber}][{rawValue}]: {logEvent.RenderMessage()}";
|
||||
}
|
||||
|
||||
public DebugCrestronLoggerSink()
|
||||
{
|
||||
CrestronLogger.Initialize(1, LoggerModeEnum.RM);
|
||||
}
|
||||
CrestronLogger.WriteToLog(message, (uint)logEvent.Level);
|
||||
}
|
||||
|
||||
public DebugCrestronLoggerSink()
|
||||
{
|
||||
CrestronLogger.Initialize(1, LoggerModeEnum.RM);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,57 +9,56 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PepperDash.Core.Logging
|
||||
namespace PepperDash.Core.Logging;
|
||||
|
||||
public class DebugErrorLogSink : ILogEventSink
|
||||
{
|
||||
public class DebugErrorLogSink : ILogEventSink
|
||||
private ITextFormatter _formatter;
|
||||
|
||||
private Dictionary<LogEventLevel, Action<string>> _errorLogMap = new Dictionary<LogEventLevel, Action<string>>
|
||||
{
|
||||
private ITextFormatter _formatter;
|
||||
{ LogEventLevel.Verbose, (msg) => ErrorLog.Notice(msg) },
|
||||
{LogEventLevel.Debug, (msg) => ErrorLog.Notice(msg) },
|
||||
{LogEventLevel.Information, (msg) => ErrorLog.Notice(msg) },
|
||||
{LogEventLevel.Warning, (msg) => ErrorLog.Warn(msg) },
|
||||
{LogEventLevel.Error, (msg) => ErrorLog.Error(msg) },
|
||||
{LogEventLevel.Fatal, (msg) => ErrorLog.Error(msg) }
|
||||
};
|
||||
public void Emit(LogEvent logEvent)
|
||||
{
|
||||
string message;
|
||||
|
||||
private Dictionary<LogEventLevel, Action<string>> _errorLogMap = new Dictionary<LogEventLevel, Action<string>>
|
||||
if (_formatter == null)
|
||||
{
|
||||
{ LogEventLevel.Verbose, (msg) => ErrorLog.Notice(msg) },
|
||||
{LogEventLevel.Debug, (msg) => ErrorLog.Notice(msg) },
|
||||
{LogEventLevel.Information, (msg) => ErrorLog.Notice(msg) },
|
||||
{LogEventLevel.Warning, (msg) => ErrorLog.Warn(msg) },
|
||||
{LogEventLevel.Error, (msg) => ErrorLog.Error(msg) },
|
||||
{LogEventLevel.Fatal, (msg) => ErrorLog.Error(msg) }
|
||||
};
|
||||
public void Emit(LogEvent logEvent)
|
||||
var programId = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
|
||||
? $"App {InitialParametersClass.ApplicationNumber}"
|
||||
: $"Room {InitialParametersClass.RoomId}";
|
||||
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}]{logEvent.RenderMessage()}";
|
||||
|
||||
if (logEvent.Properties.TryGetValue("Key", out var value) && value is ScalarValue sv && sv.Value is string rawValue)
|
||||
{
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}][{rawValue}]: {logEvent.RenderMessage()}";
|
||||
}
|
||||
} else
|
||||
{
|
||||
string message;
|
||||
var buffer = new StringWriter(new StringBuilder(256));
|
||||
|
||||
if (_formatter == null)
|
||||
{
|
||||
var programId = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
|
||||
? $"App {InitialParametersClass.ApplicationNumber}"
|
||||
: $"Room {InitialParametersClass.RoomId}";
|
||||
_formatter.Format(logEvent, buffer);
|
||||
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}]{logEvent.RenderMessage()}";
|
||||
|
||||
if (logEvent.Properties.TryGetValue("Key", out var value) && value is ScalarValue sv && sv.Value is string rawValue)
|
||||
{
|
||||
message = $"[{logEvent.Timestamp}][{logEvent.Level}][{programId}][{rawValue}]: {logEvent.RenderMessage()}";
|
||||
}
|
||||
} else
|
||||
{
|
||||
var buffer = new StringWriter(new StringBuilder(256));
|
||||
|
||||
_formatter.Format(logEvent, buffer);
|
||||
|
||||
message = buffer.ToString();
|
||||
}
|
||||
|
||||
if(!_errorLogMap.TryGetValue(logEvent.Level, out var handler))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
handler(message);
|
||||
message = buffer.ToString();
|
||||
}
|
||||
|
||||
public DebugErrorLogSink(ITextFormatter formatter = null)
|
||||
if(!_errorLogMap.TryGetValue(logEvent.Level, out var handler))
|
||||
{
|
||||
_formatter = formatter;
|
||||
return;
|
||||
}
|
||||
|
||||
handler(message);
|
||||
}
|
||||
|
||||
public DebugErrorLogSink(ITextFormatter formatter = null)
|
||||
{
|
||||
_formatter = formatter;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,73 +2,72 @@
|
||||
using System;
|
||||
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)
|
||||
{
|
||||
public static void LogException(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(ex, message, device, args);
|
||||
}
|
||||
Log.LogMessage(ex, message, device, args);
|
||||
}
|
||||
|
||||
public static void LogVerbose(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Verbose, ex, message, device, args);
|
||||
}
|
||||
public static void LogVerbose(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Verbose, ex, message, device, args);
|
||||
}
|
||||
|
||||
public static void LogVerbose(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Verbose, device, message, args);
|
||||
}
|
||||
public static void LogVerbose(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Verbose, device, message, args);
|
||||
}
|
||||
|
||||
public static void LogDebug(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Debug, ex, message, device, args);
|
||||
}
|
||||
public static void LogDebug(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Debug, ex, message, device, args);
|
||||
}
|
||||
|
||||
public static void LogDebug(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Debug, device, message, args);
|
||||
}
|
||||
public static void LogDebug(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Debug, device, message, args);
|
||||
}
|
||||
|
||||
public static void LogInformation(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Information, ex, message, device, args);
|
||||
}
|
||||
public static void LogInformation(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Information, ex, message, device, args);
|
||||
}
|
||||
|
||||
public static void LogInformation(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Information, device, message, args);
|
||||
}
|
||||
public static void LogInformation(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Information, device, message, args);
|
||||
}
|
||||
|
||||
public static void LogWarning(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Warning, ex, message, device, args);
|
||||
}
|
||||
public static void LogWarning(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Warning, ex, message, device, args);
|
||||
}
|
||||
|
||||
public static void LogWarning(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Warning, device, message, args);
|
||||
}
|
||||
public static void LogWarning(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Warning, device, message, args);
|
||||
}
|
||||
|
||||
public static void LogError(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Error, ex, message, device, args);
|
||||
}
|
||||
public static void LogError(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Error, ex, message, device, args);
|
||||
}
|
||||
|
||||
public static void LogError(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Error, device, message, args);
|
||||
}
|
||||
public static void LogError(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Error, device, message, args);
|
||||
}
|
||||
|
||||
public static void LogFatal(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Fatal, ex, message, device, args);
|
||||
}
|
||||
public static void LogFatal(this IKeyed device, Exception ex, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Fatal, ex, message, device, args);
|
||||
}
|
||||
|
||||
public static void LogFatal(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Fatal, device, message, args);
|
||||
}
|
||||
public static void LogFatal(this IKeyed device, string message, params object[] args)
|
||||
{
|
||||
Log.LogMessage(LogEventLevel.Fatal, device, message, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,25 +2,25 @@
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace PepperDash.Core.Logging
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to persist current Debug settings across program restarts
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Class to persist current Debug settings across program restarts
|
||||
/// </summary>
|
||||
public class DebugContextCollection
|
||||
{
|
||||
/// <summary>
|
||||
/// To prevent threading issues with the DeviceDebugSettings collection
|
||||
/// </summary>
|
||||
private readonly CCriticalSection _deviceDebugSettingsLock;
|
||||
/// <summary>
|
||||
/// To prevent threading issues with the DeviceDebugSettings collection
|
||||
/// </summary>
|
||||
private readonly CCriticalSection _deviceDebugSettingsLock;
|
||||
|
||||
[JsonProperty("items")] private readonly Dictionary<string, DebugContextItem> _items;
|
||||
|
||||
/// <summary>
|
||||
/// Collection of the debug settings for each device where the dictionary key is the device key
|
||||
/// </summary>
|
||||
[JsonProperty("deviceDebugSettings")]
|
||||
private Dictionary<string, object> DeviceDebugSettings { get; set; }
|
||||
/// <summary>
|
||||
/// Collection of the debug settings for each device where the dictionary key is the device key
|
||||
/// </summary>
|
||||
[JsonProperty("deviceDebugSettings")]
|
||||
private Dictionary<string, object> DeviceDebugSettings { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -28,8 +28,8 @@ namespace PepperDash.Core.Logging
|
||||
/// </summary>
|
||||
public DebugContextCollection()
|
||||
{
|
||||
_deviceDebugSettingsLock = new CCriticalSection();
|
||||
DeviceDebugSettings = new Dictionary<string, object>();
|
||||
_deviceDebugSettingsLock = new CCriticalSection();
|
||||
DeviceDebugSettings = new Dictionary<string, object>();
|
||||
_items = new Dictionary<string, DebugContextItem>();
|
||||
}
|
||||
|
||||
@@ -59,40 +59,40 @@ namespace PepperDash.Core.Logging
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// sets the settings for a device or creates a new entry
|
||||
/// </summary>
|
||||
/// <param name="deviceKey"></param>
|
||||
/// <param name="settings"></param>
|
||||
/// <returns></returns>
|
||||
public void SetDebugSettingsForKey(string deviceKey, object settings)
|
||||
/// <summary>
|
||||
/// sets the settings for a device or creates a new entry
|
||||
/// </summary>
|
||||
/// <param name="deviceKey"></param>
|
||||
/// <param name="settings"></param>
|
||||
/// <returns></returns>
|
||||
public void SetDebugSettingsForKey(string deviceKey, object settings)
|
||||
{
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
_deviceDebugSettingsLock.Enter();
|
||||
_deviceDebugSettingsLock.Enter();
|
||||
|
||||
if (DeviceDebugSettings.ContainsKey(deviceKey))
|
||||
{
|
||||
DeviceDebugSettings[deviceKey] = settings;
|
||||
}
|
||||
else
|
||||
DeviceDebugSettings.Add(deviceKey, settings);
|
||||
}
|
||||
finally
|
||||
if (DeviceDebugSettings.ContainsKey(deviceKey))
|
||||
{
|
||||
_deviceDebugSettingsLock.Leave();
|
||||
DeviceDebugSettings[deviceKey] = settings;
|
||||
}
|
||||
else
|
||||
DeviceDebugSettings.Add(deviceKey, settings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the device settings for a device by key or returns null
|
||||
/// </summary>
|
||||
/// <param name="deviceKey"></param>
|
||||
/// <returns></returns>
|
||||
public object GetDebugSettingsForKey(string deviceKey)
|
||||
finally
|
||||
{
|
||||
return DeviceDebugSettings[deviceKey];
|
||||
_deviceDebugSettingsLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the device settings for a device by key or returns null
|
||||
/// </summary>
|
||||
/// <param name="deviceKey"></param>
|
||||
/// <returns></returns>
|
||||
public object GetDebugSettingsForKey(string deviceKey)
|
||||
{
|
||||
return DeviceDebugSettings[deviceKey];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -100,16 +100,15 @@ namespace PepperDash.Core.Logging
|
||||
/// </summary>
|
||||
public class DebugContextItem
|
||||
{
|
||||
/// <summary>
|
||||
/// The level of debug messages to print
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// The level of debug messages to print
|
||||
/// </summary>
|
||||
[JsonProperty("level")]
|
||||
public int Level { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Property to tell the program not to intitialize when it boots, if desired
|
||||
/// </summary>
|
||||
[JsonProperty("doNotLoadOnNextBoot")]
|
||||
public bool DoNotLoadOnNextBoot { get; set; }
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Property to tell the program not to intitialize when it boots, if desired
|
||||
/// </summary>
|
||||
[JsonProperty("doNotLoadOnNextBoot")]
|
||||
public bool DoNotLoadOnNextBoot { get; set; }
|
||||
}
|
||||
@@ -1,271 +1,332 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Crestron.SimplSharp;
|
||||
using Org.BouncyCastle.Asn1.X509;
|
||||
using Serilog;
|
||||
using Serilog.Configuration;
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
using Serilog.Configuration;
|
||||
using WebSocketSharp.Server;
|
||||
using Crestron.SimplSharp;
|
||||
using WebSocketSharp;
|
||||
using System.Security.Authentication;
|
||||
using WebSocketSharp.Net;
|
||||
using X509Certificate2 = System.Security.Cryptography.X509Certificates.X509Certificate2;
|
||||
using System.IO;
|
||||
using Org.BouncyCastle.Asn1.X509;
|
||||
using Serilog.Formatting;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Serilog.Formatting.Json;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Authentication;
|
||||
using WebSocketSharp;
|
||||
using WebSocketSharp.Server;
|
||||
using X509Certificate2 = System.Security.Cryptography.X509Certificates.X509Certificate2;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Provides a WebSocket-based logging sink for debugging purposes, allowing log events to be broadcast to connected
|
||||
/// WebSocket clients.
|
||||
/// </summary>
|
||||
/// <remarks>This class implements the <see cref="ILogEventSink"/> interface and is designed to send
|
||||
/// formatted log events to WebSocket clients connected to a secure WebSocket server. The server is hosted locally
|
||||
/// and uses a self-signed certificate for SSL/TLS encryption.</remarks>
|
||||
public class DebugWebsocketSink : ILogEventSink, IKeyed
|
||||
{
|
||||
public class DebugWebsocketSink : ILogEventSink
|
||||
{
|
||||
private HttpServer _httpsServer;
|
||||
|
||||
private string _path = "/debug/join/";
|
||||
private const string _certificateName = "selfCres";
|
||||
private const string _certificatePassword = "cres12345";
|
||||
private HttpServer _httpsServer;
|
||||
|
||||
private readonly string _path = "/debug/join/";
|
||||
private const string _certificateName = "selfCres";
|
||||
private const string _certificatePassword = "cres12345";
|
||||
|
||||
public int Port
|
||||
{ get
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the port number on which the HTTPS server is currently running.
|
||||
/// </summary>
|
||||
public int Port
|
||||
{ get
|
||||
{
|
||||
|
||||
if(_httpsServer == null) return 0;
|
||||
return _httpsServer.Port;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the WebSocket URL for the current server instance.
|
||||
/// </summary>
|
||||
/// <remarks>The URL is dynamically constructed based on the server's current IP address, port,
|
||||
/// and WebSocket path.</remarks>
|
||||
public string Url
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_httpsServer == null) return "";
|
||||
return $"wss://{CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0)}:{_httpsServer.Port}{_httpsServer.WebSocketServices[_path].Path}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the HTTPS server is currently listening for incoming connections.
|
||||
/// </summary>
|
||||
public bool IsRunning { get => _httpsServer?.IsListening ?? false; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string Key => "DebugWebsocketSink";
|
||||
|
||||
private readonly ITextFormatter _textFormatter;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DebugWebsocketSink"/> class with the specified text formatter.
|
||||
/// </summary>
|
||||
/// <remarks>This constructor initializes the WebSocket sink and ensures that a certificate is
|
||||
/// available for secure communication. If the required certificate does not exist, it will be created
|
||||
/// automatically. Additionally, the sink is configured to stop the server when the program is
|
||||
/// stopping.</remarks>
|
||||
/// <param name="formatProvider">The text formatter used to format log messages. If null, a default JSON formatter is used.</param>
|
||||
public DebugWebsocketSink(ITextFormatter formatProvider)
|
||||
{
|
||||
|
||||
_textFormatter = formatProvider ?? new JsonFormatter();
|
||||
|
||||
if (!File.Exists($"\\user\\{_certificateName}.pfx"))
|
||||
CreateCert();
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += type =>
|
||||
{
|
||||
if (type == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
StopServer();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static void CreateCert()
|
||||
{
|
||||
try
|
||||
{
|
||||
var utility = new BouncyCertificate();
|
||||
|
||||
var ipAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0);
|
||||
var hostName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
|
||||
var domainName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME, 0);
|
||||
|
||||
CrestronConsole.PrintLine(string.Format("DomainName: {0} | HostName: {1} | {1}.{0}@{2}", domainName, hostName, ipAddress));
|
||||
|
||||
var certificate = utility.CreateSelfSignedCertificate(string.Format("CN={0}.{1}", hostName, domainName), [string.Format("{0}.{1}", hostName, domainName), ipAddress], [KeyPurposeID.id_kp_serverAuth, KeyPurposeID.id_kp_clientAuth]);
|
||||
|
||||
//Crestron fails to let us do this...perhaps it should be done through their Dll's but haven't tested
|
||||
|
||||
var separator = Path.DirectorySeparatorChar;
|
||||
|
||||
utility.CertificatePassword = _certificatePassword;
|
||||
utility.WriteCertificate(certificate, @$"{separator}user{separator}", _certificateName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Debug.Console(0, "WSS CreateCert Failed\r\n{0}\r\n{1}", ex.Message, ex.StackTrace);
|
||||
CrestronConsole.PrintLine("WSS CreateCert Failed\r\n{0}\r\n{1}", ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a log event to all connected WebSocket clients.
|
||||
/// </summary>
|
||||
/// <remarks>The log event is formatted using the configured text formatter and then broadcasted
|
||||
/// to all clients connected to the WebSocket server. If the WebSocket server is not initialized or not
|
||||
/// listening, the method exits without performing any action.</remarks>
|
||||
/// <param name="logEvent">The log event to be formatted and broadcasted. Cannot be null.</param>
|
||||
public void Emit(LogEvent logEvent)
|
||||
{
|
||||
if (_httpsServer == null || !_httpsServer.IsListening) return;
|
||||
|
||||
var sw = new StringWriter();
|
||||
_textFormatter.Format(logEvent, sw);
|
||||
|
||||
_httpsServer.WebSocketServices[_path].Sessions.Broadcast(sw.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts the WebSocket server on the specified port and configures it with the appropriate certificate.
|
||||
/// </summary>
|
||||
/// <remarks>This method initializes the WebSocket server and binds it to the specified port. It
|
||||
/// also applies the server's certificate for secure communication. Ensure that the port is not already in use
|
||||
/// and that the certificate file is accessible.</remarks>
|
||||
/// <param name="port">The port number on which the WebSocket server will listen. Must be a valid, non-negative port number.</param>
|
||||
public void StartServerAndSetPort(int port)
|
||||
{
|
||||
Debug.Console(0, "Starting Websocket Server on port: {0}", port);
|
||||
|
||||
|
||||
Start(port, $"\\user\\{_certificateName}.pfx", _certificatePassword);
|
||||
}
|
||||
|
||||
private void Start(int port, string certPath = "", string certPassword = "")
|
||||
{
|
||||
try
|
||||
{
|
||||
_httpsServer = new HttpServer(port, true);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(certPath))
|
||||
{
|
||||
Debug.Console(0, "Assigning SSL Configuration");
|
||||
|
||||
_httpsServer.SslConfiguration.ServerCertificate = new X509Certificate2(certPath, certPassword);
|
||||
_httpsServer.SslConfiguration.ClientCertificateRequired = false;
|
||||
_httpsServer.SslConfiguration.CheckCertificateRevocation = false;
|
||||
_httpsServer.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls12;
|
||||
//this is just to test, you might want to actually validate
|
||||
_httpsServer.SslConfiguration.ClientCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
|
||||
{
|
||||
Debug.Console(0, "HTTPS ClientCerticateValidation Callback triggered");
|
||||
return true;
|
||||
};
|
||||
}
|
||||
Debug.Console(0, "Adding Debug Client Service");
|
||||
_httpsServer.AddWebSocketService<DebugClient>(_path);
|
||||
Debug.Console(0, "Assigning Log Info");
|
||||
_httpsServer.Log.Level = LogLevel.Trace;
|
||||
_httpsServer.Log.Output = (d, s) =>
|
||||
{
|
||||
uint level;
|
||||
|
||||
switch(d.Level)
|
||||
{
|
||||
case WebSocketSharp.LogLevel.Fatal:
|
||||
level = 3;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Error:
|
||||
level = 2;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Warn:
|
||||
level = 1;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Info:
|
||||
level = 0;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Debug:
|
||||
level = 4;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Trace:
|
||||
level = 5;
|
||||
break;
|
||||
default:
|
||||
level = 4;
|
||||
break;
|
||||
}
|
||||
|
||||
if(_httpsServer == null) return 0;
|
||||
return _httpsServer.Port;
|
||||
}
|
||||
}
|
||||
|
||||
public string Url
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_httpsServer == null) return "";
|
||||
return $"wss://{CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0)}:{_httpsServer.Port}{_httpsServer.WebSocketServices[_path].Path}";
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsRunning { get => _httpsServer?.IsListening ?? false; }
|
||||
|
||||
|
||||
private readonly ITextFormatter _textFormatter;
|
||||
|
||||
public DebugWebsocketSink(ITextFormatter formatProvider)
|
||||
{
|
||||
|
||||
_textFormatter = formatProvider ?? new JsonFormatter();
|
||||
|
||||
if (!File.Exists($"\\user\\{_certificateName}.pfx"))
|
||||
CreateCert(null);
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += type =>
|
||||
{
|
||||
if (type == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
StopServer();
|
||||
}
|
||||
Debug.Console(level, "{1} {0}\rCaller:{2}\rMessage:{3}\rs:{4}", d.Level.ToString(), d.Date.ToString(), d.Caller.ToString(), d.Message, s);
|
||||
};
|
||||
Debug.Console(0, "Starting");
|
||||
|
||||
_httpsServer.Start();
|
||||
Debug.Console(0, "Ready");
|
||||
}
|
||||
|
||||
private void CreateCert(string[] args)
|
||||
catch (Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
//Debug.Console(0,"CreateCert Creating Utility");
|
||||
CrestronConsole.PrintLine("CreateCert Creating Utility");
|
||||
//var utility = new CertificateUtility();
|
||||
var utility = new BouncyCertificate();
|
||||
//Debug.Console(0, "CreateCert Calling CreateCert");
|
||||
CrestronConsole.PrintLine("CreateCert Calling CreateCert");
|
||||
//utility.CreateCert();
|
||||
var ipAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0);
|
||||
var hostName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
|
||||
var domainName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME, 0);
|
||||
|
||||
//Debug.Console(0, "DomainName: {0} | HostName: {1} | {1}.{0}@{2}", domainName, hostName, ipAddress);
|
||||
CrestronConsole.PrintLine(string.Format("DomainName: {0} | HostName: {1} | {1}.{0}@{2}", domainName, hostName, ipAddress));
|
||||
|
||||
var certificate = utility.CreateSelfSignedCertificate(string.Format("CN={0}.{1}", hostName, domainName), new[] { string.Format("{0}.{1}", hostName, domainName), ipAddress }, new[] { KeyPurposeID.id_kp_serverAuth, KeyPurposeID.id_kp_clientAuth });
|
||||
//Crestron fails to let us do this...perhaps it should be done through their Dll's but haven't tested
|
||||
//Debug.Print($"CreateCert Storing Certificate To My.LocalMachine");
|
||||
//utility.AddCertToStore(certificate, StoreName.My, StoreLocation.LocalMachine);
|
||||
//Debug.Console(0, "CreateCert Saving Cert to \\user\\");
|
||||
CrestronConsole.PrintLine("CreateCert Saving Cert to \\user\\");
|
||||
utility.CertificatePassword = _certificatePassword;
|
||||
utility.WriteCertificate(certificate, @"\user\", _certificateName);
|
||||
//Debug.Console(0, "CreateCert Ending CreateCert");
|
||||
CrestronConsole.PrintLine("CreateCert Ending CreateCert");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Debug.Console(0, "WSS CreateCert Failed\r\n{0}\r\n{1}", ex.Message, ex.StackTrace);
|
||||
CrestronConsole.PrintLine(string.Format("WSS CreateCert Failed\r\n{0}\r\n{1}", ex.Message, ex.StackTrace));
|
||||
}
|
||||
}
|
||||
|
||||
public void Emit(LogEvent logEvent)
|
||||
{
|
||||
if (_httpsServer == null || !_httpsServer.IsListening) return;
|
||||
|
||||
var sw = new StringWriter();
|
||||
_textFormatter.Format(logEvent, sw);
|
||||
|
||||
_httpsServer.WebSocketServices.Broadcast(sw.ToString());
|
||||
|
||||
}
|
||||
|
||||
public void StartServerAndSetPort(int port)
|
||||
{
|
||||
Debug.Console(0, "Starting Websocket Server on port: {0}", port);
|
||||
|
||||
|
||||
Start(port, $"\\user\\{_certificateName}.pfx", _certificatePassword);
|
||||
}
|
||||
|
||||
private void Start(int port, string certPath = "", string certPassword = "")
|
||||
{
|
||||
try
|
||||
{
|
||||
_httpsServer = new HttpServer(port, true);
|
||||
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(certPath))
|
||||
{
|
||||
Debug.Console(0, "Assigning SSL Configuration");
|
||||
_httpsServer.SslConfiguration = new ServerSslConfiguration(new X509Certificate2(certPath, certPassword))
|
||||
{
|
||||
ClientCertificateRequired = false,
|
||||
CheckCertificateRevocation = false,
|
||||
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls,
|
||||
//this is just to test, you might want to actually validate
|
||||
ClientCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
|
||||
{
|
||||
Debug.Console(0, "HTTPS ClientCerticateValidation Callback triggered");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
Debug.Console(0, "Adding Debug Client Service");
|
||||
_httpsServer.AddWebSocketService<DebugClient>(_path);
|
||||
Debug.Console(0, "Assigning Log Info");
|
||||
_httpsServer.Log.Level = LogLevel.Trace;
|
||||
_httpsServer.Log.Output = (d, s) =>
|
||||
{
|
||||
uint level;
|
||||
|
||||
switch(d.Level)
|
||||
{
|
||||
case WebSocketSharp.LogLevel.Fatal:
|
||||
level = 3;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Error:
|
||||
level = 2;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Warn:
|
||||
level = 1;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Info:
|
||||
level = 0;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Debug:
|
||||
level = 4;
|
||||
break;
|
||||
case WebSocketSharp.LogLevel.Trace:
|
||||
level = 5;
|
||||
break;
|
||||
default:
|
||||
level = 4;
|
||||
break;
|
||||
}
|
||||
|
||||
Debug.Console(level, "{1} {0}\rCaller:{2}\rMessage:{3}\rs:{4}", d.Level.ToString(), d.Date.ToString(), d.Caller.ToString(), d.Message, s);
|
||||
};
|
||||
Debug.Console(0, "Starting");
|
||||
|
||||
_httpsServer.Start();
|
||||
Debug.Console(0, "Ready");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, "WebSocket Failed to start {0}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public void StopServer()
|
||||
{
|
||||
Debug.Console(0, "Stopping Websocket Server");
|
||||
_httpsServer?.Stop();
|
||||
|
||||
_httpsServer = null;
|
||||
Debug.Console(0, "WebSocket Failed to start {0}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DebugWebsocketSinkExtensions
|
||||
/// <summary>
|
||||
/// Stops the WebSocket server if it is currently running.
|
||||
/// </summary>
|
||||
/// <remarks>This method halts the WebSocket server and releases any associated resources. After
|
||||
/// calling this method, the server will no longer accept or process incoming connections.</remarks>
|
||||
public void StopServer()
|
||||
{
|
||||
public static LoggerConfiguration DebugWebsocketSink(
|
||||
this LoggerSinkConfiguration loggerConfiguration,
|
||||
ITextFormatter formatProvider = null)
|
||||
{
|
||||
return loggerConfiguration.Sink(new DebugWebsocketSink(formatProvider));
|
||||
}
|
||||
}
|
||||
Debug.Console(0, "Stopping Websocket Server");
|
||||
_httpsServer?.Stop();
|
||||
|
||||
public class DebugClient : WebSocketBehavior
|
||||
{
|
||||
private DateTime _connectionTime;
|
||||
|
||||
public TimeSpan ConnectedDuration
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Context.WebSocket.IsAlive)
|
||||
{
|
||||
return DateTime.Now - _connectionTime;
|
||||
}
|
||||
else
|
||||
{
|
||||
return new TimeSpan(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public DebugClient()
|
||||
{
|
||||
Debug.Console(0, "DebugClient Created");
|
||||
}
|
||||
|
||||
protected override void OnOpen()
|
||||
{
|
||||
base.OnOpen();
|
||||
|
||||
var url = Context.WebSocket.Url;
|
||||
Debug.Console(0, Debug.ErrorLogLevel.Notice, "New WebSocket Connection from: {0}", url);
|
||||
|
||||
_connectionTime = DateTime.Now;
|
||||
}
|
||||
|
||||
protected override void OnMessage(MessageEventArgs e)
|
||||
{
|
||||
base.OnMessage(e);
|
||||
|
||||
Debug.Console(0, "WebSocket UiClient Message: {0}", e.Data);
|
||||
}
|
||||
|
||||
protected override void OnClose(CloseEventArgs e)
|
||||
{
|
||||
base.OnClose(e);
|
||||
|
||||
Debug.Console(0, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Closing: {0} reason: {1}", e.Code, e.Reason);
|
||||
|
||||
}
|
||||
|
||||
protected override void OnError(WebSocketSharp.ErrorEventArgs e)
|
||||
{
|
||||
base.OnError(e);
|
||||
|
||||
Debug.Console(2, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Error: {0} message: {1}", e.Exception, e.Message);
|
||||
}
|
||||
_httpsServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the logger to write log events to a debug WebSocket sink.
|
||||
/// </summary>
|
||||
/// <remarks>This extension method allows you to direct log events to a WebSocket sink for debugging
|
||||
/// purposes.</remarks>
|
||||
public static class DebugWebsocketSinkExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures a logger to write log events to a debug WebSocket sink.
|
||||
/// </summary>
|
||||
/// <remarks>This method adds a sink that writes log events to a WebSocket for debugging purposes.
|
||||
/// It is typically used during development to stream log events in real-time.</remarks>
|
||||
/// <param name="loggerConfiguration">The logger sink configuration to apply the WebSocket sink to.</param>
|
||||
/// <param name="formatProvider">An optional text formatter to format the log events. If not provided, a default formatter will be used.</param>
|
||||
/// <returns>A <see cref="LoggerConfiguration"/> object that can be used to further configure the logger.</returns>
|
||||
public static LoggerConfiguration DebugWebsocketSink(
|
||||
this LoggerSinkConfiguration loggerConfiguration,
|
||||
ITextFormatter formatProvider = null)
|
||||
{
|
||||
return loggerConfiguration.Sink(new DebugWebsocketSink(formatProvider));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a WebSocket client for debugging purposes, providing connection lifecycle management and message
|
||||
/// handling functionality.
|
||||
/// </summary>
|
||||
/// <remarks>The <see cref="DebugClient"/> class extends <see cref="WebSocketBehavior"/> to handle
|
||||
/// WebSocket connections, including events for opening, closing, receiving messages, and errors. It tracks the
|
||||
/// duration of the connection and logs relevant events for debugging.</remarks>
|
||||
public class DebugClient : WebSocketBehavior
|
||||
{
|
||||
private DateTime _connectionTime;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of time the WebSocket connection has been active.
|
||||
/// </summary>
|
||||
public TimeSpan ConnectedDuration
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Context.WebSocket.IsAlive)
|
||||
{
|
||||
return DateTime.Now - _connectionTime;
|
||||
}
|
||||
else
|
||||
{
|
||||
return new TimeSpan(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DebugClient"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>This constructor creates a new <see cref="DebugClient"/> instance and logs its
|
||||
/// creation using the <see cref="Debug.Console(int, string)"/> method with a debug level of 0.</remarks>
|
||||
public DebugClient()
|
||||
{
|
||||
Debug.Console(0, "DebugClient Created");
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void OnOpen()
|
||||
{
|
||||
base.OnOpen();
|
||||
|
||||
var url = Context.WebSocket.Url;
|
||||
Debug.Console(0, Debug.ErrorLogLevel.Notice, "New WebSocket Connection from: {0}", url);
|
||||
|
||||
_connectionTime = DateTime.Now;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void OnMessage(MessageEventArgs e)
|
||||
{
|
||||
base.OnMessage(e);
|
||||
|
||||
Debug.Console(0, "WebSocket UiClient Message: {0}", e.Data);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void OnClose(CloseEventArgs e)
|
||||
{
|
||||
base.OnClose(e);
|
||||
|
||||
Debug.Console(0, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Closing: {0} reason: {1}", e.Code, e.Reason);
|
||||
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void OnError(WebSocketSharp.ErrorEventArgs e)
|
||||
{
|
||||
base.OnError(e);
|
||||
|
||||
Debug.Console(2, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Error: {0} message: {1}", e.Exception, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,19 +4,17 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Not in use
|
||||
/// </summary>
|
||||
public static class NetworkComm
|
||||
{
|
||||
/// <summary>
|
||||
/// Not in use
|
||||
/// </summary>
|
||||
public static class NetworkComm
|
||||
{
|
||||
/// <summary>
|
||||
/// Not in use
|
||||
/// </summary>
|
||||
static NetworkComm()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.PasswordManagement
|
||||
{
|
||||
namespace PepperDash.Core.PasswordManagement;
|
||||
|
||||
/// <summary>
|
||||
/// JSON password configuration
|
||||
/// </summary>
|
||||
@@ -22,5 +22,4 @@ namespace PepperDash.Core.PasswordManagement
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.PasswordManagement
|
||||
{
|
||||
namespace PepperDash.Core.PasswordManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Constants
|
||||
/// </summary>
|
||||
@@ -53,5 +53,4 @@ namespace PepperDash.Core.PasswordManagement
|
||||
/// Generic string value change constant
|
||||
/// </summary>
|
||||
public const ushort StringValueChange = 201;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
using System;
|
||||
|
||||
namespace PepperDash.Core.PasswordManagement
|
||||
{
|
||||
/// <summary>
|
||||
/// A class to allow user interaction with the PasswordManager
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.PasswordManagement;
|
||||
|
||||
/// <summary>
|
||||
/// A class to allow user interaction with the PasswordManager
|
||||
/// </summary>
|
||||
public class PasswordClient
|
||||
{
|
||||
/// <summary>
|
||||
@@ -183,5 +183,4 @@ namespace PepperDash.Core.PasswordManagement
|
||||
GetPasswordByIndex(args.Index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
using System.Collections.Generic;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.PasswordManagement
|
||||
{
|
||||
/// <summary>
|
||||
/// Allows passwords to be stored and managed
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.PasswordManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Allows passwords to be stored and managed
|
||||
/// </summary>
|
||||
public class PasswordManager
|
||||
{
|
||||
/// <summary>
|
||||
@@ -190,7 +190,7 @@ namespace PepperDash.Core.PasswordManagement
|
||||
/// <summary>
|
||||
/// Protected ushort change event handler
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnUshrtChange(ushort value, ushort index, ushort type)
|
||||
@@ -237,5 +237,4 @@ namespace PepperDash.Core.PasswordManagement
|
||||
PasswordChange(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<ProjectType>Library</ProjectType>
|
||||
<Configurations>Debug;Release;Test</Configurations>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<RootNamespace>PepperDash.Core</RootNamespace>
|
||||
<AssemblyName>PepperDashCore</AssemblyName>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<TargetFramework>net8</TargetFramework>
|
||||
<Deterministic>true</Deterministic>
|
||||
<NeutralLanguage>en</NeutralLanguage>
|
||||
<OutputPath>bin\$(Configuration)\</OutputPath>
|
||||
@@ -24,6 +25,10 @@
|
||||
<DebugType>full</DebugType>
|
||||
<DefineConstants>TRACE;DEBUG;SERIES4</DefineConstants>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Test|AnyCPU'">
|
||||
<DebugType>full</DebugType>
|
||||
<DefineConstants>TRACE;DEBUG;SERIES4</DefineConstants>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<DocumentationFile>bin\4Series\$(Configuration)\PepperDashCore.xml</DocumentationFile>
|
||||
@@ -41,16 +46,22 @@
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Test|AnyCPU' ">
|
||||
<ProjectReference Include="../../src/CrestronMock/CrestronMock.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(Configuration)|$(Platform)' != 'Test|AnyCPU' ">
|
||||
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.21.128" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
|
||||
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.21.90" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Expressions" Version="4.0.0" />
|
||||
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
||||
<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="BouncyCastle.Cryptography" Version="2.6.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Serilog" Version="4.3.0" />
|
||||
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
|
||||
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
<PackageReference Include="SSH.NET" Version="2025.0.0" />
|
||||
<PackageReference Include="WebSocketSharp-netstandard" Version="1.0.1" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net6'">
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
|
||||
@@ -4,68 +4,68 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.SystemInfo
|
||||
{
|
||||
namespace PepperDash.Core.SystemInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Constants
|
||||
/// </summary>
|
||||
public class SystemInfoConstants
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort BoolValueChange = 1;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort CompleteBoolChange = 2;
|
||||
public const ushort CompleteBoolChange = 2;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort BusyBoolChange = 3;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort BusyBoolChange = 3;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort UshortValueChange = 101;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort StringValueChange = 201;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ConsoleResponseChange = 202;
|
||||
public const ushort ConsoleResponseChange = 202;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ProcessorUptimeChange = 203;
|
||||
public const ushort ProcessorUptimeChange = 203;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ProgramUptimeChange = 204;
|
||||
public const ushort ProgramUptimeChange = 204;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ObjectChange = 301;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ProcessorConfigChange = 302;
|
||||
public const ushort ProcessorConfigChange = 302;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort EthernetConfigChange = 303;
|
||||
public const ushort EthernetConfigChange = 303;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ControlSubnetConfigChange = 304;
|
||||
public const ushort ControlSubnetConfigChange = 304;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public const ushort ProgramConfigChange = 305;
|
||||
public const ushort ProgramConfigChange = 305;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -73,18 +73,18 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// </summary>
|
||||
public class ProcessorChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ProcessorInfo Processor { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
public ushort Type { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
@@ -119,18 +119,18 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// </summary>
|
||||
public class EthernetChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public EthernetInfo Adapter { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
public ushort Type { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
@@ -143,7 +143,7 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// <summary>
|
||||
/// Constructor overload
|
||||
/// </summary>
|
||||
/// <param name="ethernet"></param>
|
||||
/// <param name="ethernet"></param>
|
||||
/// <param name="type"></param>
|
||||
public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type)
|
||||
{
|
||||
@@ -154,9 +154,9 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// <summary>
|
||||
/// Constructor overload
|
||||
/// </summary>
|
||||
/// <param name="ethernet"></param>
|
||||
/// <param name="ethernet"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="index"></param>
|
||||
public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type, ushort index)
|
||||
{
|
||||
Adapter = ethernet;
|
||||
@@ -170,18 +170,18 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// </summary>
|
||||
public class ControlSubnetChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ControlSubnetInfo Adapter { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
public ushort Type { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
@@ -216,18 +216,18 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// </summary>
|
||||
public class ProgramChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ProgramInfo Program { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
public ushort Type { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
@@ -240,7 +240,7 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// <summary>
|
||||
/// Constructor overload
|
||||
/// </summary>
|
||||
/// <param name="program"></param>
|
||||
/// <param name="program"></param>
|
||||
/// <param name="type"></param>
|
||||
public ProgramChangeEventArgs(ProgramInfo program, ushort type)
|
||||
{
|
||||
@@ -251,14 +251,13 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// <summary>
|
||||
/// Constructor overload
|
||||
/// </summary>
|
||||
/// <param name="program"></param>
|
||||
/// <param name="program"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="index"></param>
|
||||
public ProgramChangeEventArgs(ProgramInfo program, ushort type, ushort index)
|
||||
{
|
||||
Program = program;
|
||||
Type = type;
|
||||
Index = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,52 +4,52 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.SystemInfo
|
||||
{
|
||||
namespace PepperDash.Core.SystemInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Processor info class
|
||||
/// </summary>
|
||||
public class ProcessorInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Model { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string SerialNumber { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Firmware { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string FirmwareDate { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string OsVersion { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string RuntimeEnvironment { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string DevicePlatform { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string ModuleDirectory { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string LocalTimeZone { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string ProgramIdTag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -66,45 +66,45 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// </summary>
|
||||
public class EthernetInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort DhcpIsOn { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Hostname { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string MacAddress { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string IpAddress { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Subnet { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Gateway { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Dns1 { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Dns2 { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Dns3 { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Domain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -121,29 +121,29 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// </summary>
|
||||
public class ControlSubnetInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Enabled { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort IsInAutomaticMode { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string MacAddress { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string IpAddress { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Subnet { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string RouterPrefix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -160,37 +160,37 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// </summary>
|
||||
public class ProgramInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Header { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string System { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string ProgramIdTag { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string CompileTime { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Database { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Environment { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Programmer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -200,5 +200,4 @@ namespace PepperDash.Core.SystemInfo
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,37 +4,37 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.SystemInfo
|
||||
{
|
||||
namespace PepperDash.Core.SystemInfo;
|
||||
|
||||
/// <summary>
|
||||
/// System Info class
|
||||
/// </summary>
|
||||
public class SystemInfoToSimpl
|
||||
{
|
||||
/// <summary>
|
||||
/// Notifies of bool change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of bool change
|
||||
/// </summary>
|
||||
public event EventHandler<BoolChangeEventArgs> BoolChange;
|
||||
/// <summary>
|
||||
/// Notifies of string change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of string change
|
||||
/// </summary>
|
||||
public event EventHandler<StringChangeEventArgs> StringChange;
|
||||
|
||||
/// <summary>
|
||||
/// Notifies of processor change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of processor change
|
||||
/// </summary>
|
||||
public event EventHandler<ProcessorChangeEventArgs> ProcessorChange;
|
||||
/// <summary>
|
||||
/// Notifies of ethernet change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of ethernet change
|
||||
/// </summary>
|
||||
public event EventHandler<EthernetChangeEventArgs> EthernetChange;
|
||||
/// <summary>
|
||||
/// Notifies of control subnet change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of control subnet change
|
||||
/// </summary>
|
||||
public event EventHandler<ControlSubnetChangeEventArgs> ControlSubnetChange;
|
||||
/// <summary>
|
||||
/// Notifies of program change
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Notifies of program change
|
||||
/// </summary>
|
||||
public event EventHandler<ProgramChangeEventArgs> ProgramChange;
|
||||
|
||||
/// <summary>
|
||||
@@ -327,10 +327,10 @@ namespace PepperDash.Core.SystemInfo
|
||||
/// <summary>
|
||||
/// private method to parse console messages
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="line"></param>
|
||||
/// <param name="dataStart"></param>
|
||||
/// <param name="dataEnd"></param>
|
||||
/// <param name="dataStart"></param>
|
||||
/// <param name="dataEnd"></param>
|
||||
/// <returns></returns>
|
||||
private string ParseConsoleResponse(string data, string line, string dataStart, string dataEnd)
|
||||
{
|
||||
@@ -458,5 +458,4 @@ namespace PepperDash.Core.SystemInfo
|
||||
ProgramChange(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,337 +20,336 @@ using Org.BouncyCastle.Crypto.Operators;
|
||||
using BigInteger = Org.BouncyCastle.Math.BigInteger;
|
||||
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
|
||||
|
||||
namespace PepperDash.Core
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Taken From https://github.com/rlipscombe/bouncy-castle-csharp/
|
||||
/// </summary>
|
||||
internal class BouncyCertificate
|
||||
{
|
||||
/// <summary>
|
||||
/// Taken From https://github.com/rlipscombe/bouncy-castle-csharp/
|
||||
/// </summary>
|
||||
internal class BouncyCertificate
|
||||
public string CertificatePassword { get; set; } = "password";
|
||||
public X509Certificate2 LoadCertificate(string issuerFileName, string password)
|
||||
{
|
||||
public string CertificatePassword { get; set; } = "password";
|
||||
public X509Certificate2 LoadCertificate(string issuerFileName, string password)
|
||||
// We need to pass 'Exportable', otherwise we can't get the private key.
|
||||
var issuerCertificate = new X509Certificate2(issuerFileName, password, X509KeyStorageFlags.Exportable);
|
||||
return issuerCertificate;
|
||||
}
|
||||
|
||||
public X509Certificate2 IssueCertificate(string subjectName, X509Certificate2 issuerCertificate, string[] subjectAlternativeNames, KeyPurposeID[] usages)
|
||||
{
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerName = issuerCertificate.Subject;
|
||||
|
||||
var random = GetSecureRandom();
|
||||
var subjectKeyPair = GenerateKeyPair(random, 2048);
|
||||
|
||||
var issuerKeyPair = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
|
||||
|
||||
var serialNumber = GenerateSerialNumber(random);
|
||||
var issuerSerialNumber = new BigInteger(issuerCertificate.GetSerialNumber());
|
||||
|
||||
const bool isCertificateAuthority = false;
|
||||
var certificate = GenerateCertificate(random, subjectName, subjectKeyPair, serialNumber,
|
||||
subjectAlternativeNames, issuerName, issuerKeyPair,
|
||||
issuerSerialNumber, isCertificateAuthority,
|
||||
usages);
|
||||
return ConvertCertificate(certificate, subjectKeyPair, random);
|
||||
}
|
||||
|
||||
public X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, string[] subjectAlternativeNames, KeyPurposeID[] usages)
|
||||
{
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerName = subjectName;
|
||||
|
||||
var random = GetSecureRandom();
|
||||
var subjectKeyPair = GenerateKeyPair(random, 2048);
|
||||
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerKeyPair = subjectKeyPair;
|
||||
|
||||
var serialNumber = GenerateSerialNumber(random);
|
||||
var issuerSerialNumber = serialNumber; // Self-signed, so it's the same serial number.
|
||||
|
||||
const bool isCertificateAuthority = true;
|
||||
var certificate = GenerateCertificate(random, subjectName, subjectKeyPair, serialNumber,
|
||||
subjectAlternativeNames, issuerName, issuerKeyPair,
|
||||
issuerSerialNumber, isCertificateAuthority,
|
||||
usages);
|
||||
return ConvertCertificate(certificate, subjectKeyPair, random);
|
||||
}
|
||||
|
||||
public X509Certificate2 CreateSelfSignedCertificate(string subjectName, string[] subjectAlternativeNames, KeyPurposeID[] usages)
|
||||
{
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerName = subjectName;
|
||||
|
||||
var random = GetSecureRandom();
|
||||
var subjectKeyPair = GenerateKeyPair(random, 2048);
|
||||
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerKeyPair = subjectKeyPair;
|
||||
|
||||
var serialNumber = GenerateSerialNumber(random);
|
||||
var issuerSerialNumber = serialNumber; // Self-signed, so it's the same serial number.
|
||||
|
||||
const bool isCertificateAuthority = false;
|
||||
var certificate = GenerateCertificate(random, subjectName, subjectKeyPair, serialNumber,
|
||||
subjectAlternativeNames, issuerName, issuerKeyPair,
|
||||
issuerSerialNumber, isCertificateAuthority,
|
||||
usages);
|
||||
return ConvertCertificate(certificate, subjectKeyPair, random);
|
||||
}
|
||||
|
||||
private SecureRandom GetSecureRandom()
|
||||
{
|
||||
// Since we're on Windows, we'll use the CryptoAPI one (on the assumption
|
||||
// that it might have access to better sources of entropy than the built-in
|
||||
// Bouncy Castle ones):
|
||||
var randomGenerator = new CryptoApiRandomGenerator();
|
||||
var random = new SecureRandom(randomGenerator);
|
||||
return random;
|
||||
}
|
||||
|
||||
private X509Certificate GenerateCertificate(SecureRandom random,
|
||||
string subjectName,
|
||||
AsymmetricCipherKeyPair subjectKeyPair,
|
||||
BigInteger subjectSerialNumber,
|
||||
string[] subjectAlternativeNames,
|
||||
string issuerName,
|
||||
AsymmetricCipherKeyPair issuerKeyPair,
|
||||
BigInteger issuerSerialNumber,
|
||||
bool isCertificateAuthority,
|
||||
KeyPurposeID[] usages)
|
||||
{
|
||||
var certificateGenerator = new X509V3CertificateGenerator();
|
||||
|
||||
certificateGenerator.SetSerialNumber(subjectSerialNumber);
|
||||
|
||||
var issuerDN = new X509Name(issuerName);
|
||||
certificateGenerator.SetIssuerDN(issuerDN);
|
||||
|
||||
// Note: The subject can be omitted if you specify a subject alternative name (SAN).
|
||||
var subjectDN = new X509Name(subjectName);
|
||||
certificateGenerator.SetSubjectDN(subjectDN);
|
||||
|
||||
// Our certificate needs valid from/to values.
|
||||
var notBefore = DateTime.UtcNow.Date;
|
||||
var notAfter = notBefore.AddYears(2);
|
||||
|
||||
certificateGenerator.SetNotBefore(notBefore);
|
||||
certificateGenerator.SetNotAfter(notAfter);
|
||||
|
||||
// The subject's public key goes in the certificate.
|
||||
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
|
||||
|
||||
AddAuthorityKeyIdentifier(certificateGenerator, issuerDN, issuerKeyPair, issuerSerialNumber);
|
||||
AddSubjectKeyIdentifier(certificateGenerator, subjectKeyPair);
|
||||
//AddBasicConstraints(certificateGenerator, isCertificateAuthority);
|
||||
|
||||
if (usages != null && usages.Any())
|
||||
AddExtendedKeyUsage(certificateGenerator, usages);
|
||||
|
||||
if (subjectAlternativeNames != null && subjectAlternativeNames.Any())
|
||||
AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames);
|
||||
|
||||
// Set the signature algorithm. This is used to generate the thumbprint which is then signed
|
||||
// with the issuer's private key. We'll use SHA-256, which is (currently) considered fairly strong.
|
||||
const string signatureAlgorithm = "SHA256WithRSA";
|
||||
|
||||
// The certificate is signed with the issuer's private key.
|
||||
ISignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerKeyPair.Private, random);
|
||||
var certificate = certificateGenerator.Generate(signatureFactory);
|
||||
return certificate;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The certificate needs a serial number. This is used for revocation,
|
||||
/// and usually should be an incrementing index (which makes it easier to revoke a range of certificates).
|
||||
/// Since we don't have anywhere to store the incrementing index, we can just use a random number.
|
||||
/// </summary>
|
||||
/// <param name="random"></param>
|
||||
/// <returns></returns>
|
||||
private BigInteger GenerateSerialNumber(SecureRandom random)
|
||||
{
|
||||
var serialNumber =
|
||||
BigIntegers.CreateRandomInRange(
|
||||
BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
|
||||
return serialNumber;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a key pair.
|
||||
/// </summary>
|
||||
/// <param name="random">The random number generator.</param>
|
||||
/// <param name="strength">The key length in bits. For RSA, 2048 bits should be considered the minimum acceptable these days.</param>
|
||||
/// <returns></returns>
|
||||
private AsymmetricCipherKeyPair GenerateKeyPair(SecureRandom random, int strength)
|
||||
{
|
||||
var keyGenerationParameters = new KeyGenerationParameters(random, strength);
|
||||
|
||||
var keyPairGenerator = new RsaKeyPairGenerator();
|
||||
keyPairGenerator.Init(keyGenerationParameters);
|
||||
var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
|
||||
return subjectKeyPair;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the Authority Key Identifier. According to http://www.alvestrand.no/objectid/2.5.29.35.html, this
|
||||
/// identifies the public key to be used to verify the signature on this certificate.
|
||||
/// In a certificate chain, this corresponds to the "Subject Key Identifier" on the *issuer* certificate.
|
||||
/// The Bouncy Castle documentation, at http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation,
|
||||
/// shows how to create this from the issuing certificate. Since we're creating a self-signed certificate, we have to do this slightly differently.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="issuerDN"></param>
|
||||
/// <param name="issuerKeyPair"></param>
|
||||
/// <param name="issuerSerialNumber"></param>
|
||||
private void AddAuthorityKeyIdentifier(X509V3CertificateGenerator certificateGenerator,
|
||||
X509Name issuerDN,
|
||||
AsymmetricCipherKeyPair issuerKeyPair,
|
||||
BigInteger issuerSerialNumber)
|
||||
{
|
||||
var authorityKeyIdentifierExtension =
|
||||
new AuthorityKeyIdentifier(
|
||||
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public),
|
||||
new GeneralNames(new GeneralName(issuerDN)),
|
||||
issuerSerialNumber);
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifierExtension);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the "Subject Alternative Names" extension. Note that you have to repeat
|
||||
/// the value from the "Subject Name" property.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="subjectAlternativeNames"></param>
|
||||
private void AddSubjectAlternativeNames(X509V3CertificateGenerator certificateGenerator,
|
||||
IEnumerable<string> subjectAlternativeNames)
|
||||
{
|
||||
var subjectAlternativeNamesExtension =
|
||||
new DerSequence(
|
||||
subjectAlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
|
||||
.ToArray<Asn1Encodable>());
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the "Extended Key Usage" extension, specifying (for example) "server authentication".
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="usages"></param>
|
||||
private void AddExtendedKeyUsage(X509V3CertificateGenerator certificateGenerator, KeyPurposeID[] usages)
|
||||
{
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(usages));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the "Basic Constraints" extension.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="isCertificateAuthority"></param>
|
||||
private void AddBasicConstraints(X509V3CertificateGenerator certificateGenerator,
|
||||
bool isCertificateAuthority)
|
||||
{
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCertificateAuthority));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the Subject Key Identifier.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="subjectKeyPair"></param>
|
||||
private void AddSubjectKeyIdentifier(X509V3CertificateGenerator certificateGenerator,
|
||||
AsymmetricCipherKeyPair subjectKeyPair)
|
||||
{
|
||||
var subjectKeyIdentifierExtension =
|
||||
new SubjectKeyIdentifier(
|
||||
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public));
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension);
|
||||
}
|
||||
|
||||
private X509Certificate2 ConvertCertificate(X509Certificate certificate,
|
||||
AsymmetricCipherKeyPair subjectKeyPair,
|
||||
SecureRandom random)
|
||||
{
|
||||
// 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
|
||||
// ...but, basically, we create a PKCS12 store (a .PFX file) in memory, and add the public and private key to that.
|
||||
var store = new Pkcs12StoreBuilder().Build();
|
||||
|
||||
// What Bouncy Castle calls "alias" is the same as what Windows terms the "friendly name".
|
||||
string friendlyName = certificate.SubjectDN.ToString();
|
||||
|
||||
// Add the certificate.
|
||||
var certificateEntry = new X509CertificateEntry(certificate);
|
||||
store.SetCertificateEntry(friendlyName, certificateEntry);
|
||||
|
||||
// Add the private key.
|
||||
store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });
|
||||
|
||||
// Convert it to an X509Certificate2 object by saving/loading it from a MemoryStream.
|
||||
// It needs a password. Since we'll remove this later, it doesn't particularly matter what we use.
|
||||
|
||||
var stream = new MemoryStream();
|
||||
store.Save(stream, CertificatePassword.ToCharArray(), random);
|
||||
|
||||
var convertedCertificate =
|
||||
new X509Certificate2(stream.ToArray(),
|
||||
CertificatePassword,
|
||||
X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
|
||||
return convertedCertificate;
|
||||
}
|
||||
|
||||
public void WriteCertificate(X509Certificate2 certificate, string outputDirectory, string certName)
|
||||
{
|
||||
// This password is the one attached to the PFX file. Use 'null' for no password.
|
||||
// Create PFX (PKCS #12) with private key
|
||||
try
|
||||
{
|
||||
// We need to pass 'Exportable', otherwise we can't get the private key.
|
||||
var issuerCertificate = new X509Certificate2(issuerFileName, password, X509KeyStorageFlags.Exportable);
|
||||
return issuerCertificate;
|
||||
var pfx = certificate.Export(X509ContentType.Pfx, CertificatePassword);
|
||||
File.WriteAllBytes(string.Format("{0}.pfx", Path.Combine(outputDirectory, certName)), pfx);
|
||||
}
|
||||
|
||||
public X509Certificate2 IssueCertificate(string subjectName, X509Certificate2 issuerCertificate, string[] subjectAlternativeNames, KeyPurposeID[] usages)
|
||||
catch (Exception ex)
|
||||
{
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerName = issuerCertificate.Subject;
|
||||
|
||||
var random = GetSecureRandom();
|
||||
var subjectKeyPair = GenerateKeyPair(random, 2048);
|
||||
|
||||
var issuerKeyPair = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
|
||||
|
||||
var serialNumber = GenerateSerialNumber(random);
|
||||
var issuerSerialNumber = new BigInteger(issuerCertificate.GetSerialNumber());
|
||||
|
||||
const bool isCertificateAuthority = false;
|
||||
var certificate = GenerateCertificate(random, subjectName, subjectKeyPair, serialNumber,
|
||||
subjectAlternativeNames, issuerName, issuerKeyPair,
|
||||
issuerSerialNumber, isCertificateAuthority,
|
||||
usages);
|
||||
return ConvertCertificate(certificate, subjectKeyPair, random);
|
||||
CrestronConsole.PrintLine(string.Format("Failed to write x509 cert pfx\r\n{0}", ex.Message));
|
||||
}
|
||||
|
||||
public X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, string[] subjectAlternativeNames, KeyPurposeID[] usages)
|
||||
// Create Base 64 encoded CER (public key only)
|
||||
using (var writer = new StreamWriter($"{Path.Combine(outputDirectory, certName)}.cer", false))
|
||||
{
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerName = subjectName;
|
||||
|
||||
var random = GetSecureRandom();
|
||||
var subjectKeyPair = GenerateKeyPair(random, 2048);
|
||||
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerKeyPair = subjectKeyPair;
|
||||
|
||||
var serialNumber = GenerateSerialNumber(random);
|
||||
var issuerSerialNumber = serialNumber; // Self-signed, so it's the same serial number.
|
||||
|
||||
const bool isCertificateAuthority = true;
|
||||
var certificate = GenerateCertificate(random, subjectName, subjectKeyPair, serialNumber,
|
||||
subjectAlternativeNames, issuerName, issuerKeyPair,
|
||||
issuerSerialNumber, isCertificateAuthority,
|
||||
usages);
|
||||
return ConvertCertificate(certificate, subjectKeyPair, random);
|
||||
}
|
||||
|
||||
public X509Certificate2 CreateSelfSignedCertificate(string subjectName, string[] subjectAlternativeNames, KeyPurposeID[] usages)
|
||||
{
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerName = subjectName;
|
||||
|
||||
var random = GetSecureRandom();
|
||||
var subjectKeyPair = GenerateKeyPair(random, 2048);
|
||||
|
||||
// It's self-signed, so these are the same.
|
||||
var issuerKeyPair = subjectKeyPair;
|
||||
|
||||
var serialNumber = GenerateSerialNumber(random);
|
||||
var issuerSerialNumber = serialNumber; // Self-signed, so it's the same serial number.
|
||||
|
||||
const bool isCertificateAuthority = false;
|
||||
var certificate = GenerateCertificate(random, subjectName, subjectKeyPair, serialNumber,
|
||||
subjectAlternativeNames, issuerName, issuerKeyPair,
|
||||
issuerSerialNumber, isCertificateAuthority,
|
||||
usages);
|
||||
return ConvertCertificate(certificate, subjectKeyPair, random);
|
||||
}
|
||||
|
||||
private SecureRandom GetSecureRandom()
|
||||
{
|
||||
// Since we're on Windows, we'll use the CryptoAPI one (on the assumption
|
||||
// that it might have access to better sources of entropy than the built-in
|
||||
// Bouncy Castle ones):
|
||||
var randomGenerator = new CryptoApiRandomGenerator();
|
||||
var random = new SecureRandom(randomGenerator);
|
||||
return random;
|
||||
}
|
||||
|
||||
private X509Certificate GenerateCertificate(SecureRandom random,
|
||||
string subjectName,
|
||||
AsymmetricCipherKeyPair subjectKeyPair,
|
||||
BigInteger subjectSerialNumber,
|
||||
string[] subjectAlternativeNames,
|
||||
string issuerName,
|
||||
AsymmetricCipherKeyPair issuerKeyPair,
|
||||
BigInteger issuerSerialNumber,
|
||||
bool isCertificateAuthority,
|
||||
KeyPurposeID[] usages)
|
||||
{
|
||||
var certificateGenerator = new X509V3CertificateGenerator();
|
||||
|
||||
certificateGenerator.SetSerialNumber(subjectSerialNumber);
|
||||
|
||||
var issuerDN = new X509Name(issuerName);
|
||||
certificateGenerator.SetIssuerDN(issuerDN);
|
||||
|
||||
// Note: The subject can be omitted if you specify a subject alternative name (SAN).
|
||||
var subjectDN = new X509Name(subjectName);
|
||||
certificateGenerator.SetSubjectDN(subjectDN);
|
||||
|
||||
// Our certificate needs valid from/to values.
|
||||
var notBefore = DateTime.UtcNow.Date;
|
||||
var notAfter = notBefore.AddYears(2);
|
||||
|
||||
certificateGenerator.SetNotBefore(notBefore);
|
||||
certificateGenerator.SetNotAfter(notAfter);
|
||||
|
||||
// The subject's public key goes in the certificate.
|
||||
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
|
||||
|
||||
AddAuthorityKeyIdentifier(certificateGenerator, issuerDN, issuerKeyPair, issuerSerialNumber);
|
||||
AddSubjectKeyIdentifier(certificateGenerator, subjectKeyPair);
|
||||
//AddBasicConstraints(certificateGenerator, isCertificateAuthority);
|
||||
|
||||
if (usages != null && usages.Any())
|
||||
AddExtendedKeyUsage(certificateGenerator, usages);
|
||||
|
||||
if (subjectAlternativeNames != null && subjectAlternativeNames.Any())
|
||||
AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames);
|
||||
|
||||
// Set the signature algorithm. This is used to generate the thumbprint which is then signed
|
||||
// with the issuer's private key. We'll use SHA-256, which is (currently) considered fairly strong.
|
||||
const string signatureAlgorithm = "SHA256WithRSA";
|
||||
|
||||
// The certificate is signed with the issuer's private key.
|
||||
ISignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerKeyPair.Private, random);
|
||||
var certificate = certificateGenerator.Generate(signatureFactory);
|
||||
return certificate;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The certificate needs a serial number. This is used for revocation,
|
||||
/// and usually should be an incrementing index (which makes it easier to revoke a range of certificates).
|
||||
/// Since we don't have anywhere to store the incrementing index, we can just use a random number.
|
||||
/// </summary>
|
||||
/// <param name="random"></param>
|
||||
/// <returns></returns>
|
||||
private BigInteger GenerateSerialNumber(SecureRandom random)
|
||||
{
|
||||
var serialNumber =
|
||||
BigIntegers.CreateRandomInRange(
|
||||
BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
|
||||
return serialNumber;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a key pair.
|
||||
/// </summary>
|
||||
/// <param name="random">The random number generator.</param>
|
||||
/// <param name="strength">The key length in bits. For RSA, 2048 bits should be considered the minimum acceptable these days.</param>
|
||||
/// <returns></returns>
|
||||
private AsymmetricCipherKeyPair GenerateKeyPair(SecureRandom random, int strength)
|
||||
{
|
||||
var keyGenerationParameters = new KeyGenerationParameters(random, strength);
|
||||
|
||||
var keyPairGenerator = new RsaKeyPairGenerator();
|
||||
keyPairGenerator.Init(keyGenerationParameters);
|
||||
var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
|
||||
return subjectKeyPair;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the Authority Key Identifier. According to http://www.alvestrand.no/objectid/2.5.29.35.html, this
|
||||
/// identifies the public key to be used to verify the signature on this certificate.
|
||||
/// In a certificate chain, this corresponds to the "Subject Key Identifier" on the *issuer* certificate.
|
||||
/// The Bouncy Castle documentation, at http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation,
|
||||
/// shows how to create this from the issuing certificate. Since we're creating a self-signed certificate, we have to do this slightly differently.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="issuerDN"></param>
|
||||
/// <param name="issuerKeyPair"></param>
|
||||
/// <param name="issuerSerialNumber"></param>
|
||||
private void AddAuthorityKeyIdentifier(X509V3CertificateGenerator certificateGenerator,
|
||||
X509Name issuerDN,
|
||||
AsymmetricCipherKeyPair issuerKeyPair,
|
||||
BigInteger issuerSerialNumber)
|
||||
{
|
||||
var authorityKeyIdentifierExtension =
|
||||
new AuthorityKeyIdentifier(
|
||||
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public),
|
||||
new GeneralNames(new GeneralName(issuerDN)),
|
||||
issuerSerialNumber);
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifierExtension);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the "Subject Alternative Names" extension. Note that you have to repeat
|
||||
/// the value from the "Subject Name" property.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="subjectAlternativeNames"></param>
|
||||
private void AddSubjectAlternativeNames(X509V3CertificateGenerator certificateGenerator,
|
||||
IEnumerable<string> subjectAlternativeNames)
|
||||
{
|
||||
var subjectAlternativeNamesExtension =
|
||||
new DerSequence(
|
||||
subjectAlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
|
||||
.ToArray<Asn1Encodable>());
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the "Extended Key Usage" extension, specifying (for example) "server authentication".
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="usages"></param>
|
||||
private void AddExtendedKeyUsage(X509V3CertificateGenerator certificateGenerator, KeyPurposeID[] usages)
|
||||
{
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(usages));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the "Basic Constraints" extension.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="isCertificateAuthority"></param>
|
||||
private void AddBasicConstraints(X509V3CertificateGenerator certificateGenerator,
|
||||
bool isCertificateAuthority)
|
||||
{
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCertificateAuthority));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the Subject Key Identifier.
|
||||
/// </summary>
|
||||
/// <param name="certificateGenerator"></param>
|
||||
/// <param name="subjectKeyPair"></param>
|
||||
private void AddSubjectKeyIdentifier(X509V3CertificateGenerator certificateGenerator,
|
||||
AsymmetricCipherKeyPair subjectKeyPair)
|
||||
{
|
||||
var subjectKeyIdentifierExtension =
|
||||
new SubjectKeyIdentifier(
|
||||
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public));
|
||||
certificateGenerator.AddExtension(
|
||||
X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension);
|
||||
}
|
||||
|
||||
private X509Certificate2 ConvertCertificate(X509Certificate certificate,
|
||||
AsymmetricCipherKeyPair subjectKeyPair,
|
||||
SecureRandom random)
|
||||
{
|
||||
// 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
|
||||
// ...but, basically, we create a PKCS12 store (a .PFX file) in memory, and add the public and private key to that.
|
||||
var store = new Pkcs12StoreBuilder().Build();
|
||||
|
||||
// What Bouncy Castle calls "alias" is the same as what Windows terms the "friendly name".
|
||||
string friendlyName = certificate.SubjectDN.ToString();
|
||||
|
||||
// Add the certificate.
|
||||
var certificateEntry = new X509CertificateEntry(certificate);
|
||||
store.SetCertificateEntry(friendlyName, certificateEntry);
|
||||
|
||||
// Add the private key.
|
||||
store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });
|
||||
|
||||
// Convert it to an X509Certificate2 object by saving/loading it from a MemoryStream.
|
||||
// It needs a password. Since we'll remove this later, it doesn't particularly matter what we use.
|
||||
|
||||
var stream = new MemoryStream();
|
||||
store.Save(stream, CertificatePassword.ToCharArray(), random);
|
||||
|
||||
var convertedCertificate =
|
||||
new X509Certificate2(stream.ToArray(),
|
||||
CertificatePassword,
|
||||
X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
|
||||
return convertedCertificate;
|
||||
}
|
||||
|
||||
public void WriteCertificate(X509Certificate2 certificate, string outputDirectory, string certName)
|
||||
{
|
||||
// This password is the one attached to the PFX file. Use 'null' for no password.
|
||||
// Create PFX (PKCS #12) with private key
|
||||
try
|
||||
{
|
||||
var pfx = certificate.Export(X509ContentType.Pfx, CertificatePassword);
|
||||
File.WriteAllBytes(string.Format("{0}.pfx", Path.Combine(outputDirectory, certName)), pfx);
|
||||
var contents = string.Format("-----BEGIN CERTIFICATE-----\r\n{0}\r\n-----END CERTIFICATE-----", Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
|
||||
writer.Write(contents);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CrestronConsole.PrintLine(string.Format("Failed to write x509 cert pfx\r\n{0}", ex.Message));
|
||||
CrestronConsole.PrintLine(string.Format("Failed to write x509 cert cer\r\n{0}", ex.Message));
|
||||
}
|
||||
// Create Base 64 encoded CER (public key only)
|
||||
using (var writer = new StreamWriter($"{Path.Combine(outputDirectory, certName)}.cer", false))
|
||||
{
|
||||
try
|
||||
{
|
||||
var contents = string.Format("-----BEGIN CERTIFICATE-----\r\n{0}\r\n-----END CERTIFICATE-----", Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
|
||||
writer.Write(contents);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CrestronConsole.PrintLine(string.Format("Failed to write x509 cert cer\r\n{0}", ex.Message));
|
||||
}
|
||||
}
|
||||
}
|
||||
public bool AddCertToStore(X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
|
||||
{
|
||||
bool bRet = false;
|
||||
|
||||
try
|
||||
{
|
||||
var store = new System.Security.Cryptography.X509Certificates.X509Store(st, sl);
|
||||
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
|
||||
store.Add(cert);
|
||||
|
||||
store.Close();
|
||||
bRet = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CrestronConsole.PrintLine(string.Format("AddCertToStore Failed\r\n{0}\r\n{1}", ex.Message, ex.StackTrace));
|
||||
}
|
||||
|
||||
return bRet;
|
||||
}
|
||||
}
|
||||
public bool AddCertToStore(X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
|
||||
{
|
||||
bool bRet = false;
|
||||
|
||||
try
|
||||
{
|
||||
var store = new System.Security.Cryptography.X509Certificates.X509Store(st, sl);
|
||||
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
|
||||
store.Add(cert);
|
||||
|
||||
store.Close();
|
||||
bRet = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CrestronConsole.PrintLine(string.Format("AddCertToStore Failed\r\n{0}\r\n{1}", ex.Message, ex.StackTrace));
|
||||
}
|
||||
|
||||
return bRet;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
using Crestron.SimplSharp.WebScripting;
|
||||
|
||||
namespace PepperDash.Core.Web.RequestHandlers
|
||||
namespace PepperDash.Core.Web.RequestHandlers;
|
||||
|
||||
/// <summary>
|
||||
/// Web API default request handler
|
||||
/// </summary>
|
||||
public class DefaultRequestHandler : WebApiBaseRequestHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Web API default request handler
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public class DefaultRequestHandler : WebApiBaseRequestHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public DefaultRequestHandler()
|
||||
: base(true)
|
||||
{ }
|
||||
}
|
||||
public DefaultRequestHandler()
|
||||
: base(true)
|
||||
{ }
|
||||
}
|
||||
@@ -1,163 +1,162 @@
|
||||
using Crestron.SimplSharp.WebScripting;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Crestron.SimplSharp.WebScripting;
|
||||
|
||||
namespace PepperDash.Core.Web.RequestHandlers
|
||||
namespace PepperDash.Core.Web.RequestHandlers;
|
||||
|
||||
public abstract class WebApiBaseRequestAsyncHandler : IHttpCwsHandler
|
||||
{
|
||||
public abstract class WebApiBaseRequestAsyncHandler:IHttpCwsHandler
|
||||
private readonly Dictionary<string, Func<HttpCwsContext, Task>> _handlers;
|
||||
protected readonly bool EnableCors;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
protected WebApiBaseRequestAsyncHandler(bool enableCors)
|
||||
{
|
||||
private readonly Dictionary<string, Func<HttpCwsContext, Task>> _handlers;
|
||||
protected readonly bool EnableCors;
|
||||
EnableCors = enableCors;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
protected WebApiBaseRequestAsyncHandler(bool enableCors)
|
||||
_handlers = new Dictionary<string, Func<HttpCwsContext, Task>>
|
||||
{
|
||||
EnableCors = enableCors;
|
||||
{"CONNECT", HandleConnect},
|
||||
{"DELETE", HandleDelete},
|
||||
{"GET", HandleGet},
|
||||
{"HEAD", HandleHead},
|
||||
{"OPTIONS", HandleOptions},
|
||||
{"PATCH", HandlePatch},
|
||||
{"POST", HandlePost},
|
||||
{"PUT", HandlePut},
|
||||
{"TRACE", HandleTrace}
|
||||
};
|
||||
}
|
||||
|
||||
_handlers = new Dictionary<string, Func<HttpCwsContext, Task>>
|
||||
{
|
||||
{"CONNECT", HandleConnect},
|
||||
{"DELETE", HandleDelete},
|
||||
{"GET", HandleGet},
|
||||
{"HEAD", HandleHead},
|
||||
{"OPTIONS", HandleOptions},
|
||||
{"PATCH", HandlePatch},
|
||||
{"POST", HandlePost},
|
||||
{"PUT", HandlePut},
|
||||
{"TRACE", HandleTrace}
|
||||
};
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
protected WebApiBaseRequestAsyncHandler()
|
||||
: this(false)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles CONNECT method requests
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
protected virtual async Task 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 async Task 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 async Task 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 async Task 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 async Task 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 async Task 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 async Task 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 async Task 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 async Task 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)
|
||||
{
|
||||
if (!_handlers.TryGetValue(context.Request.HttpMethod, out Func<HttpCwsContext, Task> handler))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
protected WebApiBaseRequestAsyncHandler()
|
||||
: this(false)
|
||||
if (EnableCors)
|
||||
{
|
||||
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
|
||||
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles CONNECT method requests
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
protected virtual async Task HandleConnect(HttpCwsContext context)
|
||||
{
|
||||
context.Response.StatusCode = 501;
|
||||
context.Response.StatusDescription = "Not Implemented";
|
||||
context.Response.End();
|
||||
}
|
||||
var handlerTask = handler(context);
|
||||
|
||||
/// <summary>
|
||||
/// Handles DELETE method requests
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
protected virtual async Task 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 async Task 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 async Task 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 async Task 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 async Task 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 async Task 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 async Task 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 async Task 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)
|
||||
{
|
||||
if (!_handlers.TryGetValue(context.Request.HttpMethod, out Func<HttpCwsContext, Task> handler))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (EnableCors)
|
||||
{
|
||||
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
|
||||
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
||||
}
|
||||
|
||||
var handlerTask = handler(context);
|
||||
|
||||
handlerTask.GetAwaiter().GetResult();
|
||||
}
|
||||
handlerTask.GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,24 +2,24 @@
|
||||
using System.Collections.Generic;
|
||||
using Crestron.SimplSharp.WebScripting;
|
||||
|
||||
namespace PepperDash.Core.Web.RequestHandlers
|
||||
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>
|
||||
/// CWS Base Handler, implements IHttpCwsHandler
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public abstract class WebApiBaseRequestHandler : IHttpCwsHandler
|
||||
protected WebApiBaseRequestHandler(bool enableCors)
|
||||
{
|
||||
private readonly Dictionary<string, Action<HttpCwsContext>> _handlers;
|
||||
protected readonly bool EnableCors;
|
||||
EnableCors = enableCors;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
protected WebApiBaseRequestHandler(bool enableCors)
|
||||
{
|
||||
EnableCors = enableCors;
|
||||
|
||||
_handlers = new Dictionary<string, Action<HttpCwsContext>>
|
||||
_handlers = new Dictionary<string, Action<HttpCwsContext>>
|
||||
{
|
||||
{"CONNECT", HandleConnect},
|
||||
{"DELETE", HandleDelete},
|
||||
@@ -31,135 +31,134 @@ namespace PepperDash.Core.Web.RequestHandlers
|
||||
{"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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
protected WebApiBaseRequestHandler()
|
||||
: this(false)
|
||||
if (EnableCors)
|
||||
{
|
||||
}
|
||||
|
||||
/// <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();
|
||||
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
|
||||
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
handler(context);
|
||||
}
|
||||
}
|
||||
@@ -7,278 +7,277 @@ using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using PepperDash.Core.Web.RequestHandlers;
|
||||
|
||||
namespace PepperDash.Core.Web
|
||||
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
|
||||
/// Web API server key
|
||||
/// </summary>
|
||||
public class WebApiServer : IKeyName
|
||||
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)
|
||||
{
|
||||
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;
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="basePath"></param>
|
||||
public WebApiServer(string key, string basePath)
|
||||
: this(key, DefaultName, basePath)
|
||||
{
|
||||
}
|
||||
|
||||
private readonly CCriticalSection _serverLock = new CCriticalSection();
|
||||
private HttpCwsServer _server;
|
||||
/// <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;
|
||||
|
||||
/// <summary>
|
||||
/// Web API server key
|
||||
/// </summary>
|
||||
public string Key { get; private set; }
|
||||
if (_server == null) _server = new HttpCwsServer(BasePath);
|
||||
|
||||
/// <summary>
|
||||
/// Web API server name
|
||||
/// </summary>
|
||||
public string Name { get; private set; }
|
||||
_server.setProcessName(Key);
|
||||
_server.HttpRequestHandler = new DefaultRequestHandler();
|
||||
|
||||
/// <summary>
|
||||
/// CWS base path, will default to "/api" if not set via initialize method
|
||||
/// </summary>
|
||||
public string BasePath { get; private set; }
|
||||
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
|
||||
CrestronEnvironment.EthernetEventHandler += CrestronEnvironment_EthernetEventHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates CWS is registered with base path
|
||||
/// </summary>
|
||||
public bool IsRegistered { get; private set; }
|
||||
/// <summary>
|
||||
/// Program status event handler
|
||||
/// </summary>
|
||||
/// <param name="programEventType"></param>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType != eProgramStatusEventType.Stopping) return;
|
||||
|
||||
/// <summary>
|
||||
/// Http request handler
|
||||
/// </summary>
|
||||
//public IHttpCwsHandler HttpRequestHandler
|
||||
//{
|
||||
// get { return _server.HttpRequestHandler; }
|
||||
// set
|
||||
// {
|
||||
// if (_server == null) return;
|
||||
// _server.HttpRequestHandler = value;
|
||||
// }
|
||||
//}
|
||||
Debug.Console(DebugInfo, this, "Program stopping. stopping server");
|
||||
|
||||
/// <summary>
|
||||
/// Received request event handler
|
||||
/// </summary>
|
||||
//public event EventHandler<HttpCwsRequestEventArgs> ReceivedRequestEvent
|
||||
//{
|
||||
// add { _server.ReceivedRequestEvent += new HttpCwsRequestEventHandler(value); }
|
||||
// remove { _server.ReceivedRequestEvent -= new HttpCwsRequestEventHandler(value); }
|
||||
//}
|
||||
Stop();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for S+. Make sure to set necessary properties using init method
|
||||
/// </summary>
|
||||
public WebApiServer()
|
||||
: this(SplusKey, DefaultName, null)
|
||||
/// <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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="basePath"></param>
|
||||
public WebApiServer(string key, string basePath)
|
||||
: this(key, DefaultName, basePath)
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="basePath"></param>
|
||||
public WebApiServer(string key, string name, string basePath)
|
||||
_server.Routes.Add(route);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a route from CWS
|
||||
/// </summary>
|
||||
/// <param name="route"></param>
|
||||
public void RemoveRoute(HttpCwsRoute route)
|
||||
{
|
||||
if (route == null)
|
||||
{
|
||||
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;
|
||||
Debug.Console(DebugInfo, this, "Failed to remote route, orute parameter is null");
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Program status event handler
|
||||
/// </summary>
|
||||
/// <param name="programEventType"></param>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
_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
|
||||
{
|
||||
if (programEventType != eProgramStatusEventType.Stopping) return;
|
||||
_serverLock.Enter();
|
||||
|
||||
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)
|
||||
if (_server == null)
|
||||
{
|
||||
Debug.Console(DebugInfo, this, "Ethernet link up. Server is alreedy registered.");
|
||||
Debug.Console(DebugInfo, this, "Server is null, unable to start");
|
||||
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)
|
||||
if (IsRegistered)
|
||||
{
|
||||
Debug.Console(DebugInfo, this, "Failed to add route, route parameter is null");
|
||||
Debug.Console(DebugInfo, this, "Server has already been started");
|
||||
return;
|
||||
}
|
||||
|
||||
_server.Routes.Add(route);
|
||||
IsRegistered = _server.Register();
|
||||
|
||||
Debug.Console(DebugInfo, this, "Starting server, registration {0}", IsRegistered ? "was successful" : "failed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a route from CWS
|
||||
/// </summary>
|
||||
/// <param name="route"></param>
|
||||
public void RemoveRoute(HttpCwsRoute route)
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (route == null)
|
||||
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, "Failed to remote route, orute parameter is null");
|
||||
Debug.Console(DebugInfo, this, "Server is null or has already been stopped");
|
||||
return;
|
||||
}
|
||||
|
||||
_server.Routes.Remove(route);
|
||||
IsRegistered = _server.Unregister() == false;
|
||||
|
||||
Debug.Console(DebugInfo, this, "Stopping server, unregistration {0}", IsRegistered ? "failed" : "was successful");
|
||||
|
||||
_server.Dispose();
|
||||
_server = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a list of the current routes
|
||||
/// </summary>
|
||||
public HttpCwsRouteCollection GetRouteCollection()
|
||||
catch (Exception ex)
|
||||
{
|
||||
return _server.Routes;
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts CWS instance
|
||||
/// </summary>
|
||||
public void Start()
|
||||
finally
|
||||
{
|
||||
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();
|
||||
}
|
||||
_serverLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stop CWS instance
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
/// <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
|
||||
{
|
||||
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();
|
||||
}
|
||||
var j = JsonConvert.SerializeObject(args.Context, Formatting.Indented);
|
||||
Debug.Console(DebugVerbose, this, "RecieveRequestEventHandler Context:\x0d\x0a{0}", j);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
catch (Exception ex)
|
||||
{
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,45 @@
|
||||
using System;
|
||||
|
||||
namespace PepperDash.Core.WebApi.Presets
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a preset
|
||||
/// </summary>
|
||||
namespace PepperDash.Core.WebApi.Presets;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a preset
|
||||
/// </summary>
|
||||
public class Preset
|
||||
{
|
||||
/// <summary>
|
||||
/// ID of preset
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// ID of preset
|
||||
/// </summary>
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// User ID
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// User ID
|
||||
/// </summary>
|
||||
public int UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Room Type ID
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Room Type ID
|
||||
/// </summary>
|
||||
public int RoomTypeId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Preset Name
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Preset Name
|
||||
/// </summary>
|
||||
public string PresetName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Preset Number
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Preset Number
|
||||
/// </summary>
|
||||
public int PresetNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Preset Data
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Preset Data
|
||||
/// </summary>
|
||||
public string Data { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public Preset()
|
||||
{
|
||||
PresetName = "";
|
||||
@@ -53,35 +53,34 @@ namespace PepperDash.Core.WebApi.Presets
|
||||
/// </summary>
|
||||
public class PresetReceivedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// True when the preset is found
|
||||
/// </summary>
|
||||
public bool LookupSuccess { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper
|
||||
/// </summary>
|
||||
public ushort ULookupSuccess { get { return (ushort)(LookupSuccess ? 1 : 0); } }
|
||||
/// <summary>
|
||||
/// True when the preset is found
|
||||
/// </summary>
|
||||
public bool LookupSuccess { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper
|
||||
/// </summary>
|
||||
public ushort ULookupSuccess { get { return (ushort)(LookupSuccess ? 1 : 0); } }
|
||||
|
||||
/// <summary>
|
||||
/// The preset
|
||||
/// </summary>
|
||||
public Preset Preset { get; private set; }
|
||||
/// <summary>
|
||||
/// The preset
|
||||
/// </summary>
|
||||
public Preset Preset { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// For Simpl+
|
||||
/// </summary>
|
||||
public PresetReceivedEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="preset"></param>
|
||||
/// <param name="success"></param>
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="preset"></param>
|
||||
/// <param name="success"></param>
|
||||
public PresetReceivedEventArgs(Preset preset, bool success)
|
||||
{
|
||||
LookupSuccess = success;
|
||||
LookupSuccess = success;
|
||||
Preset = preset;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,31 +4,31 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.WebApi.Presets
|
||||
{
|
||||
namespace PepperDash.Core.WebApi.Presets;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class User
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string ExternalId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string FirstName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string LastName { get; set; }
|
||||
}
|
||||
|
||||
@@ -38,19 +38,19 @@ namespace PepperDash.Core.WebApi.Presets
|
||||
/// </summary>
|
||||
public class UserReceivedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// True when user is found
|
||||
/// </summary>
|
||||
public bool LookupSuccess { get; private set; }
|
||||
/// <summary>
|
||||
/// True when user is found
|
||||
/// </summary>
|
||||
public bool LookupSuccess { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// For stupid S+
|
||||
/// </summary>
|
||||
public ushort ULookupSuccess { get { return (ushort)(LookupSuccess ? 1 : 0); } }
|
||||
/// <summary>
|
||||
/// For stupid S+
|
||||
/// </summary>
|
||||
public ushort ULookupSuccess { get { return (ushort)(LookupSuccess ? 1 : 0); } }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public User User { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -58,14 +58,14 @@ namespace PepperDash.Core.WebApi.Presets
|
||||
/// </summary>
|
||||
public UserReceivedEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="user"></param>
|
||||
/// <param name="success"></param>
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="user"></param>
|
||||
/// <param name="success"></param>
|
||||
public UserReceivedEventArgs(User user, bool success)
|
||||
{
|
||||
LookupSuccess = success;
|
||||
LookupSuccess = success;
|
||||
User = user;
|
||||
}
|
||||
}
|
||||
@@ -75,19 +75,18 @@ namespace PepperDash.Core.WebApi.Presets
|
||||
/// </summary>
|
||||
public class UserAndRoomMessage
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int RoomTypeId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int PresetNumber { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
using Crestron.SimplSharp; // For Basic SIMPL# Classes
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using System.IO;
|
||||
using Crestron.SimplSharp; // For Basic SIMPL# Classes
|
||||
using Crestron.SimplSharp.Net.Http;
|
||||
using Crestron.SimplSharp.Net.Https;
|
||||
using Newtonsoft.Json;
|
||||
@@ -8,266 +8,265 @@ using Newtonsoft.Json.Linq;
|
||||
using PepperDash.Core.JsonToSimpl;
|
||||
|
||||
|
||||
namespace PepperDash.Core.WebApi.Presets
|
||||
namespace PepperDash.Core.WebApi.Presets;
|
||||
|
||||
/// <summary>
|
||||
/// Passcode client for the WebApi
|
||||
/// </summary>
|
||||
public class WebApiPasscodeClient : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Passcode client for the WebApi
|
||||
/// </summary>
|
||||
public class WebApiPasscodeClient : IKeyed
|
||||
/// <summary>
|
||||
/// Notifies when user received
|
||||
/// </summary>
|
||||
public event EventHandler<UserReceivedEventArgs> UserReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Notifies when Preset received
|
||||
/// </summary>
|
||||
public event EventHandler<PresetReceivedEventArgs> PresetReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Unique identifier for this instance
|
||||
/// </summary>
|
||||
public string Key { get; private set; }
|
||||
|
||||
//string JsonMasterKey;
|
||||
|
||||
/// <summary>
|
||||
/// An embedded JsonToSimpl master object.
|
||||
/// </summary>
|
||||
JsonToSimplGenericMaster J2SMaster;
|
||||
|
||||
string UrlBase;
|
||||
|
||||
string DefaultPresetJsonFilePath;
|
||||
|
||||
User CurrentUser;
|
||||
|
||||
Preset CurrentPreset;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// SIMPL+ can only execute the default constructor. If you have variables that require initialization, please
|
||||
/// use an Initialize method
|
||||
/// </summary>
|
||||
public WebApiPasscodeClient()
|
||||
{
|
||||
/// <summary>
|
||||
/// Notifies when user received
|
||||
/// </summary>
|
||||
public event EventHandler<UserReceivedEventArgs> UserReceived;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notifies when Preset received
|
||||
/// </summary>
|
||||
public event EventHandler<PresetReceivedEventArgs> PresetReceived;
|
||||
/// <summary>
|
||||
/// Initializes the instance
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="jsonMasterKey"></param>
|
||||
/// <param name="urlBase"></param>
|
||||
/// <param name="defaultPresetJsonFilePath"></param>
|
||||
public void Initialize(string key, string jsonMasterKey, string urlBase, string defaultPresetJsonFilePath)
|
||||
{
|
||||
Key = key;
|
||||
//JsonMasterKey = jsonMasterKey;
|
||||
UrlBase = urlBase;
|
||||
DefaultPresetJsonFilePath = defaultPresetJsonFilePath;
|
||||
|
||||
/// <summary>
|
||||
/// Unique identifier for this instance
|
||||
/// </summary>
|
||||
public string Key { get; private set; }
|
||||
J2SMaster = new JsonToSimplGenericMaster();
|
||||
J2SMaster.SaveCallback = this.SaveCallback;
|
||||
J2SMaster.Initialize(jsonMasterKey);
|
||||
}
|
||||
|
||||
//string JsonMasterKey;
|
||||
/// <summary>
|
||||
/// Gets the user for a passcode
|
||||
/// </summary>
|
||||
/// <param name="passcode"></param>
|
||||
public void GetUserForPasscode(string passcode)
|
||||
{
|
||||
// Bullshit duplicate code here... These two cases should be the same
|
||||
// except for https/http and the certificate ignores
|
||||
if (!UrlBase.StartsWith("https"))
|
||||
return;
|
||||
var req = new HttpsClientRequest();
|
||||
req.Url = new UrlParser(UrlBase + "/api/users/dopin");
|
||||
req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
|
||||
req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
|
||||
req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
|
||||
var jo = new JObject();
|
||||
jo.Add("pin", passcode);
|
||||
req.ContentString = jo.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// An embedded JsonToSimpl master object.
|
||||
/// </summary>
|
||||
JsonToSimplGenericMaster J2SMaster;
|
||||
|
||||
string UrlBase;
|
||||
|
||||
string DefaultPresetJsonFilePath;
|
||||
|
||||
User CurrentUser;
|
||||
|
||||
Preset CurrentPreset;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// SIMPL+ can only execute the default constructor. If you have variables that require initialization, please
|
||||
/// use an Initialize method
|
||||
/// </summary>
|
||||
public WebApiPasscodeClient()
|
||||
var client = new HttpsClient();
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
var resp = client.Dispatch(req);
|
||||
var handler = UserReceived;
|
||||
if (resp.Code == 200)
|
||||
{
|
||||
//CrestronConsole.PrintLine("Received: {0}", resp.ContentString);
|
||||
var user = JsonConvert.DeserializeObject<User>(resp.ContentString);
|
||||
CurrentUser = user;
|
||||
if (handler != null)
|
||||
UserReceived(this, new UserReceivedEventArgs(user, true));
|
||||
}
|
||||
else
|
||||
if (handler != null)
|
||||
UserReceived(this, new UserReceivedEventArgs(null, false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roomTypeId"></param>
|
||||
/// <param name="presetNumber"></param>
|
||||
public void GetPresetForThisUser(int roomTypeId, int presetNumber)
|
||||
{
|
||||
if (CurrentUser == null)
|
||||
{
|
||||
CrestronConsole.PrintLine("GetPresetForThisUser no user loaded");
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the instance
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="jsonMasterKey"></param>
|
||||
/// <param name="urlBase"></param>
|
||||
/// <param name="defaultPresetJsonFilePath"></param>
|
||||
public void Initialize(string key, string jsonMasterKey, string urlBase, string defaultPresetJsonFilePath)
|
||||
var msg = new UserAndRoomMessage
|
||||
{
|
||||
Key = key;
|
||||
//JsonMasterKey = jsonMasterKey;
|
||||
UrlBase = urlBase;
|
||||
DefaultPresetJsonFilePath = defaultPresetJsonFilePath;
|
||||
UserId = CurrentUser.Id,
|
||||
RoomTypeId = roomTypeId,
|
||||
PresetNumber = presetNumber
|
||||
};
|
||||
|
||||
J2SMaster = new JsonToSimplGenericMaster();
|
||||
J2SMaster.SaveCallback = this.SaveCallback;
|
||||
J2SMaster.Initialize(jsonMasterKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user for a passcode
|
||||
/// </summary>
|
||||
/// <param name="passcode"></param>
|
||||
public void GetUserForPasscode(string passcode)
|
||||
var handler = PresetReceived;
|
||||
try
|
||||
{
|
||||
// Bullshit duplicate code here... These two cases should be the same
|
||||
// except for https/http and the certificate ignores
|
||||
if (!UrlBase.StartsWith("https"))
|
||||
return;
|
||||
var req = new HttpsClientRequest();
|
||||
req.Url = new UrlParser(UrlBase + "/api/users/dopin");
|
||||
req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
|
||||
req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
|
||||
req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
|
||||
var jo = new JObject();
|
||||
jo.Add("pin", passcode);
|
||||
req.ContentString = jo.ToString();
|
||||
|
||||
var client = new HttpsClient();
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
var resp = client.Dispatch(req);
|
||||
var handler = UserReceived;
|
||||
if (resp.Code == 200)
|
||||
{
|
||||
//CrestronConsole.PrintLine("Received: {0}", resp.ContentString);
|
||||
var user = JsonConvert.DeserializeObject<User>(resp.ContentString);
|
||||
CurrentUser = user;
|
||||
if (handler != null)
|
||||
UserReceived(this, new UserReceivedEventArgs(user, true));
|
||||
}
|
||||
else
|
||||
if (handler != null)
|
||||
UserReceived(this, new UserReceivedEventArgs(null, false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roomTypeId"></param>
|
||||
/// <param name="presetNumber"></param>
|
||||
public void GetPresetForThisUser(int roomTypeId, int presetNumber)
|
||||
{
|
||||
if (CurrentUser == null)
|
||||
{
|
||||
CrestronConsole.PrintLine("GetPresetForThisUser no user loaded");
|
||||
if (!UrlBase.StartsWith("https"))
|
||||
return;
|
||||
}
|
||||
|
||||
var msg = new UserAndRoomMessage
|
||||
{
|
||||
UserId = CurrentUser.Id,
|
||||
RoomTypeId = roomTypeId,
|
||||
PresetNumber = presetNumber
|
||||
};
|
||||
|
||||
var handler = PresetReceived;
|
||||
try
|
||||
{
|
||||
if (!UrlBase.StartsWith("https"))
|
||||
return;
|
||||
var req = new HttpsClientRequest();
|
||||
req.Url = new UrlParser(UrlBase + "/api/presets/userandroom");
|
||||
req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
|
||||
req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
|
||||
req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
|
||||
req.ContentString = JsonConvert.SerializeObject(msg);
|
||||
|
||||
var client = new HttpsClient();
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
|
||||
// ask for the preset
|
||||
var resp = client.Dispatch(req);
|
||||
if (resp.Code == 200) // got it
|
||||
{
|
||||
//Debug.Console(1, this, "Received: {0}", resp.ContentString);
|
||||
var preset = JsonConvert.DeserializeObject<Preset>(resp.ContentString);
|
||||
CurrentPreset = preset;
|
||||
|
||||
//if there's no preset data, load the template
|
||||
if (preset.Data == null || preset.Data.Trim() == string.Empty || JObject.Parse(preset.Data).Count == 0)
|
||||
{
|
||||
//Debug.Console(1, this, "Loaded preset has no data. Loading default template.");
|
||||
LoadDefaultPresetData();
|
||||
return;
|
||||
}
|
||||
|
||||
J2SMaster.LoadWithJson(preset.Data);
|
||||
if (handler != null)
|
||||
PresetReceived(this, new PresetReceivedEventArgs(preset, true));
|
||||
}
|
||||
else // no existing preset
|
||||
{
|
||||
CurrentPreset = new Preset();
|
||||
LoadDefaultPresetData();
|
||||
if (handler != null)
|
||||
PresetReceived(this, new PresetReceivedEventArgs(null, false));
|
||||
}
|
||||
}
|
||||
catch (HttpException e)
|
||||
{
|
||||
var resp = e.Response;
|
||||
Debug.Console(1, this, "No preset received (code {0}). Loading default template", resp.Code);
|
||||
LoadDefaultPresetData();
|
||||
if (handler != null)
|
||||
PresetReceived(this, new PresetReceivedEventArgs(null, false));
|
||||
}
|
||||
}
|
||||
|
||||
void LoadDefaultPresetData()
|
||||
{
|
||||
CurrentPreset = null;
|
||||
if (!File.Exists(DefaultPresetJsonFilePath))
|
||||
{
|
||||
Debug.Console(0, this, "Cannot load default preset file. Saving will not work");
|
||||
return;
|
||||
}
|
||||
using (StreamReader sr = new StreamReader(DefaultPresetJsonFilePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = sr.ReadToEnd();
|
||||
J2SMaster.SetJsonWithoutEvaluating(data);
|
||||
CurrentPreset = new Preset() { Data = data, UserId = CurrentUser.Id };
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Console(0, this, "Error reading default preset JSON: \r{0}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roomTypeId"></param>
|
||||
/// <param name="presetNumber"></param>
|
||||
public void SavePresetForThisUser(int roomTypeId, int presetNumber)
|
||||
{
|
||||
if (CurrentPreset == null)
|
||||
LoadDefaultPresetData();
|
||||
//return;
|
||||
|
||||
//// A new preset needs to have its numbers set
|
||||
//if (CurrentPreset.IsNewPreset)
|
||||
//{
|
||||
CurrentPreset.UserId = CurrentUser.Id;
|
||||
CurrentPreset.RoomTypeId = roomTypeId;
|
||||
CurrentPreset.PresetNumber = presetNumber;
|
||||
//}
|
||||
J2SMaster.Save(); // Will trigger callback when ready
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After save operation on JSON master happens, send it to server
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
void SaveCallback(string json)
|
||||
{
|
||||
CurrentPreset.Data = json;
|
||||
|
||||
if (!UrlBase.StartsWith("https"))
|
||||
return;
|
||||
var req = new HttpsClientRequest();
|
||||
req.Url = new UrlParser(UrlBase + "/api/presets/userandroom");
|
||||
req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
|
||||
req.Url = new UrlParser(string.Format("{0}/api/presets/addorchange", UrlBase));
|
||||
req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
|
||||
req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
|
||||
req.ContentString = JsonConvert.SerializeObject(CurrentPreset);
|
||||
req.ContentString = JsonConvert.SerializeObject(msg);
|
||||
|
||||
var client = new HttpsClient();
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
|
||||
// ask for the preset
|
||||
var resp = client.Dispatch(req);
|
||||
if (resp.Code == 200) // got it
|
||||
{
|
||||
//Debug.Console(1, this, "Received: {0}", resp.ContentString);
|
||||
var preset = JsonConvert.DeserializeObject<Preset>(resp.ContentString);
|
||||
CurrentPreset = preset;
|
||||
|
||||
//if there's no preset data, load the template
|
||||
if (preset.Data == null || preset.Data.Trim() == string.Empty || JObject.Parse(preset.Data).Count == 0)
|
||||
{
|
||||
//Debug.Console(1, this, "Loaded preset has no data. Loading default template.");
|
||||
LoadDefaultPresetData();
|
||||
return;
|
||||
}
|
||||
|
||||
J2SMaster.LoadWithJson(preset.Data);
|
||||
if (handler != null)
|
||||
PresetReceived(this, new PresetReceivedEventArgs(preset, true));
|
||||
}
|
||||
else // no existing preset
|
||||
{
|
||||
CurrentPreset = new Preset();
|
||||
LoadDefaultPresetData();
|
||||
if (handler != null)
|
||||
PresetReceived(this, new PresetReceivedEventArgs(null, false));
|
||||
}
|
||||
}
|
||||
catch (HttpException e)
|
||||
{
|
||||
var resp = e.Response;
|
||||
Debug.Console(1, this, "No preset received (code {0}). Loading default template", resp.Code);
|
||||
LoadDefaultPresetData();
|
||||
if (handler != null)
|
||||
PresetReceived(this, new PresetReceivedEventArgs(null, false));
|
||||
}
|
||||
}
|
||||
|
||||
void LoadDefaultPresetData()
|
||||
{
|
||||
CurrentPreset = null;
|
||||
if (!File.Exists(DefaultPresetJsonFilePath))
|
||||
{
|
||||
Debug.Console(0, this, "Cannot load default preset file. Saving will not work");
|
||||
return;
|
||||
}
|
||||
using (StreamReader sr = new StreamReader(DefaultPresetJsonFilePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
var resp = client.Dispatch(req);
|
||||
|
||||
// 201=created
|
||||
// 204=empty content
|
||||
if (resp.Code == 201)
|
||||
CrestronConsole.PrintLine("Preset added");
|
||||
else if (resp.Code == 204)
|
||||
CrestronConsole.PrintLine("Preset updated");
|
||||
else if (resp.Code == 209)
|
||||
CrestronConsole.PrintLine("Preset already exists. Cannot save as new.");
|
||||
else
|
||||
CrestronConsole.PrintLine("Preset save failed: {0}\r", resp.Code, resp.ContentString);
|
||||
var data = sr.ReadToEnd();
|
||||
J2SMaster.SetJsonWithoutEvaluating(data);
|
||||
CurrentPreset = new Preset() { Data = data, UserId = CurrentUser.Id };
|
||||
}
|
||||
catch (HttpException e)
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
CrestronConsole.PrintLine("Preset save exception {0}", e.Response.Code);
|
||||
Debug.Console(0, this, "Error reading default preset JSON: \r{0}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roomTypeId"></param>
|
||||
/// <param name="presetNumber"></param>
|
||||
public void SavePresetForThisUser(int roomTypeId, int presetNumber)
|
||||
{
|
||||
if (CurrentPreset == null)
|
||||
LoadDefaultPresetData();
|
||||
//return;
|
||||
|
||||
//// A new preset needs to have its numbers set
|
||||
//if (CurrentPreset.IsNewPreset)
|
||||
//{
|
||||
CurrentPreset.UserId = CurrentUser.Id;
|
||||
CurrentPreset.RoomTypeId = roomTypeId;
|
||||
CurrentPreset.PresetNumber = presetNumber;
|
||||
//}
|
||||
J2SMaster.Save(); // Will trigger callback when ready
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After save operation on JSON master happens, send it to server
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
void SaveCallback(string json)
|
||||
{
|
||||
CurrentPreset.Data = json;
|
||||
|
||||
if (!UrlBase.StartsWith("https"))
|
||||
return;
|
||||
var req = new HttpsClientRequest();
|
||||
req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
|
||||
req.Url = new UrlParser(string.Format("{0}/api/presets/addorchange", UrlBase));
|
||||
req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
|
||||
req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
|
||||
req.ContentString = JsonConvert.SerializeObject(CurrentPreset);
|
||||
|
||||
var client = new HttpsClient();
|
||||
client.HostVerification = false;
|
||||
client.PeerVerification = false;
|
||||
try
|
||||
{
|
||||
var resp = client.Dispatch(req);
|
||||
|
||||
// 201=created
|
||||
// 204=empty content
|
||||
if (resp.Code == 201)
|
||||
CrestronConsole.PrintLine("Preset added");
|
||||
else if (resp.Code == 204)
|
||||
CrestronConsole.PrintLine("Preset updated");
|
||||
else if (resp.Code == 209)
|
||||
CrestronConsole.PrintLine("Preset already exists. Cannot save as new.");
|
||||
else
|
||||
CrestronConsole.PrintLine("Preset save failed: {0}\r", resp.Code, resp.ContentString);
|
||||
}
|
||||
catch (HttpException e)
|
||||
{
|
||||
|
||||
CrestronConsole.PrintLine("Preset save exception {0}", e.Response.Code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
using System.Collections.Generic;
|
||||
using PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
namespace PepperDash.Core.Intersystem.Serialization
|
||||
namespace PepperDash.Core.Intersystem.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// Interface to determine XSig serialization for an object.
|
||||
/// </summary>
|
||||
public interface IXSigSerialization
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface to determine XSig serialization for an object.
|
||||
/// Serialize the sig data
|
||||
/// </summary>
|
||||
public interface IXSigSerialization
|
||||
{
|
||||
/// <summary>
|
||||
/// Serialize the sig data
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IEnumerable<XSigToken> Serialize();
|
||||
/// <returns></returns>
|
||||
IEnumerable<XSigToken> Serialize();
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize the sig data
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="tokens"></param>
|
||||
/// <returns></returns>
|
||||
T Deserialize<T>(IEnumerable<XSigToken> tokens) where T : class, IXSigSerialization;
|
||||
}
|
||||
/// <summary>
|
||||
/// Deserialize the sig data
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="tokens"></param>
|
||||
/// <returns></returns>
|
||||
T Deserialize<T>(IEnumerable<XSigToken> tokens) where T : class, IXSigSerialization;
|
||||
}
|
||||
@@ -1,28 +1,27 @@
|
||||
using System;
|
||||
|
||||
namespace PepperDash.Core.Intersystem.Serialization
|
||||
namespace PepperDash.Core.Intersystem.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// Class to handle this specific exception type
|
||||
/// </summary>
|
||||
public class XSigSerializationException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to handle this specific exception type
|
||||
/// default constructor
|
||||
/// </summary>
|
||||
public class XSigSerializationException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// default constructor
|
||||
/// </summary>
|
||||
public XSigSerializationException() { }
|
||||
public XSigSerializationException() { }
|
||||
|
||||
/// <summary>
|
||||
/// constructor with message
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public XSigSerializationException(string message) : base(message) { }
|
||||
/// <summary>
|
||||
/// constructor with message
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public XSigSerializationException(string message) : base(message) { }
|
||||
|
||||
/// <summary>
|
||||
/// constructor with message and innner exception
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="inner"></param>
|
||||
public XSigSerializationException(string message, Exception inner) : base(message, inner) { }
|
||||
}
|
||||
/// <summary>
|
||||
/// constructor with message and innner exception
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="inner"></param>
|
||||
public XSigSerializationException(string message, Exception inner) : base(message, inner) { }
|
||||
}
|
||||
@@ -1,88 +1,87 @@
|
||||
using System;
|
||||
|
||||
namespace PepperDash.Core.Intersystem.Tokens
|
||||
namespace PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an XSigAnalogToken
|
||||
/// </summary>
|
||||
public sealed class XSigAnalogToken : XSigToken, IFormattable
|
||||
{
|
||||
private readonly ushort _value;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an XSigAnalogToken
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public sealed class XSigAnalogToken : XSigToken, IFormattable
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
public XSigAnalogToken(int index, ushort value)
|
||||
: base(index)
|
||||
{
|
||||
private readonly ushort _value;
|
||||
// 10-bits available for analog encoded data
|
||||
if (index >= 1024 || index < 0)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
public XSigAnalogToken(int index, ushort value)
|
||||
: base(index)
|
||||
{
|
||||
// 10-bits available for analog encoded data
|
||||
if (index >= 1024 || index < 0)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
_value = value;
|
||||
}
|
||||
|
||||
_value = value;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Value
|
||||
{
|
||||
get { return _value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ushort Value
|
||||
{
|
||||
get { return _value; }
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override XSigTokenType TokenType
|
||||
{
|
||||
get { return XSigTokenType.Analog; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override XSigTokenType TokenType
|
||||
{
|
||||
get { return XSigTokenType.Analog; }
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override byte[] GetBytes()
|
||||
{
|
||||
return new[] {
|
||||
(byte)(0xC0 | ((Value & 0xC000) >> 10) | (Index - 1 >> 7)),
|
||||
(byte)((Index - 1) & 0x7F),
|
||||
(byte)((Value & 0x3F80) >> 7),
|
||||
(byte)(Value & 0x7F)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override byte[] GetBytes()
|
||||
{
|
||||
return new[] {
|
||||
(byte)(0xC0 | ((Value & 0xC000) >> 10) | (Index - 1 >> 7)),
|
||||
(byte)((Index - 1) & 0x7F),
|
||||
(byte)((Value & 0x3F80) >> 7),
|
||||
(byte)(Value & 0x7F)
|
||||
};
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="offset"></param>
|
||||
/// <returns></returns>
|
||||
public override XSigToken GetTokenWithOffset(int offset)
|
||||
{
|
||||
if (offset == 0) return this;
|
||||
return new XSigAnalogToken(Index + offset, Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="offset"></param>
|
||||
/// <returns></returns>
|
||||
public override XSigToken GetTokenWithOffset(int offset)
|
||||
{
|
||||
if (offset == 0) return this;
|
||||
return new XSigAnalogToken(Index + offset, Value);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return Index + " = 0x" + Value.ToString("X4");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return Index + " = 0x" + Value.ToString("X4");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="format"></param>
|
||||
/// <param name="formatProvider"></param>
|
||||
/// <returns></returns>
|
||||
public string ToString(string format, IFormatProvider formatProvider)
|
||||
{
|
||||
return Value.ToString(format, formatProvider);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="format"></param>
|
||||
/// <param name="formatProvider"></param>
|
||||
/// <returns></returns>
|
||||
public string ToString(string format, IFormatProvider formatProvider)
|
||||
{
|
||||
return Value.ToString(format, formatProvider);
|
||||
}
|
||||
}
|
||||
@@ -1,85 +1,84 @@
|
||||
using System;
|
||||
|
||||
namespace PepperDash.Core.Intersystem.Tokens
|
||||
namespace PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an XSigDigitalToken
|
||||
/// </summary>
|
||||
public sealed class XSigDigitalToken : XSigToken
|
||||
{
|
||||
private readonly bool _value;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an XSigDigitalToken
|
||||
///
|
||||
/// </summary>
|
||||
public sealed class XSigDigitalToken : XSigToken
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
public XSigDigitalToken(int index, bool value)
|
||||
: base(index)
|
||||
{
|
||||
private readonly bool _value;
|
||||
// 12-bits available for digital encoded data
|
||||
if (index >= 4096 || index < 0)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
public XSigDigitalToken(int index, bool value)
|
||||
: base(index)
|
||||
{
|
||||
// 12-bits available for digital encoded data
|
||||
if (index >= 4096 || index < 0)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
_value = value;
|
||||
}
|
||||
|
||||
_value = value;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool Value
|
||||
{
|
||||
get { return _value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool Value
|
||||
{
|
||||
get { return _value; }
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override XSigTokenType TokenType
|
||||
{
|
||||
get { return XSigTokenType.Digital; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override XSigTokenType TokenType
|
||||
{
|
||||
get { return XSigTokenType.Digital; }
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override byte[] GetBytes()
|
||||
{
|
||||
return new[] {
|
||||
(byte)(0x80 | (Value ? 0 : 0x20) | ((Index - 1) >> 7)),
|
||||
(byte)((Index - 1) & 0x7F)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override byte[] GetBytes()
|
||||
{
|
||||
return new[] {
|
||||
(byte)(0x80 | (Value ? 0 : 0x20) | ((Index - 1) >> 7)),
|
||||
(byte)((Index - 1) & 0x7F)
|
||||
};
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="offset"></param>
|
||||
/// <returns></returns>
|
||||
public override XSigToken GetTokenWithOffset(int offset)
|
||||
{
|
||||
if (offset == 0) return this;
|
||||
return new XSigDigitalToken(Index + offset, Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="offset"></param>
|
||||
/// <returns></returns>
|
||||
public override XSigToken GetTokenWithOffset(int offset)
|
||||
{
|
||||
if (offset == 0) return this;
|
||||
return new XSigDigitalToken(Index + offset, Value);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return Index + " = " + (Value ? "High" : "Low");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return Index + " = " + (Value ? "High" : "Low");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="formatProvider"></param>
|
||||
/// <returns></returns>
|
||||
public string ToString(IFormatProvider formatProvider)
|
||||
{
|
||||
return Value.ToString(formatProvider);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="formatProvider"></param>
|
||||
/// <returns></returns>
|
||||
public string ToString(IFormatProvider formatProvider)
|
||||
{
|
||||
return Value.ToString(formatProvider);
|
||||
}
|
||||
}
|
||||
@@ -1,81 +1,80 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace PepperDash.Core.Intersystem.Tokens
|
||||
namespace PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an XSigSerialToken
|
||||
/// </summary>
|
||||
public sealed class XSigSerialToken : XSigToken
|
||||
{
|
||||
private readonly string _value;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an XSigSerialToken
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public sealed class XSigSerialToken : XSigToken
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
public XSigSerialToken(int index, string value)
|
||||
: base(index)
|
||||
{
|
||||
private readonly string _value;
|
||||
// 10-bits available for serial encoded data
|
||||
if (index >= 1024 || index < 0)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
public XSigSerialToken(int index, string value)
|
||||
: base(index)
|
||||
{
|
||||
// 10-bits available for serial encoded data
|
||||
if (index >= 1024 || index < 0)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
_value = value;
|
||||
}
|
||||
|
||||
_value = value;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Value
|
||||
{
|
||||
get { return _value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string Value
|
||||
{
|
||||
get { return _value; }
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override XSigTokenType TokenType
|
||||
{
|
||||
get { return XSigTokenType.Serial; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public override XSigTokenType TokenType
|
||||
{
|
||||
get { return XSigTokenType.Serial; }
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override byte[] GetBytes()
|
||||
{
|
||||
var serialBytes = String.IsNullOrEmpty(Value) ? new byte[0] : Encoding.GetEncoding(28591).GetBytes(Value);
|
||||
|
||||
var xsig = new byte[serialBytes.Length + 3];
|
||||
xsig[0] = (byte)(0xC8 | (Index - 1 >> 7));
|
||||
xsig[1] = (byte)((Index - 1) & 0x7F);
|
||||
xsig[xsig.Length - 1] = 0xFF;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override byte[] GetBytes()
|
||||
{
|
||||
var serialBytes = String.IsNullOrEmpty(Value) ? new byte[0] : Encoding.GetEncoding(28591).GetBytes(Value);
|
||||
|
||||
var xsig = new byte[serialBytes.Length + 3];
|
||||
xsig[0] = (byte)(0xC8 | (Index - 1 >> 7));
|
||||
xsig[1] = (byte)((Index - 1) & 0x7F);
|
||||
xsig[xsig.Length - 1] = 0xFF;
|
||||
Buffer.BlockCopy(serialBytes, 0, xsig, 2, serialBytes.Length);
|
||||
return xsig;
|
||||
}
|
||||
|
||||
Buffer.BlockCopy(serialBytes, 0, xsig, 2, serialBytes.Length);
|
||||
return xsig;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="offset"></param>
|
||||
/// <returns></returns>
|
||||
public override XSigToken GetTokenWithOffset(int offset)
|
||||
{
|
||||
if (offset == 0) return this;
|
||||
return new XSigSerialToken(Index + offset, Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="offset"></param>
|
||||
/// <returns></returns>
|
||||
public override XSigToken GetTokenWithOffset(int offset)
|
||||
{
|
||||
if (offset == 0) return this;
|
||||
return new XSigSerialToken(Index + offset, Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return Index + " = \"" + Value + "\"";
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return Index + " = \"" + Value + "\"";
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,44 @@
|
||||
namespace PepperDash.Core.Intersystem.Tokens
|
||||
namespace PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the base class for all XSig datatypes.
|
||||
/// </summary>
|
||||
public abstract class XSigToken
|
||||
{
|
||||
private readonly int _index;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the base class for all XSig datatypes.
|
||||
/// Constructs an XSigToken with the specified index.
|
||||
/// </summary>
|
||||
public abstract class XSigToken
|
||||
/// <param name="index">Index for the data.</param>
|
||||
protected XSigToken(int index)
|
||||
{
|
||||
private readonly int _index;
|
||||
|
||||
/// <summary>
|
||||
/// Constructs an XSigToken with the specified index.
|
||||
/// </summary>
|
||||
/// <param name="index">Index for the data.</param>
|
||||
protected XSigToken(int index)
|
||||
{
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// XSig 1-based index.
|
||||
/// </summary>
|
||||
public int Index
|
||||
{
|
||||
get { return _index; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// XSigToken type.
|
||||
/// </summary>
|
||||
public abstract XSigTokenType TokenType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Generates the XSig bytes for the corresponding token.
|
||||
/// </summary>
|
||||
/// <returns>XSig byte array.</returns>
|
||||
public abstract byte[] GetBytes();
|
||||
|
||||
/// <summary>
|
||||
/// Returns a new token if necessary with an updated index based on the specified offset.
|
||||
/// </summary>
|
||||
/// <param name="offset">Offset to adjust the index with.</param>
|
||||
/// <returns>XSigToken</returns>
|
||||
public abstract XSigToken GetTokenWithOffset(int offset);
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// XSig 1-based index.
|
||||
/// </summary>
|
||||
public int Index
|
||||
{
|
||||
get { return _index; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// XSigToken type.
|
||||
/// </summary>
|
||||
public abstract XSigTokenType TokenType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Generates the XSig bytes for the corresponding token.
|
||||
/// </summary>
|
||||
/// <returns>XSig byte array.</returns>
|
||||
public abstract byte[] GetBytes();
|
||||
|
||||
/// <summary>
|
||||
/// Returns a new token if necessary with an updated index based on the specified offset.
|
||||
/// </summary>
|
||||
/// <param name="offset">Offset to adjust the index with.</param>
|
||||
/// <returns>XSigToken</returns>
|
||||
public abstract XSigToken GetTokenWithOffset(int offset);
|
||||
}
|
||||
@@ -1,23 +1,22 @@
|
||||
namespace PepperDash.Core.Intersystem.Tokens
|
||||
namespace PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
/// <summary>
|
||||
/// XSig token types.
|
||||
/// </summary>
|
||||
public enum XSigTokenType
|
||||
{
|
||||
/// <summary>
|
||||
/// XSig token types.
|
||||
/// Digital signal datatype.
|
||||
/// </summary>
|
||||
public enum XSigTokenType
|
||||
{
|
||||
/// <summary>
|
||||
/// Digital signal datatype.
|
||||
/// </summary>
|
||||
Digital,
|
||||
Digital,
|
||||
|
||||
/// <summary>
|
||||
/// Analog signal datatype.
|
||||
/// </summary>
|
||||
Analog,
|
||||
/// <summary>
|
||||
/// Analog signal datatype.
|
||||
/// </summary>
|
||||
Analog,
|
||||
|
||||
/// <summary>
|
||||
/// Serial signal datatype.
|
||||
/// </summary>
|
||||
Serial
|
||||
}
|
||||
/// <summary>
|
||||
/// Serial signal datatype.
|
||||
/// </summary>
|
||||
Serial
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using PepperDash.Core.Intersystem.Serialization;
|
||||
using PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
@@ -18,222 +18,221 @@ using PepperDash.Core.Intersystem.Tokens;
|
||||
11111111 <- denotes end of data
|
||||
*/
|
||||
|
||||
namespace PepperDash.Core.Intersystem
|
||||
namespace PepperDash.Core.Intersystem;
|
||||
|
||||
/// <summary>
|
||||
/// Helper methods for creating XSig byte sequences compatible with the Intersystem Communications (ISC) symbol.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indexing is not from the start of each signal type but rather from the beginning of the first defined signal
|
||||
/// the Intersystem Communications (ISC) symbol.
|
||||
/// </remarks>
|
||||
public static class XSigHelpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper methods for creating XSig byte sequences compatible with the Intersystem Communications (ISC) symbol.
|
||||
/// Forces all outputs to 0.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indexing is not from the start of each signal type but rather from the beginning of the first defined signal
|
||||
/// the Intersystem Communications (ISC) symbol.
|
||||
/// </remarks>
|
||||
public static class XSigHelpers
|
||||
/// <returns>Bytes in XSig format for clear outputs trigger.</returns>
|
||||
public static byte[] ClearOutputs()
|
||||
{
|
||||
/// <summary>
|
||||
/// Forces all outputs to 0.
|
||||
/// </summary>
|
||||
/// <returns>Bytes in XSig format for clear outputs trigger.</returns>
|
||||
public static byte[] ClearOutputs()
|
||||
return new byte[] { 0xFC };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluate all inputs and re-transmit any digital, analog, and permanent serail signals not set to 0.
|
||||
/// </summary>
|
||||
/// <returns>Bytes in XSig format for send status trigger.</returns>
|
||||
public static byte[] SendStatus()
|
||||
{
|
||||
return new byte[] { 0xFD };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for an IXSigStateResolver object.
|
||||
/// </summary>
|
||||
/// <param name="xSigSerialization">XSig state resolver.</param>
|
||||
/// <returns>Bytes in XSig format for each token within the state representation.</returns>
|
||||
public static byte[] GetBytes(IXSigSerialization xSigSerialization)
|
||||
{
|
||||
return GetBytes(xSigSerialization, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for an IXSigStateResolver object, with a specified offset.
|
||||
/// </summary>
|
||||
/// <param name="xSigSerialization">XSig state resolver.</param>
|
||||
/// <param name="offset">Offset to which the data will be aligned.</param>
|
||||
/// <returns>Bytes in XSig format for each token within the state representation.</returns>
|
||||
public static byte[] GetBytes(IXSigSerialization xSigSerialization, int offset)
|
||||
{
|
||||
var tokens = xSigSerialization.Serialize();
|
||||
if (tokens == null) return new byte[0];
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
return new byte[] { 0xFC };
|
||||
}
|
||||
using (var tokenWriter = new XSigTokenStreamWriter(memoryStream))
|
||||
tokenWriter.WriteXSigData(xSigSerialization, offset);
|
||||
|
||||
/// <summary>
|
||||
/// Evaluate all inputs and re-transmit any digital, analog, and permanent serail signals not set to 0.
|
||||
/// </summary>
|
||||
/// <returns>Bytes in XSig format for send status trigger.</returns>
|
||||
public static byte[] SendStatus()
|
||||
{
|
||||
return new byte[] { 0xFD };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for an IXSigStateResolver object.
|
||||
/// </summary>
|
||||
/// <param name="xSigSerialization">XSig state resolver.</param>
|
||||
/// <returns>Bytes in XSig format for each token within the state representation.</returns>
|
||||
public static byte[] GetBytes(IXSigSerialization xSigSerialization)
|
||||
{
|
||||
return GetBytes(xSigSerialization, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for an IXSigStateResolver object, with a specified offset.
|
||||
/// </summary>
|
||||
/// <param name="xSigSerialization">XSig state resolver.</param>
|
||||
/// <param name="offset">Offset to which the data will be aligned.</param>
|
||||
/// <returns>Bytes in XSig format for each token within the state representation.</returns>
|
||||
public static byte[] GetBytes(IXSigSerialization xSigSerialization, int offset)
|
||||
{
|
||||
var tokens = xSigSerialization.Serialize();
|
||||
if (tokens == null) return new byte[0];
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
using (var tokenWriter = new XSigTokenStreamWriter(memoryStream))
|
||||
tokenWriter.WriteXSigData(xSigSerialization, offset);
|
||||
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single digital signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based digital index</param>
|
||||
/// <param name="value">Digital data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for digtial information.</returns>
|
||||
public static byte[] GetBytes(int index, bool value)
|
||||
{
|
||||
return GetBytes(index, 0, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single digital signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based digital index</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="value">Digital data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for digtial information.</returns>
|
||||
public static byte[] GetBytes(int index, int offset, bool value)
|
||||
{
|
||||
return new XSigDigitalToken(index + offset, value).GetBytes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple digital signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="values">Digital signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for digital signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, bool[] values)
|
||||
{
|
||||
return GetBytes(startIndex, 0, values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple digital signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="values">Digital signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for digital signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, int offset, bool[] values)
|
||||
{
|
||||
// Digital XSig data is 2 bytes per value
|
||||
const int fixedLength = 2;
|
||||
var bytes = new byte[values.Length * fixedLength];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
Buffer.BlockCopy(GetBytes(startIndex++, offset, values[i]), 0, bytes, i * fixedLength, fixedLength);
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single analog signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based analog index</param>
|
||||
/// <param name="value">Analog data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int index, ushort value)
|
||||
{
|
||||
return GetBytes(index, 0, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single analog signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based analog index</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="value">Analog data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int index, int offset, ushort value)
|
||||
{
|
||||
return new XSigAnalogToken(index + offset, value).GetBytes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple analog signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="values">Analog signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, ushort[] values)
|
||||
{
|
||||
return GetBytes(startIndex, 0, values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple analog signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="values">Analog signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, int offset, ushort[] values)
|
||||
{
|
||||
// Analog XSig data is 4 bytes per value
|
||||
const int fixedLength = 4;
|
||||
var bytes = new byte[values.Length * fixedLength];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
Buffer.BlockCopy(GetBytes(startIndex++, offset, values[i]), 0, bytes, i * fixedLength, fixedLength);
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single serial signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based serial index</param>
|
||||
/// <param name="value">Serial data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int index, string value)
|
||||
{
|
||||
return GetBytes(index, 0, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single serial signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based serial index</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="value">Serial data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int index, int offset, string value)
|
||||
{
|
||||
return new XSigSerialToken(index + offset, value).GetBytes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple serial signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="values">Serial signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, string[] values)
|
||||
{
|
||||
return GetBytes(startIndex, 0, values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple serial signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="values">Serial signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, int offset, string[] values)
|
||||
{
|
||||
// Serial XSig data is not fixed-length like the other formats
|
||||
var dstOffset = 0;
|
||||
var bytes = new byte[values.Sum(v => v.Length + 3)];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
var data = GetBytes(startIndex++, offset, values[i]);
|
||||
Buffer.BlockCopy(data, 0, bytes, dstOffset, data.Length);
|
||||
dstOffset += data.Length;
|
||||
}
|
||||
|
||||
return bytes;
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single digital signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based digital index</param>
|
||||
/// <param name="value">Digital data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for digtial information.</returns>
|
||||
public static byte[] GetBytes(int index, bool value)
|
||||
{
|
||||
return GetBytes(index, 0, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single digital signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based digital index</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="value">Digital data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for digtial information.</returns>
|
||||
public static byte[] GetBytes(int index, int offset, bool value)
|
||||
{
|
||||
return new XSigDigitalToken(index + offset, value).GetBytes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple digital signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="values">Digital signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for digital signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, bool[] values)
|
||||
{
|
||||
return GetBytes(startIndex, 0, values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple digital signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="values">Digital signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for digital signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, int offset, bool[] values)
|
||||
{
|
||||
// Digital XSig data is 2 bytes per value
|
||||
const int fixedLength = 2;
|
||||
var bytes = new byte[values.Length * fixedLength];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
Buffer.BlockCopy(GetBytes(startIndex++, offset, values[i]), 0, bytes, i * fixedLength, fixedLength);
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single analog signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based analog index</param>
|
||||
/// <param name="value">Analog data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int index, ushort value)
|
||||
{
|
||||
return GetBytes(index, 0, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single analog signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based analog index</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="value">Analog data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int index, int offset, ushort value)
|
||||
{
|
||||
return new XSigAnalogToken(index + offset, value).GetBytes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple analog signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="values">Analog signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, ushort[] values)
|
||||
{
|
||||
return GetBytes(startIndex, 0, values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple analog signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="values">Analog signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for analog signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, int offset, ushort[] values)
|
||||
{
|
||||
// Analog XSig data is 4 bytes per value
|
||||
const int fixedLength = 4;
|
||||
var bytes = new byte[values.Length * fixedLength];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
Buffer.BlockCopy(GetBytes(startIndex++, offset, values[i]), 0, bytes, i * fixedLength, fixedLength);
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single serial signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based serial index</param>
|
||||
/// <param name="value">Serial data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int index, string value)
|
||||
{
|
||||
return GetBytes(index, 0, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get bytes for a single serial signal.
|
||||
/// </summary>
|
||||
/// <param name="index">1-based serial index</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="value">Serial data to be encoded</param>
|
||||
/// <returns>Bytes in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int index, int offset, string value)
|
||||
{
|
||||
return new XSigSerialToken(index + offset, value).GetBytes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple serial signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="values">Serial signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, string[] values)
|
||||
{
|
||||
return GetBytes(startIndex, 0, values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get byte sequence for multiple serial signals.
|
||||
/// </summary>
|
||||
/// <param name="startIndex">Starting index of the sequence.</param>
|
||||
/// <param name="offset">Index offset.</param>
|
||||
/// <param name="values">Serial signal value array.</param>
|
||||
/// <returns>Byte sequence in XSig format for serial signal information.</returns>
|
||||
public static byte[] GetBytes(int startIndex, int offset, string[] values)
|
||||
{
|
||||
// Serial XSig data is not fixed-length like the other formats
|
||||
var dstOffset = 0;
|
||||
var bytes = new byte[values.Sum(v => v.Length + 3)];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
var data = GetBytes(startIndex++, offset, values[i]);
|
||||
Buffer.BlockCopy(data, 0, bytes, dstOffset, data.Length);
|
||||
dstOffset += data.Length;
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -1,147 +1,146 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using System.IO;
|
||||
using PepperDash.Core.Intersystem.Serialization;
|
||||
using PepperDash.Core.Intersystem.Tokens;
|
||||
|
||||
namespace PepperDash.Core.Intersystem
|
||||
namespace PepperDash.Core.Intersystem;
|
||||
|
||||
/// <summary>
|
||||
/// XSigToken stream reader.
|
||||
/// </summary>
|
||||
public sealed class XSigTokenStreamReader : IDisposable
|
||||
{
|
||||
private readonly Stream _stream;
|
||||
private readonly bool _leaveOpen;
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// XSigToken stream reader.
|
||||
/// XSigToken stream reader constructor.
|
||||
/// </summary>
|
||||
public sealed class XSigTokenStreamReader : IDisposable
|
||||
/// <param name="stream">Input stream to read from.</param>
|
||||
/// <exception cref="T:System.ArgumentNullException">Stream is null.</exception>
|
||||
/// <exception cref="T:System.ArgumentException">Stream cannot be read from.</exception>
|
||||
public XSigTokenStreamReader(Stream stream)
|
||||
: this(stream, false) { }
|
||||
|
||||
/// <summary>
|
||||
/// XSigToken stream reader constructor.
|
||||
/// </summary>
|
||||
/// <param name="stream">Input stream to read from.</param>
|
||||
/// <param name="leaveOpen">Determines whether to leave the stream open or not.</param>
|
||||
/// <exception cref="ArgumentNullException">Stream is null.</exception>
|
||||
/// <exception cref="ArgumentException">Stream cannot be read from.</exception>
|
||||
public XSigTokenStreamReader(Stream stream, bool leaveOpen)
|
||||
{
|
||||
private readonly Stream _stream;
|
||||
private readonly bool _leaveOpen;
|
||||
if (stream == null)
|
||||
throw new ArgumentNullException("stream");
|
||||
if (!stream.CanRead)
|
||||
throw new ArgumentException("The specified stream cannot be read from.");
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// XSigToken stream reader constructor.
|
||||
/// </summary>
|
||||
/// <param name="stream">Input stream to read from.</param>
|
||||
/// <exception cref="T:System.ArgumentNullException">Stream is null.</exception>
|
||||
/// <exception cref="T:System.ArgumentException">Stream cannot be read from.</exception>
|
||||
public XSigTokenStreamReader(Stream stream)
|
||||
: this(stream, false) { }
|
||||
_stream = stream;
|
||||
_leaveOpen = leaveOpen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// XSigToken stream reader constructor.
|
||||
/// </summary>
|
||||
/// <param name="stream">Input stream to read from.</param>
|
||||
/// <param name="leaveOpen">Determines whether to leave the stream open or not.</param>
|
||||
/// <exception cref="ArgumentNullException">Stream is null.</exception>
|
||||
/// <exception cref="ArgumentException">Stream cannot be read from.</exception>
|
||||
public XSigTokenStreamReader(Stream stream, bool leaveOpen)
|
||||
/// <summary>
|
||||
/// Reads a 16-bit unsigned integer from the specified stream using Big Endian byte order.
|
||||
/// </summary>
|
||||
/// <param name="stream">Input stream</param>
|
||||
/// <param name="value">Result</param>
|
||||
/// <returns>True if successful, otherwise false.</returns>
|
||||
public static bool TryReadUInt16BE(Stream stream, out ushort value)
|
||||
{
|
||||
value = 0;
|
||||
if (stream.Length < 2)
|
||||
return false;
|
||||
|
||||
var buffer = new byte[2];
|
||||
stream.Read(buffer, 0, 2);
|
||||
value = (ushort)((buffer[0] << 8) | buffer[1]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read XSig token from the stream.
|
||||
/// </summary>
|
||||
/// <returns>XSigToken</returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Offset is less than 0.</exception>
|
||||
public XSigToken ReadXSigToken()
|
||||
{
|
||||
ushort prefix;
|
||||
if (!TryReadUInt16BE(_stream, out prefix))
|
||||
return null;
|
||||
|
||||
if ((prefix & 0xF880) == 0xC800) // Serial data
|
||||
{
|
||||
if (stream == null)
|
||||
throw new ArgumentNullException("stream");
|
||||
if (!stream.CanRead)
|
||||
throw new ArgumentException("The specified stream cannot be read from.");
|
||||
|
||||
_stream = stream;
|
||||
_leaveOpen = leaveOpen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a 16-bit unsigned integer from the specified stream using Big Endian byte order.
|
||||
/// </summary>
|
||||
/// <param name="stream">Input stream</param>
|
||||
/// <param name="value">Result</param>
|
||||
/// <returns>True if successful, otherwise false.</returns>
|
||||
public static bool TryReadUInt16BE(Stream stream, out ushort value)
|
||||
{
|
||||
value = 0;
|
||||
if (stream.Length < 2)
|
||||
return false;
|
||||
|
||||
var buffer = new byte[2];
|
||||
stream.Read(buffer, 0, 2);
|
||||
value = (ushort)((buffer[0] << 8) | buffer[1]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read XSig token from the stream.
|
||||
/// </summary>
|
||||
/// <returns>XSigToken</returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Offset is less than 0.</exception>
|
||||
public XSigToken ReadXSigToken()
|
||||
{
|
||||
ushort prefix;
|
||||
if (!TryReadUInt16BE(_stream, out prefix))
|
||||
return null;
|
||||
|
||||
if ((prefix & 0xF880) == 0xC800) // Serial data
|
||||
var index = ((prefix & 0x0700) >> 1) | (prefix & 0x7F);
|
||||
var n = 0;
|
||||
const int maxSerialDataLength = 252;
|
||||
var chars = new char[maxSerialDataLength];
|
||||
int ch;
|
||||
while ((ch = _stream.ReadByte()) != 0xFF)
|
||||
{
|
||||
var index = ((prefix & 0x0700) >> 1) | (prefix & 0x7F);
|
||||
var n = 0;
|
||||
const int maxSerialDataLength = 252;
|
||||
var chars = new char[maxSerialDataLength];
|
||||
int ch;
|
||||
while ((ch = _stream.ReadByte()) != 0xFF)
|
||||
{
|
||||
if (ch == -1) // Reached end of stream without end of data marker
|
||||
return null;
|
||||
|
||||
chars[n++] = (char)ch;
|
||||
}
|
||||
|
||||
return new XSigSerialToken((ushort)(index + 1), new string(chars, 0, n));
|
||||
}
|
||||
|
||||
if ((prefix & 0xC880) == 0xC000) // Analog data
|
||||
{
|
||||
ushort data;
|
||||
if (!TryReadUInt16BE(_stream, out data))
|
||||
if (ch == -1) // Reached end of stream without end of data marker
|
||||
return null;
|
||||
|
||||
var index = ((prefix & 0x0700) >> 1) | (prefix & 0x7F);
|
||||
var value = ((prefix & 0x3000) << 2) | ((data & 0x7F00) >> 1) | (data & 0x7F);
|
||||
return new XSigAnalogToken((ushort)(index + 1), (ushort)value);
|
||||
chars[n++] = (char)ch;
|
||||
}
|
||||
|
||||
if ((prefix & 0xC080) == 0x8000) // Digital data
|
||||
{
|
||||
var index = ((prefix & 0x1F00) >> 1) | (prefix & 0x7F);
|
||||
var value = (prefix & 0x2000) == 0;
|
||||
return new XSigDigitalToken((ushort)(index + 1), value);
|
||||
}
|
||||
|
||||
return null;
|
||||
return new XSigSerialToken((ushort)(index + 1), new string(chars, 0, n));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads all available XSig tokens from the stream.
|
||||
/// </summary>
|
||||
/// <returns>XSigToken collection.</returns>
|
||||
public IEnumerable<XSigToken> ReadAllXSigTokens()
|
||||
if ((prefix & 0xC880) == 0xC000) // Analog data
|
||||
{
|
||||
var tokens = new List<XSigToken>();
|
||||
XSigToken token;
|
||||
while ((token = ReadXSigToken()) != null)
|
||||
tokens.Add(token);
|
||||
ushort data;
|
||||
if (!TryReadUInt16BE(_stream, out data))
|
||||
return null;
|
||||
|
||||
return tokens;
|
||||
var index = ((prefix & 0x0700) >> 1) | (prefix & 0x7F);
|
||||
var value = ((prefix & 0x3000) << 2) | ((data & 0x7F00) >> 1) | (data & 0x7F);
|
||||
return new XSigAnalogToken((ushort)(index + 1), (ushort)value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to deserialize all XSig data within the stream from the current position.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type to deserialize the information to.</typeparam>
|
||||
/// <returns>Deserialized object.</returns>
|
||||
public T DeserializeStream<T>()
|
||||
where T : class, IXSigSerialization, new()
|
||||
if ((prefix & 0xC080) == 0x8000) // Digital data
|
||||
{
|
||||
return new T().Deserialize<T>(ReadAllXSigTokens());
|
||||
var index = ((prefix & 0x1F00) >> 1) | (prefix & 0x7F);
|
||||
var value = (prefix & 0x2000) == 0;
|
||||
return new XSigDigitalToken((ushort)(index + 1), value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes of the internal stream if specified to not leave open.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_leaveOpen)
|
||||
_stream.Dispose();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads all available XSig tokens from the stream.
|
||||
/// </summary>
|
||||
/// <returns>XSigToken collection.</returns>
|
||||
public IEnumerable<XSigToken> ReadAllXSigTokens()
|
||||
{
|
||||
var tokens = new List<XSigToken>();
|
||||
XSigToken token;
|
||||
while ((token = ReadXSigToken()) != null)
|
||||
tokens.Add(token);
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to deserialize all XSig data within the stream from the current position.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type to deserialize the information to.</typeparam>
|
||||
/// <returns>Deserialized object.</returns>
|
||||
public T DeserializeStream<T>()
|
||||
where T : class, IXSigSerialization, new()
|
||||
{
|
||||
return new T().Deserialize<T>(ReadAllXSigTokens());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes of the internal stream if specified to not leave open.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_leaveOpen)
|
||||
_stream.Dispose();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user