mirror of
https://github.com/PepperDash/Essentials.git
synced 2026-04-09 14:34:55 +00:00
Compare commits
381 Commits
v3.0.0-net
...
dev/v3-tes
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ed5e648c0 | ||
|
|
35d44f91e4 | ||
|
|
fa9dc3a2b1 | ||
|
|
7e3c62b303 | ||
|
|
884b2c2e6e | ||
|
|
daf9b4bda0 | ||
|
|
e818c9ca03 | ||
|
|
5dd6d18fcc | ||
|
|
37961b9eac | ||
|
|
24df4e7a03 | ||
|
|
bfb9838743 | ||
|
|
c98b48ff87 | ||
|
|
5c26438a1c | ||
|
|
7bec96e68b | ||
|
|
7076eafc21 | ||
|
|
b4d53dbe0e | ||
|
|
43a9661e08 | ||
|
|
7137945c94 | ||
|
|
ac393c4885 | ||
|
|
346a5e9e57 | ||
|
|
426ef4ad6b | ||
|
|
bcb65c7fa4 | ||
|
|
c2ff65dce3 | ||
|
|
3feab2593d | ||
|
|
5d90fafbd7 | ||
|
|
7f60dcb4cf | ||
|
|
574e4dfb0f | ||
|
|
76759d35cc | ||
|
|
3ece4f0b7b | ||
|
|
aaa5b0532b | ||
|
|
04c4557528 | ||
|
|
9febbf2557 | ||
|
|
eafade9569 | ||
|
|
4e5b8f3897 | ||
|
|
7bd3ccd54b | ||
|
|
790b5a6fb9 | ||
|
|
fbcd9c84da | ||
|
|
4a2c9fe311 | ||
|
|
bdd398e2e6 | ||
|
|
8be5481ac9 | ||
|
|
dbab427d69 | ||
|
|
db4f540710 | ||
|
|
b64f63ac6b | ||
|
|
b21be608f0 | ||
|
|
6ab3ed9911 | ||
|
|
a9fdf30880 | ||
|
|
963925ffef | ||
|
|
e162ed208b | ||
|
|
bd38475b10 | ||
|
|
a704e48ae6 | ||
|
|
b40200ecae | ||
|
|
9de14da201 | ||
|
|
633608c8c6 | ||
|
|
f8a81de177 | ||
|
|
39ebf6f63d | ||
|
|
3ed0bd52d8 | ||
|
|
afc5cf1a14 | ||
|
|
8ff9de817c | ||
|
|
b35d2b47cf | ||
|
|
10579f1424 | ||
|
|
f88bb13367 | ||
|
|
2924ce6916 | ||
|
|
4437074f07 | ||
|
|
0764685c51 | ||
|
|
1fb5d3e5ee | ||
|
|
1404899342 | ||
|
|
a4759c3e67 | ||
|
|
a1029cd7c7 | ||
|
|
b1a5136ec6 | ||
|
|
a7c4e2fd60 | ||
|
|
c0971a4f8e | ||
|
|
8bc6d4392b | ||
|
|
4fa7a42330 | ||
|
|
9bad3ae21b | ||
|
|
f49901d3fa | ||
|
|
7910b7931e | ||
|
|
3fb30d5561 | ||
|
|
57cd77f019 | ||
|
|
7f2bb078c8 | ||
|
|
316bb849b4 | ||
|
|
a983e2c87f | ||
|
|
babb9a77df | ||
|
|
7629921113 | ||
|
|
3878c85a7a | ||
|
|
7ad8218af0 | ||
|
|
0c4aec14d1 | ||
|
|
7d3f871460 | ||
|
|
78c9381108 | ||
|
|
a7ff2e8903 | ||
|
|
ae0b2fe086 | ||
|
|
bd11c827da | ||
|
|
7ea1efbabf | ||
|
|
9d6aaa2a0e | ||
|
|
53e7a30224 | ||
|
|
ce8b08e312 | ||
|
|
39c1f60a4d | ||
|
|
2cc37a4e40 | ||
|
|
076e5dfa9d | ||
|
|
092896bb25 | ||
|
|
7c8f0586e6 | ||
|
|
c5b0872a4c | ||
|
|
a7b88ec38d | ||
|
|
210b398a13 | ||
|
|
bce1e3610e | ||
|
|
13e833b797 | ||
|
|
6a33e7c99d | ||
|
|
2048e3f65d | ||
|
|
81df2738de | ||
|
|
08fbec416f | ||
|
|
7594b22096 | ||
|
|
d1babf6b9b | ||
|
|
2187c9fb0d | ||
|
|
a5e6059160 | ||
|
|
9ef4aedcce | ||
|
|
f7c7160bf0 | ||
|
|
dbf5740841 | ||
|
|
c07e099a79 | ||
|
|
06cb508f3a | ||
|
|
e93b5b34cc | ||
|
|
4f5d4ef87a | ||
|
|
636da8cc8c | ||
|
|
5de1e2d7bb | ||
|
|
2be078da18 | ||
|
|
03bbb84894 | ||
|
|
d17394cdd7 | ||
|
|
8467afde38 | ||
|
|
5c016fb4b8 | ||
|
|
2fbc32947c | ||
|
|
c06b57a5f9 | ||
|
|
6d64fffc50 | ||
|
|
0c4ebdaf1d | ||
|
|
2c49fb9321 | ||
|
|
c55de61da9 | ||
|
|
42444ede0a | ||
|
|
3d50f5f5ac | ||
|
|
11d62aebe1 | ||
|
|
edc10a9c2a | ||
|
|
9be5823956 | ||
|
|
35371dde22 | ||
|
|
d3ceb4d7e7 | ||
|
|
a782b57100 | ||
|
|
1360de599f | ||
|
|
fd95f5fed1 | ||
|
|
9426dff5df | ||
|
|
0d083e63c6 | ||
|
|
6ed7c96ec7 | ||
|
|
314570d6c3 | ||
|
|
ff609dfecd | ||
|
|
666be5ae59 | ||
|
|
bfc9b7e7fa | ||
|
|
b02e952765 | ||
|
|
72861a5097 | ||
|
|
44ed067f4d | ||
|
|
faa2169baf | ||
|
|
fd40b0c6d1 | ||
|
|
afcddad1cc | ||
|
|
c4cf8f13e9 | ||
|
|
c852f87a27 | ||
|
|
071174fa7d | ||
|
|
da0f28a10c | ||
|
|
0538a304ed | ||
|
|
705c5db237 | ||
|
|
2e95f5337e | ||
|
|
ba576180a7 | ||
|
|
92c9db8237 | ||
|
|
c4d064965f | ||
|
|
f27965ac29 | ||
|
|
3ce282e2db | ||
|
|
32a332a6e2 | ||
|
|
151a90c9be | ||
|
|
89e893b3b7 | ||
|
|
d01eb03890 | ||
|
|
16c92afabb | ||
|
|
dff5d2d32e | ||
|
|
317bde3814 | ||
|
|
8bab3dc966 | ||
|
|
514ac850ca | ||
|
|
44432f7a41 | ||
|
|
99253b30c2 | ||
|
|
bf248fe33e | ||
|
|
2f44040e4f | ||
|
|
10399a1be8 | ||
|
|
5409db193c | ||
|
|
f1ce54a524 | ||
|
|
7c72a0d905 | ||
|
|
5d5e78629e | ||
|
|
dab5484d6e | ||
|
|
5c35a3be45 | ||
|
|
6cb98e12fa | ||
|
|
608601990b | ||
|
|
3e0f318f7f | ||
|
|
98d0cc8fdc | ||
|
|
c557c6cdd6 | ||
|
|
8525134ae7 | ||
|
|
7330ae2e30 | ||
|
|
a57dddba5e | ||
|
|
1197b15a33 | ||
|
|
ea6a7568fc | ||
|
|
3a2a059ce1 | ||
|
|
f9d9df9d5c | ||
|
|
c284c4275f | ||
|
|
0418f8a7cc | ||
|
|
a5d409e93a | ||
|
|
59944c0e2f | ||
|
|
419177ccd5 | ||
|
|
bd01e2bacc | ||
|
|
2928c5cf94 | ||
|
|
82b5dc96c1 | ||
|
|
37cea8a11c | ||
|
|
a3f0901fa0 | ||
|
|
f91f435768 | ||
|
|
5120b2b574 | ||
|
|
7c90027578 | ||
|
|
bb694b4200 | ||
|
|
087d0a1149 | ||
|
|
4747c16b02 | ||
|
|
aa4d241dde | ||
|
|
9fc5586531 | ||
|
|
d33fd56529 | ||
|
|
8fc4d21f02 | ||
|
|
6d93662b31 | ||
|
|
11b190e76f | ||
|
|
df03a71cbc | ||
|
|
72e67a1c4c | ||
|
|
f8728b6825 | ||
|
|
d9ef8a2289 | ||
|
|
278408a3bc | ||
|
|
fd70377c7f | ||
|
|
06341b14f3 | ||
|
|
d7f9c74b2f | ||
|
|
5921b5dbb0 | ||
|
|
ba0de5128f | ||
|
|
b0a090062f | ||
|
|
9c0cab8218 | ||
|
|
c0af637108 | ||
|
|
9c9eaea928 | ||
|
|
9de94bd65f | ||
|
|
ff46fb8f29 | ||
|
|
d9243def30 | ||
|
|
258699fbcd | ||
|
|
738504e9fc | ||
|
|
cae1bbd6e6 | ||
|
|
dea4407e3e | ||
|
|
ab08a546f7 | ||
|
|
ef98d47792 | ||
|
|
c05976ee60 | ||
|
|
4ca1031bef | ||
|
|
6d61c4525e | ||
|
|
3db274ace5 | ||
|
|
f0f708294c | ||
|
|
a00d186c62 | ||
|
|
0bfec16622 | ||
|
|
51da668dfd | ||
|
|
d2b7400039 | ||
|
|
2424838b7f | ||
|
|
9556edc064 | ||
|
|
94e7b8210f | ||
|
|
f9088691fd | ||
|
|
e40b6a8b4c | ||
|
|
c3b39a87da | ||
|
|
06dc0e947e | ||
|
|
147997f460 | ||
|
|
49abec5eea | ||
|
|
6830efe42a | ||
|
|
d013068a0c | ||
|
|
52916d29f4 | ||
|
|
19e8489166 | ||
|
|
fe33443b25 | ||
|
|
8cf195b262 | ||
|
|
40406b797d | ||
|
|
65bc408ebf | ||
|
|
9d49fb8357 | ||
|
|
fb7797dac7 | ||
|
|
574f5f6dc9 | ||
|
|
e49c69a12f | ||
|
|
7889cba196 | ||
|
|
033aa1f3dd | ||
|
|
9b6c2d80ea | ||
|
|
a0fc731701 | ||
|
|
f2d0dca7b8 | ||
|
|
ab4e85d081 | ||
|
|
47017da527 | ||
|
|
4f0d464ba4 | ||
|
|
0107422507 | ||
|
|
1a366790e7 | ||
|
|
97448f4f0f | ||
|
|
cf3ece4237 | ||
|
|
bb4b2f88b6 | ||
|
|
808e8042a7 | ||
|
|
0bc4388bfd | ||
|
|
dbc132c0da | ||
|
|
5bb0ab2626 | ||
|
|
27bf36c58c | ||
|
|
ce886aea63 | ||
|
|
ef920bf54c | ||
|
|
88466818ce | ||
|
|
0871a902e1 | ||
|
|
a031424752 | ||
|
|
fd1ba345aa | ||
|
|
e03874a7a9 | ||
|
|
2efab4f196 | ||
|
|
a41aba1904 | ||
|
|
d0ca6721f5 | ||
|
|
c732eb48f2 | ||
|
|
efe70208d3 | ||
|
|
615f640ebb | ||
|
|
ee6f9416a3 | ||
|
|
4fc6ecbd0b | ||
|
|
58bcc3315d | ||
|
|
08cc84a8e8 | ||
|
|
226014fee0 | ||
|
|
dc7f99e176 | ||
|
|
f0af9f8d19 | ||
|
|
31143f56df | ||
|
|
43989b9588 | ||
|
|
8db559f197 | ||
|
|
86f20da116 | ||
|
|
0674dbda37 | ||
|
|
592607f3c8 | ||
|
|
ea0a779f8b | ||
|
|
86e4d2f7fb | ||
|
|
0069233e13 | ||
|
|
4048efb07e | ||
|
|
b12cdbc75c | ||
|
|
b47f1d6b77 | ||
|
|
1dbac7d1c8 | ||
|
|
799d4c127c | ||
|
|
a6cd9a0571 | ||
|
|
80da4ad98f | ||
|
|
b283ed34b4 | ||
|
|
899f13eadb | ||
|
|
fc1e29565e | ||
|
|
f9a74567d2 | ||
|
|
53b1e5d142 | ||
|
|
78e9ea8070 | ||
|
|
df201558a5 | ||
|
|
130c874684 | ||
|
|
aee40ffe14 | ||
|
|
3ffad13abf | ||
|
|
5ee7aaa991 | ||
|
|
4fa8433e73 | ||
|
|
5fe99518a0 | ||
|
|
5a2a2129e6 | ||
|
|
4fbfda62d6 | ||
|
|
b8ab54cbe0 | ||
|
|
f6f1619bc2 | ||
|
|
41fd4d6adc | ||
|
|
5b73f8fbd2 | ||
|
|
c70a8edc24 | ||
|
|
7987eb8f9b | ||
|
|
260677a37f | ||
|
|
eeb0e84dc7 | ||
|
|
d282487da6 | ||
|
|
da30424657 | ||
|
|
311452beac | ||
|
|
789113008e | ||
|
|
660836bd5a | ||
|
|
97b2ffed9c | ||
|
|
2bbefa062d | ||
|
|
3421b2f28c | ||
|
|
82889e9794 | ||
|
|
1dcd4e328c | ||
|
|
e76369726d | ||
|
|
2bf0f2092b | ||
|
|
f8455d4110 | ||
|
|
c1eccfd790 | ||
|
|
f1a89161bc | ||
|
|
e59c50d0aa | ||
|
|
9d313d8c7c | ||
|
|
9813673b66 | ||
|
|
f006ed0076 | ||
|
|
ddbcc13c50 | ||
|
|
2a70fc678e | ||
|
|
056614cba1 | ||
|
|
5ff587a8c9 | ||
|
|
26c1baa1f8 | ||
|
|
2b15c2a56f | ||
|
|
a076d531bc | ||
|
|
5e880f0111 | ||
|
|
8f1fb86d37 | ||
|
|
2fa297a204 |
13
.config/dotnet-tools.json
Normal file
13
.config/dotnet-tools.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"csharpier": {
|
||||
"version": "1.2.4",
|
||||
"commands": [
|
||||
"csharpier"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,13 @@ on:
|
||||
- '**'
|
||||
|
||||
jobs:
|
||||
runTests:
|
||||
uses: PepperDash/workflow-templates/.github/workflows/essentialsplugins-run-tests.yml@main
|
||||
secrets: inherit
|
||||
getVersion:
|
||||
uses: PepperDash/workflow-templates/.github/workflows/essentialsplugins-getversion.yml@main
|
||||
secrets: inherit
|
||||
needs: runTests
|
||||
build-4Series:
|
||||
uses: PepperDash/workflow-templates/.github/workflows/essentialsplugins-4Series-builds.yml@main
|
||||
secrets: inherit
|
||||
@@ -19,4 +23,5 @@ jobs:
|
||||
version: ${{ needs.getVersion.outputs.version }}
|
||||
tag: ${{ needs.getVersion.outputs.tag }}
|
||||
channel: ${{ needs.getVersion.outputs.channel }}
|
||||
bypassPackageCheck: true
|
||||
bypassPackageCheck: true
|
||||
devToolsVersion: ${{ vars.ESSENTIALSDEVTOOLSVERSION }}
|
||||
247
.github/workflows/essentials-3-dev-build.yml
vendored
247
.github/workflows/essentials-3-dev-build.yml
vendored
@@ -1,247 +0,0 @@
|
||||
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 "=================================="
|
||||
4
.github/workflows/publish-docs.yml
vendored
4
.github/workflows/publish-docs.yml
vendored
@@ -26,9 +26,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
- name: Dotnet Setup
|
||||
uses: actions/setup-dotnet@v4
|
||||
uses: actions/setup-dotnet@v5
|
||||
with:
|
||||
dotnet-version: 8.x
|
||||
|
||||
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -393,4 +393,7 @@ essentials-framework/Essentials Interfaces/PepperDash_Essentials_Interfaces/Pepp
|
||||
/._PepperDash.Essentials.sln
|
||||
.vscode/settings.json
|
||||
_site/
|
||||
api/
|
||||
api/
|
||||
*.DS_Store
|
||||
/._PepperDash.Essentials.4Series.sln
|
||||
dotnet
|
||||
|
||||
9
.vscode/extensions.json
vendored
Normal file
9
.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"ms-dotnettools.vscode-dotnet-runtime",
|
||||
"ms-dotnettools.csharp",
|
||||
"ms-dotnettools.csdevkit",
|
||||
"vivaxy.vscode-conventional-commits",
|
||||
"mhutchie.git-graph"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
# Crestron Library Usage Analysis - PepperDash Essentials
|
||||
|
||||
This document provides a comprehensive analysis of Crestron classes and interfaces used throughout the PepperDash Essentials framework, organized by namespace and library component.
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The PepperDash Essentials framework extensively leverages Crestron SDK components across 100+ files, providing abstractions for:
|
||||
- Control system hardware (processors, touchpanels, IO devices)
|
||||
- Communication interfaces (Serial, TCP/IP, SSH, CEC, IR)
|
||||
- Device management and routing
|
||||
- User interface components and smart objects
|
||||
- System monitoring and diagnostics
|
||||
|
||||
## 1. Core Crestron Libraries
|
||||
|
||||
### 1.1 Crestron.SimplSharp
|
||||
|
||||
**Primary Usage**: Foundational framework components, collections, and basic types.
|
||||
|
||||
**Key Files**:
|
||||
- Multiple files across all projects use `Crestron.SimplSharp` namespaces
|
||||
- Provides basic C# runtime support for Crestron processors
|
||||
|
||||
### 1.2 Crestron.SimplSharpPro
|
||||
|
||||
**Primary Usage**: Main hardware abstraction layer for Crestron devices.
|
||||
|
||||
**Key Classes Used**:
|
||||
|
||||
#### CrestronControlSystem
|
||||
- **File**: `/src/PepperDash.Essentials/ControlSystem.cs`
|
||||
- **Usage**: Base class for the main control system implementation
|
||||
- **Implementation**: `public class ControlSystem : CrestronControlSystem, ILoadConfig`
|
||||
|
||||
#### Device (Base Class)
|
||||
- **Files**: 50+ files inherit from or use this class
|
||||
- **Key Implementations**:
|
||||
- `/src/PepperDash.Core/Device.cs` - Core device abstraction
|
||||
- `/src/PepperDash.Essentials.Core/Devices/EssentialsDevice.cs` - Extended device base
|
||||
- `/src/PepperDash.Essentials.Core/Room/Room.cs` - Room device implementation
|
||||
- `/src/PepperDash.Essentials.Core/Devices/CrestronProcessor.cs` - Processor device wrapper
|
||||
|
||||
#### BasicTriList
|
||||
- **Files**: 30+ files use this class extensively
|
||||
- **Primary Usage**: Touchpanel communication and SIMPL bridging
|
||||
- **Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/Touchpanels/TriListExtensions.cs` - Extension methods for signal handling
|
||||
- `/src/PepperDash.Essentials.Core/Devices/EssentialsBridgeableDevice.cs` - Bridge interface
|
||||
- `/src/PepperDash.Essentials.Core/Touchpanels/ModalDialog.cs` - UI dialog implementation
|
||||
|
||||
#### BasicTriListWithSmartObject
|
||||
- **Files**: Multiple touchpanel and UI files
|
||||
- **Usage**: Enhanced touchpanel support with smart object integration
|
||||
- **Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/Touchpanels/Interfaces.cs` - Interface definitions
|
||||
- `/src/PepperDash.Essentials.Core/SmartObjects/SubpageReferenceList/SubpageReferenceList.cs`
|
||||
|
||||
## 2. Communication Hardware
|
||||
|
||||
### 2.1 Serial Communication (ComPort)
|
||||
|
||||
**Primary Class**: `ComPort`
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/Comm and IR/ComPortController.cs`
|
||||
- `/src/PepperDash.Essentials.Core/Comm and IR/CommFactory.cs`
|
||||
|
||||
**Usage Pattern**:
|
||||
```csharp
|
||||
public class ComPortController : Device, IBasicCommunicationWithStreamDebugging
|
||||
public static ComPort GetComPort(EssentialsControlPropertiesConfig config)
|
||||
```
|
||||
|
||||
**Interface Support**: `IComPorts` - Used for devices that provide multiple COM ports
|
||||
|
||||
### 2.2 IR Communication (IROutputPort)
|
||||
|
||||
**Primary Class**: `IROutputPort`
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/Devices/IrOutputPortController.cs`
|
||||
- `/src/PepperDash.Essentials.Core/Devices/GenericIRController.cs`
|
||||
- `/src/PepperDash.Essentials.Core/Comm and IR/IRPortHelper.cs`
|
||||
|
||||
**Usage Pattern**:
|
||||
```csharp
|
||||
public class IrOutputPortController : Device
|
||||
IROutputPort IrPort;
|
||||
public IrOutputPortController(string key, IROutputPort port, string irDriverFilepath)
|
||||
```
|
||||
|
||||
### 2.3 CEC Communication (ICec)
|
||||
|
||||
**Primary Interface**: `ICec`
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/Comm and IR/CecPortController.cs`
|
||||
- `/src/PepperDash.Essentials.Core/Comm and IR/CommFactory.cs`
|
||||
|
||||
**Usage Pattern**:
|
||||
```csharp
|
||||
public class CecPortController : Device, IBasicCommunicationWithStreamDebugging
|
||||
public static ICec GetCecPort(ControlPropertiesConfig config)
|
||||
```
|
||||
|
||||
## 3. Input/Output Hardware
|
||||
|
||||
### 3.1 Digital Input
|
||||
|
||||
**Primary Interface**: `IDigitalInput`
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/CrestronIO/GenericDigitalInputDevice.cs`
|
||||
- `/src/PepperDash.Essentials.Core/Microphone Privacy/MicrophonePrivacyController.cs`
|
||||
|
||||
**Usage Pattern**:
|
||||
```csharp
|
||||
public List<IDigitalInput> Inputs { get; private set; }
|
||||
void AddInput(IDigitalInput input)
|
||||
```
|
||||
|
||||
### 3.2 Versiport Support
|
||||
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/CrestronIO/GenericVersiportInputDevice.cs`
|
||||
- `/src/PepperDash.Essentials.Core/CrestronIO/GenericVersiportAnalogInputDevice.cs`
|
||||
- `/src/PepperDash.Essentials.Core/CrestronIO/GenericVersiportOutputDevice.cs`
|
||||
|
||||
**Usage**: Provides flexible I/O port configuration for various signal types
|
||||
|
||||
## 4. Touchpanel Hardware
|
||||
|
||||
### 4.1 MPC3 Touchpanel
|
||||
|
||||
**Primary Class**: `MPC3Basic`
|
||||
**Key File**: `/src/PepperDash.Essentials.Core/Touchpanels/Mpc3Touchpanel.cs`
|
||||
|
||||
**Usage Pattern**:
|
||||
```csharp
|
||||
public class Mpc3TouchpanelController : Device
|
||||
readonly MPC3Basic _touchpanel;
|
||||
_touchpanel = processor.ControllerTouchScreenSlotDevice as MPC3Basic;
|
||||
```
|
||||
|
||||
### 4.2 TSW Series Support
|
||||
|
||||
**Evidence**: References found in messenger files and mobile control components
|
||||
**Usage**: Integrated through mobile control messaging system for TSW touchpanel features
|
||||
|
||||
## 5. Timer and Threading
|
||||
|
||||
### 5.1 CTimer
|
||||
|
||||
**Primary Class**: `CTimer`
|
||||
**Key File**: `/src/PepperDash.Core/PasswordManagement/PasswordManager.cs`
|
||||
|
||||
**Usage Pattern**:
|
||||
```csharp
|
||||
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Started"));
|
||||
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Reset"));
|
||||
```
|
||||
|
||||
## 6. Networking and Communication
|
||||
|
||||
### 6.1 Ethernet Communication
|
||||
|
||||
**Libraries Used**:
|
||||
- `Crestron.SimplSharpPro.EthernetCommunication`
|
||||
- `Crestron.SimplSharp.Net.Utilities.EthernetHelper`
|
||||
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Core/Comm/GenericTcpIpClient.cs`
|
||||
- `/src/PepperDash.Core/Comm/GenericTcpIpServer.cs`
|
||||
- `/src/PepperDash.Core/Comm/GenericSecureTcpIpClient.cs`
|
||||
- `/src/PepperDash.Core/Comm/GenericSshClient.cs`
|
||||
- `/src/PepperDash.Core/Comm/GenericUdpServer.cs`
|
||||
|
||||
**Usage Pattern**:
|
||||
```csharp
|
||||
public class GenericTcpIpClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
||||
public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
||||
```
|
||||
|
||||
## 7. Device Management Libraries
|
||||
|
||||
### 7.1 DeviceSupport
|
||||
|
||||
**Library**: `Crestron.SimplSharpPro.DeviceSupport`
|
||||
**Usage**: Core device support infrastructure used throughout the framework
|
||||
|
||||
### 7.2 DM (DigitalMedia)
|
||||
|
||||
**Library**: `Crestron.SimplSharpPro.DM`
|
||||
**Usage**: Digital media routing and switching support
|
||||
**Evidence**: Found in routing configuration and DM output card references
|
||||
|
||||
## 8. User Interface Libraries
|
||||
|
||||
### 8.1 UI Components
|
||||
|
||||
**Library**: `Crestron.SimplSharpPro.UI`
|
||||
**Usage**: User interface elements and touchpanel controls
|
||||
|
||||
### 8.2 Smart Objects
|
||||
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/SmartObjects/SmartObjectDynamicList.cs`
|
||||
- `/src/PepperDash.Essentials.Core/SmartObjects/SubpageReferenceList/SubpageReferenceList.cs`
|
||||
|
||||
**Usage**: Advanced UI components with dynamic content
|
||||
|
||||
## 9. System Monitoring and Diagnostics
|
||||
|
||||
### 9.1 Diagnostics
|
||||
|
||||
**Library**: `Crestron.SimplSharpPro.Diagnostics`
|
||||
**Usage**: System health monitoring and performance tracking
|
||||
|
||||
### 9.2 System Information
|
||||
|
||||
**Key Files**:
|
||||
- `/src/PepperDash.Essentials.Core/Monitoring/SystemMonitorController.cs`
|
||||
|
||||
**Usage**: Provides system status, Ethernet information, and program details
|
||||
|
||||
## 10. Integration Patterns
|
||||
|
||||
### 10.1 SIMPL Bridging
|
||||
|
||||
**Pattern**: Extensive use of `BasicTriList` for SIMPL integration
|
||||
**Files**: Bridge classes throughout the framework implement `LinkToApi` methods:
|
||||
```csharp
|
||||
public abstract void LinkToApi(BasicTriList trilist, uint joinStart, string joinMapKey, EiscApiAdvanced bridge);
|
||||
```
|
||||
|
||||
### 10.2 Device Factory Pattern
|
||||
|
||||
**Implementation**: Factory classes create hardware-specific implementations
|
||||
**Example**: `CommFactory.cs` provides communication device creation
|
||||
|
||||
### 10.3 Extension Methods
|
||||
|
||||
**Pattern**: Extensive use of extension methods for Crestron classes
|
||||
**Example**: `TriListExtensions.cs` adds 30+ extension methods to `BasicTriList`
|
||||
|
||||
## 11. Signal Processing
|
||||
|
||||
### 11.1 Signal Types
|
||||
|
||||
**Bool Signals**: Digital control and feedback
|
||||
**UShort Signals**: Analog values and numeric data
|
||||
**String Signals**: Text and configuration data
|
||||
|
||||
**Implementation**: Comprehensive signal handling in `TriListExtensions.cs`
|
||||
|
||||
## 12. Error Handling and Logging
|
||||
|
||||
**Pattern**: Consistent use of Crestron's Debug logging throughout
|
||||
**Examples**:
|
||||
```csharp
|
||||
Debug.LogMessage(LogEventLevel.Information, "Device {0} is not a valid device", dc.PortDeviceKey);
|
||||
Debug.LogMessage(LogEventLevel.Debug, "Error Waking Panel. Maybe testing with Xpanel?");
|
||||
```
|
||||
|
||||
## 13. Threading and Synchronization
|
||||
|
||||
**Components**:
|
||||
- CTimer for time-based operations
|
||||
- Thread-safe collections and patterns
|
||||
- Event-driven programming models
|
||||
|
||||
## Conclusion
|
||||
|
||||
The PepperDash Essentials framework demonstrates sophisticated integration with the Crestron ecosystem, leveraging:
|
||||
|
||||
- **Core Infrastructure**: CrestronControlSystem, Device base classes
|
||||
- **Communication**: COM, IR, CEC, TCP/IP, SSH protocols
|
||||
- **Hardware Abstraction**: Touchpanels, I/O devices, processors
|
||||
- **User Interface**: Smart objects, signal processing, SIMPL bridging
|
||||
- **System Services**: Monitoring, diagnostics, device management
|
||||
|
||||
This analysis shows that Essentials serves as a comprehensive middleware layer, abstracting Crestron hardware complexities while providing modern software development patterns and practices.
|
||||
|
||||
---
|
||||
*Generated: [Current Date]*
|
||||
*Framework Version: PepperDash Essentials (Based on codebase analysis)*
|
||||
|
||||
@@ -36,49 +36,151 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{02EA681E-C
|
||||
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}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Core.Tests", "src\PepperDash.Core.Tests\PepperDash.Core.Tests.csproj", "{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash.Essentials.Core.Tests", "src\PepperDash.Essentials.Core.Tests\PepperDash.Essentials.Core.Tests.csproj", "{F508E0BA-E885-424F-9D4C-359CF0011DEF}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug 4.7.2|Any CPU = Debug 4.7.2|Any CPU
|
||||
Debug 4.7.2|x64 = Debug 4.7.2|x64
|
||||
Debug 4.7.2|x86 = Debug 4.7.2|x86
|
||||
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
|
||||
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 4.7.2|x64.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug 4.7.2|x64.Build.0 = Debug 4.7.2|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug 4.7.2|x86.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{53E204B7-97DD-441D-A96C-721DF014DF82}.Debug 4.7.2|x86.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}.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
|
||||
{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 4.7.2|x64.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug 4.7.2|x64.Build.0 = Debug 4.7.2|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug 4.7.2|x86.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{CB3B11BA-625C-4D35-B663-FDC5BE9A230E}.Debug 4.7.2|x86.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}.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
|
||||
{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 4.7.2|x64.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug 4.7.2|x64.Build.0 = Debug 4.7.2|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug 4.7.2|x86.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{3D192FED-8FFC-4CB5-B5F7-BA307ABA254B}.Debug 4.7.2|x86.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}.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
|
||||
{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 4.7.2|x64.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug 4.7.2|x64.Build.0 = Debug 4.7.2|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug 4.7.2|x86.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{F6D362DE-2256-44B1-927A-8CE4705D839A}.Debug 4.7.2|x86.Build.0 = Debug 4.7.2|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
|
||||
{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 4.7.2|x64.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug 4.7.2|x64.Build.0 = Debug 4.7.2|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug 4.7.2|x86.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{B438694F-8FF7-464A-9EC8-10427374471F}.Debug 4.7.2|x86.Build.0 = Debug 4.7.2|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
|
||||
{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 4.7.2|x64.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug 4.7.2|x64.Build.0 = Debug 4.7.2|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug 4.7.2|x86.ActiveCfg = Debug 4.7.2|Any CPU
|
||||
{E5336563-1194-501E-BC4A-79AD9283EF90}.Debug 4.7.2|x86.Build.0 = Debug 4.7.2|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
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Debug 4.7.2|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Debug 4.7.2|x64.ActiveCfg = Debug|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Debug 4.7.2|x86.ActiveCfg = Debug|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Debug 4.7.2|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Debug 4.7.2|x64.ActiveCfg = Debug|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Debug 4.7.2|x86.ActiveCfg = Debug|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -90,6 +192,8 @@ Global
|
||||
{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}
|
||||
{680BA287-E61F-4B8D-BD7A-84C2504F5F9C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{F508E0BA-E885-424F-9D4C-359CF0011DEF} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {6907A4BF-7201-47CF-AAB1-3597F3B8E1C3}
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
"_appLogoPath": "docs/images/favicon-32x32.png",
|
||||
"_appFaviconPath": "docs/images/favicon.ico",
|
||||
"_disableToc": false,
|
||||
"_enableNewTab": true,
|
||||
"pdf": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,23 +4,44 @@
|
||||
[YouTube Video - Getting Started with PepperDash Essentials](https://youtu.be/FxEZtbpCwiQ)
|
||||
***
|
||||
|
||||
## Download or clone
|
||||
## Get a CPZ
|
||||
|
||||
You may clone Essentials at <https://github.com/PepperDash/Essentials.git>
|
||||
### Prerequisites
|
||||
|
||||
* [VS Code](https://code.visualstudio.com/)
|
||||
* [.NET 9 SDK](https://dotnet.microsoft.com/en-us/download)
|
||||
* [Git](https://git-scm.com/)
|
||||
|
||||
> Note: Essentials 2.x.x uses .NET Framework 4.7.2 currently. The .NET 9 SDK will build the project with the appropriate references
|
||||
|
||||
### Build From Source
|
||||
|
||||
1. Clone the repo: `git clone https://github.com/PepperDash/Essentials.git`
|
||||
2. Open the folder in VS Code
|
||||
3. Build using the dotnet CLI: `dotnet build`
|
||||
|
||||
### Download the latest release
|
||||
|
||||
The latest release can be found on [Github](https://github.com/PepperDash/Essentials/releases/latest)
|
||||
|
||||
## How to Get Started
|
||||
|
||||
This section assumes knowledge of loading programs to and working with the file system on a Crestron processor.
|
||||
2. Using an SFTP client or Crestron Toolbox, load the downloaded (or built) cpz to the processor in program slot 1
|
||||
1. If using SFTP, connect via SSH and start the program by sending console command `progload -p:1`
|
||||
3. On first boot, the Essentials Application will build the necessary configuration folder structure in the user/program1/ path.
|
||||
4. The application has some example configuration files included. Copy `/Program01/Example Configuration/EssentialsSpaceHuddleRoom/configurationFile-HuddleSpace-2-Source.json` to the `/User/Program1/` folder.
|
||||
6. Reset the program via console `progreset -p:1`. The program will load the example configuration file.
|
||||
|
||||
1. Using an SFTP client, load `PepperDashEssentials1.4.32.cpz` to the processor in program slot 1 and start the program by sending console command `progload -p:1`
|
||||
1. On first boot, the Essentials Application will build the necessary configuration folder structure in the User/Program1/ path.
|
||||
1. The application has some example configuration files included. Copy `/Program01/Example Configuration/EssentialsSpaceHuddleRoom/configurationFile-HuddleSpace-2-Source.json` to the `/User/Program1/` folder.
|
||||
1. Copy the SGD files from `/Program01/SGD` to `/User/Program1/sgd`
|
||||
1. Reset the program via console `progreset -p:1`. The program will load the example configuration file.
|
||||
1. Via console, you can run the `devlist:1` command to get some insight into what has been loaded from the configuration file into the system . This will print the basic device information in the form of ["key"] "Name". The "key" value is what we can use to interact with each device uniquely.
|
||||
1. Run the command `devprops:1 display-1`. This will print the real-time property values of the device with key "display-1".
|
||||
1. Run the command `devmethods:1 display-1`. This will print the public methods available for the device with key "display-1".
|
||||
1. Run the command `devjson:1 {"deviceKey":"display-1","methodName":"PowerOn", "params": []}`. This will call the method PowerOn() on the device with key "display-1".
|
||||
1. Run the provided example XPanel SmartGraphics project and connect to your processor at the appropriate IPID.
|
||||
Once Essentials is running with a valid configuration, the following console commands can be used to see what's going on:
|
||||
|
||||
Next: [Standalone use](~/docs/Standalone-Use.md)
|
||||
* ```devlist:1```
|
||||
* Print the list of devices in [{key}] {name} format
|
||||
* The key of a device can be used with the rest of the commands to get more information
|
||||
* `devprops:1 {deviceKey}`
|
||||
* Print the real-time property values of the device with key "display-1".
|
||||
* `devmethods:1 display-1`
|
||||
* Print the public methods available for the device with key "display-1".
|
||||
* `devjson:1 {"deviceKey":"display-1","methodName":"PowerOn", "params": []}`
|
||||
* Call the method `PowerOn()` on the device with key "display-1".
|
||||
|
||||
Next: [Standalone use](~/docs/usage/Standalone-Use.md)
|
||||
|
||||
@@ -39,7 +39,7 @@ Thanks!
|
||||
|
||||
## Collaboration
|
||||
|
||||
Essentials is an open-source project and we encourage collaboration on this community project. For features that may not be useful to the greater community, or for just-plain learning, we want to remind developers to try writing plugins for Essentials. More information can be found here: [Plugins](~/docs/Plugins.md)
|
||||
Essentials is an open-source project and we encourage collaboration on this community project. For features that may not be useful to the greater community, or for just-plain learning, we want to remind developers to try writing plugins for Essentials. More information can be found here: [Plugins](~/docs/technical-docs/Plugins.md)
|
||||
|
||||
### Open-source-collaborative workflow
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Deprecated
|
||||
|
||||
**Note : this entry is out of date - please see [Plugins](~/docs/Plugins.md)**
|
||||
**Note : this entry is out of date - please see [Plugins](~/docs/technical-docs/Plugins.md)**
|
||||
|
||||
## What are Essentials Plugins?
|
||||
|
||||
|
||||
@@ -358,7 +358,7 @@ Example device config: <https://github.com/PepperDash/Essentials/blob/main/Peppe
|
||||
|
||||
1. A bridge need not only bridge between applications on the same processor. A bridge may bridge to an application on a completely separate processor; simply define the ip address in the Bridge control properties accordingly.
|
||||
|
||||
1. For devices included in Essentials, you will be able to find defined join maps below. If you are building your own plugins, you will need to build the join map yourself. It would be beneficial to review the wiki entry on the [Feedback Class](~/docs/Feedback-Classes.md) for this.
|
||||
1. For devices included in Essentials, you will be able to find defined join maps below. If you are building your own plugins, you will need to build the join map yourself. It would be beneficial to review the wiki entry on the [Feedback Class](~/docs/technical-docs/Feedback-Classes.md) for this.
|
||||
|
||||
1. When building plugins, we highly recommend reusing JoinMaps, as this will make code more easily interchangeable. For example; if you were to build a display plugin, we'd recommend you use/extend the existing DisplayControllerJoinMap. This way, you can swap plugins without needing any change on the Simpl Windows side. This is extremely powerful when maintaining Simpl Windows code bases for large deployments that may utilize differing equipment per room. If you can build a Simpl Windows program that interacts with established join maps, you can swap out the device via config without any change needed to Simpl Windows.
|
||||
|
||||
@@ -474,4 +474,4 @@ Example device config: <https://github.com/PepperDash/Essentials/blob/main/Peppe
|
||||
|
||||
We've provided an [example program](https://github.com/PepperDash/EssentialsSIMPLWindowsBridgeExample) for SIMPL Windows that works with the provided example Essentials configuration file [SIMPLBridgeExample_configurationFile.json](https://github.com/PepperDash/Essentials/blob/main/PepperDashEssentials/Example%20Configuration/SIMPLBridging/SIMPLBridgeExample_configurationFile.json). Load Essentials and the example SIMPL program to two slots on the same processor and you can get a better idea of how to take advantage of SIMPL Windows bridging.
|
||||
|
||||
Next: [Essentials architecture](~/docs/Arch-summary.md)
|
||||
Next: [Essentials architecture](~/docs/technical-docs/Arch-summary.md)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SIMPL Windows Bridging
|
||||
|
||||
**Note : this entry is out of date - please see [SIMPL Windows Bridging - Updated](~/docs/SIMPL-Bridging-Updated.md)**
|
||||
**Note : this entry is out of date - please see [SIMPL Windows Bridging - Updated](~/docs/usage/SIMPL-Bridging-Updated.md)**
|
||||
|
||||
Essentials allows for devices defined within the SIMPL# Pro application to be bridged to a SIMPL Windows application over Ethernet Intersystem Communication (EISC). This allows a SIMPL Windows program to take advantage of some of the features of the SIMPL# Pro environment, without requiring the entire application to be written in C#.
|
||||
|
||||
@@ -356,7 +356,7 @@ Example device config: <https://github.com/PepperDash/Essentials/blob/main/Peppe
|
||||
|
||||
1. A bridge need not only bridge between applications on the same processor. A bridge may bridge to an application on a completely separate processor; simply define the ip address in the Bridge control properties accordingly.
|
||||
|
||||
1. For devices included in Essentials, you will be able to find defined join maps below. If you are building your own plugins, you will need to build the join map yourself. It would be beneficial to review the wiki entry on the [Feedback Class](~/docs/Feedback-Classes.md) for this.
|
||||
1. For devices included in Essentials, you will be able to find defined join maps below. If you are building your own plugins, you will need to build the join map yourself. It would be beneficial to review the wiki entry on the [Feedback Class](~/docs/technical-docs/Feedback-Classes.md) for this.
|
||||
|
||||
1. When building plugins, we highly recommend reusing JoinMaps, as this will make code more easily interchangeable. For example; if you were to build a display plugin, we'd recommend you use/extend the existing DisplayControllerJoinMap. This way, you can swap plugins without needing any change on the Simpl Windows side. This is extremely powerful when maintaining Simpl Windows code bases for large deployments that may utilize differing equipment per room. If you can build a Simpl Windows program that interacts with established join maps, you can swap out the device via config without any change needed to Simpl Windows.
|
||||
|
||||
@@ -472,4 +472,4 @@ Example device config: <https://github.com/PepperDash/Essentials/blob/main/Peppe
|
||||
|
||||
We've provided an [example program](https://github.com/PepperDash/EssentialsSIMPLWindowsBridgeExample) for SIMPL Windows that works with the provided example Essentials configuration file [SIMPLBridgeExample_configurationFile.json](https://github.com/PepperDash/Essentials/blob/main/PepperDashEssentials/Example%20Configuration/SIMPLBridging/SIMPLBridgeExample_configurationFile.json). Load Essentials and the example SIMPL program to two slots on the same processor and you can get a better idea of how to take advantage of SIMPL Windows bridging.
|
||||
|
||||
Next: [Essentials architecture](~/docs/Arch-summary.md)
|
||||
Next: [Essentials architecture](~/docs/technical-docs/Arch-summary.md)
|
||||
|
||||
148
docs/docs/how-to/how-to-add-docs.md
Normal file
148
docs/docs/how-to/how-to-add-docs.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# How to Add Documentation to Essentials
|
||||
|
||||
This guide explains how to add new documentation articles to the Essentials docFx site.
|
||||
|
||||
## Overview
|
||||
|
||||
The Essentials documentation uses [docFx](https://dotnet.github.io/docfx/) to generate a static documentation website. Documentation files are organized in a hierarchical structure with a table of contents (TOC) file that defines the site navigation. Documentation should be organized and written to fit into the [Diátaxis](https://diataxis.fr/start-here/) conceptual framework.
|
||||
|
||||
## Documentation Structure
|
||||
|
||||
Documentation files are located in `/docs/docs/` and organized into the following subdirectories:
|
||||
|
||||
- **how-to/** - Step-by-step guides and tutorials
|
||||
- **usage/** - Usage documentation for SIMPL bridging, standalone use, and hardware integration
|
||||
- **technical-docs/** - Technical documentation including architecture, plugins, and API references
|
||||
- **images/** - Image assets used in documentation
|
||||
|
||||
## Adding a New Document
|
||||
|
||||
### Step 1: Create Your Markdown File
|
||||
|
||||
1. Determine which category your document belongs to (how-to, usage, or technical-docs)
|
||||
2. Create a new `.md` file in the appropriate subdirectory
|
||||
3. Use a descriptive filename with hyphens (e.g., `my-new-feature.md`)
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
# For a how-to guide
|
||||
touch /docs/docs/how-to/configure-audio-settings.md
|
||||
|
||||
# For usage documentation
|
||||
touch /docs/docs/usage/video-switcher-control.md
|
||||
|
||||
# For technical documentation
|
||||
touch /docs/docs/technical-docs/custom-device-plugin.md
|
||||
```
|
||||
|
||||
### Step 2: Write Your Content
|
||||
|
||||
Start your markdown file with a level 1 heading (`#`) that serves as the page title:
|
||||
|
||||
```markdown
|
||||
# Your Document Title
|
||||
|
||||
Brief introduction to the topic.
|
||||
|
||||
## Section Heading
|
||||
|
||||
Content goes here...
|
||||
|
||||
### Subsection
|
||||
|
||||
More detailed content...
|
||||
```
|
||||
|
||||
**Markdown Features:**
|
||||
- Use standard markdown syntax
|
||||
- Include code blocks with language specifiers (```csharp, ```json, etc.)
|
||||
- Add images: ``
|
||||
- Link to other docs: `[Link text](../usage/related-doc.md)`
|
||||
|
||||
### Step 3: Add to Table of Contents
|
||||
|
||||
Edit `/docs/docs/toc.yml` to add your new document to the navigation:
|
||||
|
||||
```yaml
|
||||
- name: How-to's
|
||||
items:
|
||||
- href: how-to/how-to-add-docs.md
|
||||
- href: how-to/your-new-doc.md # Add your document here
|
||||
```
|
||||
|
||||
**TOC Structure:**
|
||||
- `name:` - Display name in the navigation menu
|
||||
- `href:` - Relative path to the markdown file
|
||||
- `items:` - Nested items for hierarchical navigation
|
||||
|
||||
**Example with nested items:**
|
||||
```yaml
|
||||
- name: Usage
|
||||
items:
|
||||
- name: SIMPL Bridging
|
||||
href: usage/SIMPL-Bridging-Updated.md
|
||||
items:
|
||||
- name: Your Sub-Topic
|
||||
href: usage/your-sub-topic.md
|
||||
```
|
||||
|
||||
### Step 4: Test Locally
|
||||
|
||||
Build and preview the docFx site locally to verify your changes:
|
||||
|
||||
```bash
|
||||
# Navigate to the docs directory
|
||||
cd docs
|
||||
|
||||
# Build the documentation
|
||||
docfx build
|
||||
|
||||
# Serve the site locally
|
||||
docfx serve _site
|
||||
```
|
||||
|
||||
Then open your browser to `http://localhost:8080` to view the site.
|
||||
|
||||
## Best Practices
|
||||
|
||||
### File Naming
|
||||
- Use lowercase with hyphens: `my-document-name.md`
|
||||
- Be descriptive but concise
|
||||
- Avoid special characters
|
||||
|
||||
### Content Guidelines
|
||||
- Start with a clear introduction
|
||||
- Use hierarchical headings (H1 → H2 → H3)
|
||||
- Include code examples where appropriate
|
||||
- Add images to illustrate complex concepts
|
||||
- Link to related documentation
|
||||
|
||||
### TOC Organization
|
||||
- Group related documents under the same parent
|
||||
- Order items logically (basic → advanced)
|
||||
- Keep the TOC hierarchy shallow (2-3 levels max)
|
||||
- Use clear, descriptive names for navigation items
|
||||
|
||||
## Common Issues
|
||||
|
||||
### Document Not Appearing
|
||||
- Verify the file path in `toc.yml` is correct and uses forward slashes
|
||||
- Ensure the markdown file exists in the specified location
|
||||
- Check for YAML syntax errors in `toc.yml`
|
||||
|
||||
### Images Not Loading
|
||||
- Verify image path is relative to the markdown file location
|
||||
- Use `../images/` for files in the images directory
|
||||
- Ensure image files are committed to the repository
|
||||
|
||||
### Broken Links
|
||||
- Use relative paths for internal links
|
||||
- Test all links after building the site
|
||||
- Use `.md` extension when linking to other documentation files
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [docFx Documentation](https://dotnet.github.io/docfx/)
|
||||
- [Markdown Guide](https://www.markdownguide.org/)
|
||||
- [YAML Syntax](https://yaml.org/spec/1.2/spec.html)
|
||||
- [Diátaxis](https://diataxis.fr/start-here/)
|
||||
@@ -26,7 +26,7 @@ Types of things in `DeviceManager`:
|
||||
|
||||
A Device doesn't always represent a physical piece of hardware, but rather a logical construct that "does something" and is used by one or more other devices in the running program. For example, we create a room device, and its corresponding Fusion device, and that room has a Cisco codec device, with an attached SSh client device. All of these lie in a flat collection in the `DeviceManager`.
|
||||
|
||||
> The `DeviceManager` is nothing more than a modified collection of things, and technically those things don't have to be Devices, but must at least implement the `IKeyed` (`PepperDash.Core.IKeyed`) interface (simply so items can be looked up by their key.) Items in the `DeviceManager` that are Devices are run through additional steps of [activation](~/docs/Arch-activate.md#2-pre-activation) at startup. This collection of devices is all interrelated by their string keys.
|
||||
> The `DeviceManager` is nothing more than a modified collection of things, and technically those things don't have to be Devices, but must at least implement the `IKeyed` (`PepperDash.Core.IKeyed`) interface (simply so items can be looked up by their key.) Items in the `DeviceManager` that are Devices are run through additional steps of [activation](~/docs/technical-docs/Arch-activate.md#2-pre-activation) at startup. This collection of devices is all interrelated by their string keys.
|
||||
|
||||
In this flat design, we spin up devices, and then introduce them to their "coworkers and bosses" - the other devices and logical units that they will interact with - and get them all operating together to form a running unit. For example: A room configuration will contain a "VideoCodecKey" property and a "DefaultDisplayKey" property. The `DeviceManager` provides the room with the codec or displays having the appropriate keys. What the room does with those is dependent on its coding.
|
||||
|
||||
@@ -38,4 +38,4 @@ This flat structure ensures that every device in a system exists in one place an
|
||||
|
||||

|
||||
|
||||
Next: [Configurable lifecycle](~/docs/Arch-lifecycle.md)
|
||||
Next: [Configurable lifecycle](~/docs/technical-docs/Arch-lifecycle.md)
|
||||
@@ -32,7 +32,7 @@ If the `CustomActivate()` method is long, consider breaking it up into many smal
|
||||
Note: It is best-practice in Essentials to not write arbitrarily-timed startup sequences to ensure that a "system" or room is functional. Rather, we encourage the developer to use various properties and conditions on devices to aggregate together "room is ready" statuses that can trigger further action. This ensures that all devices can be up and alive, allowing them to be debugged within a program that may otherwise be misbehaving - as well as not making users and expensive developers wait for code to start up!
|
||||
|
||||
```cs
|
||||
public override bool CustomActivate()
|
||||
protected override bool CustomActivate()
|
||||
{
|
||||
Debug.Console(0, this, "Final activation. Setting up actions and feedbacks");
|
||||
SetupFunctions();
|
||||
@@ -52,7 +52,7 @@ We can see in the example below that during the `CustomActivate()` phase, we def
|
||||
### **Example**
|
||||
|
||||
```cs
|
||||
public override bool CustomActivate()
|
||||
protected override bool CustomActivate()
|
||||
{
|
||||
foreach (var i in Config.Inputs)
|
||||
{
|
||||
@@ -105,7 +105,7 @@ Each of the three activation phases operates in a try/catch block for each devic
|
||||
|
||||
In any real-world system, devices and business logic need to talk to each other, otherwise, what's the point of all this coding? When creating your classes and configuration, it is best practice to _try_ not to "plug" one device into another during construction or activation. For example your touchpanel controller class has a `Display1` property that holds the display-1 object. Rather, it may be better to refer to the device as it is stored in the `DeviceManager` when it's needed using the static `DeviceManager.GetDeviceForKey(key)` method to get a reference to the device, which can be cast using various interfaces/class types, and then interacted with. This prevents objects from being referenced in places where the developer may later forget to dereference them, causing memory leak. This will become more important as Essentials becomes more able to be reconfigured at runtime.
|
||||
|
||||
As an example, [connection-based routing](~/docs/Connection-based-routing.md#essentials-connection-based-routing) uses these methods. When a route is requested, the collection of tielines and devices is searched for the devices and paths necessary to complete a route, but there are no devices or tie lines that are object-referenced in running code. It can all be torn down and reconfigured without any memory-management dereferencing, setting things to null.
|
||||
As an example, [connection-based routing](~/docs/technical-docs/Connection-based-routing.md#essentials-connection-based-routing) uses these methods. When a route is requested, the collection of tielines and devices is searched for the devices and paths necessary to complete a route, but there are no devices or tie lines that are object-referenced in running code. It can all be torn down and reconfigured without any memory-management dereferencing, setting things to null.
|
||||
|
||||
## Device Initialization
|
||||
|
||||
@@ -115,7 +115,7 @@ The main task that should be undertaken in the `Initialize()` method for any 3rd
|
||||
|
||||
### Example (from `PepperDash.Essentials.Devices.Common.VideoCodec.Cisco.CiscoSparkCodec`)
|
||||
```cs
|
||||
public override void Initialize()
|
||||
protected override void Initialize()
|
||||
{
|
||||
var socket = Communication as ISocketStatus;
|
||||
if (socket != null)
|
||||
@@ -155,4 +155,4 @@ Robust C#-based system code should not depend on "order" or "time" to get runnin
|
||||
|
||||
When designing new Device-based classes, be it rooms, devices, port controllers, bridges, make them as independent as possible. They could exist alone in a program with no required partner objects, and just quietly exist without failing. We want the system to be fast and flexible, and keeping the interdependence between objects at a minimum improves this flexibility into the future.
|
||||
|
||||
Next: [More architecture](~/docs/Arch-topics.md)
|
||||
Next: [More architecture](~/docs/technical-docs/Arch-topics.md)
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
The diagram below describes how Essentials gets a program up and running.
|
||||
|
||||
(The various activation phases are covered in more detail on the [next page](~/docs/Arch-activate.md))
|
||||
(The various activation phases are covered in more detail on the [next page](~/docs/technical-docs/Arch-activate.md))
|
||||
|
||||

|
||||
|
||||
Next: [Activation phases](~/docs/Arch-activate.md)
|
||||
Next: [Activation phases](~/docs/technical-docs/Arch-activate.md)
|
||||
@@ -16,4 +16,4 @@ The diagram below shows the reference dependencies that exist between the differ
|
||||
|
||||

|
||||
|
||||
Next: [Architecture](~/docs/Arch-1.md)
|
||||
Next: [Architecture](~/docs/technical-docs/Arch-1.md)
|
||||
@@ -1,48 +1,52 @@
|
||||
- name: Get Started With Essentials
|
||||
- href: ../index.md
|
||||
- href: Get-started.md
|
||||
- href: Get-started.md
|
||||
- name: How-to's
|
||||
items:
|
||||
- name: How to add an article or doc page
|
||||
href: how-to/how-to-add-docs.md
|
||||
- name: Usage
|
||||
items:
|
||||
- href: Standalone-Use.md
|
||||
- href: SIMPL-Bridging-Updated.md
|
||||
- href: usage/Standalone-Use.md
|
||||
- href: usage/SIMPL-Bridging-Updated.md
|
||||
items:
|
||||
- name: Join Maps
|
||||
href: JoinMaps.md
|
||||
href: usage/JoinMaps.md
|
||||
- name: Bridging to Hardware Resources
|
||||
href: Bridging-To-Hardware-Resources.md
|
||||
href: usage/Bridging-To-Hardware-Resources.md
|
||||
items:
|
||||
- name: GenericComm Bridging
|
||||
href: GenericComm.md
|
||||
href: usage/GenericComm.md
|
||||
- name: RelayOutput Bridging
|
||||
href: RelayOutput.md
|
||||
href: usage/RelayOutput.md
|
||||
- name: Digital Input Bridging
|
||||
href: DigitalInput.md
|
||||
href: usage/DigitalInput.md
|
||||
- name: IR Driver Bridging
|
||||
href: IR-Driver-Bridging.md
|
||||
href: usage/IR-Driver-Bridging.md
|
||||
- name: Technical documentation
|
||||
items:
|
||||
- href: Arch-summary.md
|
||||
- href: technical-docs/Arch-summary.md
|
||||
- name: Devices and DeviceManager
|
||||
href: Arch-1.md
|
||||
href: technical-docs/Arch-1.md
|
||||
- name: Configurable lifecycle
|
||||
href: Arch-lifecycle.md
|
||||
href: technical-docs/Arch-lifecycle.md
|
||||
- name: Activation phases
|
||||
href: Arch-activate.md
|
||||
href: technical-docs/Arch-activate.md
|
||||
- name: More
|
||||
href: Arch-topics.md
|
||||
href: technical-docs/Arch-topics.md
|
||||
- name: Plugins
|
||||
href: Plugins.md
|
||||
href: technical-docs/Plugins.md
|
||||
- name: Communication Basics
|
||||
href: Communication-Basics.md
|
||||
href: technical-docs/Communication-Basics.md
|
||||
- name: Debugging
|
||||
href: Debugging.md
|
||||
href: technical-docs/Debugging.md
|
||||
- name: Feedback Classes
|
||||
href: Feedback-Classes.md
|
||||
href: technical-docs/Feedback-Classes.md
|
||||
- name: Connection Based Routing
|
||||
href: Connection-Based-Routing.md
|
||||
href: technical-docs/Connection-Based-Routing.md
|
||||
- name: Configuration Structure
|
||||
href: ConfigurationStructure.md
|
||||
href: technical-docs/ConfigurationStructure.md
|
||||
- name: Supported Devices
|
||||
href: Supported-Devices.md
|
||||
href: technical-docs/Supported-Devices.md
|
||||
- name: Glossary of Terms
|
||||
href: Glossary-of-Terms.md
|
||||
href: technical-docs/Glossary-of-Terms.md
|
||||
@@ -6,10 +6,10 @@ One of the most powerful features of Essentials is the ability to bridge SIMPL t
|
||||
|
||||
Follow the links below for examples of bridging to hardware and network resources.
|
||||
|
||||
**[GenericComm Bridging](~/docs/GenericComm.md)**
|
||||
**[GenericComm Bridging](~/docs/usage/GenericComm.md)**
|
||||
|
||||
**[RelayOutput Bridging](~/docs/RelayOutput.md)**
|
||||
**[RelayOutput Bridging](~/docs/usage/RelayOutput.md)**
|
||||
|
||||
**[Digital Input Bridging](~/docs/DigitalInput.md)**
|
||||
**[Digital Input Bridging](~/docs/usage/DigitalInput.md)**
|
||||
|
||||
**[Card Frame Bridging](~/docs/CardFrame.md)**
|
||||
@@ -286,7 +286,7 @@ Example device config: <https://github.com/PepperDash/Essentials/blob/main/Peppe
|
||||
|
||||
3. A bridge need not only bridge between applications on the same processor. A bridge may bridge to an application on a completely separate processor; simply define the ip address in the Bridge control properties accordingly.
|
||||
|
||||
4. For devices included in Essentials, you will be able to find defined join maps below. If you are building your own plugins, you will need to build the join map yourself. It would be beneficial to review the wiki entry on the [Feedback Class](~/docs/Feedback-Classes.md) for this.
|
||||
4. For devices included in Essentials, you will be able to find defined join maps below. If you are building your own plugins, you will need to build the join map yourself. It would be beneficial to review the wiki entry on the [Feedback Class](~/docs/technical-docs/Feedback-Classes.md) for this.
|
||||
|
||||
5. When building plugins, we highly recommend reusing JoinMaps, as this will make code more easily interchangeable. For example; if you were to build a display plugin, we'd recommend you use/extend the existing `DisplayControllerJoinMap`. This way, you can swap plugins without needing any change on the SIMPL Windows side. This is extremely powerful when maintaining SIMPL Windows code bases for large deployments that may utilize differing equipment per room. If you can build a SIMPL Windows program that interacts with established join maps, you can swap out the device via config without any change needed to SIMPL Windows.
|
||||
|
||||
@@ -302,7 +302,7 @@ Example device config: <https://github.com/PepperDash/Essentials/blob/main/Peppe
|
||||
|
||||
## Join Map Documentation
|
||||
|
||||
[Join Map Documentation](~/docs/JoinMaps.md)
|
||||
[Join Map Documentation](~/docs/usage/JoinMaps.md)
|
||||
|
||||
## Device Type Join Maps
|
||||
|
||||
@@ -408,4 +408,4 @@ Please note that these joinmaps _may_ be using a deprecated implementation. The
|
||||
|
||||
We've provided an [example program](https://github.com/PepperDash/EssentialsSIMPLWindowsBridgeExample) for SIMPL Windows that works with the provided example Essentials configuration file [SIMPLBridgeExample_configurationFile.json](https://github.com/PepperDash/Essentials/blob/main/PepperDashEssentials/Example%20Configuration/SIMPLBridging/SIMPLBridgeExample_configurationFile.json). Load Essentials and the example SIMPL program to two slots on the same processor and you can get a better idea of how to take advantage of SIMPL Windows bridging.
|
||||
|
||||
Next: [Essentials architecture](~/docs/Arch-summary.md)
|
||||
Next: [Essentials architecture](~/docs/technical-docs/Arch-summary.md)
|
||||
@@ -8,7 +8,7 @@ By defining devices and a room in a JSON configuration file, Essentials can cont
|
||||
|
||||
### Devices
|
||||
|
||||
Essentials supports device plugins for communicating with various devices using both standard Crestron CIP communications, Cresnet, SSH, or other TCP/IP-based communication methods. See [the Plugins section](~/docs/Plugins.md) for more details
|
||||
Essentials supports device plugins for communicating with various devices using both standard Crestron CIP communications, Cresnet, SSH, or other TCP/IP-based communication methods. See [the Plugins section](~/docs/technical-docs/Plugins.md) for more details
|
||||
|
||||
### Rooms
|
||||
|
||||
@@ -16,4 +16,4 @@ In order to tie together equipment into a unit that comprises what devices are u
|
||||
|
||||
See Also: [[Supported Devices|Supported-Devices]]
|
||||
|
||||
Next: [Simpl Windows bridging](~/docs/SIMPL-Bridging-Updated.md)
|
||||
Next: [Simpl Windows bridging](~/docs/usage/SIMPL-Bridging-Updated.md)
|
||||
@@ -8,12 +8,12 @@ Essentials is a collection of C# libraries that can be used in many ways. It is
|
||||
|
||||
## Get started
|
||||
|
||||
- [Download essentials build or clone repo](~/docs/Get-started.md)
|
||||
- [How to get started](~/docs/Get-started.md)
|
||||
- [Download an Essentials build or clone the repo](~/docs/Get-started.md)
|
||||
- [Get started](~/docs/Get-started.md)
|
||||
- [YouTube Video Series Playlist](https://youtube.com/playlist?list=PLKOoNNwgPFZdV5wDEBDZxTHu1KROspaBu)
|
||||
- [Discord Server](https://discord.gg/6Vh3ssDdPs)
|
||||
|
||||
Or use the links to the right to navigate our documentation.
|
||||
Or use the links to the left to navigate our documentation.
|
||||
|
||||
---
|
||||
|
||||
@@ -25,21 +25,12 @@ Or use the links to the right to navigate our documentation.
|
||||
- Shared resources made easily available
|
||||
- More flexibility with less code
|
||||
- Configurable using simple JSON files
|
||||
- Is awesome
|
||||
|
||||
---
|
||||
|
||||
## Comment
|
||||
|
||||
The Essentials wiki is clearly in-progress right now. Take a look at the links to the right. We are actively working on this documentation, so please be patient with us. If you have any comments on or suggestions for the documentation, please file an issue here, with as much detail as you can provide: <https://github.com/PepperDash/Essentials/issues>
|
||||
|
||||
Thanks!
|
||||
|
||||
---
|
||||
|
||||
## Collaboration
|
||||
|
||||
Essentials is an open-source project and we encourage collaboration on this community project. For features that may not be useful to the greater community, or for just-plain learning, we want to remind developers to try writing plugins for Essentials. More information can be found here: [Plugins](~/docs/Plugins.md)
|
||||
Essentials is an open-source project and we encourage collaboration on this community project. For features that may not be useful to the greater community, or for just-plain learning, we want to remind developers to try writing plugins for Essentials. More information can be found here: [Plugins](~/docs/technical-docs/Plugins.md)
|
||||
|
||||
### Open-source-collaborative workflow
|
||||
|
||||
@@ -52,7 +43,7 @@ The `main` branch always contain the latest stable version. The `development` br
|
||||
- Example: `feature/add-awesomeness` or `hotfix/really-big-oops`
|
||||
- When working on a new feature or bugfix, branch from the `development` branch. When working on a hotfix, branch from `main`.
|
||||
3. Make commits as necessary (often is better). And use concise, descriptive language, leveraging issue notation and/or [Closing Keywords](https://help.github.com/articles/closing-issues-using-keywords) to ensure any issues addressed by your work are referenced accordingly.
|
||||
4. When the scope of the work for your branch is complete, make sure to rebase your branch in case further progress has been made since the repo was forked
|
||||
4. When the scope of the work for your branch is complete, make sure to update your branch in case further progress has been made since the repo was forked
|
||||
5. Create a Pull Request to pull your branch into the appropriate branch in the main repository.
|
||||
6. Your Pull Request will be reviewed by our team and evaluated for inclusion into the main repository.
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
<Project>
|
||||
<ItemGroup>
|
||||
<None Include="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).clz" Condition="$(ProjectType) == 'Library'">
|
||||
<None Include="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).clz" Condition="$(ProjectType) == 'Library' And '$(TargetFramework)' != '' And '$(TargetName)' != '' And '$(TargetDir)' != ''">
|
||||
<Pack>true</Pack>
|
||||
<PackagePath>build;</PackagePath>
|
||||
</None>
|
||||
<None Include="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).cpz" Condition="$(ProjectType) == 'Program'">
|
||||
<None Include="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).cpz" Condition="$(ProjectType) == 'Program' And '$(TargetFramework)' != '' And '$(TargetName)' != '' And '$(TargetDir)' != '' And ( '$(TargetFramework)' != 'net6.0' ) And ( '$(TargetFramework)' != 'net8.0' )">
|
||||
<Pack>true</Pack>
|
||||
<PackagePath>build;</PackagePath>
|
||||
</None>
|
||||
<None Include="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).cplz" Condition="$(ProjectType) == 'ProgramLibrary'">
|
||||
<None Include="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).cplz" Condition="$(ProjectType) == 'ProgramLibrary' And '$(TargetFramework)' != '' And '$(TargetName)' != '' And '$(TargetDir)' != ''">
|
||||
<Pack>true</Pack>
|
||||
<PackagePath>build;</PackagePath>
|
||||
</None>
|
||||
@@ -23,23 +23,32 @@
|
||||
<FileName>$(TargetDir)$(TargetName).$(Version).$(TargetFramework).cpz</FileName>
|
||||
</PropertyGroup>
|
||||
|
||||
<Target Name="DeleteCLZ" BeforeTargets="PreBuildEvent" Condition="$(ProjectType) == 'Library' And $(TargetDir) != '' And Exists($(FileName))">
|
||||
<Delete Files="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).clz">
|
||||
<Target Name="DeleteCLZ" BeforeTargets="CoreBuild" Condition="$(ProjectType) == 'Library' And $(TargetDir) != ''">
|
||||
<ItemGroup>
|
||||
<OldCLZFiles Include="$(TargetDir)$(TargetName).*.$(TargetFramework).clz" />
|
||||
</ItemGroup>
|
||||
<Delete Files="@(OldCLZFiles)" Condition="@(OldCLZFiles) != ''">
|
||||
<Output TaskParameter="DeletedFiles" ItemName="DeletedList"/>
|
||||
</Delete>
|
||||
<Message Text="Deleted files: '@(DeletedList)'" />
|
||||
<Message Text="Deleted old CLZ files: '@(DeletedList)'" Condition="@(DeletedList) != ''" />
|
||||
</Target>
|
||||
<Target Name="DeleteCPZ" BeforeTargets="PreBuildEvent" Condition="$(ProjectType) == 'Program' And $(TargetDir) != '' And Exists($(FileName))">
|
||||
<Delete Files="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).cpz">
|
||||
<Target Name="DeleteCPZ" BeforeTargets="CoreBuild" Condition="$(ProjectType) == 'Program' And $(TargetDir) != ''">
|
||||
<ItemGroup>
|
||||
<OldCPZFiles Include="$(TargetDir)$(TargetName).*.$(TargetFramework).cpz" />
|
||||
</ItemGroup>
|
||||
<Delete Files="@(OldCPZFiles)" Condition="@(OldCPZFiles) != ''">
|
||||
<Output TaskParameter="DeletedFiles" ItemName="DeletedList"/>
|
||||
</Delete>
|
||||
<Message Text="Deleted files: '@(DeletedList)'" />
|
||||
<Message Text="Deleted old CPZ files: '@(DeletedList)'" Condition="@(DeletedList) != ''" />
|
||||
</Target>
|
||||
<Target Name="DeleteCPLZ" BeforeTargets="PreBuildEvent" Condition="$(ProjectType) == 'ProgramLibrary' And $(TargetDir) != '' And Exists($(FileName))">
|
||||
<Delete Files="$(TargetDir)$(TargetName).$(Version).$(TargetFramework).cplz">
|
||||
<Target Name="DeleteCPLZ" BeforeTargets="CoreBuild" Condition="$(ProjectType) == 'ProgramLibrary' And $(TargetDir) != ''">
|
||||
<ItemGroup>
|
||||
<OldCPLZFiles Include="$(TargetDir)$(TargetName).*.$(TargetFramework).cplz" />
|
||||
</ItemGroup>
|
||||
<Delete Files="@(OldCPLZFiles)" Condition="@(OldCPLZFiles) != ''">
|
||||
<Output TaskParameter="DeletedFiles" ItemName="DeletedList"/>
|
||||
</Delete>
|
||||
<Message Text="Deleted files: '@(DeletedList)'" />
|
||||
<Message Text="Deleted old CPLZ files: '@(DeletedList)'" Condition="@(DeletedList) != ''" />
|
||||
</Target>
|
||||
|
||||
<Target Name="CreateCPLZ" AfterTargets="Build" Condition="$(ProjectType) == 'ProgramLibrary' And $(TargetDir) != ''" DependsOnTargets="DeleteCPLZ">
|
||||
|
||||
36
src/PepperDash.Core.Abstractions/DebugServiceRegistration.cs
Normal file
36
src/PepperDash.Core.Abstractions/DebugServiceRegistration.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
namespace PepperDash.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Allows pre-registration of Crestron service implementations before the <c>Debug</c>
|
||||
/// static class initialises. Call <see cref="Register"/> from the composition root
|
||||
/// (e.g. ControlSystem constructor) <em>before</em> any code touches <c>Debug.*</c>.
|
||||
/// Test projects should call it with no-op / in-memory implementations so that the
|
||||
/// <c>Debug</c> static constructor never tries to reach the real Crestron SDK.
|
||||
/// </summary>
|
||||
public static class DebugServiceRegistration
|
||||
{
|
||||
/// <summary>Gets the registered environment abstraction, or <c>null</c> if not registered.</summary>
|
||||
public static ICrestronEnvironment? Environment { get; private set; }
|
||||
|
||||
/// <summary>Gets the registered console abstraction, or <c>null</c> if not registered.</summary>
|
||||
public static ICrestronConsole? Console { get; private set; }
|
||||
|
||||
/// <summary>Gets the registered data-store abstraction, or <c>null</c> if not registered.</summary>
|
||||
public static ICrestronDataStore? DataStore { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Registers the service implementations that <c>Debug</c> will use when its
|
||||
/// static constructor runs. Any parameter may be <c>null</c> to leave the
|
||||
/// corresponding service unregistered (the <c>Debug</c> class will skip that
|
||||
/// capability gracefully).
|
||||
/// </summary>
|
||||
public static void Register(
|
||||
ICrestronEnvironment? environment,
|
||||
ICrestronConsole? console,
|
||||
ICrestronDataStore? dataStore)
|
||||
{
|
||||
Environment = environment;
|
||||
Console = console;
|
||||
DataStore = dataStore;
|
||||
}
|
||||
}
|
||||
100
src/PepperDash.Core.Abstractions/Enums.cs
Normal file
100
src/PepperDash.Core.Abstractions/Enums.cs
Normal file
@@ -0,0 +1,100 @@
|
||||
namespace PepperDash.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors Crestron's <c>eDevicePlatform</c> without requiring the Crestron SDK.
|
||||
/// </summary>
|
||||
public enum DevicePlatform
|
||||
{
|
||||
/// <summary>Hardware appliance (e.g. CP4, MC4).</summary>
|
||||
Appliance,
|
||||
/// <summary>Crestron Virtual Control / server runtime.</summary>
|
||||
Server,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors Crestron's <c>eRuntimeEnvironment</c>.
|
||||
/// </summary>
|
||||
public enum RuntimeEnvironment
|
||||
{
|
||||
/// <summary>SimplSharpPro program slot (hardware 4-series).</summary>
|
||||
SimplSharpPro,
|
||||
/// <summary>SimplSharp (older 3-series or server environments).</summary>
|
||||
SimplSharp,
|
||||
/// <summary>Any other environment — check for completeness.</summary>
|
||||
Other,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors Crestron's <c>ConsoleAccessLevelEnum</c>.
|
||||
/// </summary>
|
||||
public enum ConsoleAccessLevel
|
||||
{
|
||||
AccessAdministrator = 0,
|
||||
AccessOperator = 1,
|
||||
AccessProgrammer = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors Crestron's <c>eProgramStatusEventType</c>.
|
||||
/// </summary>
|
||||
public enum ProgramStatusEventType
|
||||
{
|
||||
Starting,
|
||||
Stopping,
|
||||
Paused,
|
||||
Resumed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors the event type used by Crestron's <c>EthernetEventArgs</c>.
|
||||
/// </summary>
|
||||
public enum EthernetEventType
|
||||
{
|
||||
LinkDown = 0,
|
||||
LinkUp = 1,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for Crestron ethernet link events.
|
||||
/// </summary>
|
||||
public class PepperDashEthernetEventArgs : EventArgs
|
||||
{
|
||||
public EthernetEventType EthernetEventType { get; }
|
||||
public short EthernetAdapter { get; }
|
||||
|
||||
public PepperDashEthernetEventArgs(EthernetEventType eventType, short adapter)
|
||||
{
|
||||
EthernetEventType = eventType;
|
||||
EthernetAdapter = adapter;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors the set of <c>CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET</c> values
|
||||
/// used across this codebase — does not aim to be exhaustive.
|
||||
/// </summary>
|
||||
public enum EthernetParameterType
|
||||
{
|
||||
GetCurrentIpAddress,
|
||||
GetHostname,
|
||||
GetDomainName,
|
||||
GetLinkStatus,
|
||||
GetCurrentDhcpState,
|
||||
GetCurrentIpMask,
|
||||
GetCurrentRouter,
|
||||
GetMacAddress,
|
||||
GetDnsServer,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors Crestron's <c>SocketStatus</c> without requiring the Crestron SDK.
|
||||
/// </summary>
|
||||
public enum PepperDashSocketStatus
|
||||
{
|
||||
SocketNotConnected = 0,
|
||||
SocketConnected = 2,
|
||||
SocketConnectionInProgress = 6,
|
||||
SocketConnectFailed = 11,
|
||||
SocketDisconnecting = 12,
|
||||
SocketBrokenRemotely = 7,
|
||||
}
|
||||
32
src/PepperDash.Core.Abstractions/ICrestronConsole.cs
Normal file
32
src/PepperDash.Core.Abstractions/ICrestronConsole.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
namespace PepperDash.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts <c>Crestron.SimplSharp.CrestronConsole</c> to allow unit testing
|
||||
/// without the Crestron SDK.
|
||||
/// </summary>
|
||||
public interface ICrestronConsole
|
||||
{
|
||||
/// <summary>Prints a line to the Crestron console/telnet output.</summary>
|
||||
void PrintLine(string message);
|
||||
|
||||
/// <summary>Prints text (without newline) to the Crestron console/telnet output.</summary>
|
||||
void Print(string message);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a response string to the console for the currently-executing console command.
|
||||
/// </summary>
|
||||
void ConsoleCommandResponse(string message);
|
||||
|
||||
/// <summary>
|
||||
/// Registers a new command with the Crestron console.
|
||||
/// </summary>
|
||||
/// <param name="callback">Handler invoked when the command is typed.</param>
|
||||
/// <param name="command">Command name (no spaces).</param>
|
||||
/// <param name="helpText">Help text shown by the Crestron console.</param>
|
||||
/// <param name="accessLevel">Minimum access level required to run the command.</param>
|
||||
void AddNewConsoleCommand(
|
||||
Action<string> callback,
|
||||
string command,
|
||||
string helpText,
|
||||
ConsoleAccessLevel accessLevel);
|
||||
}
|
||||
31
src/PepperDash.Core.Abstractions/ICrestronDataStore.cs
Normal file
31
src/PepperDash.Core.Abstractions/ICrestronDataStore.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
namespace PepperDash.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts <c>Crestron.SimplSharp.CrestronDataStore.CrestronDataStoreStatic</c>
|
||||
/// to allow unit testing without the Crestron SDK.
|
||||
/// </summary>
|
||||
public interface ICrestronDataStore
|
||||
{
|
||||
/// <summary>Initialises the data store. Must be called once before any other operation.</summary>
|
||||
void InitStore();
|
||||
|
||||
/// <summary>Reads an integer value from the local (program-slot) store.</summary>
|
||||
/// <returns><c>true</c> if the value was found and read successfully.</returns>
|
||||
bool TryGetLocalInt(string key, out int value);
|
||||
|
||||
/// <summary>Writes an integer value to the local (program-slot) store.</summary>
|
||||
/// <returns><c>true</c> on success.</returns>
|
||||
bool SetLocalInt(string key, int value);
|
||||
|
||||
/// <summary>Writes an unsigned integer value to the local (program-slot) store.</summary>
|
||||
/// <returns><c>true</c> on success.</returns>
|
||||
bool SetLocalUint(string key, uint value);
|
||||
|
||||
/// <summary>Reads a boolean value from the local (program-slot) store.</summary>
|
||||
/// <returns><c>true</c> if the value was found and read successfully.</returns>
|
||||
bool TryGetLocalBool(string key, out bool value);
|
||||
|
||||
/// <summary>Writes a boolean value to the local (program-slot) store.</summary>
|
||||
/// <returns><c>true</c> on success.</returns>
|
||||
bool SetLocalBool(string key, bool value);
|
||||
}
|
||||
52
src/PepperDash.Core.Abstractions/ICrestronEnvironment.cs
Normal file
52
src/PepperDash.Core.Abstractions/ICrestronEnvironment.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
namespace PepperDash.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts <c>Crestron.SimplSharp.CrestronEnvironment</c> to allow unit testing
|
||||
/// without the Crestron SDK.
|
||||
/// </summary>
|
||||
public interface ICrestronEnvironment
|
||||
{
|
||||
/// <summary>Gets the platform the program is executing on.</summary>
|
||||
DevicePlatform DevicePlatform { get; }
|
||||
|
||||
/// <summary>Gets the current runtime environment.</summary>
|
||||
RuntimeEnvironment RuntimeEnvironment { get; }
|
||||
|
||||
/// <summary>Gets the platform-appropriate newline string.</summary>
|
||||
string NewLine { get; }
|
||||
|
||||
/// <summary>Gets the application number (program slot).</summary>
|
||||
uint ApplicationNumber { get; }
|
||||
|
||||
/// <summary>Gets the room ID (used in Crestron Virtual Control / server environments).</summary>
|
||||
uint RoomId { get; }
|
||||
|
||||
/// <summary>Raised when program status changes (starting, stopping, etc.).</summary>
|
||||
event EventHandler<ProgramStatusEventArgs> ProgramStatusChanged;
|
||||
|
||||
/// <summary>Raised when the ethernet link changes state.</summary>
|
||||
event EventHandler<PepperDashEthernetEventArgs> EthernetEventReceived;
|
||||
|
||||
/// <summary>Gets the application root directory path.</summary>
|
||||
string GetApplicationRootDirectory();
|
||||
|
||||
/// <summary>
|
||||
/// Returns <c>true</c> when running on real Crestron hardware.
|
||||
/// Returns <c>false</c> in test / dev environments so that SDK-specific
|
||||
/// sinks and enrichers can be safely skipped.
|
||||
/// </summary>
|
||||
bool IsHardwareRuntime { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for <see cref="ICrestronEnvironment.ProgramStatusChanged"/>.
|
||||
/// </summary>
|
||||
public class ProgramStatusEventArgs : EventArgs
|
||||
{
|
||||
public ProgramStatusEventType EventType { get; }
|
||||
|
||||
public ProgramStatusEventArgs(ProgramStatusEventType eventType)
|
||||
{
|
||||
EventType = eventType;
|
||||
}
|
||||
}
|
||||
16
src/PepperDash.Core.Abstractions/IEthernetHelper.cs
Normal file
16
src/PepperDash.Core.Abstractions/IEthernetHelper.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace PepperDash.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts <c>Crestron.SimplSharp.CrestronEthernetHelper</c> to allow unit testing
|
||||
/// without the Crestron SDK.
|
||||
/// </summary>
|
||||
public interface IEthernetHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns a network parameter string for the specified adapter.
|
||||
/// </summary>
|
||||
/// <param name="parameter">The parameter to retrieve.</param>
|
||||
/// <param name="ethernetAdapterId">Ethernet adapter index (0 = LAN A).</param>
|
||||
/// <returns>String value of the requested parameter.</returns>
|
||||
string GetEthernetParameter(EthernetParameterType parameter, short ethernetAdapterId);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>PepperDash.Core.Abstractions</RootNamespace>
|
||||
<AssemblyName>PepperDash.Core.Abstractions</AssemblyName>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Deterministic>true</Deterministic>
|
||||
<NeutralLanguage>en</NeutralLanguage>
|
||||
<Title>PepperDash Core Abstractions</Title>
|
||||
<Company>PepperDash Technologies</Company>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<RepositoryUrl>https://github.com/PepperDash/PepperDashCore</RepositoryUrl>
|
||||
<NullableContextOptions>enable</NullableContextOptions>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<InformationalVersion>$(Version)</InformationalVersion>
|
||||
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
||||
<!-- No Crestron SDK reference — this project must remain hardware-agnostic so test projects can reference it -->
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
323
src/PepperDash.Core.Tests/Devices/DeviceTests.cs
Normal file
323
src/PepperDash.Core.Tests/Devices/DeviceTests.cs
Normal file
@@ -0,0 +1,323 @@
|
||||
using FluentAssertions;
|
||||
using PepperDash.Core;
|
||||
using Xunit;
|
||||
|
||||
namespace PepperDash.Core.Tests.Devices;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <see cref="Device"/> — the base class for all PepperDash devices.
|
||||
/// These run without Crestron hardware; Debug is initialized with fakes via TestInitializer.
|
||||
/// </summary>
|
||||
public class DeviceTests
|
||||
{
|
||||
// -----------------------------------------------------------------------
|
||||
// Construction
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SingleArg_SetsKey()
|
||||
{
|
||||
var device = new Device("my-device");
|
||||
|
||||
device.Key.Should().Be("my-device");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SingleArg_SetsNameToEmpty()
|
||||
{
|
||||
var device = new Device("my-device");
|
||||
|
||||
device.Name.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_TwoArg_SetsKeyAndName()
|
||||
{
|
||||
var device = new Device("my-device", "My Device");
|
||||
|
||||
device.Key.Should().Be("my-device");
|
||||
device.Name.Should().Be("My Device");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_KeyWithDot_StillSetsKey()
|
||||
{
|
||||
// The dot triggers a debug log warning but must not prevent construction.
|
||||
var device = new Device("parent.child");
|
||||
|
||||
device.Key.Should().Be("parent.child");
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// ToString
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void ToString_WithName_FormatsKeyDashName()
|
||||
{
|
||||
var device = new Device("cam-01", "Front Camera");
|
||||
|
||||
device.ToString().Should().Be("cam-01 - Front Camera");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WithoutName_UsesDashPlaceholder()
|
||||
{
|
||||
var device = new Device("cam-01");
|
||||
|
||||
device.ToString().Should().Be("cam-01 - ---");
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// DefaultDevice
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void DefaultDevice_IsNotNull()
|
||||
{
|
||||
Device.DefaultDevice.Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultDevice_HasKeyDefault()
|
||||
{
|
||||
Device.DefaultDevice.Key.Should().Be("Default");
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// CustomActivate / Activate / Deactivate / Initialize
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void CustomActivate_DefaultReturnTrue()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
|
||||
device.CallCustomActivate().Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deactivate_DefaultReturnsTrue()
|
||||
{
|
||||
var device = new Device("d1");
|
||||
|
||||
device.Deactivate().Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Activate_CallsCustomActivate_AndReturnsItsResult()
|
||||
{
|
||||
var stub = new ActivateTrackingDevice("d1", result: false);
|
||||
|
||||
stub.Activate().Should().BeFalse();
|
||||
stub.CustomActivateCalled.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Activate_TrueWhenCustomActivateReturnsTrue()
|
||||
{
|
||||
var stub = new ActivateTrackingDevice("d1", result: true);
|
||||
|
||||
stub.Activate().Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Initialize_DoesNotThrow()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var act = () => device.CallInitialize();
|
||||
|
||||
act.Should().NotThrow();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// PreActivate
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void PreActivate_NoActions_DoesNotThrow()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var act = () => device.PreActivate();
|
||||
|
||||
act.Should().NotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PreActivate_RunsRegisteredActionsInOrder()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var order = new List<int>();
|
||||
|
||||
device.AddPreActivationAction(() => order.Add(1));
|
||||
device.AddPreActivationAction(() => order.Add(2));
|
||||
device.AddPreActivationAction(() => order.Add(3));
|
||||
|
||||
device.PreActivate();
|
||||
|
||||
order.Should().Equal(1, 2, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PreActivate_ContinuesAfterFaultingAction()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var reached = false;
|
||||
|
||||
device.AddPreActivationAction(() => throw new InvalidOperationException("boom"));
|
||||
device.AddPreActivationAction(() => reached = true);
|
||||
|
||||
var act = () => device.PreActivate();
|
||||
|
||||
act.Should().NotThrow("exceptions in individual actions must be caught internally");
|
||||
reached.Should().BeTrue("actions after a faulting action must still run");
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// PostActivate
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void PostActivate_NoActions_DoesNotThrow()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var act = () => device.PostActivate();
|
||||
|
||||
act.Should().NotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PostActivate_RunsRegisteredActionsInOrder()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var order = new List<int>();
|
||||
|
||||
device.AddPostActivationAction(() => order.Add(1));
|
||||
device.AddPostActivationAction(() => order.Add(2));
|
||||
|
||||
device.PostActivate();
|
||||
|
||||
order.Should().Equal(1, 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PostActivate_ContinuesAfterFaultingAction()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var reached = false;
|
||||
|
||||
device.AddPostActivationAction(() => throw new Exception("boom"));
|
||||
device.AddPostActivationAction(() => reached = true);
|
||||
|
||||
var act = () => device.PostActivate();
|
||||
|
||||
act.Should().NotThrow();
|
||||
reached.Should().BeTrue();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Pre and Post actions are independent lists
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void PreActivationActions_DoNotRunOnPostActivate()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var preRan = false;
|
||||
|
||||
device.AddPreActivationAction(() => preRan = true);
|
||||
device.PostActivate();
|
||||
|
||||
preRan.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PostActivationActions_DoNotRunOnPreActivate()
|
||||
{
|
||||
var device = new TestDevice("d1");
|
||||
var postRan = false;
|
||||
|
||||
device.AddPostActivationAction(() => postRan = true);
|
||||
device.PreActivate();
|
||||
|
||||
postRan.Should().BeFalse();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// OnFalse
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void OnFalse_FiresAction_WhenBoolIsFalse()
|
||||
{
|
||||
var device = new Device("d1");
|
||||
var fired = false;
|
||||
|
||||
device.OnFalse(false, () => fired = true);
|
||||
|
||||
fired.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnFalse_DoesNotFireAction_WhenBoolIsTrue()
|
||||
{
|
||||
var device = new Device("d1");
|
||||
var fired = false;
|
||||
|
||||
device.OnFalse(true, () => fired = true);
|
||||
|
||||
fired.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnFalse_DoesNotFireAction_ForNonBoolType()
|
||||
{
|
||||
var device = new Device("d1");
|
||||
var fired = false;
|
||||
|
||||
device.OnFalse("not a bool", () => fired = true);
|
||||
device.OnFalse(0, () => fired = true);
|
||||
device.OnFalse(null!, () => fired = true);
|
||||
|
||||
fired.Should().BeFalse();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Helpers
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Exposes protected Device members so test methods can call them directly.
|
||||
/// </summary>
|
||||
private class TestDevice : Device
|
||||
{
|
||||
public TestDevice(string key) : base(key) { }
|
||||
public TestDevice(string key, string name) : base(key, name) { }
|
||||
|
||||
public void AddPreActivationAction(Action act) => base.AddPreActivationAction(act);
|
||||
public void AddPostActivationAction(Action act) => base.AddPostActivationAction(act);
|
||||
public bool CallCustomActivate() => base.CustomActivate();
|
||||
public void CallInitialize() => base.Initialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records whether CustomActivate was invoked and returns a configured result.
|
||||
/// Used to verify Activate() correctly delegates to CustomActivate().
|
||||
/// </summary>
|
||||
private sealed class ActivateTrackingDevice : Device
|
||||
{
|
||||
private readonly bool _result;
|
||||
public bool CustomActivateCalled { get; private set; }
|
||||
|
||||
public ActivateTrackingDevice(string key, bool result = true) : base(key)
|
||||
{
|
||||
_result = result;
|
||||
}
|
||||
|
||||
protected override bool CustomActivate()
|
||||
{
|
||||
CustomActivateCalled = true;
|
||||
return _result;
|
||||
}
|
||||
}
|
||||
}
|
||||
38
src/PepperDash.Core.Tests/Fakes/CrestronConsoleFakes.cs
Normal file
38
src/PepperDash.Core.Tests/Fakes/CrestronConsoleFakes.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using PepperDash.Core.Abstractions;
|
||||
|
||||
namespace PepperDash.Core.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// No-op ICrestronConsole that captures output for test assertions.
|
||||
/// </summary>
|
||||
public class CapturingCrestronConsole : ICrestronConsole
|
||||
{
|
||||
public List<string> Lines { get; } = new();
|
||||
public List<string> CommandResponses { get; } = new();
|
||||
public List<(string Command, string HelpText)> RegisteredCommands { get; } = new();
|
||||
|
||||
public void PrintLine(string message) => Lines.Add(message);
|
||||
public void Print(string message) => Lines.Add(message);
|
||||
public void ConsoleCommandResponse(string message) => CommandResponses.Add(message);
|
||||
|
||||
public void AddNewConsoleCommand(
|
||||
Action<string> callback,
|
||||
string command,
|
||||
string helpText,
|
||||
ConsoleAccessLevel accessLevel)
|
||||
{
|
||||
RegisteredCommands.Add((command, helpText));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimal no-op ICrestronConsole that discards all output. Useful when you only
|
||||
/// care about the system under test and not what it logs.
|
||||
/// </summary>
|
||||
public class NoOpCrestronConsole : ICrestronConsole
|
||||
{
|
||||
public void PrintLine(string message) { }
|
||||
public void Print(string message) { }
|
||||
public void ConsoleCommandResponse(string message) { }
|
||||
public void AddNewConsoleCommand(Action<string> _, string __, string ___, ConsoleAccessLevel ____) { }
|
||||
}
|
||||
49
src/PepperDash.Core.Tests/Fakes/CrestronEnvironmentFakes.cs
Normal file
49
src/PepperDash.Core.Tests/Fakes/CrestronEnvironmentFakes.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using PepperDash.Core.Abstractions;
|
||||
|
||||
namespace PepperDash.Core.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// Configurable ICrestronEnvironment for unit tests.
|
||||
/// Defaults: Appliance / SimplSharpPro / ApplicationNumber=1.
|
||||
/// </summary>
|
||||
public class FakeCrestronEnvironment : ICrestronEnvironment
|
||||
{
|
||||
public DevicePlatform DevicePlatform { get; set; } = DevicePlatform.Appliance;
|
||||
public RuntimeEnvironment RuntimeEnvironment { get; set; } = RuntimeEnvironment.SimplSharpPro;
|
||||
public string NewLine { get; set; } = "\r\n";
|
||||
public uint ApplicationNumber { get; set; } = 1;
|
||||
public uint RoomId { get; set; } = 0;
|
||||
|
||||
public event EventHandler<ProgramStatusEventArgs>? ProgramStatusChanged;
|
||||
public event EventHandler<PepperDashEthernetEventArgs>? EthernetEventReceived;
|
||||
|
||||
public string GetApplicationRootDirectory() => System.IO.Path.GetTempPath();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool IsHardwareRuntime => false;
|
||||
|
||||
/// <summary>Simulates a program status event for tests.</summary>
|
||||
public void RaiseProgramStatus(ProgramStatusEventType type) =>
|
||||
ProgramStatusChanged?.Invoke(this, new ProgramStatusEventArgs(type));
|
||||
|
||||
/// <summary>Simulates an ethernet event for tests.</summary>
|
||||
public void RaiseEthernetEvent(EthernetEventType type, short adapter = 0) =>
|
||||
EthernetEventReceived?.Invoke(this, new PepperDashEthernetEventArgs(type, adapter));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No-op IEthernetHelper that returns configurable values.
|
||||
/// </summary>
|
||||
public class FakeEthernetHelper : IEthernetHelper
|
||||
{
|
||||
private readonly Dictionary<EthernetParameterType, string> _values = new();
|
||||
|
||||
public FakeEthernetHelper Seed(EthernetParameterType param, string value)
|
||||
{
|
||||
_values[param] = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public string GetEthernetParameter(EthernetParameterType parameter, short ethernetAdapterId) =>
|
||||
_values.TryGetValue(parameter, out var v) ? v : string.Empty;
|
||||
}
|
||||
59
src/PepperDash.Core.Tests/Fakes/InMemoryCrestronDataStore.cs
Normal file
59
src/PepperDash.Core.Tests/Fakes/InMemoryCrestronDataStore.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using PepperDash.Core.Abstractions;
|
||||
|
||||
namespace PepperDash.Core.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// In-memory ICrestronDataStore backed by a dictionary.
|
||||
/// Use in unit tests to verify that keys are read from and written to the store correctly.
|
||||
/// </summary>
|
||||
public class InMemoryCrestronDataStore : ICrestronDataStore
|
||||
{
|
||||
private readonly Dictionary<string, object> _store = new();
|
||||
|
||||
public bool Initialized { get; private set; }
|
||||
|
||||
public void InitStore() => Initialized = true;
|
||||
|
||||
public bool TryGetLocalInt(string key, out int value)
|
||||
{
|
||||
if (_store.TryGetValue(key, out var raw) && raw is int i)
|
||||
{
|
||||
value = i;
|
||||
return true;
|
||||
}
|
||||
value = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool SetLocalInt(string key, int value)
|
||||
{
|
||||
_store[key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool SetLocalUint(string key, uint value)
|
||||
{
|
||||
_store[key] = (int)value;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryGetLocalBool(string key, out bool value)
|
||||
{
|
||||
if (_store.TryGetValue(key, out var raw) && raw is bool b)
|
||||
{
|
||||
value = b;
|
||||
return true;
|
||||
}
|
||||
value = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool SetLocalBool(string key, bool value)
|
||||
{
|
||||
_store[key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Seeds a key for testing read paths.</summary>
|
||||
public void Seed(string key, object value) => _store[key] = value;
|
||||
}
|
||||
171
src/PepperDash.Core.Tests/Logging/DebugServiceTests.cs
Normal file
171
src/PepperDash.Core.Tests/Logging/DebugServiceTests.cs
Normal file
@@ -0,0 +1,171 @@
|
||||
using FluentAssertions;
|
||||
using PepperDash.Core.Abstractions;
|
||||
using PepperDash.Core.Tests.Fakes;
|
||||
using Xunit;
|
||||
|
||||
namespace PepperDash.Core.Tests.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for Debug-related service interfaces and implementations.
|
||||
/// These tests verify the behaviour of the abstractions in isolation (no Crestron SDK required).
|
||||
/// </summary>
|
||||
public class DebugServiceTests
|
||||
{
|
||||
// -----------------------------------------------------------------------
|
||||
// ICrestronDataStore — InMemoryCrestronDataStore
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void DataStore_InitStore_SetsInitializedFlag()
|
||||
{
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
store.Initialized.Should().BeFalse("not yet initialized");
|
||||
|
||||
store.InitStore();
|
||||
|
||||
store.Initialized.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DataStore_SetAndGetLocalInt_RoundTrips()
|
||||
{
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
|
||||
store.SetLocalInt("MyKey", 42).Should().BeTrue();
|
||||
store.TryGetLocalInt("MyKey", out var value).Should().BeTrue();
|
||||
value.Should().Be(42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DataStore_TryGetLocalInt_ReturnsFalse_WhenKeyAbsent()
|
||||
{
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
|
||||
store.TryGetLocalInt("Missing", out var value).Should().BeFalse();
|
||||
value.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DataStore_SetAndGetLocalBool_RoundTrips()
|
||||
{
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
|
||||
store.SetLocalBool("FlagKey", true).Should().BeTrue();
|
||||
store.TryGetLocalBool("FlagKey", out var value).Should().BeTrue();
|
||||
value.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DataStore_TryGetLocalBool_ReturnsFalse_WhenKeyAbsent()
|
||||
{
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
|
||||
store.TryGetLocalBool("Missing", out var value).Should().BeFalse();
|
||||
value.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DataStore_SetLocalUint_CanBeReadBackAsInt()
|
||||
{
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
|
||||
store.SetLocalUint("UintKey", 3u).Should().BeTrue();
|
||||
store.TryGetLocalInt("UintKey", out var value).Should().BeTrue();
|
||||
value.Should().Be(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DataStore_Seed_AllowsTestSetupOfReadPaths()
|
||||
{
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
store.Seed("MyLevel", 2);
|
||||
|
||||
store.TryGetLocalInt("MyLevel", out var level).Should().BeTrue();
|
||||
level.Should().Be(2);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// DebugServiceRegistration
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void ServiceRegistration_Register_StoresAllThreeServices()
|
||||
{
|
||||
var env = new FakeCrestronEnvironment();
|
||||
var console = new NoOpCrestronConsole();
|
||||
var store = new InMemoryCrestronDataStore();
|
||||
|
||||
DebugServiceRegistration.Register(env, console, store);
|
||||
|
||||
DebugServiceRegistration.Environment.Should().BeSameAs(env);
|
||||
DebugServiceRegistration.Console.Should().BeSameAs(console);
|
||||
DebugServiceRegistration.DataStore.Should().BeSameAs(store);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ServiceRegistration_Register_AcceptsNullsWithoutThrowing()
|
||||
{
|
||||
var act = () => DebugServiceRegistration.Register(null, null, null);
|
||||
act.Should().NotThrow();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// ICrestronEnvironment — FakeCrestronEnvironment
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void FakeEnvironment_DefaultsToAppliance()
|
||||
{
|
||||
var env = new FakeCrestronEnvironment();
|
||||
env.DevicePlatform.Should().Be(DevicePlatform.Appliance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FakeEnvironment_RaiseProgramStatus_FiresEvent()
|
||||
{
|
||||
var env = new FakeCrestronEnvironment();
|
||||
ProgramStatusEventType? received = null;
|
||||
env.ProgramStatusChanged += (_, e) => received = e.EventType;
|
||||
|
||||
env.RaiseProgramStatus(ProgramStatusEventType.Stopping);
|
||||
|
||||
received.Should().Be(ProgramStatusEventType.Stopping);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FakeEnvironment_RaiseEthernetEvent_FiresEvent()
|
||||
{
|
||||
var env = new FakeCrestronEnvironment();
|
||||
EthernetEventType? received = null;
|
||||
env.EthernetEventReceived += (_, e) => received = e.EthernetEventType;
|
||||
|
||||
env.RaiseEthernetEvent(EthernetEventType.LinkUp, adapter: 0);
|
||||
|
||||
received.Should().Be(EthernetEventType.LinkUp);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// ICrestronConsole — CapturingCrestronConsole
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void CapturingConsole_PrintLine_CapturesMessage()
|
||||
{
|
||||
var console = new CapturingCrestronConsole();
|
||||
|
||||
console.PrintLine("hello world");
|
||||
|
||||
console.Lines.Should().ContainSingle().Which.Should().Be("hello world");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CapturingConsole_AddNewConsoleCommand_RecordsCommandName()
|
||||
{
|
||||
var console = new CapturingCrestronConsole();
|
||||
|
||||
console.AddNewConsoleCommand(_ => { }, "appdebug", "Sets debug level", ConsoleAccessLevel.AccessOperator);
|
||||
|
||||
console.RegisteredCommands.Should().ContainSingle()
|
||||
.Which.Command.Should().Be("appdebug");
|
||||
}
|
||||
}
|
||||
30
src/PepperDash.Core.Tests/PepperDash.Core.Tests.csproj
Normal file
30
src/PepperDash.Core.Tests/PepperDash.Core.Tests.csproj
Normal file
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<IsPackable>false</IsPackable>
|
||||
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="7.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Reference the Abstractions project only — no Crestron SDK dependency -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PepperDash.Core.Abstractions\PepperDash.Core.Abstractions.csproj" />
|
||||
<!-- PepperDash.Core is referenced so we can test Device and other concrete types.
|
||||
DebugServiceRegistration.Register() is called via a [ModuleInitializer] before any
|
||||
test runs, so Debug's static constructor uses fakes and never touches the Crestron SDK. -->
|
||||
<ProjectReference Include="..\PepperDash.Core\PepperDash.Core.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
29
src/PepperDash.Core.Tests/TestInitializer.cs
Normal file
29
src/PepperDash.Core.Tests/TestInitializer.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using PepperDash.Core.Abstractions;
|
||||
using PepperDash.Core.Tests.Fakes;
|
||||
|
||||
namespace PepperDash.Core.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Runs once before any type in this assembly is accessed.
|
||||
/// Registers fake Crestron service implementations with <see cref="DebugServiceRegistration"/>
|
||||
/// so that the <c>Debug</c> static constructor uses them instead of the real Crestron SDK.
|
||||
/// This must remain a module initializer (not a test fixture) because the static constructor
|
||||
/// fires the first time <em>any</em> type in PepperDash.Core is referenced — before xUnit
|
||||
/// has a chance to run fixture setup code.
|
||||
/// </summary>
|
||||
internal static class TestInitializer
|
||||
{
|
||||
[ModuleInitializer]
|
||||
internal static void Initialize()
|
||||
{
|
||||
DebugServiceRegistration.Register(
|
||||
new FakeCrestronEnvironment
|
||||
{
|
||||
DevicePlatform = DevicePlatform.Server, // avoids any appliance-only code paths
|
||||
RuntimeEnvironment = RuntimeEnvironment.Other, // skips console command registration
|
||||
},
|
||||
new NoOpCrestronConsole(),
|
||||
new InMemoryCrestronDataStore());
|
||||
}
|
||||
}
|
||||
35
src/PepperDash.Core/Adapters/CrestronConsoleAdapter.cs
Normal file
35
src/PepperDash.Core/Adapters/CrestronConsoleAdapter.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using Crestron.SimplSharp;
|
||||
using PdCore = PepperDash.Core.Abstractions;
|
||||
|
||||
namespace PepperDash.Core.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production adapter — delegates ICrestronConsole calls to the real Crestron SDK.
|
||||
/// </summary>
|
||||
public sealed class CrestronConsoleAdapter : PdCore.ICrestronConsole
|
||||
{
|
||||
public void PrintLine(string message) => CrestronConsole.PrintLine(message);
|
||||
|
||||
public void Print(string message) => CrestronConsole.Print(message);
|
||||
|
||||
public void ConsoleCommandResponse(string message) =>
|
||||
CrestronConsole.ConsoleCommandResponse(message);
|
||||
|
||||
public void AddNewConsoleCommand(
|
||||
Action<string> callback,
|
||||
string command,
|
||||
string helpText,
|
||||
PdCore.ConsoleAccessLevel accessLevel)
|
||||
{
|
||||
var crestronLevel = accessLevel switch
|
||||
{
|
||||
PdCore.ConsoleAccessLevel.AccessAdministrator => ConsoleAccessLevelEnum.AccessAdministrator,
|
||||
PdCore.ConsoleAccessLevel.AccessProgrammer => ConsoleAccessLevelEnum.AccessProgrammer,
|
||||
_ => ConsoleAccessLevelEnum.AccessOperator,
|
||||
};
|
||||
|
||||
// Wrap Action<string> in a lambda — Crestron's delegate is not a standard Action<string>.
|
||||
CrestronConsole.AddNewConsoleCommand(s => callback(s), command, helpText, crestronLevel);
|
||||
}
|
||||
}
|
||||
42
src/PepperDash.Core/Adapters/CrestronDataStoreAdapter.cs
Normal file
42
src/PepperDash.Core/Adapters/CrestronDataStoreAdapter.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using Crestron.SimplSharp.CrestronDataStore;
|
||||
using PepperDash.Core.Abstractions;
|
||||
|
||||
namespace PepperDash.Core.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production adapter — delegates ICrestronDataStore calls to the real Crestron SDK.
|
||||
/// </summary>
|
||||
public sealed class CrestronDataStoreAdapter : ICrestronDataStore
|
||||
{
|
||||
public void InitStore() => CrestronDataStoreStatic.InitCrestronDataStore();
|
||||
|
||||
public bool TryGetLocalInt(string key, out int value)
|
||||
{
|
||||
var err = CrestronDataStoreStatic.GetLocalIntValue(key, out value);
|
||||
return err == CrestronDataStore.CDS_ERROR.CDS_SUCCESS;
|
||||
}
|
||||
|
||||
public bool SetLocalInt(string key, int value)
|
||||
{
|
||||
var err = CrestronDataStoreStatic.SetLocalIntValue(key, value);
|
||||
return err == CrestronDataStore.CDS_ERROR.CDS_SUCCESS;
|
||||
}
|
||||
|
||||
public bool SetLocalUint(string key, uint value)
|
||||
{
|
||||
var err = CrestronDataStoreStatic.SetLocalUintValue(key, value);
|
||||
return err == CrestronDataStore.CDS_ERROR.CDS_SUCCESS;
|
||||
}
|
||||
|
||||
public bool TryGetLocalBool(string key, out bool value)
|
||||
{
|
||||
var err = CrestronDataStoreStatic.GetLocalBoolValue(key, out value);
|
||||
return err == CrestronDataStore.CDS_ERROR.CDS_SUCCESS;
|
||||
}
|
||||
|
||||
public bool SetLocalBool(string key, bool value)
|
||||
{
|
||||
var err = CrestronDataStoreStatic.SetLocalBoolValue(key, value);
|
||||
return err == CrestronDataStore.CDS_ERROR.CDS_SUCCESS;
|
||||
}
|
||||
}
|
||||
71
src/PepperDash.Core/Adapters/CrestronEnvironmentAdapter.cs
Normal file
71
src/PepperDash.Core/Adapters/CrestronEnvironmentAdapter.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using Crestron.SimplSharp;
|
||||
using PdCore = PepperDash.Core.Abstractions;
|
||||
|
||||
namespace PepperDash.Core.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production adapter — delegates ICrestronEnvironment calls to the real Crestron SDK.
|
||||
/// </summary>
|
||||
public sealed class CrestronEnvironmentAdapter : PdCore.ICrestronEnvironment
|
||||
{
|
||||
// Subscribe once in constructor and re-raise as our event types.
|
||||
private event EventHandler<PdCore.ProgramStatusEventArgs>? _programStatusChanged;
|
||||
private event EventHandler<PdCore.PepperDashEthernetEventArgs>? _ethernetEventReceived;
|
||||
|
||||
public CrestronEnvironmentAdapter()
|
||||
{
|
||||
CrestronEnvironment.ProgramStatusEventHandler += type =>
|
||||
_programStatusChanged?.Invoke(this, new PdCore.ProgramStatusEventArgs(MapProgramStatus(type)));
|
||||
|
||||
CrestronEnvironment.EthernetEventHandler += args =>
|
||||
_ethernetEventReceived?.Invoke(this, new PdCore.PepperDashEthernetEventArgs(
|
||||
args.EthernetEventType == eEthernetEventType.LinkDown
|
||||
? PdCore.EthernetEventType.LinkDown
|
||||
: PdCore.EthernetEventType.LinkUp,
|
||||
(short)args.EthernetAdapter));
|
||||
}
|
||||
|
||||
public PdCore.DevicePlatform DevicePlatform =>
|
||||
CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
|
||||
? PdCore.DevicePlatform.Appliance
|
||||
: PdCore.DevicePlatform.Server;
|
||||
|
||||
public PdCore.RuntimeEnvironment RuntimeEnvironment =>
|
||||
CrestronEnvironment.RuntimeEnvironment == eRuntimeEnvironment.SimplSharpPro
|
||||
? PdCore.RuntimeEnvironment.SimplSharpPro
|
||||
: PdCore.RuntimeEnvironment.Other;
|
||||
|
||||
public string NewLine => CrestronEnvironment.NewLine;
|
||||
|
||||
public uint ApplicationNumber => InitialParametersClass.ApplicationNumber;
|
||||
|
||||
public uint RoomId => uint.TryParse(InitialParametersClass.RoomId, out var r) ? r : 0;
|
||||
|
||||
public event EventHandler<PdCore.ProgramStatusEventArgs> ProgramStatusChanged
|
||||
{
|
||||
add => _programStatusChanged += value;
|
||||
remove => _programStatusChanged -= value;
|
||||
}
|
||||
|
||||
public event EventHandler<PdCore.PepperDashEthernetEventArgs> EthernetEventReceived
|
||||
{
|
||||
add => _ethernetEventReceived += value;
|
||||
remove => _ethernetEventReceived -= value;
|
||||
}
|
||||
|
||||
public string GetApplicationRootDirectory() =>
|
||||
Crestron.SimplSharp.CrestronIO.Directory.GetApplicationRootDirectory();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool IsHardwareRuntime => true;
|
||||
|
||||
private static PdCore.ProgramStatusEventType MapProgramStatus(eProgramStatusEventType type) =>
|
||||
type switch
|
||||
{
|
||||
eProgramStatusEventType.Stopping => PdCore.ProgramStatusEventType.Stopping,
|
||||
eProgramStatusEventType.Paused => PdCore.ProgramStatusEventType.Paused,
|
||||
eProgramStatusEventType.Resumed => PdCore.ProgramStatusEventType.Resumed,
|
||||
_ => PdCore.ProgramStatusEventType.Starting,
|
||||
};
|
||||
}
|
||||
39
src/PepperDash.Core/Adapters/CrestronEthernetAdapter.cs
Normal file
39
src/PepperDash.Core/Adapters/CrestronEthernetAdapter.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using Crestron.SimplSharp;
|
||||
using PepperDash.Core.Abstractions;
|
||||
|
||||
namespace PepperDash.Core.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production adapter — delegates IEthernetHelper calls to the real Crestron SDK.
|
||||
/// </summary>
|
||||
public sealed class CrestronEthernetAdapter : IEthernetHelper
|
||||
{
|
||||
public string GetEthernetParameter(EthernetParameterType parameter, short ethernetAdapterId)
|
||||
{
|
||||
var crestronParam = parameter switch
|
||||
{
|
||||
EthernetParameterType.GetCurrentIpAddress =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
|
||||
EthernetParameterType.GetHostname =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME,
|
||||
EthernetParameterType.GetDomainName =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME,
|
||||
EthernetParameterType.GetLinkStatus =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_LINK_STATUS,
|
||||
EthernetParameterType.GetCurrentDhcpState =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE,
|
||||
EthernetParameterType.GetCurrentIpMask =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK,
|
||||
EthernetParameterType.GetCurrentRouter =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER,
|
||||
EthernetParameterType.GetMacAddress =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS,
|
||||
EthernetParameterType.GetDnsServer =>
|
||||
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DNS_SERVER,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(parameter), parameter, null),
|
||||
};
|
||||
|
||||
return CrestronEthernetHelper.GetEthernetParameter(crestronParam, ethernetAdapterId);
|
||||
}
|
||||
}
|
||||
@@ -84,10 +84,9 @@ namespace PepperDash.Core;
|
||||
port.TextReceived += Port_TextReceivedStringDelimiter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnects this gather from the Port's TextReceived event. This will not fire LineReceived
|
||||
/// after the this call.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Stop method
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
Port.TextReceived -= Port_TextReceived;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
using System.Timers;
|
||||
using PepperDash.Core;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
@@ -20,7 +20,7 @@ public class CommunicationStreamDebugging
|
||||
/// <summary>
|
||||
/// Timer to disable automatically if not manually disabled
|
||||
/// </summary>
|
||||
private CTimer DebugExpiryPeriod;
|
||||
private Timer DebugExpiryPeriod;
|
||||
|
||||
/// <summary>
|
||||
/// The current debug setting
|
||||
@@ -93,7 +93,9 @@ public class CommunicationStreamDebugging
|
||||
|
||||
StopDebugTimer();
|
||||
|
||||
DebugExpiryPeriod = new CTimer((o) => DisableDebugging(), _DebugTimeoutInMs);
|
||||
DebugExpiryPeriod = new Timer(_DebugTimeoutInMs) { AutoReset = false };
|
||||
DebugExpiryPeriod.Elapsed += (s, e) => DisableDebugging();
|
||||
DebugExpiryPeriod.Start();
|
||||
|
||||
if ((setting & eStreamDebuggingSetting.Rx) == eStreamDebuggingSetting.Rx)
|
||||
RxStreamDebuggingIsEnabled = true;
|
||||
@@ -155,22 +157,3 @@ public enum eStreamDebuggingSetting
|
||||
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,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using JsonConverter = NewtonsoftJson::Newtonsoft.Json.JsonConverterAttribute;
|
||||
using JsonIgnore = NewtonsoftJson::Newtonsoft.Json.JsonIgnoreAttribute;
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
using NullValueHandling = NewtonsoftJson::Newtonsoft.Json.NullValueHandling;
|
||||
using StringEnumConverter = NewtonsoftJson::Newtonsoft.Json.Converters.StringEnumConverter;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
|
||||
@@ -27,25 +27,25 @@ public delegate void GenericSocketStatusChangeEventDelegate(ISocketStatus client
|
||||
/// <summary>
|
||||
/// EventArgs class for socket status changes
|
||||
/// </summary>
|
||||
public class GenericSocketStatusChageEventArgs : EventArgs
|
||||
{
|
||||
public class GenericSocketStatusChageEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the Client
|
||||
/// </summary>
|
||||
public ISocketStatus Client { get; private set; }
|
||||
public ISocketStatus Client { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
public GenericSocketStatusChageEventArgs(ISocketStatus client)
|
||||
{
|
||||
Client = client;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericSocketStatusChageEventArgs() { }
|
||||
public GenericSocketStatusChageEventArgs(ISocketStatus client)
|
||||
{
|
||||
Client = client;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericSocketStatusChageEventArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -60,22 +60,22 @@ public delegate void GenericTcpServerStateChangedEventDelegate(ServerState state
|
||||
public class GenericTcpServerStateChangedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the State
|
||||
/// </summary>
|
||||
public ServerState State { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
public GenericTcpServerStateChangedEventArgs(ServerState state)
|
||||
{
|
||||
State = state;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerStateChangedEventArgs() { }
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerStateChangedEventArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -91,20 +91,22 @@ public delegate void GenericTcpServerSocketStatusChangeEventDelegate(object sock
|
||||
public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the Socket
|
||||
/// </summary>
|
||||
public object Socket { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the index of the client from which the status change was received
|
||||
/// </summary>
|
||||
public uint ReceivedFromClientIndex { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the ClientStatus
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <param name="clientStatus"></param>
|
||||
@@ -115,7 +117,7 @@ public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <param name="clientIndex"></param>
|
||||
@@ -126,10 +128,10 @@ public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs
|
||||
ReceivedFromClientIndex = clientIndex;
|
||||
ClientStatus = clientStatus;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerSocketStatusChangeEventArgs() { }
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerSocketStatusChangeEventArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -138,28 +140,28 @@ public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs
|
||||
public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the index of the client from which the text was received
|
||||
/// </summary>
|
||||
public uint ReceivedFromClientIndex { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets the index of the client from which the text was received as a ushort
|
||||
/// </summary>
|
||||
public ushort ReceivedFromClientIndexShort
|
||||
{
|
||||
get
|
||||
{
|
||||
return (ushort)ReceivedFromClientIndex;
|
||||
}
|
||||
}
|
||||
public ushort ReceivedFromClientIndexShort
|
||||
{
|
||||
get
|
||||
{
|
||||
return (ushort)ReceivedFromClientIndex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the Text
|
||||
/// </summary>
|
||||
public string Text { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs(string text)
|
||||
@@ -168,7 +170,7 @@ public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <param name="clientIndex"></param>
|
||||
@@ -177,10 +179,10 @@ public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs
|
||||
Text = text;
|
||||
ReceivedFromClientIndex = clientIndex;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs() { }
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerCommMethodReceiveTextArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -189,22 +191,23 @@ public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs
|
||||
public class GenericTcpServerClientReadyForcommunicationsEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets IsReady
|
||||
/// </summary>
|
||||
public bool IsReady;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="isReady"></param>
|
||||
public GenericTcpServerClientReadyForcommunicationsEventArgs(bool isReady)
|
||||
{
|
||||
IsReady = isReady;
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -213,11 +216,12 @@ public class GenericTcpServerClientReadyForcommunicationsEventArgs : EventArgs
|
||||
public class GenericUdpConnectedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the UConnected
|
||||
/// </summary>
|
||||
public ushort UConnected;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Gets or sets the Connected status
|
||||
/// </summary>
|
||||
public bool Connected;
|
||||
|
||||
@@ -227,7 +231,7 @@ public class GenericUdpConnectedEventArgs : EventArgs
|
||||
public GenericUdpConnectedEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="uconnected"></param>
|
||||
public GenericUdpConnectedEventArgs(ushort uconnected)
|
||||
@@ -236,7 +240,7 @@ public class GenericUdpConnectedEventArgs : EventArgs
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="connected"></param>
|
||||
public GenericUdpConnectedEventArgs(bool connected)
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Timers;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using PepperDash.Core.Logging;
|
||||
@@ -181,7 +182,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
|
||||
// private Timer for auto reconnect
|
||||
private CTimer RetryTimer;
|
||||
private Timer RetryTimer;
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -264,12 +265,12 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
/// </summary>
|
||||
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatInterval = (value * 1000); } }
|
||||
|
||||
CTimer HeartbeatSendTimer;
|
||||
CTimer HeartbeatAckTimer;
|
||||
Timer HeartbeatSendTimer;
|
||||
Timer HeartbeatAckTimer;
|
||||
|
||||
// Used to force disconnection on a dead connect attempt
|
||||
CTimer ConnectFailTimer;
|
||||
CTimer WaitForSharedKey;
|
||||
Timer ConnectFailTimer;
|
||||
Timer WaitForSharedKey;
|
||||
private int ConnectionCount;
|
||||
|
||||
bool ProgramIsStopping;
|
||||
@@ -277,7 +278,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
/// <summary>
|
||||
/// Queue lock
|
||||
/// </summary>
|
||||
CCriticalSection DequeueLock = new CCriticalSection();
|
||||
private readonly object _dequeueLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Receive Queue size. Defaults to 20. Will set to 20 if QueueSize property is less than 20. Use constructor or set queue size property before
|
||||
@@ -357,7 +358,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
{
|
||||
if (config == null)
|
||||
{
|
||||
Debug.Console(0, this, "Could not initialize client with key: {0}", Key);
|
||||
this.LogWarning( "Could not initialize client with key: {0}", Key);
|
||||
return;
|
||||
}
|
||||
try
|
||||
@@ -397,7 +398,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, "Exception initializing client with key: {0}\rException: {1}", Key, ex);
|
||||
this.LogError("Exception initializing client with key: {0}\rException: {1}", Key, ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,7 +411,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping || programEventType == eProgramStatusEventType.Paused)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Program stopping. Closing _client connection");
|
||||
this.LogInformation("Program stopping. Closing _client connection");
|
||||
ProgramIsStopping = true;
|
||||
Disconnect();
|
||||
}
|
||||
@@ -437,17 +438,17 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
public void Connect()
|
||||
{
|
||||
ConnectionCount++;
|
||||
Debug.Console(2, this, "Attempting connect Count:{0}", ConnectionCount);
|
||||
this.LogVerbose("Attempting connect Count:{0}", ConnectionCount);
|
||||
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already connected. Ignoring.");
|
||||
this.LogInformation("Already connected. Ignoring.");
|
||||
return;
|
||||
}
|
||||
if (IsTryingToConnect)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already trying to connect. Ignoring.");
|
||||
this.LogInformation("Already trying to connect. Ignoring.");
|
||||
return;
|
||||
}
|
||||
try
|
||||
@@ -460,17 +461,17 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No address set");
|
||||
this.LogWarning("DynamicTcpClient: No address set");
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: Invalid port");
|
||||
this.LogWarning("DynamicTcpClient: Invalid port");
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No Shared Key set");
|
||||
this.LogWarning("DynamicTcpClient: No Shared Key set");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -491,9 +492,10 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
|
||||
//var timeOfConnect = DateTime.Now.ToString("HH:mm:ss.fff");
|
||||
|
||||
ConnectFailTimer = new CTimer(o =>
|
||||
ConnectFailTimer = new Timer(30000) { AutoReset = false };
|
||||
ConnectFailTimer.Elapsed += (s, e) =>
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Connect attempt has not finished after 30sec Count:{0}", ConnectionCount);
|
||||
this.LogError("Connect attempt has not finished after 30sec Count:{0}", ConnectionCount);
|
||||
if (IsTryingToConnect)
|
||||
{
|
||||
IsTryingToConnect = false;
|
||||
@@ -505,12 +507,13 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
//SecureClient.DisconnectFromServer();
|
||||
//CheckClosedAndTryReconnect();
|
||||
}
|
||||
}, 30000);
|
||||
};
|
||||
ConnectFailTimer.Start();
|
||||
|
||||
Debug.Console(2, this, "Making Connection Count:{0}", ConnectionCount);
|
||||
this.LogVerbose("Making Connection Count:{0}", ConnectionCount);
|
||||
_client.ConnectToServerAsync(o =>
|
||||
{
|
||||
Debug.Console(2, this, "ConnectToServerAsync Count:{0} Ran!", ConnectionCount);
|
||||
this.LogVerbose("ConnectToServerAsync Count:{0} Ran!", ConnectionCount);
|
||||
|
||||
if (ConnectFailTimer != null)
|
||||
{
|
||||
@@ -520,22 +523,22 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
|
||||
if (o.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(2, this, "_client connected to {0} on port {1}", o.AddressClientConnectedTo, o.LocalPortNumberOfClient);
|
||||
this.LogVerbose("_client connected to {0} on port {1}", o.AddressClientConnectedTo, o.LocalPortNumberOfClient);
|
||||
o.ReceiveDataAsync(Receive);
|
||||
|
||||
if (SharedKeyRequired)
|
||||
{
|
||||
WaitingForSharedKeyResponse = true;
|
||||
WaitForSharedKey = new CTimer(timer =>
|
||||
WaitForSharedKey = new Timer(15000) { AutoReset = false };
|
||||
WaitForSharedKey.Elapsed += (s, e) =>
|
||||
{
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Shared key exchange timer expired. IsReadyForCommunication={0}", IsReadyForCommunication);
|
||||
// Debug.Console(1, this, "Connect attempt failed {0}", c.ClientStatus);
|
||||
this.LogWarning("Shared key exchange timer expired. IsReadyForCommunication={0}", IsReadyForCommunication);
|
||||
// This is the only case where we should call DisconectFromServer...Event handeler will trigger the cleanup
|
||||
o.DisconnectFromServer();
|
||||
//CheckClosedAndTryReconnect();
|
||||
//OnClientReadyForcommunications(false); // Should send false event
|
||||
}, 15000);
|
||||
};
|
||||
WaitForSharedKey.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -549,14 +552,14 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Connect attempt failed {0}", o.ClientStatus);
|
||||
this.LogWarning("Connect attempt failed {0}", o.ClientStatus);
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "_client connection exception: {0}", ex.Message);
|
||||
this.LogError("_client connection exception: {0}", ex.Message);
|
||||
IsTryingToConnect = false;
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
@@ -592,14 +595,14 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
{
|
||||
if (_client == null) return;
|
||||
|
||||
Debug.Console(1, this, "Disconnecting client");
|
||||
this.LogInformation("Disconnecting client");
|
||||
if (IsConnected)
|
||||
_client.DisconnectFromServer();
|
||||
|
||||
// close up client. ALWAYS use this when disconnecting.
|
||||
IsTryingToConnect = false;
|
||||
|
||||
Debug.Console(2, this, "Disconnecting _client {0}", DisconnectCalledByUser ? ", Called by user" : "");
|
||||
this.LogVerbose("Disconnecting _client {0}", DisconnectCalledByUser ? ", Called by user" : "");
|
||||
_client.SocketStatusChange -= Client_SocketStatusChange;
|
||||
_client.Dispose();
|
||||
_client = null;
|
||||
@@ -620,14 +623,14 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
{
|
||||
if (_client != null)
|
||||
{
|
||||
Debug.Console(2, this, "Cleaning up remotely closed/failed connection.");
|
||||
this.LogVerbose("Cleaning up remotely closed/failed connection.");
|
||||
Disconnect();
|
||||
}
|
||||
if (!DisconnectCalledByUser && AutoReconnect)
|
||||
{
|
||||
var halfInterval = AutoReconnectIntervalMs / 2;
|
||||
var rndTime = new Random().Next(-halfInterval, halfInterval) + AutoReconnectIntervalMs;
|
||||
Debug.Console(2, this, "Attempting reconnect in {0} ms, randomized", rndTime);
|
||||
this.LogVerbose("Attempting reconnect in {0} ms, randomized", rndTime);
|
||||
if (RetryTimer != null)
|
||||
{
|
||||
RetryTimer.Stop();
|
||||
@@ -635,7 +638,9 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
if (AutoReconnectTriggered != null)
|
||||
AutoReconnectTriggered(this, new EventArgs());
|
||||
RetryTimer = new CTimer(o => Connect(), rndTime);
|
||||
RetryTimer = new Timer(rndTime) { AutoReset = false };
|
||||
RetryTimer.Elapsed += (s, e) => Connect();
|
||||
RetryTimer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -654,13 +659,13 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
{
|
||||
var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray();
|
||||
str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
||||
Debug.Console(2, this, "_client Received:\r--------\r{0}\r--------", str);
|
||||
this.LogVerbose("_client Received:\r--------\r{0}\r--------", str);
|
||||
if (!string.IsNullOrEmpty(checkHeartbeat(str)))
|
||||
{
|
||||
|
||||
if (SharedKeyRequired && str == "SharedKey:")
|
||||
{
|
||||
Debug.Console(2, this, "Server asking for shared key, sending");
|
||||
this.LogVerbose("Server asking for shared key, sending");
|
||||
SendText(SharedKey + "\n");
|
||||
}
|
||||
else if (SharedKeyRequired && str == "Shared Key Match")
|
||||
@@ -668,7 +673,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
StopWaitForSharedKeyTimer();
|
||||
|
||||
|
||||
Debug.Console(2, this, "Shared key confirmed. Ready for communication");
|
||||
this.LogVerbose("Shared key confirmed. Ready for communication");
|
||||
OnClientReadyForcommunications(true); // Successful key exchange
|
||||
}
|
||||
else
|
||||
@@ -688,7 +693,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error receiving data: {1}. Error: {0}", ex.Message, str);
|
||||
this.LogError("Error receiving data: {1}. Error: {0}", str, ex.Message);
|
||||
}
|
||||
if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
client.ReceiveDataAsync(Receive);
|
||||
@@ -696,19 +701,18 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
//Check to see if there is a subscription to the TextReceivedQueueInvoke event. If there is start the dequeue thread.
|
||||
if (handler != null)
|
||||
{
|
||||
var gotLock = DequeueLock.TryEnter();
|
||||
if (gotLock)
|
||||
CrestronInvoke.BeginInvoke((o) => DequeueEvent());
|
||||
if (System.Threading.Monitor.TryEnter(_dequeueLock))
|
||||
System.Threading.Tasks.Task.Run(() => DequeueEvent());
|
||||
}
|
||||
}
|
||||
else //JAG added this as I believe the error return is 0 bytes like the server. See help when hover on ReceiveAsync
|
||||
}
|
||||
else //JAG added this as I believe the error return is 0 bytes like the server. See help when hover on ReceiveAsync
|
||||
{
|
||||
client.DisconnectFromServer();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This method gets spooled up in its own thread an protected by a CCriticalSection to prevent multiple threads from running concurrently.
|
||||
/// This method gets spooled up in its own thread an protected by a lock to prevent multiple threads from running concurrently.
|
||||
/// It will dequeue items as they are enqueued automatically.
|
||||
/// </summary>
|
||||
void DequeueEvent()
|
||||
@@ -728,13 +732,10 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.LogException(e, "DequeueEvent error");
|
||||
}
|
||||
// Make sure to leave the CCritical section in case an exception above stops this thread, or we won't be able to restart it.
|
||||
if (DequeueLock != null)
|
||||
{
|
||||
DequeueLock.Leave();
|
||||
this.LogError(e, "DequeueEvent error: {0}", e.Message);
|
||||
}
|
||||
// Make sure to release the lock in case an exception above stops this thread, or we won't be able to restart it.
|
||||
System.Threading.Monitor.Exit(_dequeueLock);
|
||||
}
|
||||
|
||||
void HeartbeatStart()
|
||||
@@ -745,11 +746,15 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
if (HeartbeatSendTimer == null)
|
||||
{
|
||||
|
||||
HeartbeatSendTimer = new CTimer(this.SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
|
||||
HeartbeatSendTimer = new Timer(HeartbeatInterval) { AutoReset = true };
|
||||
HeartbeatSendTimer.Elapsed += (s, e) => SendHeartbeat(null);
|
||||
HeartbeatSendTimer.Start();
|
||||
}
|
||||
if (HeartbeatAckTimer == null)
|
||||
{
|
||||
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
|
||||
HeartbeatAckTimer = new Timer(HeartbeatInterval * 2) { AutoReset = true };
|
||||
HeartbeatAckTimer.Elapsed += (s, e) => HeartbeatAckTimerFail(null);
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -759,13 +764,13 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
|
||||
if (HeartbeatSendTimer != null)
|
||||
{
|
||||
Debug.Console(2, this, "Stoping Heartbeat Send");
|
||||
this.LogVerbose("Stoping Heartbeat Send");
|
||||
HeartbeatSendTimer.Stop();
|
||||
HeartbeatSendTimer = null;
|
||||
}
|
||||
if (HeartbeatAckTimer != null)
|
||||
{
|
||||
Debug.Console(2, this, "Stoping Heartbeat Ack");
|
||||
this.LogVerbose("Stoping Heartbeat Ack");
|
||||
HeartbeatAckTimer.Stop();
|
||||
HeartbeatAckTimer = null;
|
||||
}
|
||||
@@ -774,7 +779,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
void SendHeartbeat(object notused)
|
||||
{
|
||||
this.SendText(HeartbeatString);
|
||||
Debug.Console(2, this, "Sending Heartbeat");
|
||||
this.LogVerbose("Sending Heartbeat");
|
||||
|
||||
}
|
||||
|
||||
@@ -793,13 +798,17 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
{
|
||||
if (HeartbeatAckTimer != null)
|
||||
{
|
||||
HeartbeatAckTimer.Reset(HeartbeatInterval * 2);
|
||||
HeartbeatAckTimer.Stop();
|
||||
HeartbeatAckTimer.Interval = HeartbeatInterval * 2;
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
|
||||
HeartbeatAckTimer = new Timer(HeartbeatInterval * 2) { AutoReset = true };
|
||||
HeartbeatAckTimer.Elapsed += (s, e) => HeartbeatAckTimerFail(null);
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
Debug.Console(2, this, "Heartbeat Received: {0}, from Server", HeartbeatString);
|
||||
this.LogVerbose("Heartbeat Received: {0}, from Server", HeartbeatString);
|
||||
return remainingText;
|
||||
}
|
||||
}
|
||||
@@ -807,7 +816,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error checking heartbeat: {0}", ex.Message);
|
||||
this.LogError(ex, "Error checking heartbeat: {0}", ex.Message);
|
||||
}
|
||||
return received;
|
||||
}
|
||||
@@ -821,7 +830,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Heartbeat not received from Server...DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE");
|
||||
this.LogWarning("Heartbeat not received from Server...DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE");
|
||||
SendText("Heartbeat not received by server, closing connection");
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
@@ -829,7 +838,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorLog.Error("Heartbeat timeout Error on _client: {0}, {1}", Key, ex);
|
||||
this.LogError(ex, "Heartbeat timeout Error on _client: {0}, {1}", Key, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -862,14 +871,14 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
// HOW IN THE HELL DO WE CATCH AN EXCEPTION IN SENDING?????
|
||||
if (n <= 0)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", this.Key);
|
||||
this.LogWarning("[{0}] Sent zero bytes. Was there an error?", this.Key);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, "Error sending text: {1}. Error: {0}", ex.Message, text);
|
||||
this.LogError(ex, "Error sending text: {1}. Error: {0}", ex.Message, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -888,7 +897,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, "Error sending bytes. Error: {0}", ex.Message);
|
||||
this.LogError(ex, "Error sending bytes. Error: {0}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -907,7 +916,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
try
|
||||
{
|
||||
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
|
||||
this.LogVerbose("Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
|
||||
|
||||
OnConnectionChange();
|
||||
// The client could be null or disposed by this time...
|
||||
@@ -920,7 +929,7 @@ public class GenericSecureTcpIpClient : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error in socket status change callback. Error: {0}\r\r{1}", ex, ex.InnerException);
|
||||
this.LogError(ex, "Error in socket status change callback. Error: {0}\r\r{1}", ex, ex.InnerException);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,9 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Timers;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using PepperDash.Core.Logging;
|
||||
@@ -80,7 +83,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
public string Hostname { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
/// The port number on which the server is listening.
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
|
||||
@@ -113,7 +116,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SharedKey is sent for varification to the server. Shared key can be any text (255 char limit in SIMPL+ Module), but must match the Shared Key on the Server module
|
||||
/// SharedKey is sent for verification to the server. Shared key can be any text (255 char limit in SIMPL+ Module), but must match the Shared Key on the Server module
|
||||
/// </summary>
|
||||
public string SharedKey { get; set; }
|
||||
|
||||
@@ -221,7 +224,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
/// <summary>
|
||||
/// private Timer for auto reconnect
|
||||
/// </summary>
|
||||
CTimer RetryTimer;
|
||||
System.Timers.Timer RetryTimer;
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -253,13 +256,13 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
/// </summary>
|
||||
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatInterval = (value * 1000); } }
|
||||
|
||||
CTimer HeartbeatSendTimer;
|
||||
CTimer HeartbeatAckTimer;
|
||||
System.Timers.Timer HeartbeatSendTimer;
|
||||
System.Timers.Timer HeartbeatAckTimer;
|
||||
/// <summary>
|
||||
/// Used to force disconnection on a dead connect attempt
|
||||
/// </summary>
|
||||
CTimer ConnectFailTimer;
|
||||
CTimer WaitForSharedKey;
|
||||
System.Timers.Timer ConnectFailTimer;
|
||||
System.Timers.Timer WaitForSharedKey;
|
||||
private int ConnectionCount;
|
||||
/// <summary>
|
||||
/// Internal secure client
|
||||
@@ -271,7 +274,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
/// <summary>
|
||||
/// Queue lock
|
||||
/// </summary>
|
||||
CCriticalSection DequeueLock = new CCriticalSection();
|
||||
private readonly object _dequeueLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Receive Queue size. Defaults to 20. Will set to 20 if QueueSize property is less than 20. Use constructor or set queue size property before
|
||||
@@ -336,8 +339,9 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
#region Methods
|
||||
|
||||
/// <summary>
|
||||
/// Just to help S+ set the key
|
||||
/// Initializes the client's key property, which is used to identify this client instance.
|
||||
/// </summary>
|
||||
/// <param name="key">The unique key that identifies this client instance.</param>
|
||||
public void Initialize(string key)
|
||||
{
|
||||
Key = key;
|
||||
@@ -346,7 +350,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
/// <summary>
|
||||
/// Initialize called by the constructor that accepts a client config object. Can be called later to reset properties of client.
|
||||
/// </summary>
|
||||
/// <param name="clientConfigObject"></param>
|
||||
/// <param name="clientConfigObject">The configuration object containing the client's settings.</param>
|
||||
public void Initialize(TcpClientConfigObject clientConfigObject)
|
||||
{
|
||||
try
|
||||
@@ -361,7 +365,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
SharedKey = clientConfigObject.SharedKey;
|
||||
SharedKeyRequired = clientConfigObject.SharedKeyRequired;
|
||||
HeartbeatEnabled = clientConfigObject.HeartbeatRequired;
|
||||
HeartbeatRequiredIntervalInSeconds = clientConfigObject.HeartbeatRequiredIntervalInSeconds > 0 ?
|
||||
HeartbeatRequiredIntervalInSeconds = clientConfigObject.HeartbeatRequiredIntervalInSeconds > 0 ?
|
||||
clientConfigObject.HeartbeatRequiredIntervalInSeconds : (ushort)15;
|
||||
HeartbeatString = string.IsNullOrEmpty(clientConfigObject.HeartbeatStringToMatch) ? "heartbeat" : clientConfigObject.HeartbeatStringToMatch;
|
||||
Port = TcpSshProperties.Port;
|
||||
@@ -387,7 +391,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping || programEventType == eProgramStatusEventType.Paused)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Program stopping. Closing Client connection");
|
||||
this.LogInformation("Program stopping. Closing Client connection");
|
||||
ProgramIsStopping = true;
|
||||
Disconnect();
|
||||
}
|
||||
@@ -400,17 +404,17 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
public void Connect()
|
||||
{
|
||||
ConnectionCount++;
|
||||
Debug.Console(2, this, "Attempting connect Count:{0}", ConnectionCount);
|
||||
this.LogVerbose("Attempting connect Count:{0}", ConnectionCount);
|
||||
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already connected. Ignoring.");
|
||||
this.LogInformation("Already connected. Ignoring.");
|
||||
return;
|
||||
}
|
||||
if (IsTryingToConnect)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already trying to connect. Ignoring.");
|
||||
this.LogInformation("Already trying to connect. Ignoring.");
|
||||
return;
|
||||
}
|
||||
try
|
||||
@@ -423,17 +427,17 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No address set");
|
||||
this.LogWarning("DynamicTcpClient: No address set");
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: Invalid port");
|
||||
this.LogWarning("DynamicTcpClient: Invalid port");
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No Shared Key set");
|
||||
this.LogWarning("DynamicTcpClient: No Shared Key set");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -454,9 +458,10 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
//var timeOfConnect = DateTime.Now.ToString("HH:mm:ss.fff");
|
||||
|
||||
ConnectFailTimer = new CTimer(o =>
|
||||
ConnectFailTimer = new System.Timers.Timer(30000) { AutoReset = false };
|
||||
ConnectFailTimer.Elapsed += (s, e) =>
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Connect attempt has not finished after 30sec Count:{0}", ConnectionCount);
|
||||
this.LogError("Connect attempt has not finished after 30sec Count:{0}", ConnectionCount);
|
||||
if (IsTryingToConnect)
|
||||
{
|
||||
IsTryingToConnect = false;
|
||||
@@ -468,12 +473,13 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
//SecureClient.DisconnectFromServer();
|
||||
//CheckClosedAndTryReconnect();
|
||||
}
|
||||
}, 30000);
|
||||
};
|
||||
ConnectFailTimer.Start();
|
||||
|
||||
Debug.Console(2, this, "Making Connection Count:{0}", ConnectionCount);
|
||||
this.LogVerbose("Making Connection Count:{0}", ConnectionCount);
|
||||
Client.ConnectToServerAsync(o =>
|
||||
{
|
||||
Debug.Console(2, this, "ConnectToServerAsync Count:{0} Ran!", ConnectionCount);
|
||||
this.LogVerbose("ConnectToServerAsync Count:{0} Ran!", ConnectionCount);
|
||||
|
||||
if (ConnectFailTimer != null)
|
||||
{
|
||||
@@ -483,22 +489,22 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
if (o.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(2, this, "Client connected to {0} on port {1}", o.AddressClientConnectedTo, o.LocalPortNumberOfClient);
|
||||
this.LogVerbose("Client connected to {0} on port {1}", o.AddressClientConnectedTo, o.LocalPortNumberOfClient);
|
||||
o.ReceiveDataAsync(Receive);
|
||||
|
||||
if (SharedKeyRequired)
|
||||
{
|
||||
WaitingForSharedKeyResponse = true;
|
||||
WaitForSharedKey = new CTimer(timer =>
|
||||
WaitForSharedKey = new System.Timers.Timer(15000) { AutoReset = false };
|
||||
WaitForSharedKey.Elapsed += (s, e) =>
|
||||
{
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Shared key exchange timer expired. IsReadyForCommunication={0}", IsReadyForCommunication);
|
||||
// Debug.Console(1, this, "Connect attempt failed {0}", c.ClientStatus);
|
||||
this.LogWarning("Shared key exchange timer expired. IsReadyForCommunication={0}", IsReadyForCommunication);
|
||||
// This is the only case where we should call DisconectFromServer...Event handeler will trigger the cleanup
|
||||
o.DisconnectFromServer();
|
||||
//CheckClosedAndTryReconnect();
|
||||
//OnClientReadyForcommunications(false); // Should send false event
|
||||
}, 15000);
|
||||
};
|
||||
WaitForSharedKey.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -512,14 +518,14 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Connect attempt failed {0}", o.ClientStatus);
|
||||
this.LogWarning("Connect attempt failed {0}", o.ClientStatus);
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Client connection exception: {0}", ex.Message);
|
||||
this.LogError("Client connection exception: {0}", ex.Message);
|
||||
IsTryingToConnect = false;
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
@@ -556,7 +562,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
if (Client != null)
|
||||
{
|
||||
//SecureClient.DisconnectFromServer();
|
||||
Debug.Console(2, this, "Disconnecting Client {0}", DisconnectCalledByUser ? ", Called by user" : "");
|
||||
this.LogVerbose("Disconnecting Client {0}", DisconnectCalledByUser ? ", Called by user" : "");
|
||||
Client.SocketStatusChange -= Client_SocketStatusChange;
|
||||
Client.Dispose();
|
||||
Client = null;
|
||||
@@ -578,22 +584,24 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
if (Client != null)
|
||||
{
|
||||
Debug.Console(2, this, "Cleaning up remotely closed/failed connection.");
|
||||
this.LogVerbose("Cleaning up remotely closed/failed connection.");
|
||||
Cleanup();
|
||||
}
|
||||
if (!DisconnectCalledByUser && AutoReconnect)
|
||||
{
|
||||
var halfInterval = AutoReconnectIntervalMs / 2;
|
||||
var rndTime = new Random().Next(-halfInterval, halfInterval) + AutoReconnectIntervalMs;
|
||||
Debug.Console(2, this, "Attempting reconnect in {0} ms, randomized", rndTime);
|
||||
this.LogVerbose("Attempting reconnect in {0} ms, randomized", rndTime);
|
||||
if (RetryTimer != null)
|
||||
{
|
||||
RetryTimer.Stop();
|
||||
RetryTimer = null;
|
||||
}
|
||||
if(AutoReconnectTriggered != null)
|
||||
if (AutoReconnectTriggered != null)
|
||||
AutoReconnectTriggered(this, new EventArgs());
|
||||
RetryTimer = new CTimer(o => Connect(), rndTime);
|
||||
RetryTimer = new System.Timers.Timer(rndTime) { AutoReset = false };
|
||||
RetryTimer.Elapsed += (s, e) => Connect();
|
||||
RetryTimer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -612,13 +620,13 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray();
|
||||
str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
||||
Debug.Console(2, this, "Client Received:\r--------\r{0}\r--------", str);
|
||||
this.LogVerbose("Client Received:\r--------\r{0}\r--------", str);
|
||||
if (!string.IsNullOrEmpty(checkHeartbeat(str)))
|
||||
{
|
||||
|
||||
if (SharedKeyRequired && str == "SharedKey:")
|
||||
{
|
||||
Debug.Console(2, this, "Server asking for shared key, sending");
|
||||
this.LogVerbose("Server asking for shared key, sending");
|
||||
SendText(SharedKey + "\n");
|
||||
}
|
||||
else if (SharedKeyRequired && str == "Shared Key Match")
|
||||
@@ -626,7 +634,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
StopWaitForSharedKeyTimer();
|
||||
|
||||
|
||||
Debug.Console(2, this, "Shared key confirmed. Ready for communication");
|
||||
this.LogVerbose("Shared key confirmed. Ready for communication");
|
||||
OnClientReadyForcommunications(true); // Successful key exchange
|
||||
}
|
||||
else
|
||||
@@ -646,7 +654,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error receiving data: {1}. Error: {0}", ex.Message, str);
|
||||
this.LogError("Error receiving data: {1}. Error: {0}", ex.Message, str);
|
||||
}
|
||||
if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
client.ReceiveDataAsync(Receive);
|
||||
@@ -654,9 +662,8 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
//Check to see if there is a subscription to the TextReceivedQueueInvoke event. If there is start the dequeue thread.
|
||||
if (handler != null)
|
||||
{
|
||||
var gotLock = DequeueLock.TryEnter();
|
||||
if (gotLock)
|
||||
CrestronInvoke.BeginInvoke((o) => DequeueEvent());
|
||||
if (Monitor.TryEnter(_dequeueLock))
|
||||
Task.Run(() => DequeueEvent());
|
||||
}
|
||||
}
|
||||
else //JAG added this as I believe the error return is 0 bytes like the server. See help when hover on ReceiveAsync
|
||||
@@ -666,7 +673,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This method gets spooled up in its own thread an protected by a CCriticalSection to prevent multiple threads from running concurrently.
|
||||
/// This method gets spooled up in its own thread an protected by a lock to prevent multiple threads from running concurrently.
|
||||
/// It will dequeue items as they are enqueued automatically.
|
||||
/// </summary>
|
||||
void DequeueEvent()
|
||||
@@ -686,28 +693,29 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.LogException(e, "DequeueEvent error");
|
||||
}
|
||||
// Make sure to leave the CCritical section in case an exception above stops this thread, or we won't be able to restart it.
|
||||
if (DequeueLock != null)
|
||||
{
|
||||
DequeueLock.Leave();
|
||||
this.LogError("DequeueEvent error: {0}", e.Message, e);
|
||||
}
|
||||
// Make sure to release the lock in case an exception above stops this thread, or we won't be able to restart it.
|
||||
Monitor.Exit(_dequeueLock);
|
||||
}
|
||||
|
||||
void HeartbeatStart()
|
||||
{
|
||||
if (HeartbeatEnabled)
|
||||
{
|
||||
Debug.Console(2, this, "Starting Heartbeat");
|
||||
this.LogVerbose("Starting Heartbeat");
|
||||
if (HeartbeatSendTimer == null)
|
||||
{
|
||||
|
||||
HeartbeatSendTimer = new CTimer(this.SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
|
||||
HeartbeatSendTimer = new System.Timers.Timer(HeartbeatInterval) { AutoReset = true };
|
||||
HeartbeatSendTimer.Elapsed += (s, e) => SendHeartbeat(null);
|
||||
HeartbeatSendTimer.Start();
|
||||
}
|
||||
if (HeartbeatAckTimer == null)
|
||||
{
|
||||
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
|
||||
HeartbeatAckTimer = new System.Timers.Timer(HeartbeatInterval * 2) { AutoReset = true };
|
||||
HeartbeatAckTimer.Elapsed += (s, e) => HeartbeatAckTimerFail(null);
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,13 +725,13 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
if (HeartbeatSendTimer != null)
|
||||
{
|
||||
Debug.Console(2, this, "Stoping Heartbeat Send");
|
||||
this.LogVerbose("Stopping Heartbeat Send");
|
||||
HeartbeatSendTimer.Stop();
|
||||
HeartbeatSendTimer = null;
|
||||
}
|
||||
if (HeartbeatAckTimer != null)
|
||||
{
|
||||
Debug.Console(2, this, "Stoping Heartbeat Ack");
|
||||
this.LogVerbose("Stopping Heartbeat Ack");
|
||||
HeartbeatAckTimer.Stop();
|
||||
HeartbeatAckTimer = null;
|
||||
}
|
||||
@@ -732,7 +740,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
void SendHeartbeat(object notused)
|
||||
{
|
||||
this.SendText(HeartbeatString);
|
||||
Debug.Console(2, this, "Sending Heartbeat");
|
||||
this.LogVerbose("Sending Heartbeat");
|
||||
|
||||
}
|
||||
|
||||
@@ -751,13 +759,17 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
if (HeartbeatAckTimer != null)
|
||||
{
|
||||
HeartbeatAckTimer.Reset(HeartbeatInterval * 2);
|
||||
HeartbeatAckTimer.Stop();
|
||||
HeartbeatAckTimer.Interval = HeartbeatInterval * 2;
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
|
||||
HeartbeatAckTimer = new System.Timers.Timer(HeartbeatInterval * 2) { AutoReset = true };
|
||||
HeartbeatAckTimer.Elapsed += (s, e) => HeartbeatAckTimerFail(null);
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
Debug.Console(2, this, "Heartbeat Received: {0}, from Server", HeartbeatString);
|
||||
this.LogVerbose("Heartbeat Received: {0}, from Server", HeartbeatString);
|
||||
return remainingText;
|
||||
}
|
||||
}
|
||||
@@ -765,7 +777,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error checking heartbeat: {0}", ex.Message);
|
||||
this.LogError("Error checking heartbeat: {0}", ex.Message, ex);
|
||||
}
|
||||
return received;
|
||||
}
|
||||
@@ -779,7 +791,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Heartbeat not received from Server...DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE");
|
||||
this.LogWarning("Heartbeat not received from Server...DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE");
|
||||
SendText("Heartbeat not received by server, closing connection");
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
@@ -787,7 +799,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorLog.Error("Heartbeat timeout Error on Client: {0}, {1}", Key, ex);
|
||||
this.LogError("Heartbeat timeout Error on Client: {0}, {1}", Key, ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -820,14 +832,14 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
// HOW IN THE HELL DO WE CATCH AN EXCEPTION IN SENDING?????
|
||||
if (n <= 0)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", this.Key);
|
||||
this.LogWarning("[{0}] Sent zero bytes. Was there an error?", this.Key);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, "Error sending text: {1}. Error: {0}", ex.Message, text);
|
||||
this.LogError("Error sending text: {1}. Error: {0}", text, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -846,7 +858,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, "Error sending bytes. Error: {0}", ex.Message);
|
||||
this.LogError("Error sending bytes. Error: {0}", ex.Message, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -865,7 +877,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
try
|
||||
{
|
||||
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
|
||||
this.LogDebug("Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
|
||||
|
||||
OnConnectionChange();
|
||||
// The client could be null or disposed by this time...
|
||||
@@ -878,7 +890,7 @@ public class GenericSecureTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error in socket status change callback. Error: {0}\r\r{1}", ex, ex.InnerException);
|
||||
this.LogError("Error in socket status change callback. Error: {0}\r\r{1}", ex, ex.InnerException);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,8 @@
|
||||
/*PepperDash Technology Corp.
|
||||
JAG
|
||||
Copyright: 2017
|
||||
------------------------------------
|
||||
***Notice of Ownership and Copyright***
|
||||
The material in which this notice appears is the property of PepperDash Technology Corporation,
|
||||
which claims copyright under the laws of the United States of America in the entire body of material
|
||||
and in all parts thereof, regardless of the use to which it is being put. Any use, in whole or in part,
|
||||
of this material by another party without the express written permission of PepperDash Technology Corporation is prohibited.
|
||||
PepperDash Technology Corporation reserves all rights under applicable laws.
|
||||
------------------------------------ */
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Timers;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using PepperDash.Core.Logging;
|
||||
@@ -69,12 +59,17 @@ public class GenericSecureTcpIpServer : Device
|
||||
/// <summary>
|
||||
/// Server listen lock
|
||||
/// </summary>
|
||||
CCriticalSection ServerCCSection = new CCriticalSection();
|
||||
private readonly object _serverLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Queue lock
|
||||
/// </summary>
|
||||
CCriticalSection DequeueLock = new CCriticalSection();
|
||||
private readonly object _dequeueLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast lock
|
||||
/// </summary>
|
||||
private readonly object _broadcastLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Receive Queue size. Defaults to 20. Will set to 20 if QueueSize property is less than 20. Use constructor or set queue size property before
|
||||
@@ -96,7 +91,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
/// <summary>
|
||||
/// Timer to operate the bandaid monitor client in a loop.
|
||||
/// </summary>
|
||||
CTimer MonitorClientTimer;
|
||||
Timer MonitorClientTimer;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
@@ -263,7 +258,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
public string HeartbeatStringToMatch { get; set; }
|
||||
|
||||
//private timers for Heartbeats per client
|
||||
Dictionary<uint, CTimer> HeartbeatTimerDictionary = new Dictionary<uint, CTimer>();
|
||||
Dictionary<uint, Timer> HeartbeatTimerDictionary = new Dictionary<uint, Timer>();
|
||||
|
||||
//flags to show the secure server is waiting for client at index to send the shared key
|
||||
List<uint> WaitingForSharedKey = new List<uint>();
|
||||
@@ -399,18 +394,19 @@ public class GenericSecureTcpIpServer : Device
|
||||
/// </summary>
|
||||
public void Listen()
|
||||
{
|
||||
ServerCCSection.Enter();
|
||||
lock (_serverLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': Invalid port", Key);
|
||||
this.LogError("Server '{0}': Invalid port", Key);
|
||||
ErrorLog.Warn(string.Format("Server '{0}': Invalid port", Key));
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': No Shared Key set", Key);
|
||||
this.LogError("Server '{0}': No Shared Key set", Key);
|
||||
ErrorLog.Warn(string.Format("Server '{0}': No Shared Key set", Key));
|
||||
return;
|
||||
}
|
||||
@@ -434,22 +430,21 @@ public class GenericSecureTcpIpServer : Device
|
||||
SocketErrorCodes status = SecureServer.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback);
|
||||
if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Error starting WaitForConnectionAsync {0}", status);
|
||||
this.LogError("Error starting WaitForConnectionAsync {0}", status);
|
||||
}
|
||||
else
|
||||
{
|
||||
ServerStopped = false;
|
||||
}
|
||||
OnServerStateChange(SecureServer.State);
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Secure Server Status: {0}, Socket Status: {1}", SecureServer.State, SecureServer.ServerSocketStatus);
|
||||
ServerCCSection.Leave();
|
||||
this.LogInformation("Secure Server Status: {0}, Socket Status: {1}", SecureServer.State, SecureServer.ServerSocketStatus);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ServerCCSection.Leave();
|
||||
ErrorLog.Error("{1} Error with Dynamic Server: {0}", ex.ToString(), Key);
|
||||
this.LogException(ex, "{1} Error with Dynamic Server: {0}", ex.ToString(), Key);
|
||||
}
|
||||
} // end lock
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -459,18 +454,18 @@ public class GenericSecureTcpIpServer : Device
|
||||
{
|
||||
try
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Stopping Listener");
|
||||
this.LogVerbose("Stopping Listener");
|
||||
if (SecureServer != null)
|
||||
{
|
||||
SecureServer.Stop();
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server State: {0}", SecureServer.State);
|
||||
this.LogVerbose("Server State: {0}", SecureServer.State);
|
||||
OnServerStateChange(SecureServer.State);
|
||||
}
|
||||
ServerStopped = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error stopping server. Error: {0}", ex);
|
||||
this.LogException(ex, "Error stopping server. Error: {0}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,11 +478,11 @@ public class GenericSecureTcpIpServer : Device
|
||||
try
|
||||
{
|
||||
SecureServer.Disconnect(client);
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected client index: {0}", client);
|
||||
this.LogVerbose("Disconnected client index: {0}", client);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Disconnecting client index: {0}. Error: {1}", client, ex);
|
||||
this.LogException(ex, "Error Disconnecting client index: {0}. Error: {1}", client, ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -495,7 +490,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
/// </summary>
|
||||
public void DisconnectAllClientsForShutdown()
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Disconnecting All Clients");
|
||||
this.LogInformation("Disconnecting All Clients");
|
||||
if (SecureServer != null)
|
||||
{
|
||||
SecureServer.SocketStatusChange -= SecureServer_SocketStatusChange;
|
||||
@@ -507,17 +502,17 @@ public class GenericSecureTcpIpServer : Device
|
||||
try
|
||||
{
|
||||
SecureServer.Disconnect(i);
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected client index: {0}", i);
|
||||
this.LogInformation("Disconnected client index: {0}", i);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Disconnecting client index: {0}. Error: {1}", i, ex);
|
||||
this.LogException(ex, "Error Disconnecting client index: {0}. Error: {1}", i, ex.Message);
|
||||
}
|
||||
}
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server Status: {0}", SecureServer.ServerSocketStatus);
|
||||
this.LogInformation("Server Status: {0}", SecureServer.ServerSocketStatus);
|
||||
}
|
||||
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected All Clients");
|
||||
this.LogInformation("Disconnected All Clients");
|
||||
ConnectedClientsIndexes.Clear();
|
||||
|
||||
if (!ProgramIsStopping)
|
||||
@@ -535,8 +530,8 @@ public class GenericSecureTcpIpServer : Device
|
||||
/// <param name="text"></param>
|
||||
public void BroadcastText(string text)
|
||||
{
|
||||
CCriticalSection CCBroadcast = new CCriticalSection();
|
||||
CCBroadcast.Enter();
|
||||
lock (_broadcastLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (ConnectedClientsIndexes.Count > 0)
|
||||
@@ -552,13 +547,12 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
}
|
||||
}
|
||||
CCBroadcast.Leave();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CCBroadcast.Leave();
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Broadcasting messages from server. Error: {0}", ex.Message);
|
||||
this.LogException(ex, "Error Broadcasting messages from server. Error: {0}", ex.Message);
|
||||
}
|
||||
} // end lock
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -579,7 +573,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, "Error sending text to client. Text: {1}. Error: {0}", ex.Message, text);
|
||||
this.LogException(ex, "Error sending text to client. Text: {1}. Error: {0}", ex.Message, text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -597,13 +591,19 @@ public class GenericSecureTcpIpServer : Device
|
||||
if (noDelimiter.Contains(HeartbeatStringToMatch))
|
||||
{
|
||||
if (HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
HeartbeatTimerDictionary[clientIndex].Reset(HeartbeatRequiredIntervalMs);
|
||||
{
|
||||
HeartbeatTimerDictionary[clientIndex].Stop();
|
||||
HeartbeatTimerDictionary[clientIndex].Interval = HeartbeatRequiredIntervalMs;
|
||||
HeartbeatTimerDictionary[clientIndex].Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
CTimer HeartbeatTimer = new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs);
|
||||
HeartbeatTimerDictionary.Add(clientIndex, HeartbeatTimer);
|
||||
var heartbeatTimer = new Timer(HeartbeatRequiredIntervalMs) { AutoReset = false };
|
||||
heartbeatTimer.Elapsed += (s, e) => HeartbeatTimer_CallbackFunction(clientIndex);
|
||||
heartbeatTimer.Start();
|
||||
HeartbeatTimerDictionary.Add(clientIndex, heartbeatTimer);
|
||||
}
|
||||
Debug.Console(1, this, "Heartbeat Received: {0}, from client index: {1}", HeartbeatStringToMatch, clientIndex);
|
||||
this.LogDebug("Heartbeat Received: {0}, from client index: {1}", HeartbeatStringToMatch, clientIndex);
|
||||
// Return Heartbeat
|
||||
SendTextToClient(HeartbeatStringToMatch, clientIndex);
|
||||
return remainingText;
|
||||
@@ -612,19 +612,25 @@ public class GenericSecureTcpIpServer : Device
|
||||
else
|
||||
{
|
||||
if (HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
HeartbeatTimerDictionary[clientIndex].Reset(HeartbeatRequiredIntervalMs);
|
||||
{
|
||||
HeartbeatTimerDictionary[clientIndex].Stop();
|
||||
HeartbeatTimerDictionary[clientIndex].Interval = HeartbeatRequiredIntervalMs;
|
||||
HeartbeatTimerDictionary[clientIndex].Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
CTimer HeartbeatTimer = new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs);
|
||||
HeartbeatTimerDictionary.Add(clientIndex, HeartbeatTimer);
|
||||
var heartbeatTimer = new Timer(HeartbeatRequiredIntervalMs) { AutoReset = false };
|
||||
heartbeatTimer.Elapsed += (s, e) => HeartbeatTimer_CallbackFunction(clientIndex);
|
||||
heartbeatTimer.Start();
|
||||
HeartbeatTimerDictionary.Add(clientIndex, heartbeatTimer);
|
||||
}
|
||||
Debug.Console(1, this, "Heartbeat Received: {0}, from client index: {1}", received, clientIndex);
|
||||
this.LogInformation("Heartbeat Received: {0}, from client index: {1}", received, clientIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error checking heartbeat: {0}", ex.Message);
|
||||
this.LogException(ex, "Error checking heartbeat: {0}", ex.Message);
|
||||
}
|
||||
return received;
|
||||
}
|
||||
@@ -636,11 +642,11 @@ public class GenericSecureTcpIpServer : Device
|
||||
/// <returns></returns>
|
||||
public string GetClientIPAddress(uint clientIndex)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress Index: {0}", clientIndex);
|
||||
this.LogInformation("GetClientIPAddress Index: {0}", clientIndex);
|
||||
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex)))
|
||||
{
|
||||
var ipa = this.SecureServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress IPAddreess: {0}", ipa);
|
||||
this.LogInformation("GetClientIPAddress IPAddreess: {0}", ipa);
|
||||
return ipa;
|
||||
|
||||
}
|
||||
@@ -663,14 +669,13 @@ public class GenericSecureTcpIpServer : Device
|
||||
clientIndex = (uint)o;
|
||||
address = SecureServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Heartbeat not received for Client index {2} IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE {1}",
|
||||
this.LogInformation("Heartbeat not received for Client index {2} IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE {1}",
|
||||
address, string.IsNullOrEmpty(HeartbeatStringToMatch) ? "" : ("HeartbeatStringToMatch: " + HeartbeatStringToMatch), clientIndex);
|
||||
|
||||
if (SecureServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
SendTextToClient("Heartbeat not received by server, closing connection", clientIndex);
|
||||
|
||||
var discoResult = SecureServer.Disconnect(clientIndex);
|
||||
//Debug.Console(1, this, "{0}", discoResult);
|
||||
|
||||
if (HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
{
|
||||
@@ -699,11 +704,9 @@ public class GenericSecureTcpIpServer : Device
|
||||
try
|
||||
{
|
||||
|
||||
|
||||
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.SecureServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.SecureServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
|
||||
if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange ConnectedCLients: {0} ServerState: {1} Port: {2}", SecureServer.NumberOfClientsConnected, SecureServer.State, SecureServer.PortNumber);
|
||||
this.LogInformation("SecureServerSocketStatusChange ConnectedCLients: {0} ServerState: {1} Port: {2}", SecureServer.NumberOfClientsConnected, SecureServer.State, SecureServer.PortNumber);
|
||||
|
||||
if (ConnectedClientsIndexes.Contains(clientIndex))
|
||||
ConnectedClientsIndexes.Remove(clientIndex);
|
||||
@@ -725,12 +728,12 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Change Callback. Error: {0}", ex);
|
||||
this.LogException(ex, "Error in Socket Status Change Callback. Error: {0}", ex.Message);
|
||||
}
|
||||
//Use a thread for this event so that the server state updates to listening while this event is processed. Listening must be added to the server state
|
||||
//after every client connection so that the server can check and see if it is at max clients. Due to this the event fires and server listening enum bit flag
|
||||
//is not set. Putting in a thread allows the state to update before this event processes so that the subscribers to this event get accurate isListening in the event.
|
||||
CrestronInvoke.BeginInvoke(o => onConnectionChange(clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex)), null);
|
||||
System.Threading.Tasks.Task.Run(() => onConnectionChange(clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex)));
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -745,7 +748,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
{
|
||||
try
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "ConnectCallback: IPAddress: {0}. Index: {1}. Status: {2}",
|
||||
this.LogInformation("ConnectCallback: IPAddress: {0}. Index: {1}. Status: {2}",
|
||||
server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex),
|
||||
clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex));
|
||||
if (clientIndex != 0)
|
||||
@@ -765,7 +768,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
byte[] b = Encoding.GetEncoding(28591).GetBytes("SharedKey:");
|
||||
server.SendDataAsync(clientIndex, b, b.Length, (x, y, z) => { });
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Sent Shared Key Request to client at {0}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
|
||||
this.LogInformation("Sent Shared Key Request to client at {0}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -775,7 +778,10 @@ public class GenericSecureTcpIpServer : Device
|
||||
{
|
||||
if (!HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
{
|
||||
HeartbeatTimerDictionary.Add(clientIndex, new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs));
|
||||
var heartbeatTimer = new Timer(HeartbeatRequiredIntervalMs) { AutoReset = false };
|
||||
heartbeatTimer.Elapsed += (s, e) => HeartbeatTimer_CallbackFunction(clientIndex);
|
||||
heartbeatTimer.Start();
|
||||
HeartbeatTimerDictionary.Add(clientIndex, heartbeatTimer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -784,19 +790,19 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Client attempt faulty.");
|
||||
this.LogError("Client attempt faulty.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Connect Callback. Error: {0}", ex);
|
||||
this.LogException(ex, "Error in Socket Status Connect Callback. Error: {0}", ex.Message);
|
||||
}
|
||||
|
||||
// Rearm the listner
|
||||
SocketErrorCodes status = server.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback);
|
||||
if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Socket status connect callback status {0}", status);
|
||||
this.LogError("Socket status connect callback status {0}", status);
|
||||
if (status == SocketErrorCodes.SOCKET_CONNECTION_IN_PROGRESS)
|
||||
{
|
||||
// There is an issue where on a failed negotiation we need to stop and start the server. This should still leave connected clients intact.
|
||||
@@ -833,7 +839,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
if (received != SharedKey)
|
||||
{
|
||||
byte[] b = Encoding.GetEncoding(28591).GetBytes("Shared key did not match server. Disconnecting");
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
|
||||
this.LogWarning("Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
|
||||
mySecureTCPServer.SendData(clientIndex, b, b.Length);
|
||||
mySecureTCPServer.Disconnect(clientIndex);
|
||||
|
||||
@@ -844,7 +850,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
byte[] success = Encoding.GetEncoding(28591).GetBytes("Shared Key Match");
|
||||
mySecureTCPServer.SendDataAsync(clientIndex, success, success.Length, null);
|
||||
OnServerClientReadyForCommunications(clientIndex);
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
|
||||
this.LogInformation("Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(checkHeartbeat(clientIndex, received)))
|
||||
{
|
||||
@@ -857,7 +863,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Receiving data: {0}. Error: {1}", received, ex);
|
||||
this.LogException(ex, "Error Receiving data: {0}. Error: {1}", received, ex.Message);
|
||||
}
|
||||
if (mySecureTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
mySecureTCPServer.ReceiveDataAsync(clientIndex, SecureReceivedDataAsyncCallback);
|
||||
@@ -865,9 +871,8 @@ public class GenericSecureTcpIpServer : Device
|
||||
//Check to see if there is a subscription to the TextReceivedQueueInvoke event. If there is start the dequeue thread.
|
||||
if (handler != null)
|
||||
{
|
||||
var gotLock = DequeueLock.TryEnter();
|
||||
if (gotLock)
|
||||
CrestronInvoke.BeginInvoke((o) => DequeueEvent());
|
||||
if (System.Threading.Monitor.TryEnter(_dequeueLock))
|
||||
System.Threading.Tasks.Task.Run(() => DequeueEvent());
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -877,7 +882,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This method gets spooled up in its own thread an protected by a CCriticalSection to prevent multiple threads from running concurrently.
|
||||
/// This method gets spooled up in its own thread an protected by a lock to prevent multiple threads from running concurrently.
|
||||
/// It will dequeue items as they are enqueued automatically.
|
||||
/// </summary>
|
||||
void DequeueEvent()
|
||||
@@ -897,13 +902,10 @@ public class GenericSecureTcpIpServer : Device
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.LogException(e, "DequeueEvent error");
|
||||
}
|
||||
// Make sure to leave the CCritical section in case an exception above stops this thread, or we won't be able to restart it.
|
||||
if (DequeueLock != null)
|
||||
{
|
||||
DequeueLock.Leave();
|
||||
this.LogError(e, "DequeueEvent error");
|
||||
}
|
||||
// Make sure to release the lock in case an exception above stops this thread, or we won't be able to restart it.
|
||||
System.Threading.Monitor.Exit(_dequeueLock);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -974,7 +976,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
if (MonitorClient != null)
|
||||
MonitorClient.Disconnect();
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Program stopping. Closing server");
|
||||
this.LogInformation("Program stopping. Closing server");
|
||||
KillServer();
|
||||
}
|
||||
}
|
||||
@@ -1000,7 +1002,9 @@ public class GenericSecureTcpIpServer : Device
|
||||
{
|
||||
return;
|
||||
}
|
||||
MonitorClientTimer = new CTimer(o => RunMonitorClient(), 60000);
|
||||
MonitorClientTimer = new Timer(60000) { AutoReset = false };
|
||||
MonitorClientTimer.Elapsed += (s, e) => RunMonitorClient();
|
||||
MonitorClientTimer.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1015,7 +1019,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
//MonitorClient.ConnectionChange += MonitorClient_ConnectionChange;
|
||||
MonitorClient.ClientReadyForCommunications += MonitorClient_IsReadyForComm;
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Starting monitor check");
|
||||
this.LogInformation("Starting monitor check");
|
||||
|
||||
MonitorClient.Connect();
|
||||
// From here MonitorCLient either connects or hangs, MonitorClient will call back
|
||||
@@ -1042,7 +1046,7 @@ public class GenericSecureTcpIpServer : Device
|
||||
{
|
||||
if (args.IsReady)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Monitor client connection success. Disconnecting in 2s");
|
||||
this.LogInformation("Monitor client connection success. Disconnecting in 2s");
|
||||
MonitorClientTimer.Stop();
|
||||
MonitorClientTimer = null;
|
||||
MonitorClientFailureCount = 0;
|
||||
@@ -1063,13 +1067,13 @@ public class GenericSecureTcpIpServer : Device
|
||||
StopMonitorClient();
|
||||
if (MonitorClientFailureCount < MonitorClientMaxFailureCount)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Warning, "Monitor client connection has hung {0} time{1}, maximum {2}",
|
||||
this.LogWarning("Monitor client connection has hung {0} time{1}, maximum {2}",
|
||||
MonitorClientFailureCount, MonitorClientFailureCount > 1 ? "s" : "", MonitorClientMaxFailureCount);
|
||||
StartMonitorClient();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error,
|
||||
this.LogError(
|
||||
"\r***************************\rMonitor client connection has hung a maximum of {0} times. \r***************************",
|
||||
MonitorClientMaxFailureCount);
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Timers;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using Org.BouncyCastle.Utilities;
|
||||
using PepperDash.Core.Logging;
|
||||
using Renci.SshNet;
|
||||
using Renci.SshNet.Common;
|
||||
@@ -79,7 +78,7 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// SSH Client
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus
|
||||
{
|
||||
@@ -132,11 +131,9 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
|
||||
ShellStream TheStream;
|
||||
|
||||
CTimer ReconnectTimer;
|
||||
Timer ReconnectTimer;
|
||||
|
||||
//Lock object to prevent simulatneous connect/disconnect operations
|
||||
//private CCriticalSection connectLock = new CCriticalSection();
|
||||
private SemaphoreSlim connectLock = new SemaphoreSlim(1);
|
||||
private System.Threading.SemaphoreSlim connectLock = new System.Threading.SemaphoreSlim(1);
|
||||
|
||||
private bool DisconnectLogged = false;
|
||||
|
||||
@@ -147,51 +144,53 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
Key = key;
|
||||
Hostname = hostname;
|
||||
Port = port;
|
||||
Username = username;
|
||||
Password = password;
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
Key = key;
|
||||
Hostname = hostname;
|
||||
Port = port;
|
||||
Username = username;
|
||||
Password = password;
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
|
||||
ReconnectTimer = new CTimer(o =>
|
||||
{
|
||||
if (ConnectEnabled)
|
||||
ReconnectTimer = new Timer { AutoReset = false, Enabled = false };
|
||||
ReconnectTimer.Elapsed += (s, e) =>
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
}, System.Threading.Timeout.Infinite);
|
||||
}
|
||||
if (ConnectEnabled)
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S+ Constructor - Must set all properties before calling Connect
|
||||
/// </summary>
|
||||
public GenericSshClient()
|
||||
: base(SPlusKey)
|
||||
{
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
/// <summary>
|
||||
/// S+ Constructor - Must set all properties before calling Connect
|
||||
/// </summary>
|
||||
public GenericSshClient()
|
||||
: base(SPlusKey)
|
||||
{
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
|
||||
ReconnectTimer = new CTimer(o =>
|
||||
ReconnectTimer = new Timer { AutoReset = false, Enabled = false };
|
||||
ReconnectTimer.Elapsed += (s, e) =>
|
||||
{
|
||||
if (ConnectEnabled)
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
}, System.Threading.Timeout.Infinite);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles closing this up when the program shuts down
|
||||
/// </summary>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
if (Client != null)
|
||||
{
|
||||
this.LogDebug("Program stopping. Closing connection");
|
||||
/// <summary>
|
||||
/// Handles closing this up when the program shuts down
|
||||
/// </summary>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
if (Client != null)
|
||||
{
|
||||
this.LogDebug("Program stopping. Closing connection");
|
||||
Disconnect();
|
||||
}
|
||||
}
|
||||
@@ -224,10 +223,10 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
this.LogDebug("Attempting connect");
|
||||
|
||||
// Cancel reconnect if running.
|
||||
if (ReconnectTimer != null)
|
||||
{
|
||||
ReconnectTimer.Stop();
|
||||
}
|
||||
if (ReconnectTimer != null)
|
||||
{
|
||||
ReconnectTimer.Stop();
|
||||
}
|
||||
|
||||
// Cleanup the old client if it already exists
|
||||
if (Client != null)
|
||||
@@ -265,11 +264,10 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
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.LogException(ie, "CONNECTION failure: Cannot reach host");
|
||||
}
|
||||
|
||||
if (ie is System.Net.Sockets.SocketException socketException)
|
||||
@@ -289,10 +287,12 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
if (AutoReconnect)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {autoReconnect}, {autoReconnectInterval}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Stop();
|
||||
ReconnectTimer.Interval = AutoReconnectIntervalMs;
|
||||
ReconnectTimer.Start();
|
||||
}
|
||||
}
|
||||
catch(SshOperationTimeoutException ex)
|
||||
catch (SshOperationTimeoutException ex)
|
||||
{
|
||||
this.LogWarning("Connection attempt timed out: {message}", ex.Message);
|
||||
|
||||
@@ -301,19 +301,22 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
if (AutoReconnect)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Stop();
|
||||
ReconnectTimer.Interval = AutoReconnectIntervalMs;
|
||||
ReconnectTimer.Start();
|
||||
}
|
||||
}
|
||||
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);
|
||||
ReconnectTimer.Stop();
|
||||
ReconnectTimer.Interval = AutoReconnectIntervalMs;
|
||||
ReconnectTimer.Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -324,18 +327,14 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnect the clients and put away it's resources.
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
ConnectEnabled = false;
|
||||
// Stop trying reconnects, if we are
|
||||
if (ReconnectTimer != null)
|
||||
{
|
||||
ReconnectTimer.Stop();
|
||||
// ReconnectTimer = null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Disconnect method
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
ConnectEnabled = false;
|
||||
// Stop trying reconnects, if we are
|
||||
ReconnectTimer.Stop();
|
||||
|
||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||
}
|
||||
@@ -361,15 +360,15 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex,"Exception in Kill Client");
|
||||
this.LogException(ex, "Exception in Kill Client");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kills the stream
|
||||
/// </summary>
|
||||
void KillStream()
|
||||
{
|
||||
void KillStream()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (TheStream != null)
|
||||
@@ -385,60 +384,60 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
{
|
||||
this.LogException(ex, "Exception in Kill Stream:{0}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the keyboard interactive authentication, should it be required.
|
||||
/// </summary>
|
||||
void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
|
||||
{
|
||||
foreach (AuthenticationPrompt prompt in e.Prompts)
|
||||
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
|
||||
prompt.Response = Password;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
|
||||
/// </summary>
|
||||
void Stream_DataReceived(object sender, ShellDataEventArgs e)
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles the keyboard interactive authentication, should it be required.
|
||||
/// </summary>
|
||||
void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
|
||||
{
|
||||
foreach (AuthenticationPrompt prompt in e.Prompts)
|
||||
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
|
||||
prompt.Response = Password;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
|
||||
/// </summary>
|
||||
void Stream_DataReceived(object sender, ShellDataEventArgs e)
|
||||
{
|
||||
if (((ShellStream)sender).Length <= 0L)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var response = ((ShellStream)sender).Read();
|
||||
var response = ((ShellStream)sender).Read();
|
||||
|
||||
var bytesHandler = BytesReceived;
|
||||
|
||||
if (bytesHandler != null)
|
||||
{
|
||||
var bytesHandler = BytesReceived;
|
||||
|
||||
if (bytesHandler != null)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(response);
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
this.LogInformation("Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
this.LogInformation("Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
}
|
||||
|
||||
var textHandler = TextReceived;
|
||||
if (textHandler != null)
|
||||
{
|
||||
}
|
||||
|
||||
var textHandler = TextReceived;
|
||||
if (textHandler != null)
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
this.LogInformation("Received: '{0}'", ComTextHelper.GetDebugText(response));
|
||||
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(response));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
|
||||
/// event
|
||||
/// </summary>
|
||||
void Client_ErrorOccurred(object sender, ExceptionEventArgs e)
|
||||
{
|
||||
CrestronInvoke.BeginInvoke(o =>
|
||||
/// <summary>
|
||||
/// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
|
||||
/// event
|
||||
/// </summary>
|
||||
void Client_ErrorOccurred(object sender, ExceptionEventArgs e)
|
||||
{
|
||||
System.Threading.Tasks.Task.Run(() =>
|
||||
{
|
||||
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
|
||||
this.LogError("Disconnected by remote");
|
||||
@@ -456,7 +455,9 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
if (AutoReconnect && ConnectEnabled)
|
||||
{
|
||||
this.LogDebug("Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Reset(AutoReconnectIntervalMs);
|
||||
ReconnectTimer.Stop();
|
||||
ReconnectTimer.Interval = AutoReconnectIntervalMs;
|
||||
ReconnectTimer.Start();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -472,49 +473,50 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
|
||||
#region IBasicCommunication Members
|
||||
|
||||
/// <summary>
|
||||
/// Sends text to the server
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public void SendText(string text)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Client != null && TheStream != null && IsConnected)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
this.LogInformation(
|
||||
"Sending {length} characters of text: '{text}'",
|
||||
text.Length,
|
||||
ComTextHelper.GetDebugText(text));
|
||||
|
||||
TheStream.Write(text);
|
||||
TheStream.Flush();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.LogDebug("Client is null or disconnected. Cannot Send Text");
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
/// <summary>
|
||||
/// Sends text to the server
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public void SendText(string text)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LogError("ObjectDisposedException sending '{message}'. Restarting connection...", text.Trim());
|
||||
if (Client != null && TheStream != null && IsConnected)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
this.LogInformation(
|
||||
"Sending {length} characters of text: '{text}'",
|
||||
text.Length,
|
||||
ComTextHelper.GetDebugText(text));
|
||||
|
||||
TheStream.Write(text);
|
||||
TheStream.Flush();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.LogDebug("Client is null or disconnected. Cannot Send Text");
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
this.LogError("ObjectDisposedException sending '{message}'. Restarting connection...", text.Trim());
|
||||
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
ReconnectTimer.Reset();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ReconnectTimer.Stop();
|
||||
ReconnectTimer.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex, "Exception sending text: '{message}'", text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends Bytes to the server
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Client != null && TheStream != null && IsConnected)
|
||||
@@ -535,57 +537,57 @@ public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoR
|
||||
this.LogException(ex, "ObjectDisposedException sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||
|
||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||
ReconnectTimer.Reset();
|
||||
ReconnectTimer.Stop();
|
||||
ReconnectTimer.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogException(ex, "Exception sending {message}", ComTextHelper.GetEscapedText(bytes));
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
//*****************************************************************************************************
|
||||
//*****************************************************************************************************
|
||||
/// <summary>
|
||||
/// Fired when connection changes
|
||||
/// </summary>
|
||||
public class SshConnectionChangeEventArgs : EventArgs
|
||||
{
|
||||
//*****************************************************************************************************
|
||||
//*****************************************************************************************************
|
||||
/// <summary>
|
||||
/// Connection State
|
||||
/// Fired when connection changes
|
||||
/// </summary>
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Connection Status represented as a ushort
|
||||
/// </summary>
|
||||
public ushort UIsConnected { get { return (ushort)(Client.IsConnected ? 1 : 0); } }
|
||||
|
||||
/// <summary>
|
||||
/// The client
|
||||
/// </summary>
|
||||
public GenericSshClient Client { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Socket Status as represented by
|
||||
/// </summary>
|
||||
public ushort Status { get { return Client.UStatus; } }
|
||||
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public SshConnectionChangeEventArgs() { }
|
||||
|
||||
/// <summary>
|
||||
/// EventArgs class
|
||||
/// </summary>
|
||||
/// <param name="isConnected">Connection State</param>
|
||||
/// <param name="client">The Client</param>
|
||||
public SshConnectionChangeEventArgs(bool isConnected, GenericSshClient client)
|
||||
public class SshConnectionChangeEventArgs : EventArgs
|
||||
{
|
||||
IsConnected = isConnected;
|
||||
Client = client;
|
||||
/// <summary>
|
||||
/// Connection State
|
||||
/// </summary>
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Connection Status represented as a ushort
|
||||
/// </summary>
|
||||
public ushort UIsConnected { get { return (ushort)(Client.IsConnected ? 1 : 0); } }
|
||||
|
||||
/// <summary>
|
||||
/// The client
|
||||
/// </summary>
|
||||
public GenericSshClient Client { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Socket Status as represented by
|
||||
/// </summary>
|
||||
public ushort Status { get { return Client.UStatus; } }
|
||||
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public SshConnectionChangeEventArgs() { }
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,24 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using Timer = System.Timers.Timer;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using Newtonsoft.Json;
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
using Required = NewtonsoftJson::Newtonsoft.Json.Required;
|
||||
using PepperDash.Core.Logging;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// A class to handle basic TCP/IP communications with a server
|
||||
/// </summary>
|
||||
public class GenericTcpIpClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
||||
public class GenericTcpIpClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
||||
{
|
||||
private const string SplusKey = "Uninitialized TcpIpClient";
|
||||
/// <summary>
|
||||
@@ -19,44 +26,44 @@ namespace PepperDash.Core;
|
||||
/// </summary>
|
||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Fires when data is received from the server and returns it as a Byte array
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
/// <summary>
|
||||
/// Fires when data is received from the server and returns it as a Byte array
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Fires when data is received from the server and returns it as text
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
/// <summary>
|
||||
/// Fires when data is received from the server and returns it as text
|
||||
/// </summary>
|
||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
|
||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
|
||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||
|
||||
|
||||
private string _hostname;
|
||||
private string _hostname;
|
||||
|
||||
/// <summary>
|
||||
/// Address of server
|
||||
/// </summary>
|
||||
public string Hostname
|
||||
{
|
||||
get
|
||||
{
|
||||
return _hostname;
|
||||
}
|
||||
get
|
||||
{
|
||||
return _hostname;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
_hostname = value;
|
||||
if (_client != null)
|
||||
{
|
||||
_client.AddressClientConnectedTo = _hostname;
|
||||
}
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
_hostname = value;
|
||||
if (_client != null)
|
||||
{
|
||||
_client.AddressClientConnectedTo = _hostname;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port on server
|
||||
@@ -78,19 +85,19 @@ namespace PepperDash.Core;
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The actual client class
|
||||
/// </summary>
|
||||
private TCPClient _client;
|
||||
/// <summary>
|
||||
/// The actual client class
|
||||
/// </summary>
|
||||
private TCPClient _client;
|
||||
|
||||
/// <summary>
|
||||
/// Bool showing if socket is connected
|
||||
/// </summary>
|
||||
public bool IsConnected
|
||||
{
|
||||
get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
/// <summary>
|
||||
/// 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>
|
||||
@@ -99,15 +106,15 @@ namespace PepperDash.Core;
|
||||
get { return (ushort)(IsConnected ? 1 : 0); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// _client socket status Read only
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus
|
||||
{
|
||||
get
|
||||
/// <summary>
|
||||
/// _client socket status Read only
|
||||
/// </summary>
|
||||
public SocketStatus ClientStatus
|
||||
{
|
||||
get
|
||||
{
|
||||
return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
|
||||
}
|
||||
return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -119,26 +126,20 @@ namespace PepperDash.Core;
|
||||
get { return (ushort)ClientStatus; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <summary>
|
||||
/// Status text shows the message associated with socket status
|
||||
/// </summary>
|
||||
public string ClientStatusText { get { return ClientStatus.ToString(); } }
|
||||
/// </summary>
|
||||
public string ClientStatusText { get { return ClientStatus.ToString(); } }
|
||||
|
||||
/// <summary>
|
||||
/// Ushort representation of client status
|
||||
/// </summary>
|
||||
[Obsolete]
|
||||
public ushort UClientStatus { get { return (ushort)ClientStatus; } }
|
||||
/// <summary>
|
||||
/// Connection failure reason
|
||||
/// </summary>
|
||||
public string ConnectionFailure { get { return ClientStatus.ToString(); } }
|
||||
|
||||
/// <summary>
|
||||
/// Connection failure reason
|
||||
/// </summary>
|
||||
public string ConnectionFailure { get { return ClientStatus.ToString(); } }
|
||||
|
||||
/// <summary>
|
||||
/// bool to track if auto reconnect should be set on the socket
|
||||
/// </summary>
|
||||
public bool AutoReconnect { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the AutoReconnect
|
||||
/// </summary>
|
||||
public bool AutoReconnect { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// S+ helper for AutoReconnect
|
||||
@@ -149,29 +150,29 @@ namespace PepperDash.Core;
|
||||
set { AutoReconnect = value == 1; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Milliseconds to wait before attempting to reconnect. Defaults to 5000
|
||||
/// </summary>
|
||||
public int AutoReconnectIntervalMs { get; set; }
|
||||
/// <summary>
|
||||
/// Milliseconds to wait before attempting to reconnect. Defaults to 5000
|
||||
/// </summary>
|
||||
public int AutoReconnectIntervalMs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Set only when the disconnect method is called
|
||||
/// </summary>
|
||||
bool DisconnectCalledByUser;
|
||||
/// <summary>
|
||||
/// Set only when the disconnect method is called
|
||||
/// </summary>
|
||||
bool DisconnectCalledByUser;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool Connected
|
||||
{
|
||||
get { return _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public bool Connected
|
||||
{
|
||||
get { return _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
||||
}
|
||||
|
||||
//Lock object to prevent simulatneous connect/disconnect operations
|
||||
private CCriticalSection connectLock = new CCriticalSection();
|
||||
private readonly object _connectLock = new();
|
||||
|
||||
// private Timer for auto reconnect
|
||||
private CTimer RetryTimer;
|
||||
private Timer RetryTimer;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
@@ -180,9 +181,9 @@ namespace PepperDash.Core;
|
||||
/// <param name="address"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="bufferSize"></param>
|
||||
public GenericTcpIpClient(string key, string address, int port, int bufferSize)
|
||||
: base(key)
|
||||
{
|
||||
public GenericTcpIpClient(string key, string address, int port, int bufferSize)
|
||||
: base(key)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
@@ -190,10 +191,7 @@ namespace PepperDash.Core;
|
||||
Port = port;
|
||||
BufferSize = bufferSize;
|
||||
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
SetupRetryTimer();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -208,28 +206,30 @@ namespace PepperDash.Core;
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
BufferSize = 2000;
|
||||
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
SetupRetryTimer();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor for S+
|
||||
/// </summary>
|
||||
public GenericTcpIpClient()
|
||||
: base(SplusKey)
|
||||
: base(SplusKey)
|
||||
{
|
||||
StreamDebugging = new CommunicationStreamDebugging(SplusKey);
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
BufferSize = 2000;
|
||||
|
||||
RetryTimer = new CTimer(o =>
|
||||
{
|
||||
Reconnect();
|
||||
}, Timeout.Infinite);
|
||||
}
|
||||
SetupRetryTimer();
|
||||
}
|
||||
|
||||
private void SetupRetryTimer()
|
||||
{
|
||||
RetryTimer = new Timer { AutoReset = false, Enabled = false };
|
||||
RetryTimer.Elapsed += (s, e) => Reconnect();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Just to help S+ set the key
|
||||
@@ -246,7 +246,7 @@ namespace PepperDash.Core;
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
Debug.Console(1, this, "Program stopping. Closing connection");
|
||||
this.LogInformation("Program stopping. Closing connection");
|
||||
Deactivate();
|
||||
}
|
||||
}
|
||||
@@ -255,42 +255,41 @@ namespace PepperDash.Core;
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override bool Deactivate()
|
||||
{
|
||||
public override bool Deactivate()
|
||||
{
|
||||
RetryTimer.Stop();
|
||||
RetryTimer.Dispose();
|
||||
if (_client != null)
|
||||
{
|
||||
_client.SocketStatusChange -= this.Client_SocketStatusChange;
|
||||
_client.SocketStatusChange -= this.Client_SocketStatusChange;
|
||||
DisconnectClient();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to connect to the server
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
public void Connect()
|
||||
{
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': No address set", Key);
|
||||
this.LogWarning("GenericTcpIpClient '{0}': No address set", Key);
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': Invalid port", Key);
|
||||
this.LogWarning("GenericTcpIpClient '{0}': Invalid port", Key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
lock (_connectLock)
|
||||
{
|
||||
connectLock.Enter();
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(1, this, "Connection already connected. Exiting Connect()");
|
||||
this.LogInformation("Connection already connected. Exiting Connect()");
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -303,11 +302,7 @@ namespace PepperDash.Core;
|
||||
_client.ConnectToServerAsync(ConnectToServerCallback);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Reconnect()
|
||||
{
|
||||
@@ -315,44 +310,34 @@ namespace PepperDash.Core;
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
lock (_connectLock)
|
||||
{
|
||||
connectLock.Enter();
|
||||
if (IsConnected || DisconnectCalledByUser == true)
|
||||
{
|
||||
Debug.Console(1, this, "Reconnect no longer needed. Exiting Reconnect()");
|
||||
this.LogInformation("Reconnect no longer needed. Exiting Reconnect()");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Attempting reconnect now");
|
||||
this.LogInformation("Attempting reconnect now");
|
||||
_client.ConnectToServerAsync(ConnectToServerCallback);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to disconnect the client
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
try
|
||||
public void Disconnect()
|
||||
{
|
||||
lock (_connectLock)
|
||||
{
|
||||
connectLock.Enter();
|
||||
DisconnectCalledByUser = true;
|
||||
|
||||
// Stop trying reconnects, if we are
|
||||
RetryTimer.Stop();
|
||||
DisconnectClient();
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Does the actual disconnect business
|
||||
@@ -361,7 +346,7 @@ namespace PepperDash.Core;
|
||||
{
|
||||
if (_client != null)
|
||||
{
|
||||
Debug.Console(1, this, "Disconnecting client");
|
||||
this.LogInformation("Disconnecting client");
|
||||
if (IsConnected)
|
||||
_client.DisconnectFromServer();
|
||||
}
|
||||
@@ -371,50 +356,47 @@ namespace PepperDash.Core;
|
||||
/// Callback method for connection attempt
|
||||
/// </summary>
|
||||
/// <param name="c"></param>
|
||||
void ConnectToServerCallback(TCPClient c)
|
||||
{
|
||||
void ConnectToServerCallback(TCPClient c)
|
||||
{
|
||||
if (c.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(0, this, "Server connection result: {0}", c.ClientStatus);
|
||||
this.LogInformation("Server connection result: {0}", c.ClientStatus);
|
||||
WaitAndTryReconnect();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Server connection result: {0}", c.ClientStatus);
|
||||
this.LogInformation("Server connection result: {0}", c.ClientStatus);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnects, waits and attemtps to connect again
|
||||
/// </summary>
|
||||
void WaitAndTryReconnect()
|
||||
{
|
||||
CrestronInvoke.BeginInvoke(o =>
|
||||
void WaitAndTryReconnect()
|
||||
{
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
lock (_connectLock)
|
||||
{
|
||||
connectLock.Enter();
|
||||
if (!IsConnected && AutoReconnect && !DisconnectCalledByUser && _client != null)
|
||||
{
|
||||
DisconnectClient();
|
||||
Debug.Console(1, this, "Attempting reconnect, status={0}", _client.ClientStatus);
|
||||
RetryTimer.Reset(AutoReconnectIntervalMs);
|
||||
this.LogInformation("Attempting reconnect, status={0}", _client.ClientStatus);
|
||||
RetryTimer.Stop();
|
||||
RetryTimer.Interval = AutoReconnectIntervalMs;
|
||||
RetryTimer.Start();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectLock.Leave();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recieves incoming data
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="numBytes"></param>
|
||||
void Receive(TCPClient client, int numBytes)
|
||||
{
|
||||
void Receive(TCPClient client, int numBytes)
|
||||
{
|
||||
if (client != null)
|
||||
{
|
||||
if (numBytes > 0)
|
||||
@@ -425,7 +407,7 @@ namespace PepperDash.Core;
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
this.LogInformation("Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
}
|
||||
@@ -436,129 +418,135 @@ namespace PepperDash.Core;
|
||||
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
this.LogInformation("Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
}
|
||||
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
|
||||
}
|
||||
}
|
||||
}
|
||||
client.ReceiveDataAsync(Receive);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// General send method
|
||||
/// </summary>
|
||||
public void SendText(string text)
|
||||
{
|
||||
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
|
||||
// Check debug level before processing byte array
|
||||
/// <summary>
|
||||
/// General send method
|
||||
/// </summary>
|
||||
public void SendText(string text)
|
||||
{
|
||||
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));
|
||||
this.LogInformation("Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
||||
if (_client != null)
|
||||
_client.SendData(bytes, bytes.Length);
|
||||
}
|
||||
_client.SendData(bytes, bytes.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is useful from console and...?
|
||||
/// </summary>
|
||||
public void SendEscapedText(string text)
|
||||
{
|
||||
var unescapedText = Regex.Replace(text, @"\\x([0-9a-fA-F][0-9a-fA-F])", s =>
|
||||
{
|
||||
var hex = s.Groups[1].Value;
|
||||
return ((char)Convert.ToByte(hex, 16)).ToString();
|
||||
});
|
||||
SendText(unescapedText);
|
||||
}
|
||||
/// <summary>
|
||||
/// SendEscapedText method
|
||||
/// </summary>
|
||||
public void SendEscapedText(string text)
|
||||
{
|
||||
var unescapedText = Regex.Replace(text, @"\\x([0-9a-fA-F][0-9a-fA-F])", s =>
|
||||
{
|
||||
var hex = s.Groups[1].Value;
|
||||
return ((char)Convert.ToByte(hex, 16)).ToString();
|
||||
});
|
||||
SendText(unescapedText);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends Bytes to the server
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
this.LogInformation("Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
if (_client != null)
|
||||
_client.SendData(bytes, bytes.Length);
|
||||
}
|
||||
_client.SendData(bytes, bytes.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Socket Status Change Handler
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="clientSocketStatus"></param>
|
||||
void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus)
|
||||
{
|
||||
void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus)
|
||||
{
|
||||
if (clientSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(0, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
this.LogDebug("Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
WaitAndTryReconnect();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
_client.ReceiveDataAsync(Receive);
|
||||
this.LogDebug("Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
|
||||
_client.ReceiveDataAsync(Receive);
|
||||
}
|
||||
|
||||
var handler = ConnectionChange;
|
||||
if (handler != null)
|
||||
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
|
||||
}
|
||||
}
|
||||
var handler = ConnectionChange;
|
||||
if (handler != null)
|
||||
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configuration properties for TCP/SSH Connections
|
||||
/// </summary>
|
||||
public class TcpSshPropertiesConfig
|
||||
{
|
||||
public class TcpSshPropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// Address to connect to
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Address { get; set; }
|
||||
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Address { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Port to connect to
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public int Port { get; set; }
|
||||
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public int Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Username credential
|
||||
/// </summary>
|
||||
public string Username { get; set; }
|
||||
public string Username { get; set; }
|
||||
/// <summary>
|
||||
/// Passord credential
|
||||
/// </summary>
|
||||
public string Password { get; set; }
|
||||
public string Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to 32768
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
/// <summary>
|
||||
/// Defaults to 32768
|
||||
/// </summary>
|
||||
public int BufferSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to true
|
||||
/// </summary>
|
||||
public bool AutoReconnect { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the AutoReconnect
|
||||
/// </summary>
|
||||
public bool AutoReconnect { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defaults to 5000ms
|
||||
/// </summary>
|
||||
public int AutoReconnectIntervalMs { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the AutoReconnectIntervalMs
|
||||
/// </summary>
|
||||
public int AutoReconnectIntervalMs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// When true, turns off echo for the SSH session
|
||||
/// </summary>
|
||||
[JsonProperty("disableSshEcho")]
|
||||
public bool DisableSshEcho { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor
|
||||
/// </summary>
|
||||
public TcpSshPropertiesConfig()
|
||||
{
|
||||
BufferSize = 32768;
|
||||
AutoReconnect = true;
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
public TcpSshPropertiesConfig()
|
||||
{
|
||||
BufferSize = 32768;
|
||||
AutoReconnect = true;
|
||||
AutoReconnectIntervalMs = 5000;
|
||||
Username = "";
|
||||
Password = "";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,9 @@ PepperDash Technology Corporation reserves all rights under applicable laws.
|
||||
------------------------------------ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Timers;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using PepperDash.Core.Logging;
|
||||
@@ -210,7 +209,7 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
/// <summary>
|
||||
/// private Timer for auto reconnect
|
||||
/// </summary>
|
||||
CTimer RetryTimer;
|
||||
Timer RetryTimer;
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -237,13 +236,13 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
/// </summary>
|
||||
public int HeartbeatInterval = 50000;
|
||||
|
||||
CTimer HeartbeatSendTimer;
|
||||
CTimer HeartbeatAckTimer;
|
||||
Timer HeartbeatSendTimer;
|
||||
Timer HeartbeatAckTimer;
|
||||
/// <summary>
|
||||
/// Used to force disconnection on a dead connect attempt
|
||||
/// </summary>
|
||||
CTimer ConnectFailTimer;
|
||||
CTimer WaitForSharedKey;
|
||||
Timer ConnectFailTimer;
|
||||
Timer WaitForSharedKey;
|
||||
private int ConnectionCount;
|
||||
/// <summary>
|
||||
/// Internal secure client
|
||||
@@ -303,7 +302,7 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping || programEventType == eProgramStatusEventType.Paused)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Program stopping. Closing Client connection");
|
||||
this.LogInformation("Program stopping. Closing Client connection");
|
||||
ProgramIsStopping = true;
|
||||
Disconnect();
|
||||
}
|
||||
@@ -316,17 +315,17 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
public void Connect()
|
||||
{
|
||||
ConnectionCount++;
|
||||
Debug.Console(2, this, "Attempting connect Count:{0}", ConnectionCount);
|
||||
this.LogDebug("Attempting connect Count:{0}", ConnectionCount);
|
||||
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already connected. Ignoring.");
|
||||
this.LogInformation("Already connected. Ignoring.");
|
||||
return;
|
||||
}
|
||||
if (IsTryingToConnect)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already trying to connect. Ignoring.");
|
||||
this.LogInformation("Already trying to connect. Ignoring.");
|
||||
return;
|
||||
}
|
||||
try
|
||||
@@ -339,17 +338,17 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No address set");
|
||||
this.LogWarning("DynamicTcpClient: No address set");
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: Invalid port");
|
||||
this.LogWarning("DynamicTcpClient: Invalid port");
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No Shared Key set");
|
||||
this.LogWarning("DynamicTcpClient: No Shared Key set");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -370,9 +369,10 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
//var timeOfConnect = DateTime.Now.ToString("HH:mm:ss.fff");
|
||||
|
||||
ConnectFailTimer = new CTimer(o =>
|
||||
ConnectFailTimer = new Timer(30000) { AutoReset = false };
|
||||
ConnectFailTimer.Elapsed += (s, e) =>
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Connect attempt has not finished after 30sec Count:{0}", ConnectionCount);
|
||||
this.LogError("Connect attempt has not finished after 30sec Count:{0}", ConnectionCount);
|
||||
if (IsTryingToConnect)
|
||||
{
|
||||
IsTryingToConnect = false;
|
||||
@@ -384,12 +384,13 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
//SecureClient.DisconnectFromServer();
|
||||
//CheckClosedAndTryReconnect();
|
||||
}
|
||||
}, 30000);
|
||||
};
|
||||
ConnectFailTimer.Start();
|
||||
|
||||
Debug.Console(2, this, "Making Connection Count:{0}", ConnectionCount);
|
||||
this.LogDebug("Making Connection Count:{0}", ConnectionCount);
|
||||
Client.ConnectToServerAsync(o =>
|
||||
{
|
||||
Debug.Console(2, this, "ConnectToServerAsync Count:{0} Ran!", ConnectionCount);
|
||||
this.LogDebug("ConnectToServerAsync Count:{0} Ran!", ConnectionCount);
|
||||
|
||||
if (ConnectFailTimer != null)
|
||||
{
|
||||
@@ -399,22 +400,22 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
if (o.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
Debug.Console(2, this, "Client connected to {0} on port {1}", o.AddressClientConnectedTo, o.LocalPortNumberOfClient);
|
||||
this.LogVerbose("Client connected to {0} on port {1}", o.AddressClientConnectedTo, o.LocalPortNumberOfClient);
|
||||
o.ReceiveDataAsync(Receive);
|
||||
|
||||
if (SharedKeyRequired)
|
||||
{
|
||||
WaitingForSharedKeyResponse = true;
|
||||
WaitForSharedKey = new CTimer(timer =>
|
||||
WaitForSharedKey = new Timer(15000) { AutoReset = false };
|
||||
WaitForSharedKey.Elapsed += (s, e) =>
|
||||
{
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Shared key exchange timer expired. IsReadyForCommunication={0}", IsReadyForCommunication);
|
||||
// Debug.Console(1, this, "Connect attempt failed {0}", c.ClientStatus);
|
||||
this.LogWarning("Shared key exchange timer expired. IsReadyForCommunication={0}", IsReadyForCommunication);
|
||||
// This is the only case where we should call DisconectFromServer...Event handeler will trigger the cleanup
|
||||
o.DisconnectFromServer();
|
||||
//CheckClosedAndTryReconnect();
|
||||
//OnClientReadyForcommunications(false); // Should send false event
|
||||
}, 15000);
|
||||
};
|
||||
WaitForSharedKey.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -428,14 +429,15 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Connect attempt failed {0}", o.ClientStatus);
|
||||
this.LogWarning("Connect attempt failed {0}", o.ClientStatus);
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Client connection exception: {0}", ex.Message);
|
||||
this.LogException(ex, "Client connection exception: {0}", ex.Message);
|
||||
this.LogVerbose("Stack Trace: {0}", ex.StackTrace);
|
||||
IsTryingToConnect = false;
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
@@ -472,7 +474,7 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
if (Client != null)
|
||||
{
|
||||
//SecureClient.DisconnectFromServer();
|
||||
Debug.Console(2, this, "Disconnecting Client {0}", DisconnectCalledByUser ? ", Called by user" : "");
|
||||
this.LogVerbose("Disconnecting Client {0}", DisconnectCalledByUser ? ", Called by user" : "");
|
||||
Client.SocketStatusChange -= Client_SocketStatusChange;
|
||||
Client.Dispose();
|
||||
Client = null;
|
||||
@@ -494,20 +496,22 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
if (Client != null)
|
||||
{
|
||||
Debug.Console(2, this, "Cleaning up remotely closed/failed connection.");
|
||||
this.LogVerbose("Cleaning up remotely closed/failed connection.");
|
||||
Cleanup();
|
||||
}
|
||||
if (!DisconnectCalledByUser && AutoReconnect)
|
||||
{
|
||||
var halfInterval = AutoReconnectIntervalMs / 2;
|
||||
var rndTime = new Random().Next(-halfInterval, halfInterval) + AutoReconnectIntervalMs;
|
||||
Debug.Console(2, this, "Attempting reconnect in {0} ms, randomized", rndTime);
|
||||
this.LogVerbose("Attempting reconnect in {0} ms, randomized", rndTime);
|
||||
if (RetryTimer != null)
|
||||
{
|
||||
RetryTimer.Stop();
|
||||
RetryTimer = null;
|
||||
}
|
||||
RetryTimer = new CTimer(o => Connect(), rndTime);
|
||||
RetryTimer = new Timer(rndTime) { AutoReset = false };
|
||||
RetryTimer.Elapsed += (s, e) => Connect();
|
||||
RetryTimer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,18 +530,18 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray();
|
||||
str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
||||
Debug.Console(2, this, "Client Received:\r--------\r{0}\r--------", str);
|
||||
this.LogVerbose("Client Received:\r--------\r{0}\r--------", str);
|
||||
if (!string.IsNullOrEmpty(checkHeartbeat(str)))
|
||||
{
|
||||
if (SharedKeyRequired && str == "SharedKey:")
|
||||
{
|
||||
Debug.Console(2, this, "Server asking for shared key, sending");
|
||||
this.LogVerbose("Server asking for shared key, sending");
|
||||
SendText(SharedKey + "\n");
|
||||
}
|
||||
else if (SharedKeyRequired && str == "Shared Key Match")
|
||||
{
|
||||
StopWaitForSharedKeyTimer();
|
||||
Debug.Console(2, this, "Shared key confirmed. Ready for communication");
|
||||
this.LogVerbose("Shared key confirmed. Ready for communication");
|
||||
OnClientReadyForcommunications(true); // Successful key exchange
|
||||
}
|
||||
else
|
||||
@@ -553,7 +557,8 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error receiving data: {1}. Error: {0}", ex.Message, str);
|
||||
this.LogException(ex, "Error receiving data: {1}. Error: {0}", ex.Message, str);
|
||||
this.LogVerbose("Stack Trace: {0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
@@ -564,15 +569,19 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
if (HeartbeatEnabled)
|
||||
{
|
||||
Debug.Console(2, this, "Starting Heartbeat");
|
||||
this.LogVerbose("Starting Heartbeat");
|
||||
if (HeartbeatSendTimer == null)
|
||||
{
|
||||
|
||||
HeartbeatSendTimer = new CTimer(this.SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
|
||||
HeartbeatSendTimer = new Timer(HeartbeatInterval) { AutoReset = true };
|
||||
HeartbeatSendTimer.Elapsed += (s, e) => SendHeartbeat(null);
|
||||
HeartbeatSendTimer.Start();
|
||||
}
|
||||
if (HeartbeatAckTimer == null)
|
||||
{
|
||||
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
|
||||
HeartbeatAckTimer = new Timer(HeartbeatInterval * 2) { AutoReset = true };
|
||||
HeartbeatAckTimer.Elapsed += (s, e) => HeartbeatAckTimerFail(null);
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -582,13 +591,13 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
if (HeartbeatSendTimer != null)
|
||||
{
|
||||
Debug.Console(2, this, "Stoping Heartbeat Send");
|
||||
this.LogVerbose("Stoping Heartbeat Send");
|
||||
HeartbeatSendTimer.Stop();
|
||||
HeartbeatSendTimer = null;
|
||||
}
|
||||
if (HeartbeatAckTimer != null)
|
||||
{
|
||||
Debug.Console(2, this, "Stoping Heartbeat Ack");
|
||||
this.LogVerbose("Stoping Heartbeat Ack");
|
||||
HeartbeatAckTimer.Stop();
|
||||
HeartbeatAckTimer = null;
|
||||
}
|
||||
@@ -597,7 +606,7 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
void SendHeartbeat(object notused)
|
||||
{
|
||||
this.SendText(HeartbeatString);
|
||||
Debug.Console(2, this, "Sending Heartbeat");
|
||||
this.LogVerbose("Sending Heartbeat");
|
||||
|
||||
}
|
||||
|
||||
@@ -616,13 +625,17 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
{
|
||||
if (HeartbeatAckTimer != null)
|
||||
{
|
||||
HeartbeatAckTimer.Reset(HeartbeatInterval * 2);
|
||||
HeartbeatAckTimer.Stop();
|
||||
HeartbeatAckTimer.Interval = HeartbeatInterval * 2;
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
|
||||
HeartbeatAckTimer = new Timer(HeartbeatInterval * 2) { AutoReset = true };
|
||||
HeartbeatAckTimer.Elapsed += (s, e) => HeartbeatAckTimerFail(null);
|
||||
HeartbeatAckTimer.Start();
|
||||
}
|
||||
Debug.Console(2, this, "Heartbeat Received: {0}, from Server", HeartbeatString);
|
||||
this.LogVerbose("Heartbeat Received: {0}, from Server", HeartbeatString);
|
||||
return remainingText;
|
||||
}
|
||||
}
|
||||
@@ -630,7 +643,8 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error checking heartbeat: {0}", ex.Message);
|
||||
this.LogException(ex, "Error checking heartbeat: {0}", ex.Message);
|
||||
this.LogVerbose("Stack Trace: {0}", ex.StackTrace);
|
||||
}
|
||||
return received;
|
||||
}
|
||||
@@ -644,7 +658,7 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Heartbeat not received from Server...DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE");
|
||||
this.LogWarning("Heartbeat not received from Server...DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE");
|
||||
SendText("Heartbeat not received by server, closing connection");
|
||||
CheckClosedAndTryReconnect();
|
||||
}
|
||||
@@ -652,7 +666,8 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorLog.Error("Heartbeat timeout Error on Client: {0}, {1}", Key, ex);
|
||||
this.LogException(ex, "Heartbeat timeout Error on Client: {0}, {1}", Key, ex.Message);
|
||||
this.LogVerbose("Stack Trace: {0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -685,14 +700,15 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
// HOW IN THE HELL DO WE CATCH AN EXCEPTION IN SENDING?????
|
||||
if (n <= 0)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", this.Key);
|
||||
this.LogWarning("[{0}] Sent zero bytes. Was there an error?", this.Key);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, "Error sending text: {1}. Error: {0}", ex.Message, text);
|
||||
this.LogException(ex, "Error sending text: {1}. Error: {0}", ex.Message, text);
|
||||
this.LogVerbose("Stack Trace: {0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -711,7 +727,8 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, this, "Error sending bytes. Error: {0}", ex.Message);
|
||||
this.LogException(ex, "Error sending bytes. Error: {0}", ex.Message);
|
||||
this.LogVerbose("Stack Trace: {0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -730,7 +747,7 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
try
|
||||
{
|
||||
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
|
||||
this.LogVerbose("Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
|
||||
|
||||
OnConnectionChange();
|
||||
|
||||
@@ -744,7 +761,8 @@ public class GenericTcpIpClient_ForServer : Device, IAutoReconnect
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error in socket status change callback. Error: {0}\r\r{1}", ex, ex.InnerException);
|
||||
this.LogException(ex, "Error in socket status change callback. Error: {0}", ex.Message);
|
||||
this.LogVerbose("Stack Trace: {0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Timers;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using PepperDash.Core.Logging;
|
||||
@@ -61,9 +62,14 @@ public class GenericTcpIpServer : Device
|
||||
#region Properties/Variables
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Server listen lock
|
||||
/// </summary>
|
||||
CCriticalSection ServerCCSection = new CCriticalSection();
|
||||
object _serverLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast lock
|
||||
/// </summary>
|
||||
private readonly object _broadcastLock = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -74,7 +80,7 @@ public class GenericTcpIpServer : Device
|
||||
/// <summary>
|
||||
/// Timer to operate the bandaid monitor client in a loop.
|
||||
/// </summary>
|
||||
CTimer MonitorClientTimer;
|
||||
Timer MonitorClientTimer;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
@@ -244,7 +250,7 @@ public class GenericTcpIpServer : Device
|
||||
public string HeartbeatStringToMatch { get; set; }
|
||||
|
||||
//private timers for Heartbeats per client
|
||||
Dictionary<uint, CTimer> HeartbeatTimerDictionary = new Dictionary<uint, CTimer>();
|
||||
Dictionary<uint, Timer> HeartbeatTimerDictionary = new Dictionary<uint, Timer>();
|
||||
|
||||
//flags to show the secure server is waiting for client at index to send the shared key
|
||||
List<uint> WaitingForSharedKey = new List<uint>();
|
||||
@@ -365,12 +371,12 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
else
|
||||
{
|
||||
ErrorLog.Error("Could not initialize server with key: {0}", serverConfigObject.Key);
|
||||
this.LogError("Could not initialize server with key: {0}", serverConfigObject.Key);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
ErrorLog.Error("Could not initialize server with key: {0}", serverConfigObject.Key);
|
||||
this.LogError("Could not initialize server with key: {0}", serverConfigObject.Key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,19 +385,18 @@ public class GenericTcpIpServer : Device
|
||||
/// </summary>
|
||||
public void Listen()
|
||||
{
|
||||
ServerCCSection.Enter();
|
||||
lock (_serverLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': Invalid port", Key);
|
||||
ErrorLog.Warn(string.Format("Server '{0}': Invalid port", Key));
|
||||
this.LogError("Server '{0}': Invalid port", Key);
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': No Shared Key set", Key);
|
||||
ErrorLog.Warn(string.Format("Server '{0}': No Shared Key set", Key));
|
||||
this.LogError("Server '{0}': No Shared Key set", Key);
|
||||
return;
|
||||
}
|
||||
if (IsListening)
|
||||
@@ -417,18 +422,15 @@ public class GenericTcpIpServer : Device
|
||||
ServerStopped = false;
|
||||
myTcpServer.WaitForConnectionAsync(IPAddress.Any, TcpConnectCallback);
|
||||
OnServerStateChange(myTcpServer.State);
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "TCP Server Status: {0}, Socket Status: {1}", myTcpServer.State, myTcpServer.ServerSocketStatus);
|
||||
this.LogInformation("TCP Server Status: {0}, Socket Status: {1}", myTcpServer.State, myTcpServer.ServerSocketStatus);
|
||||
|
||||
// StartMonitorClient();
|
||||
|
||||
|
||||
ServerCCSection.Leave();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ServerCCSection.Leave();
|
||||
ErrorLog.Error("{1} Error with Dynamic Server: {0}", ex.ToString(), Key);
|
||||
this.LogException(ex, "Error with Dynamic Server: {0}", ex.Message);
|
||||
}
|
||||
} // end lock
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -438,18 +440,18 @@ public class GenericTcpIpServer : Device
|
||||
{
|
||||
try
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Stopping Listener");
|
||||
this.LogDebug("Stopping Listener");
|
||||
if (myTcpServer != null)
|
||||
{
|
||||
myTcpServer.Stop();
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server State: {0}", myTcpServer.State);
|
||||
this.LogDebug("Server State: {0}", myTcpServer.State);
|
||||
OnServerStateChange(myTcpServer.State);
|
||||
}
|
||||
ServerStopped = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error stopping server. Error: {0}", ex);
|
||||
this.LogException(ex, "Error stopping server. Error: {0}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,11 +464,11 @@ public class GenericTcpIpServer : Device
|
||||
try
|
||||
{
|
||||
myTcpServer.Disconnect(client);
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected client index: {0}", client);
|
||||
this.LogVerbose("Disconnected client index: {0}", client);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Disconnecting client index: {0}. Error: {1}", client, ex);
|
||||
this.LogException(ex, "Error Disconnecting client index: {0}. Error: {1}", client, ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -474,7 +476,7 @@ public class GenericTcpIpServer : Device
|
||||
/// </summary>
|
||||
public void DisconnectAllClientsForShutdown()
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Disconnecting All Clients");
|
||||
this.LogInformation("Disconnecting All Clients");
|
||||
if (myTcpServer != null)
|
||||
{
|
||||
myTcpServer.SocketStatusChange -= TcpServer_SocketStatusChange;
|
||||
@@ -486,17 +488,17 @@ public class GenericTcpIpServer : Device
|
||||
try
|
||||
{
|
||||
myTcpServer.Disconnect(i);
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected client index: {0}", i);
|
||||
this.LogVerbose("Disconnected client index: {0}", i);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Disconnecting client index: {0}. Error: {1}", i, ex);
|
||||
this.LogException(ex, "Error Disconnecting client index: {0}. Error: {1}", i, ex.Message);
|
||||
}
|
||||
}
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server Status: {0}", myTcpServer.ServerSocketStatus);
|
||||
this.LogVerbose("Server Status: {0}", myTcpServer.ServerSocketStatus);
|
||||
}
|
||||
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected All Clients");
|
||||
this.LogInformation("Disconnected All Clients");
|
||||
ConnectedClientsIndexes.Clear();
|
||||
|
||||
if (!ProgramIsStopping)
|
||||
@@ -514,8 +516,8 @@ public class GenericTcpIpServer : Device
|
||||
/// <param name="text"></param>
|
||||
public void BroadcastText(string text)
|
||||
{
|
||||
CCriticalSection CCBroadcast = new CCriticalSection();
|
||||
CCBroadcast.Enter();
|
||||
lock (_broadcastLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (ConnectedClientsIndexes.Count > 0)
|
||||
@@ -531,13 +533,12 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
}
|
||||
}
|
||||
CCBroadcast.Leave();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CCBroadcast.Leave();
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Broadcasting messages from server. Error: {0}", ex.Message);
|
||||
this.LogException(ex, "Error Broadcasting messages from server. Error: {0}", ex.Message);
|
||||
}
|
||||
} // end lock
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -558,7 +559,7 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, "Error sending text to client. Text: {1}. Error: {0}", ex.Message, text);
|
||||
this.LogException(ex, "Error sending text to client. Text: {1}. Error: {0}", ex.Message, text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -576,13 +577,19 @@ public class GenericTcpIpServer : Device
|
||||
if (noDelimiter.Contains(HeartbeatStringToMatch))
|
||||
{
|
||||
if (HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
HeartbeatTimerDictionary[clientIndex].Reset(HeartbeatRequiredIntervalMs);
|
||||
{
|
||||
HeartbeatTimerDictionary[clientIndex].Stop();
|
||||
HeartbeatTimerDictionary[clientIndex].Interval = HeartbeatRequiredIntervalMs;
|
||||
HeartbeatTimerDictionary[clientIndex].Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
CTimer HeartbeatTimer = new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs);
|
||||
HeartbeatTimerDictionary.Add(clientIndex, HeartbeatTimer);
|
||||
var heartbeatTimer = new Timer(HeartbeatRequiredIntervalMs) { AutoReset = false };
|
||||
heartbeatTimer.Elapsed += (s, e) => HeartbeatTimer_CallbackFunction(clientIndex);
|
||||
heartbeatTimer.Start();
|
||||
HeartbeatTimerDictionary.Add(clientIndex, heartbeatTimer);
|
||||
}
|
||||
Debug.Console(1, this, "Heartbeat Received: {0}, from client index: {1}", HeartbeatStringToMatch, clientIndex);
|
||||
this.LogVerbose("Heartbeat Received: {0}, from client index: {1}", HeartbeatStringToMatch, clientIndex);
|
||||
// Return Heartbeat
|
||||
SendTextToClient(HeartbeatStringToMatch, clientIndex);
|
||||
return remainingText;
|
||||
@@ -591,19 +598,25 @@ public class GenericTcpIpServer : Device
|
||||
else
|
||||
{
|
||||
if (HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
HeartbeatTimerDictionary[clientIndex].Reset(HeartbeatRequiredIntervalMs);
|
||||
{
|
||||
HeartbeatTimerDictionary[clientIndex].Stop();
|
||||
HeartbeatTimerDictionary[clientIndex].Interval = HeartbeatRequiredIntervalMs;
|
||||
HeartbeatTimerDictionary[clientIndex].Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
CTimer HeartbeatTimer = new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs);
|
||||
HeartbeatTimerDictionary.Add(clientIndex, HeartbeatTimer);
|
||||
var heartbeatTimer = new Timer(HeartbeatRequiredIntervalMs) { AutoReset = false };
|
||||
heartbeatTimer.Elapsed += (s, e) => HeartbeatTimer_CallbackFunction(clientIndex);
|
||||
heartbeatTimer.Start();
|
||||
HeartbeatTimerDictionary.Add(clientIndex, heartbeatTimer);
|
||||
}
|
||||
Debug.Console(1, this, "Heartbeat Received: {0}, from client index: {1}", received, clientIndex);
|
||||
this.LogVerbose("Heartbeat Received: {0}, from client index: {1}", received, clientIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(1, this, "Error checking heartbeat: {0}", ex.Message);
|
||||
this.LogException(ex, "Error checking heartbeat: {0}", ex.Message);
|
||||
}
|
||||
return received;
|
||||
}
|
||||
@@ -615,11 +628,11 @@ public class GenericTcpIpServer : Device
|
||||
/// <returns>IP address of the client</returns>
|
||||
public string GetClientIPAddress(uint clientIndex)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress Index: {0}", clientIndex);
|
||||
this.LogVerbose("GetClientIPAddress Index: {0}", clientIndex);
|
||||
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex)))
|
||||
{
|
||||
var ipa = this.myTcpServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress IPAddreess: {0}", ipa);
|
||||
this.LogVerbose("GetClientIPAddress IPAddreess: {0}", ipa);
|
||||
return ipa;
|
||||
|
||||
}
|
||||
@@ -642,14 +655,13 @@ public class GenericTcpIpServer : Device
|
||||
clientIndex = (uint)o;
|
||||
address = myTcpServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Heartbeat not received for Client index {2} IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE {1}",
|
||||
this.LogWarning("Heartbeat not received for Client index {2} IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE {1}",
|
||||
address, string.IsNullOrEmpty(HeartbeatStringToMatch) ? "" : ("HeartbeatStringToMatch: " + HeartbeatStringToMatch), clientIndex);
|
||||
|
||||
if (myTcpServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
SendTextToClient("Heartbeat not received by server, closing connection", clientIndex);
|
||||
|
||||
var discoResult = myTcpServer.Disconnect(clientIndex);
|
||||
//Debug.Console(1, this, "{0}", discoResult);
|
||||
|
||||
if (HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
{
|
||||
@@ -660,7 +672,8 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorLog.Error("{3}: Heartbeat timeout Error on Client Index: {0}, at address: {1}, error: {2}", clientIndex, address, ex.Message, Key);
|
||||
this.LogException(ex, "Heartbeat timeout Error on Client Index: {0}, at address: {1}, error: {2}", clientIndex, address, ex.Message);
|
||||
this.LogVerbose("Stack Trace:\r{0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -678,7 +691,7 @@ public class GenericTcpIpServer : Device
|
||||
try
|
||||
{
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.myTcpServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.myTcpServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
|
||||
this.LogInformation("SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.myTcpServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.myTcpServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
|
||||
if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
{
|
||||
if (ConnectedClientsIndexes.Contains(clientIndex))
|
||||
@@ -697,7 +710,7 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Change Callback. Error: {0}", ex);
|
||||
this.LogException(ex, "Error in Socket Status Change Callback. Error: {0}", ex);
|
||||
}
|
||||
onConnectionChange(clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex));
|
||||
}
|
||||
@@ -714,7 +727,7 @@ public class GenericTcpIpServer : Device
|
||||
{
|
||||
try
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "ConnectCallback: IPAddress: {0}. Index: {1}. Status: {2}",
|
||||
this.LogDebug("ConnectCallback: IPAddress: {0}. Index: {1}. Status: {2}",
|
||||
server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex),
|
||||
clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex));
|
||||
if (clientIndex != 0)
|
||||
@@ -734,17 +747,21 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
byte[] b = Encoding.GetEncoding(28591).GetBytes("SharedKey:");
|
||||
server.SendDataAsync(clientIndex, b, b.Length, (x, y, z) => { });
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Sent Shared Key Request to client at {0}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
|
||||
this.LogDebug("Sent Shared Key Request to client at {0}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
|
||||
}
|
||||
else
|
||||
{
|
||||
this.LogDebug("Client at index {0} is ready for communications", clientIndex);
|
||||
OnServerClientReadyForCommunications(clientIndex);
|
||||
}
|
||||
if (HeartbeatRequired)
|
||||
{
|
||||
if (!HeartbeatTimerDictionary.ContainsKey(clientIndex))
|
||||
{
|
||||
HeartbeatTimerDictionary.Add(clientIndex, new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs));
|
||||
var heartbeatTimer = new Timer(HeartbeatRequiredIntervalMs) { AutoReset = false };
|
||||
heartbeatTimer.Elapsed += (s, e) => HeartbeatTimer_CallbackFunction(clientIndex);
|
||||
heartbeatTimer.Start();
|
||||
HeartbeatTimerDictionary.Add(clientIndex, heartbeatTimer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -753,7 +770,7 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Client attempt faulty.");
|
||||
this.LogError("Client attempt faulty.");
|
||||
if (!ServerStopped)
|
||||
{
|
||||
server.WaitForConnectionAsync(IPAddress.Any, TcpConnectCallback);
|
||||
@@ -763,15 +780,15 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Connect Callback. Error: {0}", ex);
|
||||
this.LogException(ex, "Error in Socket Status Connect Callback. Error: {0}", ex.Message);
|
||||
this.LogVerbose("Stack Trace:\r{0}", ex.StackTrace);
|
||||
}
|
||||
//Debug.Console(1, this, Debug.ErrorLogLevel, "((((((Server State bitfield={0}; maxclient={1}; ServerStopped={2}))))))",
|
||||
// server.State,
|
||||
// MaxClients,
|
||||
// ServerStopped);
|
||||
if ((server.State & ServerState.SERVER_LISTENING) != ServerState.SERVER_LISTENING && MaxClients > 1 && !ServerStopped)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Waiting for next connection");
|
||||
this.LogDebug("Waiting for next connection");
|
||||
server.WaitForConnectionAsync(IPAddress.Any, TcpConnectCallback);
|
||||
|
||||
}
|
||||
@@ -802,7 +819,7 @@ public class GenericTcpIpServer : Device
|
||||
if (received != SharedKey)
|
||||
{
|
||||
byte[] b = Encoding.GetEncoding(28591).GetBytes("Shared key did not match server. Disconnecting");
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
|
||||
this.LogWarning("Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
|
||||
myTCPServer.SendData(clientIndex, b, b.Length);
|
||||
myTCPServer.Disconnect(clientIndex);
|
||||
return;
|
||||
@@ -812,7 +829,7 @@ public class GenericTcpIpServer : Device
|
||||
byte[] success = Encoding.GetEncoding(28591).GetBytes("Shared Key Match");
|
||||
myTCPServer.SendDataAsync(clientIndex, success, success.Length, null);
|
||||
OnServerClientReadyForCommunications(clientIndex);
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
|
||||
this.LogDebug("Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
|
||||
}
|
||||
|
||||
else if (!string.IsNullOrEmpty(checkHeartbeat(clientIndex, received)))
|
||||
@@ -820,7 +837,7 @@ public class GenericTcpIpServer : Device
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Receiving data: {0}. Error: {1}", received, ex);
|
||||
this.LogException(ex, "Error Receiving data: {0}. Error: {1}", received, ex);
|
||||
}
|
||||
if (myTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
|
||||
myTCPServer.ReceiveDataAsync(clientIndex, TcpServerReceivedDataAsyncCallback);
|
||||
@@ -901,7 +918,7 @@ public class GenericTcpIpServer : Device
|
||||
if (MonitorClient != null)
|
||||
MonitorClient.Disconnect();
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Program stopping. Closing server");
|
||||
this.LogInformation("Program stopping. Closing server");
|
||||
KillServer();
|
||||
}
|
||||
}
|
||||
@@ -927,7 +944,9 @@ public class GenericTcpIpServer : Device
|
||||
{
|
||||
return;
|
||||
}
|
||||
MonitorClientTimer = new CTimer(o => RunMonitorClient(), 60000);
|
||||
MonitorClientTimer = new Timer(60000) { AutoReset = false };
|
||||
MonitorClientTimer.Elapsed += (s, e) => RunMonitorClient();
|
||||
MonitorClientTimer.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -942,7 +961,7 @@ public class GenericTcpIpServer : Device
|
||||
//MonitorClient.ConnectionChange += MonitorClient_ConnectionChange;
|
||||
MonitorClient.ClientReadyForCommunications += MonitorClient_IsReadyForComm;
|
||||
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Starting monitor check");
|
||||
this.LogDebug("Starting monitor check");
|
||||
|
||||
MonitorClient.Connect();
|
||||
// From here MonitorCLient either connects or hangs, MonitorClient will call back
|
||||
@@ -969,7 +988,7 @@ public class GenericTcpIpServer : Device
|
||||
{
|
||||
if (args.IsReady)
|
||||
{
|
||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Monitor client connection success. Disconnecting in 2s");
|
||||
this.LogInformation("Monitor client connection success. Disconnecting in 2s");
|
||||
MonitorClientTimer.Stop();
|
||||
MonitorClientTimer = null;
|
||||
MonitorClientFailureCount = 0;
|
||||
@@ -990,13 +1009,13 @@ public class GenericTcpIpServer : Device
|
||||
StopMonitorClient();
|
||||
if (MonitorClientFailureCount < MonitorClientMaxFailureCount)
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Warning, "Monitor client connection has hung {0} time{1}, maximum {2}",
|
||||
this.LogWarning("Monitor client connection has hung {0} time{1}, maximum {2}",
|
||||
MonitorClientFailureCount, MonitorClientFailureCount > 1 ? "s" : "", MonitorClientMaxFailureCount);
|
||||
StartMonitorClient();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Console(2, this, Debug.ErrorLogLevel.Error,
|
||||
this.LogError(
|
||||
"\r***************************\rMonitor client connection has hung a maximum of {0} times.\r***************************",
|
||||
MonitorClientMaxFailureCount);
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using Newtonsoft.Json;
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
using PepperDash.Core.Logging;
|
||||
using Required = NewtonsoftJson::Newtonsoft.Json.Required;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
@@ -57,7 +60,7 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Represents a GenericUdpReceiveTextExtraArgs
|
||||
/// </summary>
|
||||
public ushort UStatus
|
||||
{
|
||||
@@ -180,7 +183,7 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
if (programEventType != eProgramStatusEventType.Stopping)
|
||||
return;
|
||||
|
||||
Debug.Console(1, this, "Program stopping. Disabling Server");
|
||||
this.LogInformation("Program stopping. Disabling Server");
|
||||
Disconnect();
|
||||
}
|
||||
|
||||
@@ -196,20 +199,20 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
|
||||
if (string.IsNullOrEmpty(Hostname))
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericUdpServer '{0}': No address set", Key);
|
||||
this.LogWarning("GenericUdpServer '{0}': No address set", Key);
|
||||
return;
|
||||
}
|
||||
if (Port < 1 || Port > 65535)
|
||||
{
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericUdpServer '{0}': Invalid port", Key);
|
||||
this.LogWarning("GenericUdpServer '{0}': Invalid port", Key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var status = Server.EnableUDPServer(Hostname, Port);
|
||||
|
||||
Debug.Console(2, this, "SocketErrorCode: {0}", status);
|
||||
this.LogVerbose("SocketErrorCode: {0}", status);
|
||||
if (status == SocketErrorCodes.SOCKET_OK)
|
||||
IsConnected = true;
|
||||
|
||||
@@ -244,7 +247,7 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
/// <param name="numBytes"></param>
|
||||
void Receive(UDPServer server, int numBytes)
|
||||
{
|
||||
Debug.Console(2, this, "Received {0} bytes", numBytes);
|
||||
this.LogVerbose("Received {0} bytes", numBytes);
|
||||
|
||||
try
|
||||
{
|
||||
@@ -260,13 +263,13 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
if (dataRecivedExtra != null)
|
||||
dataRecivedExtra(this, new GenericUdpReceiveTextExtraArgs(str, sourceIp, sourcePort, bytes));
|
||||
|
||||
Debug.Console(2, this, "Bytes: {0}", bytes.ToString());
|
||||
this.LogVerbose("Bytes: {0}", bytes.ToString());
|
||||
var bytesHandler = BytesReceived;
|
||||
if (bytesHandler != null)
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
{
|
||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
this.LogInformation("Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||
}
|
||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||
}
|
||||
@@ -274,7 +277,7 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
if (textHandler != null)
|
||||
{
|
||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
this.LogInformation("Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
|
||||
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
|
||||
}
|
||||
}
|
||||
@@ -299,7 +302,7 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
if (IsConnected && Server != null)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
||||
this.LogVerbose("Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
||||
|
||||
Server.SendData(bytes, bytes.Length);
|
||||
}
|
||||
@@ -312,7 +315,7 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
public void SendBytes(byte[] bytes)
|
||||
{
|
||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
this.LogInformation("Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||
|
||||
if (IsConnected && Server != null)
|
||||
Server.SendData(bytes, bytes.Length);
|
||||
@@ -350,18 +353,18 @@ public class GenericUdpServer : Device, ISocketStatusWithStreamDebugging
|
||||
/// <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;
|
||||
}
|
||||
{
|
||||
Text = text;
|
||||
IpAddress = ipAddress;
|
||||
Port = port;
|
||||
Bytes = bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stupid S+ Constructor
|
||||
/// </summary>
|
||||
public GenericUdpReceiveTextExtraArgs() { }
|
||||
}
|
||||
/// <summary>
|
||||
/// Stupid S+ Constructor
|
||||
/// </summary>
|
||||
public GenericUdpReceiveTextExtraArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
|
||||
69
src/PepperDash.Core/Comm/StreamDebuggingExtensions.cs
Normal file
69
src/PepperDash.Core/Comm/StreamDebuggingExtensions.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Extension methods for stream debugging
|
||||
/// </summary>
|
||||
public static class StreamDebuggingExtensions
|
||||
{
|
||||
private static readonly string app = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance ? $"App {InitialParametersClass.ApplicationNumber}" : $"{InitialParametersClass.RoomId}";
|
||||
|
||||
/// <summary>
|
||||
/// Print the sent bytes to the console
|
||||
/// </summary>
|
||||
/// <param name="comms">comms device</param>
|
||||
/// <param name="bytes">bytes to print</param>
|
||||
public static void PrintSentBytes(this IStreamDebugging comms, byte[] bytes)
|
||||
{
|
||||
if (!comms.StreamDebugging.TxStreamDebuggingIsEnabled) return;
|
||||
|
||||
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
|
||||
CrestronConsole.PrintLine($"[{timestamp}][{app}][{comms.Key}] Sending {bytes.Length} bytes: '{ComTextHelper.GetEscapedText(bytes)}'");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Print the received bytes to the console
|
||||
/// </summary>
|
||||
/// <param name="comms">comms device</param>
|
||||
/// <param name="bytes">bytes to print</param>
|
||||
public static void PrintReceivedBytes(this IStreamDebugging comms, byte[] bytes)
|
||||
{
|
||||
if (!comms.StreamDebugging.RxStreamDebuggingIsEnabled) return;
|
||||
|
||||
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
|
||||
CrestronConsole.PrintLine($"[{timestamp}][{app}][{comms.Key}] Received {bytes.Length} bytes: '{ComTextHelper.GetEscapedText(bytes)}'");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Print the sent text to the console
|
||||
/// </summary>
|
||||
/// <param name="comms">comms device</param>
|
||||
/// <param name="text">text to print</param>
|
||||
public static void PrintSentText(this IStreamDebugging comms, string text)
|
||||
{
|
||||
if (!comms.StreamDebugging.TxStreamDebuggingIsEnabled) return;
|
||||
|
||||
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
|
||||
CrestronConsole.PrintLine($"[{timestamp}][{app}][{comms.Key}] Sending Text: '{ComTextHelper.GetDebugText(text)}'");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Print the received text to the console
|
||||
/// </summary>
|
||||
/// <param name="comms">comms device</param>
|
||||
/// <param name="text">text to print</param>
|
||||
public static void PrintReceivedText(this IStreamDebugging comms, string text)
|
||||
{
|
||||
if (!comms.StreamDebugging.RxStreamDebuggingIsEnabled) return;
|
||||
|
||||
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
|
||||
CrestronConsole.PrintLine($"[{timestamp}][{app}][{comms.Key}] Received Text: '{ComTextHelper.GetDebugText(text)}'");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
|
||||
@@ -74,5 +74,13 @@ public enum eControlMethod
|
||||
/// <summary>
|
||||
/// Secure TCP/IP
|
||||
/// </summary>
|
||||
SecureTcpIp
|
||||
SecureTcpIp,
|
||||
/// <summary>
|
||||
/// Crestron COM bridge
|
||||
/// </summary>
|
||||
ComBridge,
|
||||
/// <summary>
|
||||
/// Crestron Infinet EX device
|
||||
/// </summary>
|
||||
InfinetEx
|
||||
}
|
||||
24
src/PepperDash.Core/Comm/eStreamDebuggingDataTypeSettings.cs
Normal file
24
src/PepperDash.Core/Comm/eStreamDebuggingDataTypeSettings.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
|
||||
namespace PepperDash.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// The available settings for stream debugging data format 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
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronSockets;
|
||||
using System.Text.RegularExpressions;
|
||||
using Newtonsoft.Json;
|
||||
using JsonConverter = NewtonsoftJson::Newtonsoft.Json.JsonConverterAttribute;
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
using StringEnumConverter = NewtonsoftJson::Newtonsoft.Json.Converters.StringEnumConverter;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
@@ -39,7 +43,7 @@ public interface ICommunicationReceiver : IKeyed
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a device that uses basic connection
|
||||
/// Extends <see cref="ICommunicationReceiver"/> with methods for sending text and bytes to a device.
|
||||
/// </summary>
|
||||
public interface IBasicCommunication : ICommunicationReceiver
|
||||
{
|
||||
@@ -54,7 +58,7 @@ public interface IBasicCommunication : ICommunicationReceiver
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
void SendBytes(byte[] bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a device that implements IBasicCommunication and IStreamDebugging
|
||||
@@ -67,7 +71,7 @@ public interface IBasicCommunicationWithStreamDebugging : IBasicCommunication, I
|
||||
/// <summary>
|
||||
/// Represents a device with stream debugging capablities
|
||||
/// </summary>
|
||||
public interface IStreamDebugging
|
||||
public interface IStreamDebugging : IKeyed
|
||||
{
|
||||
/// <summary>
|
||||
/// Object to enable stream debugging
|
||||
@@ -91,7 +95,7 @@ public interface IStreamDebugging
|
||||
/// The current socket status of the client
|
||||
/// </summary>
|
||||
[JsonProperty("clientStatus")]
|
||||
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
SocketStatus ClientStatus { get; }
|
||||
}
|
||||
|
||||
@@ -135,59 +139,60 @@ public interface ISocketStatusWithStreamDebugging : ISocketStatus, IStreamDebugg
|
||||
Disconnected
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This delegate defines handler for IBasicCommunication status changes
|
||||
/// </summary>
|
||||
/// <param name="comm">Device firing the status change</param>
|
||||
/// <param name="status"></param>
|
||||
public delegate void GenericCommMethodStatusHandler(IBasicCommunication comm, eGenericCommMethodStatusChangeType status);
|
||||
/// <summary>
|
||||
/// This delegate defines handler for IBasicCommunication status changes
|
||||
/// </summary>
|
||||
/// <param name="comm">Device firing the status change</param>
|
||||
/// <param name="status"></param>
|
||||
public delegate void GenericCommMethodStatusHandler(IBasicCommunication comm, eGenericCommMethodStatusChangeType status);
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Event args for bytes received from a communication method
|
||||
/// </summary>
|
||||
public class GenericCommMethodReceiveBytesArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// The bytes received
|
||||
/// </summary>
|
||||
public byte[] Bytes { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="bytes"></param>
|
||||
public GenericCommMethodReceiveBytesArgs(byte[] bytes)
|
||||
{
|
||||
Bytes = bytes;
|
||||
}
|
||||
{
|
||||
Bytes = bytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericCommMethodReceiveBytesArgs() { }
|
||||
}
|
||||
/// <summary>
|
||||
/// S+ Constructor
|
||||
/// </summary>
|
||||
public GenericCommMethodReceiveBytesArgs() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Event args for text received
|
||||
/// </summary>
|
||||
public class GenericCommMethodReceiveTextArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// The text received
|
||||
/// </summary>
|
||||
public string Text { get; private set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// The delimiter used to determine the end of a message, if applicable
|
||||
/// </summary>
|
||||
public string Delimiter { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
public GenericCommMethodReceiveTextArgs(string text)
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
@@ -209,7 +214,7 @@ public interface ISocketStatusWithStreamDebugging : ISocketStatus, IStreamDebugg
|
||||
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// Helper class to get escaped text for debugging communication streams
|
||||
/// </summary>
|
||||
public class ComTextHelper
|
||||
{
|
||||
@@ -243,4 +248,4 @@ public interface ISocketStatusWithStreamDebugging : ISocketStatus, IStreamDebugg
|
||||
{
|
||||
return Regex.Replace(text, @"[^\u0020-\u007E]", a => GetEscapedText(a.Value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Formatting = NewtonsoftJson::Newtonsoft.Json.Formatting;
|
||||
using JArray = NewtonsoftJson::Newtonsoft.Json.Linq.JArray;
|
||||
using JObject = NewtonsoftJson::Newtonsoft.Json.Linq.JObject;
|
||||
using JToken = NewtonsoftJson::Newtonsoft.Json.Linq.JToken;
|
||||
using PepperDash.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
@@ -14,35 +18,52 @@ namespace PepperDash.Core.Config;
|
||||
/// </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)
|
||||
const string template = "template";
|
||||
const string system = "system";
|
||||
const string systemUrl = "system_url";
|
||||
const string templateUrl = "template_url";
|
||||
const string info = "info";
|
||||
const string devices = "devices";
|
||||
const string rooms = "rooms";
|
||||
const string sourceLists = "sourceLists";
|
||||
const string destinationLists = "destinationLists";
|
||||
const string cameraLists = "cameraLists";
|
||||
const string audioControlPointLists = "audioControlPointLists";
|
||||
|
||||
const string tieLines = "tieLines";
|
||||
const string joinMaps = "joinMaps";
|
||||
const string global = "global";
|
||||
|
||||
|
||||
/// <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
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Error,
|
||||
Debug.LogError(
|
||||
"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)
|
||||
if(jsonObj[template] != null && jsonObj[system] != null)
|
||||
{
|
||||
// it's a double-config, merge it.
|
||||
var merged = MergeConfigs(jsonObj);
|
||||
if (jsonObj["system_url"] != null)
|
||||
if (jsonObj[systemUrl] != null)
|
||||
{
|
||||
merged["systemUrl"] = jsonObj["system_url"].Value<string>();
|
||||
merged[systemUrl] = (string)jsonObj[systemUrl];
|
||||
}
|
||||
|
||||
if (jsonObj["template_url"] != null)
|
||||
if (jsonObj[templateUrl] != null)
|
||||
{
|
||||
merged["templateUrl"] = jsonObj["template_url"].Value<string>();
|
||||
merged[templateUrl] = (string)jsonObj[templateUrl];
|
||||
}
|
||||
|
||||
jsonObj = merged;
|
||||
@@ -67,6 +88,9 @@ namespace PepperDash.Core.Config;
|
||||
/// </summary>
|
||||
/// <param name="doubleConfig"></param>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// MergeConfigs method
|
||||
/// </summary>
|
||||
public static JObject MergeConfigs(JObject doubleConfig)
|
||||
{
|
||||
var system = JObject.FromObject(doubleConfig["system"]);
|
||||
@@ -74,30 +98,30 @@ namespace PepperDash.Core.Config;
|
||||
var merged = new JObject();
|
||||
|
||||
// Put together top-level objects
|
||||
if (system["info"] != null)
|
||||
merged.Add("info", Merge(template["info"], system["info"], "infO"));
|
||||
if (system[info] != null)
|
||||
merged.Add(info, Merge(template[info], system[info], info));
|
||||
else
|
||||
merged.Add("info", template["info"]);
|
||||
merged.Add(info, template[info]);
|
||||
|
||||
merged.Add("devices", MergeArraysOnTopLevelProperty(template["devices"] as JArray,
|
||||
system["devices"] as JArray, "key", "devices"));
|
||||
merged.Add(devices, MergeArraysOnTopLevelProperty(template[devices] as JArray,
|
||||
system[devices] as JArray, "key", devices));
|
||||
|
||||
if (system["rooms"] == null)
|
||||
merged.Add("rooms", template["rooms"]);
|
||||
if (system[rooms] == null)
|
||||
merged.Add(rooms, template[rooms]);
|
||||
else
|
||||
merged.Add("rooms", MergeArraysOnTopLevelProperty(template["rooms"] as JArray,
|
||||
system["rooms"] as JArray, "key", "rooms"));
|
||||
merged.Add(rooms, MergeArraysOnTopLevelProperty(template[rooms] as JArray,
|
||||
system[rooms] as JArray, "key", rooms));
|
||||
|
||||
if (system["sourceLists"] == null)
|
||||
merged.Add("sourceLists", template["sourceLists"]);
|
||||
if (system[sourceLists] == null)
|
||||
merged.Add(sourceLists, template[sourceLists]);
|
||||
else
|
||||
merged.Add("sourceLists", Merge(template["sourceLists"], system["sourceLists"], "sourceLists"));
|
||||
merged.Add(sourceLists, Merge(template[sourceLists], system[sourceLists], sourceLists));
|
||||
|
||||
if (system["destinationLists"] == null)
|
||||
merged.Add("destinationLists", template["destinationLists"]);
|
||||
if (system[destinationLists] == null)
|
||||
merged.Add(destinationLists, template[destinationLists]);
|
||||
else
|
||||
merged.Add("destinationLists",
|
||||
Merge(template["destinationLists"], system["destinationLists"], "destinationLists"));
|
||||
merged.Add(destinationLists,
|
||||
Merge(template[destinationLists], system[destinationLists], destinationLists));
|
||||
|
||||
|
||||
if (system["cameraLists"] == null)
|
||||
@@ -119,19 +143,18 @@ namespace PepperDash.Core.Config;
|
||||
else if (system["tieLines"] != null)
|
||||
merged.Add("tieLines", system["tieLines"]);
|
||||
else
|
||||
merged.Add("tieLines", new JArray());
|
||||
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"));
|
||||
if (system[global] != null)
|
||||
merged.Add(global, Merge(template[global], system[global], global));
|
||||
else
|
||||
merged.Add("global", template["global"]);
|
||||
merged.Add(global, template[global]);
|
||||
|
||||
//Debug.Console(2, "MERGED CONFIG RESULT: \x0d\x0a{0}", merged);
|
||||
return merged;
|
||||
}
|
||||
|
||||
@@ -225,7 +248,7 @@ namespace PepperDash.Core.Config;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Cannot merge items at path {0}: \r{1}", propPath, e);
|
||||
Debug.LogError($"Cannot merge items at path {propPath}: \r{e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
using Serilog;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
@@ -4,188 +4,191 @@ using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
//*********************************************************************************************************
|
||||
//*********************************************************************************************************
|
||||
/// <summary>
|
||||
/// Represents a Device
|
||||
/// </summary>
|
||||
public class Device : IKeyName
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// The core event and status-bearing class that most if not all device and connectors can derive from.
|
||||
/// Unique Key
|
||||
/// </summary>
|
||||
public class Device : IKeyName
|
||||
public string Key { get; protected set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the Name
|
||||
/// </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; } }
|
||||
|
||||
List<Action> _PreActivationActions;
|
||||
List<Action> _PostActivationActions;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static Device DefaultDevice { get { return _DefaultDevice; } }
|
||||
static Device _DefaultDevice = new Device("Default", "Default");
|
||||
|
||||
/// <summary>
|
||||
/// Base constructor for all Devices.
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
public Device(string key)
|
||||
{
|
||||
Key = key;
|
||||
if (key.Contains(".")) Debug.LogMessage(LogEventLevel.Information, "WARNING: Device key should not include '.'", this);
|
||||
Name = "";
|
||||
}
|
||||
|
||||
/// <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 bool Enabled { get; protected set; }
|
||||
/// <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;
|
||||
}
|
||||
|
||||
///// <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; } }
|
||||
//public Device(DeviceConfig config)
|
||||
// : this(config.Key, config.Name)
|
||||
//{
|
||||
// Config = config;
|
||||
//}
|
||||
|
||||
List<Action> _PreActivationActions;
|
||||
List<Action> _PostActivationActions;
|
||||
/// <summary>
|
||||
/// Adds a pre activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
protected void AddPreActivationAction(Action act)
|
||||
{
|
||||
if (_PreActivationActions == null)
|
||||
_PreActivationActions = new List<Action>();
|
||||
_PreActivationActions.Add(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static Device DefaultDevice { get { return _DefaultDevice; } }
|
||||
static Device _DefaultDevice = new Device("Default", "Default");
|
||||
/// <summary>
|
||||
/// Adds a post activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
/// <summary>
|
||||
/// AddPostActivationAction method
|
||||
/// </summary>
|
||||
protected void AddPostActivationAction(Action act)
|
||||
{
|
||||
if (_PostActivationActions == null)
|
||||
_PostActivationActions = new List<Action>();
|
||||
_PostActivationActions.Add(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base constructor for all Devices.
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
public Device(string key)
|
||||
{
|
||||
Key = key;
|
||||
if (key.Contains(".")) Debug.LogMessage(LogEventLevel.Information, "WARNING: Device key should not include '.'", this);
|
||||
Name = "";
|
||||
}
|
||||
|
||||
/// <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;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a pre activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
public void AddPreActivationAction(Action act)
|
||||
{
|
||||
if (_PreActivationActions == null)
|
||||
_PreActivationActions = new List<Action>();
|
||||
_PreActivationActions.Add(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a post activation action
|
||||
/// </summary>
|
||||
/// <param name="act"></param>
|
||||
public void AddPostActivationAction(Action act)
|
||||
{
|
||||
if (_PostActivationActions == null)
|
||||
_PostActivationActions = new List<Action>();
|
||||
_PostActivationActions.Add(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the preactivation actions
|
||||
/// </summary>
|
||||
public void PreActivate()
|
||||
{
|
||||
if (_PreActivationActions != null)
|
||||
_PreActivationActions.ForEach(a =>
|
||||
/// <summary>
|
||||
/// PreActivate method
|
||||
/// </summary>
|
||||
public void PreActivate()
|
||||
{
|
||||
if (_PreActivationActions != null)
|
||||
_PreActivationActions.ForEach(a =>
|
||||
{
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
a.Invoke();
|
||||
}
|
||||
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()
|
||||
{
|
||||
//if (_PreActivationActions != null)
|
||||
// _PreActivationActions.ForEach(a => a.Invoke());
|
||||
var result = CustomActivate();
|
||||
//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 =>
|
||||
a.Invoke();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
try
|
||||
{
|
||||
a.Invoke();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogMessage(e, "Error in PostActivationAction: " + e.Message, this);
|
||||
}
|
||||
});
|
||||
}
|
||||
Debug.LogMessage(e, "Error in PreActivationAction: " + e.Message, this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called in between Pre and PostActivationActions when Activate() is called.
|
||||
/// Override to provide addtitional setup when calling activation. Overriding classes
|
||||
/// do not need to call base.CustomActivate()
|
||||
/// </summary>
|
||||
/// <returns>true if device activated successfully.</returns>
|
||||
public virtual bool CustomActivate() { return true; }
|
||||
/// <summary>
|
||||
/// Activate method
|
||||
/// </summary>
|
||||
public bool Activate()
|
||||
{
|
||||
//if (_PreActivationActions != null)
|
||||
// _PreActivationActions.ForEach(a => a.Invoke());
|
||||
var result = CustomActivate();
|
||||
//if(result && _PostActivationActions != null)
|
||||
// _PostActivationActions.ForEach(a => a.Invoke());
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call to deactivate device - unlink events, etc. Overriding classes do not
|
||||
/// need to call base.Deactivate()
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual bool Deactivate() { return true; }
|
||||
/// <summary>
|
||||
/// PostActivate method
|
||||
/// </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>
|
||||
/// Call this method to start communications with a device. Overriding classes do not need to call base.Initialize()
|
||||
/// </summary>
|
||||
public virtual void Initialize()
|
||||
{
|
||||
}
|
||||
/// <summary>
|
||||
/// Called in between Pre and PostActivationActions when Activate() is called.
|
||||
/// Override to provide addtitional setup when calling activation. Overriding classes
|
||||
/// do not need to call base.CustomActivate()
|
||||
/// </summary>
|
||||
/// <returns>true if device activated successfully.</returns>
|
||||
/// <summary>
|
||||
/// CustomActivate method
|
||||
/// </summary>
|
||||
protected virtual bool CustomActivate() { return true; }
|
||||
|
||||
/// <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>
|
||||
/// <param name="a">Action to be run when o is false</param>
|
||||
public void OnFalse(object o, Action a)
|
||||
{
|
||||
if (o is bool && !(bool)o) a();
|
||||
}
|
||||
/// <summary>
|
||||
/// Call to deactivate device - unlink events, etc. Overriding classes do not
|
||||
/// need to call base.Deactivate()
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual bool Deactivate() { return true; }
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Call this method to start communications with a device. Overriding classes do not need to call base.Initialize()
|
||||
/// </summary>
|
||||
protected virtual void Initialize()
|
||||
{
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <param name="a">Action to be run when o is false</param>
|
||||
public void OnFalse(object o, Action a)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using Crestron.SimplSharp;
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Class to help with accessing values from the CrestronEthernetHelper class
|
||||
/// Represents an EthernetHelper.
|
||||
/// </summary>
|
||||
public class EthernetHelper
|
||||
{
|
||||
@@ -24,9 +26,9 @@ namespace PepperDash.Core;
|
||||
|
||||
// ADD OTHER HELPERS HERE
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the PortNumber
|
||||
/// </summary>
|
||||
public int PortNumber { get; private set; }
|
||||
|
||||
private EthernetHelper(int portNumber)
|
||||
|
||||
@@ -16,19 +16,19 @@ namespace PepperDash.Core;
|
||||
/// </summary>
|
||||
public bool State { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Boolean ushort value property
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the IntValue
|
||||
/// </summary>
|
||||
public ushort IntValue { get { return (ushort)(State ? 1 : 0); } }
|
||||
|
||||
/// <summary>
|
||||
/// Boolean change event args type
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Type
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Boolean change event args index
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Index
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -64,9 +64,9 @@ namespace PepperDash.Core;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ushort change event args
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Represents a UshrtChangeEventArgs
|
||||
/// </summary>
|
||||
public class UshrtChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
@@ -74,14 +74,14 @@ namespace PepperDash.Core;
|
||||
/// </summary>
|
||||
public ushort IntValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Ushort change event args type
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Type
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Ushort change event args index
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Index
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -117,9 +117,9 @@ namespace PepperDash.Core;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// String change event args
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Represents a StringChangeEventArgs
|
||||
/// </summary>
|
||||
public class StringChangeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
@@ -127,14 +127,14 @@ namespace PepperDash.Core;
|
||||
/// </summary>
|
||||
public string StringValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// String change event args type
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Type
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// string change event args index
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Index
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
|
||||
namespace PepperDash.Core.GenericRESTfulCommunications;
|
||||
|
||||
/// <summary>
|
||||
/// Constants
|
||||
/// </summary>
|
||||
public class GenericRESTfulConstants
|
||||
{
|
||||
/// <summary>
|
||||
/// Generic boolean change
|
||||
/// </summary>
|
||||
public const ushort BoolValueChange = 1;
|
||||
/// <summary>
|
||||
/// Generic Ushort change
|
||||
/// </summary>
|
||||
public const ushort UshrtValueChange = 101;
|
||||
/// <summary>
|
||||
/// Response Code Ushort change
|
||||
/// </summary>
|
||||
public const ushort ResponseCodeChange = 102;
|
||||
/// <summary>
|
||||
/// Generic String chagne
|
||||
/// </summary>
|
||||
public const ushort StringValueChange = 201;
|
||||
/// <summary>
|
||||
/// Response string change
|
||||
/// </summary>
|
||||
public const ushort ResponseStringChange = 202;
|
||||
/// <summary>
|
||||
/// Error string change
|
||||
/// </summary>
|
||||
public const ushort ErrorStringChange = 203;
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.Net.Http;
|
||||
using Crestron.SimplSharp.Net.Https;
|
||||
|
||||
namespace PepperDash.Core.GenericRESTfulCommunications;
|
||||
|
||||
/// <summary>
|
||||
/// Generic RESTful communication class
|
||||
/// </summary>
|
||||
public class 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);
|
||||
}
|
||||
else if (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
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
|
||||
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 = "";
|
||||
|
||||
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 "" ;
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,14 +32,14 @@ namespace PepperDash.Core.JsonStandardObjects;
|
||||
/// </summary>
|
||||
public DeviceConfig Device { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Device change event args type
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Type
|
||||
/// </summary>
|
||||
public ushort Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Device change event args index
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the Index
|
||||
/// </summary>
|
||||
public ushort Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -58,6 +58,9 @@ namespace PepperDash.Core.JsonStandardObjects;
|
||||
/// </summary>
|
||||
/// <param name="uniqueID"></param>
|
||||
/// <param name="deviceKey"></param>
|
||||
/// <summary>
|
||||
/// Initialize method
|
||||
/// </summary>
|
||||
public void Initialize(string uniqueID, string deviceKey)
|
||||
{
|
||||
// S+ set EvaluateFb low
|
||||
|
||||
@@ -47,9 +47,9 @@ namespace PepperDash.Core.JsonStandardObjects;
|
||||
]
|
||||
}
|
||||
*/
|
||||
/// <summary>
|
||||
/// Device communication parameter class
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Represents a ComParamsConfig
|
||||
/// </summary>
|
||||
public class ComParamsConfig
|
||||
{
|
||||
/// <summary>
|
||||
@@ -207,9 +207,9 @@ namespace PepperDash.Core.JsonStandardObjects;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Device properties class
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Represents a PropertiesConfig
|
||||
/// </summary>
|
||||
public class PropertiesConfig
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -122,9 +122,9 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S+ types enum
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Enumeration of SPlusType values
|
||||
/// </summary>
|
||||
public enum SPlusType
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -49,9 +49,9 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a master by its key. Case-insensitive
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// GetMasterByFile method
|
||||
/// </summary>
|
||||
public static JsonToSimplMaster GetMasterByFile(string file)
|
||||
{
|
||||
return Masters.FirstOrDefault(m => m.UniqueID.Equals(file, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using JArray = NewtonsoftJson::Newtonsoft.Json.Linq.JArray;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
@@ -128,7 +130,7 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
var item = array.FirstOrDefault(o =>
|
||||
{
|
||||
var prop = o[SearchPropertyName];
|
||||
return prop != null && prop.Value<string>()
|
||||
return prop != null && ((string)prop)
|
||||
.Equals(SearchPropertyValue, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
if (item == null)
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using PepperDash.Core.Logging;
|
||||
using JValue = NewtonsoftJson::Newtonsoft.Json.Linq.JValue;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
@@ -28,9 +31,9 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
/// </summary>
|
||||
public SPlusValuesDelegate GetAllValuesDelegate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Use a callback to reduce task switch/threading
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the SetAllPathsDelegate
|
||||
/// </summary>
|
||||
public SPlusValuesDelegate SetAllPathsDelegate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -89,7 +92,7 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
if (Master != null)
|
||||
Master.AddChild(this);
|
||||
else
|
||||
Debug.Console(1, "JSON Child [{0}] cannot link to master {1}", key, masterUniqueId);
|
||||
this.LogWarning("JSON Child [{0}] cannot link to master {1}", key, masterUniqueId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -105,46 +108,46 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
/// </summary>
|
||||
public void SetBoolPath(ushort index, string path)
|
||||
{
|
||||
Debug.Console(1, "JSON Child[{0}] SetBoolPath {1}={2}", Key, index, path);
|
||||
this.LogDebug("JSON Child[{0}] SetBoolPath {1}={2}", Key, index, path);
|
||||
if (path == null || path.Trim() == string.Empty) return;
|
||||
BoolPaths[index] = path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set the JPath for a ushort out index.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// SetUshortPath method
|
||||
/// </summary>
|
||||
public void SetUshortPath(ushort index, string path)
|
||||
{
|
||||
Debug.Console(1, "JSON Child[{0}] SetUshortPath {1}={2}", Key, index, path);
|
||||
this.LogDebug("JSON Child[{0}] SetUshortPath {1}={2}", Key, index, path);
|
||||
if (path == null || path.Trim() == string.Empty) return;
|
||||
UshortPaths[index] = path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set the JPath for a string output index.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// SetStringPath method
|
||||
/// </summary>
|
||||
public void SetStringPath(ushort index, string path)
|
||||
{
|
||||
Debug.Console(1, "JSON Child[{0}] SetStringPath {1}={2}", Key, index, path);
|
||||
this.LogDebug("JSON Child[{0}] SetStringPath {1}={2}", Key, index, path);
|
||||
if (path == null || path.Trim() == string.Empty) return;
|
||||
StringPaths[index] = path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evalutates all outputs with defined paths. called by S+ when paths are ready to process
|
||||
/// and by Master when file is read.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// ProcessAll method
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public virtual void ProcessAll()
|
||||
{
|
||||
if (!LinkedToObject)
|
||||
{
|
||||
Debug.Console(1, this, "Not linked to object in file. Skipping");
|
||||
this.LogDebug("Not linked to object in file. Skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
if (SetAllPathsDelegate == null)
|
||||
{
|
||||
Debug.Console(1, this, "No SetAllPathsDelegate set. Ignoring ProcessAll");
|
||||
this.LogDebug("No SetAllPathsDelegate set. Ignoring ProcessAll");
|
||||
return;
|
||||
}
|
||||
SetAllPathsDelegate();
|
||||
@@ -204,11 +207,11 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
bool Process(string path, out string response)
|
||||
{
|
||||
path = GetFullPath(path);
|
||||
Debug.Console(1, "JSON Child[{0}] Processing {1}", Key, path);
|
||||
this.LogDebug("JSON Child[{0}] Processing {1}", Key, path);
|
||||
response = "";
|
||||
if (Master == null)
|
||||
{
|
||||
Debug.Console(1, "JSONChild[{0}] cannot process without Master attached", Key);
|
||||
this.LogWarning("JSONChild[{0}] cannot process without Master attached", Key);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -230,8 +233,8 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
if (isCount)
|
||||
response = (t.HasValues ? t.Children().Count() : 0).ToString();
|
||||
else
|
||||
response = t.Value<string>();
|
||||
Debug.Console(1, " ='{0}'", response);
|
||||
response = (string)t;
|
||||
this.LogDebug(" ='{0}'", response);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -257,13 +260,13 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
{
|
||||
if (!LinkedToObject)
|
||||
{
|
||||
Debug.Console(1, this, "Not linked to object in file. Skipping");
|
||||
this.LogDebug("Not linked to object in file. Skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
if (SetAllPathsDelegate == null)
|
||||
{
|
||||
Debug.Console(1, this, "No SetAllPathsDelegate set. Ignoring UpdateInputsForMaster");
|
||||
this.LogDebug("No SetAllPathsDelegate set. Ignoring UpdateInputsForMaster");
|
||||
return;
|
||||
}
|
||||
SetAllPathsDelegate();
|
||||
@@ -325,7 +328,7 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
var path = GetFullPath(keyPath);
|
||||
try
|
||||
{
|
||||
Debug.Console(1, "JSON Child[{0}] Queueing value on master {1}='{2}'", Key, path, valueToSave);
|
||||
this.LogDebug("JSON Child[{0}] Queueing value on master {1}='{2}'", Key, path, valueToSave);
|
||||
|
||||
//var token = Master.JsonObject.SelectToken(path);
|
||||
//if (token != null) // The path exists in the file
|
||||
@@ -333,7 +336,7 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Console(1, "JSON Child[{0}] Failed setting value for path '{1}'\r{2}", Key, path, e);
|
||||
this.LogDebug("JSON Child[{0}] Failed setting value for path '{1}'\r{2}", Key, path, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using PepperDash.Core.Logging;
|
||||
using Formatting = NewtonsoftJson::Newtonsoft.Json.Formatting;
|
||||
using JObject = NewtonsoftJson::Newtonsoft.Json.Linq.JObject;
|
||||
using JValue = NewtonsoftJson::Newtonsoft.Json.Linq.JValue;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
@@ -125,7 +130,7 @@ public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
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);
|
||||
this.LogInformation("Checking '{0}' for '{1}'", fileDirectory, fileName);
|
||||
|
||||
if (Directory.Exists(fileDirectory))
|
||||
{
|
||||
@@ -139,7 +144,7 @@ public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
var msg = string.Format("JSON file not found: {0}", Filepath);
|
||||
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
this.LogError(msg);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -148,18 +153,18 @@ public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
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);
|
||||
this.LogInformation("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);
|
||||
this.LogInformation("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);
|
||||
this.LogInformation("JSON File Path is {0}", FilePathName);
|
||||
|
||||
var json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);
|
||||
|
||||
@@ -172,7 +177,7 @@ public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
else
|
||||
{
|
||||
OnStringChange(string.Format("'{0}' not found", fileDirectory), 0, JsonToSimplConstants.StringValueChange);
|
||||
Debug.Console(1, "'{0}' not found", fileDirectory);
|
||||
this.LogError("'{0}' not found", fileDirectory);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -180,12 +185,12 @@ public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
var msg = string.Format("EvaluateFile Exception: Message\r{0}", e.Message);
|
||||
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
this.LogException(e, "EvaluateFile Exception: {0}", e.Message);
|
||||
|
||||
var stackTrace = string.Format("EvaluateFile: Stack Trace\r{0}", e.StackTrace);
|
||||
OnStringChange(stackTrace, 0, JsonToSimplConstants.StringValueChange);
|
||||
CrestronConsole.PrintLine(stackTrace);
|
||||
ErrorLog.Error(stackTrace);
|
||||
this.LogVerbose("EvaluateFile: Stack Trace\r{0}", e.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,63 +214,31 @@ public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
// 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);
|
||||
this.LogInformation("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);
|
||||
this.LogInformation("Master [{0}] No updated values to save. Skipping", UniqueID);
|
||||
return;
|
||||
}
|
||||
lock (FileLock)
|
||||
{
|
||||
Debug.Console(1, "Saving");
|
||||
this.LogInformation("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);
|
||||
this.LogInformation("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);
|
||||
this.LogWarning("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))
|
||||
@@ -278,11 +251,13 @@ public class JsonToSimplFileMaster : JsonToSimplMaster
|
||||
catch (Exception e)
|
||||
{
|
||||
string err = string.Format("Error writing JSON file:\r{0}", e);
|
||||
Debug.Console(0, err);
|
||||
ErrorLog.Warn(err);
|
||||
this.LogException(e, "Error writing JSON file: {0}", e.Message);
|
||||
this.LogVerbose("Stack Trace:\r{0}", e.StackTrace);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using PepperDash.Core.Logging;
|
||||
using Renci.SshNet.Messages;
|
||||
using JObject = NewtonsoftJson::Newtonsoft.Json.Linq.JObject;
|
||||
using JValue = NewtonsoftJson::Newtonsoft.Json.Linq.JValue;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
@@ -60,6 +65,9 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
/// Loads JSON into JsonObject, but does not trigger evaluation by children
|
||||
/// </summary>
|
||||
/// <param name="json"></param>
|
||||
/// <summary>
|
||||
/// SetJsonWithoutEvaluating method
|
||||
/// </summary>
|
||||
public void SetJsonWithoutEvaluating(string json)
|
||||
{
|
||||
try
|
||||
@@ -68,13 +76,15 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Console(0, this, "JSON parsing failed:\r{0}", e);
|
||||
this.LogException(e, "JSON parsing failed:\r{0}", e.Message);
|
||||
this.LogVerbose("Stack Trace:\r{0}", e.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Save method
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public override void Save()
|
||||
{
|
||||
// this code is duplicated in the other masters!!!!!!!!!!!!!
|
||||
@@ -82,36 +92,36 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
// Make each child update their values into master object
|
||||
foreach (var child in Children)
|
||||
{
|
||||
Debug.Console(1, this, "Master. checking child [{0}] for updates to save", child.Key);
|
||||
this.LogDebug("Master. checking child [{0}] for updates to save", child.Key);
|
||||
child.UpdateInputsForMaster();
|
||||
}
|
||||
|
||||
if (UnsavedValues == null || UnsavedValues.Count == 0)
|
||||
{
|
||||
Debug.Console(1, this, "Master. No updated values to save. Skipping");
|
||||
this.LogDebug("Master. No updated values to save. Skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
lock (WriteLock)
|
||||
{
|
||||
Debug.Console(1, this, "Saving");
|
||||
this.LogDebug("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, this, "Master Updating '{0}'", path);
|
||||
this.LogDebug("Master Updating '{0}'", path);
|
||||
}
|
||||
else // No token. Let's make one
|
||||
{
|
||||
Debug.Console(1, "Master Cannot write value onto missing property: '{0}'", path);
|
||||
this.LogDebug("Master Cannot write value onto missing property: '{0}'", path);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (SaveCallback != null)
|
||||
SaveCallback(JsonObject.ToString());
|
||||
else
|
||||
Debug.Console(0, this, "WARNING: No save callback defined.");
|
||||
this.LogDebug("WARNING: No save callback defined.");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,16 @@
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using JArray = NewtonsoftJson::Newtonsoft.Json.Linq.JArray;
|
||||
using JObject = NewtonsoftJson::Newtonsoft.Json.Linq.JObject;
|
||||
using JValue = NewtonsoftJson::Newtonsoft.Json.Linq.JValue;
|
||||
using JsonSerializationException = NewtonsoftJson::Newtonsoft.Json.JsonSerializationException;
|
||||
using JsonTextReader = NewtonsoftJson::Newtonsoft.Json.JsonTextReader;
|
||||
using PepperDash.Core.Logging;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
@@ -52,10 +59,9 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
}
|
||||
string _DebugName = "";
|
||||
|
||||
/// <summary>
|
||||
/// This will be prepended to all paths to allow path swapping or for more organized
|
||||
/// sub-paths
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the PathPrefix
|
||||
/// </summary>
|
||||
public string PathPrefix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -119,6 +125,9 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
/// Adds a child "module" to this master
|
||||
/// </summary>
|
||||
/// <param name="child"></param>
|
||||
/// <summary>
|
||||
/// AddChild method
|
||||
/// </summary>
|
||||
public void AddChild(JsonToSimplChildObjectBase child)
|
||||
{
|
||||
if (!Children.Contains(child))
|
||||
@@ -127,18 +136,17 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called from the child to add changed or new values for saving
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// AddUnsavedValue method
|
||||
/// </summary>
|
||||
public void AddUnsavedValue(string path, JValue value)
|
||||
{
|
||||
if (UnsavedValues.ContainsKey(path))
|
||||
{
|
||||
Debug.Console(0, "Master[{0}] WARNING - Attempt to add duplicate value for path '{1}'.\r Ingoring. Please ensure that path does not exist on multiple modules.", UniqueID, path);
|
||||
this.LogWarning("Master[{0}] WARNING - Attempt to add duplicate value for path '{1}'.\r Ingoring. Please ensure that path does not exist on multiple modules.", UniqueID, path);
|
||||
}
|
||||
else
|
||||
UnsavedValues.Add(path, value);
|
||||
//Debug.Console(0, "Master[{0}] Unsaved size={1}", UniqueID, UnsavedValues.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -159,7 +167,7 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
/// <returns></returns>
|
||||
public static JObject ParseObject(string json)
|
||||
{
|
||||
using (var reader = new JsonTextReader(new StringReader(json)))
|
||||
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
|
||||
{
|
||||
var startDepth = reader.Depth;
|
||||
var obj = JObject.Load(reader);
|
||||
@@ -177,7 +185,7 @@ namespace PepperDash.Core.JsonToSimpl;
|
||||
public static JArray ParseArray(string json)
|
||||
{
|
||||
|
||||
using (var reader = new JsonTextReader(new StringReader(json)))
|
||||
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
|
||||
{
|
||||
var startDepth = reader.Depth;
|
||||
var obj = JArray.Load(reader);
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
using System;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using JObject = NewtonsoftJson::Newtonsoft.Json.Linq.JObject;
|
||||
using JValue = NewtonsoftJson::Newtonsoft.Json.Linq.JValue;
|
||||
using PepperDash.Core.Config;
|
||||
using PepperDash.Core.Logging;
|
||||
|
||||
namespace PepperDash.Core.JsonToSimpl;
|
||||
|
||||
@@ -58,7 +62,7 @@ public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
// 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);
|
||||
this.LogInformation("Checking for local file {0}", localFilepath);
|
||||
var actualLocalFile = GetActualFileInfoFromPath(localFilepath);
|
||||
|
||||
if (actualLocalFile != null)
|
||||
@@ -70,7 +74,7 @@ public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
// and create the local.
|
||||
else
|
||||
{
|
||||
Debug.Console(1, this, "Local JSON file not found {0}\rLoading portal JSON file", localFilepath);
|
||||
this.LogInformation("Local JSON file not found {0}\rLoading portal JSON file", localFilepath);
|
||||
var actualPortalFile = GetActualFileInfoFromPath(portalFilepath);
|
||||
if (actualPortalFile != null)
|
||||
{
|
||||
@@ -83,14 +87,13 @@ public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
else
|
||||
{
|
||||
var msg = string.Format("Portal JSON file not found: {0}", PortalFilepath);
|
||||
Debug.Console(1, this, msg);
|
||||
ErrorLog.Error(msg);
|
||||
this.LogError(msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// At this point we should have a local file. Do it.
|
||||
Debug.Console(1, "Reading local JSON file {0}", ActualFilePath);
|
||||
this.LogInformation("Reading local JSON file {0}", ActualFilePath);
|
||||
|
||||
string json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);
|
||||
|
||||
@@ -104,8 +107,7 @@ public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
catch (Exception e)
|
||||
{
|
||||
var msg = string.Format("JSON parsing failed:\r{0}", e);
|
||||
CrestronConsole.PrintLine(msg);
|
||||
ErrorLog.Error(msg);
|
||||
this.LogError(msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -128,6 +130,9 @@ public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
/// <summary>
|
||||
/// setDebugLevel method
|
||||
/// </summary>
|
||||
public void setDebugLevel(uint level)
|
||||
{
|
||||
Debug.SetDebugLevel(level);
|
||||
@@ -143,30 +148,30 @@ public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
// 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);
|
||||
this.LogInformation("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);
|
||||
this.LogInformation("Master [{0}] No updated values to save. Skipping", UniqueID);
|
||||
return;
|
||||
}
|
||||
lock (FileLock)
|
||||
{
|
||||
Debug.Console(1, "Saving");
|
||||
this.LogInformation("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);
|
||||
this.LogInformation("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);
|
||||
this.LogWarning("JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -180,8 +185,8 @@ public class JsonToSimplPortalFileMaster : JsonToSimplMaster
|
||||
catch (Exception e)
|
||||
{
|
||||
string err = string.Format("Error writing JSON file:\r{0}", e);
|
||||
Debug.Console(0, err);
|
||||
ErrorLog.Warn(err);
|
||||
this.LogException(e, "Error writing JSON file: {0}", e.Message);
|
||||
this.LogVerbose("Stack Trace:\r{0}", e.StackTrace);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace PepperDash.Core.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Enriches log events with Crestron-specific context properties, such as the application name based on the device platform.
|
||||
/// </summary>
|
||||
public class CrestronEnricher : ILogEventEnricher
|
||||
{
|
||||
static readonly string _appName;
|
||||
@@ -27,6 +30,11 @@ public class CrestronEnricher : ILogEventEnricher
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Enriches the log event with Crestron-specific properties.
|
||||
/// </summary>
|
||||
/// <param name="logEvent"></param>
|
||||
/// <param name="propertyFactory"></param>
|
||||
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
|
||||
{
|
||||
var property = propertyFactory.CreateProperty("App", _appName);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,280 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Crestron.SimplSharp;
|
||||
using Crestron.SimplSharp.CrestronIO;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a debugging context
|
||||
/// </summary>
|
||||
public class DebugContext
|
||||
{
|
||||
/// <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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
|
||||
|
||||
LoadMemory();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to save memory when shutting down
|
||||
/// </summary>
|
||||
/// <param name="programEventType"></param>
|
||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
||||
{
|
||||
if (programEventType == eProgramStatusEventType.Stopping)
|
||||
{
|
||||
if (SaveTimer != null)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
SetDebugLevel(Convert.ToInt32(levelString));
|
||||
}
|
||||
catch
|
||||
{
|
||||
CrestronConsole.PrintLine("Usage: appdebug:P [0-2]");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class DebugContextSaveData
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int Level { get; set; }
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using Serilog.Events;
|
||||
using System;
|
||||
using System;
|
||||
using Serilog.Events;
|
||||
using Log = PepperDash.Core.Debug;
|
||||
|
||||
namespace PepperDash.Core.Logging;
|
||||
|
||||
@@ -1,62 +1,70 @@
|
||||
using System.Collections.Generic;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using Crestron.SimplSharp;
|
||||
using Newtonsoft.Json;
|
||||
using JsonProperty = NewtonsoftJson::Newtonsoft.Json.JsonPropertyAttribute;
|
||||
|
||||
namespace PepperDash.Core.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Class to persist current Debug settings across program restarts
|
||||
/// </summary>
|
||||
public class DebugContextCollection
|
||||
{
|
||||
public class DebugContextCollection
|
||||
{
|
||||
/// <summary>
|
||||
/// To prevent threading issues with the DeviceDebugSettings collection
|
||||
/// </summary>
|
||||
private readonly CCriticalSection _deviceDebugSettingsLock;
|
||||
private readonly object _deviceDebugSettingsLock = new();
|
||||
|
||||
[JsonProperty("items")] private readonly Dictionary<string, DebugContextItem> _items;
|
||||
[JsonProperty("items")]
|
||||
private readonly Dictionary<string, DebugContextItem> _items = new Dictionary<string, DebugContextItem>();
|
||||
|
||||
/// <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; }
|
||||
private Dictionary<string, object> DeviceDebugSettings { get; set; } = new Dictionary<string, object>();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor
|
||||
/// </summary>
|
||||
public DebugContextCollection()
|
||||
{
|
||||
_deviceDebugSettingsLock = new CCriticalSection();
|
||||
DeviceDebugSettings = new Dictionary<string, object>();
|
||||
_items = new Dictionary<string, DebugContextItem>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Default constructor
|
||||
/// </summary>
|
||||
public DebugContextCollection()
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Sets the level of a given context item, and adds that item if it does not
|
||||
/// exist
|
||||
/// </summary>
|
||||
/// <param name="contextKey"></param>
|
||||
/// <param name="level"></param>
|
||||
public void SetLevel(string contextKey, int level)
|
||||
{
|
||||
if (level < 0 || level > 2)
|
||||
return;
|
||||
GetOrCreateItem(contextKey).Level = level;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a level or creates it if not existing
|
||||
/// </summary>
|
||||
/// <param name="contextKey"></param>
|
||||
/// <returns></returns>
|
||||
public DebugContextItem GetOrCreateItem(string contextKey)
|
||||
{
|
||||
if (!_items.ContainsKey(contextKey))
|
||||
_items[contextKey] = new DebugContextItem { Level = 0 };
|
||||
return _items[contextKey];
|
||||
}
|
||||
/// <summary>
|
||||
/// Sets the level of a given context item, and adds that item if it does not
|
||||
/// exist
|
||||
/// </summary>
|
||||
/// <param name="contextKey"></param>
|
||||
/// <param name="level"></param>
|
||||
/// <summary>
|
||||
/// SetLevel method
|
||||
/// </summary>
|
||||
public void SetLevel(string contextKey, int level)
|
||||
{
|
||||
if (level < 0 || level > 2)
|
||||
return;
|
||||
GetOrCreateItem(contextKey).Level = level;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a level or creates it if not existing
|
||||
/// </summary>
|
||||
/// <param name="contextKey"></param>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// GetOrCreateItem method
|
||||
/// </summary>
|
||||
public DebugContextItem GetOrCreateItem(string contextKey)
|
||||
{
|
||||
if (!_items.ContainsKey(contextKey))
|
||||
_items[contextKey] = new DebugContextItem { Level = 0 };
|
||||
return _items[contextKey];
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -67,10 +75,8 @@ namespace PepperDash.Core.Logging;
|
||||
/// <returns></returns>
|
||||
public void SetDebugSettingsForKey(string deviceKey, object settings)
|
||||
{
|
||||
try
|
||||
lock (_deviceDebugSettingsLock)
|
||||
{
|
||||
_deviceDebugSettingsLock.Enter();
|
||||
|
||||
if (DeviceDebugSettings.ContainsKey(deviceKey))
|
||||
{
|
||||
DeviceDebugSettings[deviceKey] = settings;
|
||||
@@ -78,10 +84,6 @@ namespace PepperDash.Core.Logging;
|
||||
else
|
||||
DeviceDebugSettings.Add(deviceKey, settings);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_deviceDebugSettingsLock.Leave();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -93,22 +95,22 @@ namespace PepperDash.Core.Logging;
|
||||
{
|
||||
return DeviceDebugSettings[deviceKey];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains information about
|
||||
/// </summary>
|
||||
public class DebugContextItem
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains information about
|
||||
/// </summary>
|
||||
public class DebugContextItem
|
||||
{
|
||||
/// <summary>
|
||||
/// The level of debug messages to print
|
||||
/// </summary>
|
||||
[JsonProperty("level")]
|
||||
public int Level { get; set; }
|
||||
[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; }
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,27 @@
|
||||
using Crestron.SimplSharp;
|
||||
using Org.BouncyCastle.Asn1.X509;
|
||||
extern alias NewtonsoftJson;
|
||||
|
||||
using System;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Crestron.SimplSharp;
|
||||
using Serilog;
|
||||
using Serilog.Configuration;
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
using Serilog.Formatting;
|
||||
using JObject = NewtonsoftJson::Newtonsoft.Json.Linq.JObject;
|
||||
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;
|
||||
using WebSocketSharp.Net;
|
||||
|
||||
namespace PepperDash.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Provides a WebSocket-based logging sink for debugging purposes, allowing log events to be broadcast to connected
|
||||
/// WebSocket clients.
|
||||
/// <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
|
||||
@@ -25,25 +29,28 @@ namespace PepperDash.Core;
|
||||
public class DebugWebsocketSink : ILogEventSink, IKeyed
|
||||
{
|
||||
private HttpServer _httpsServer;
|
||||
|
||||
|
||||
private readonly string _path = "/debug/join/";
|
||||
private const string _certificateName = "selfCres";
|
||||
private const string _certificatePassword = "cres12345";
|
||||
private static string CertPath =>
|
||||
$"{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}{_certificateName}.pfx";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the port number on which the HTTPS server is currently running.
|
||||
/// <summary>
|
||||
/// Gets the port number on which the HTTPS server is currently running.
|
||||
/// </summary>
|
||||
public int Port
|
||||
{ get
|
||||
{
|
||||
|
||||
if(_httpsServer == null) return 0;
|
||||
public int Port
|
||||
{
|
||||
get
|
||||
{
|
||||
|
||||
if (_httpsServer == null) return 0;
|
||||
return _httpsServer.Port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the WebSocket URL for the current server instance.
|
||||
/// <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>
|
||||
@@ -51,80 +58,123 @@ public class DebugWebsocketSink : ILogEventSink, IKeyed
|
||||
{
|
||||
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}";
|
||||
if (_httpsServer == null || !_httpsServer.IsListening) return "";
|
||||
var service = _httpsServer.WebSocketServices[_path];
|
||||
if (service == null) return "";
|
||||
return $"wss://{CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0)}:{_httpsServer.Port}{service.Path}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the HTTPS server is currently listening for incoming connections.
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the HTTPS server is currently listening for incoming connections.
|
||||
/// </summary>
|
||||
public bool IsRunning { get => _httpsServer?.IsListening ?? false; }
|
||||
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>
|
||||
/// <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"))
|
||||
if (!File.Exists(CertPath))
|
||||
CreateCert();
|
||||
|
||||
CrestronEnvironment.ProgramStatusEventHandler += type =>
|
||||
try
|
||||
{
|
||||
if (type == eProgramStatusEventType.Stopping)
|
||||
CrestronEnvironment.ProgramStatusEventHandler += type =>
|
||||
{
|
||||
StopServer();
|
||||
}
|
||||
};
|
||||
if (type == eProgramStatusEventType.Stopping)
|
||||
StopServer();
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
// CrestronEnvironment is not available in test / dev environments — safe to skip.
|
||||
}
|
||||
}
|
||||
|
||||
private static void CreateCert()
|
||||
{
|
||||
// NOTE: This method is called from the constructor, which is itself called during Debug's static
|
||||
// constructor before _logger is assigned. Do NOT call any Debug.Log* methods here — use
|
||||
// CrestronConsole.PrintLine only, to avoid a NullReferenceException that would poison the Debug type.
|
||||
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));
|
||||
CrestronConsole.PrintLine(string.Format("CreateCert: 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]);
|
||||
var subjectName = string.Format("CN={0}.{1}", hostName, domainName);
|
||||
var fqdn = string.Format("{0}.{1}", hostName, domainName);
|
||||
|
||||
//Crestron fails to let us do this...perhaps it should be done through their Dll's but haven't tested
|
||||
using var rsa = RSA.Create(2048);
|
||||
|
||||
var request = new CertificateRequest(
|
||||
subjectName,
|
||||
rsa,
|
||||
HashAlgorithmName.SHA256,
|
||||
RSASignaturePadding.Pkcs1);
|
||||
|
||||
// Subject Key Identifier
|
||||
request.CertificateExtensions.Add(
|
||||
new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
|
||||
|
||||
// Extended Key Usage: server + client auth
|
||||
request.CertificateExtensions.Add(
|
||||
new X509EnhancedKeyUsageExtension(
|
||||
new OidCollection
|
||||
{
|
||||
new Oid("1.3.6.1.5.5.7.3.1"), // id-kp-serverAuth
|
||||
new Oid("1.3.6.1.5.5.7.3.2") // id-kp-clientAuth
|
||||
},
|
||||
false));
|
||||
|
||||
// Subject Alternative Names: DNS + IP
|
||||
var sanBuilder = new SubjectAlternativeNameBuilder();
|
||||
sanBuilder.AddDnsName(fqdn);
|
||||
if (System.Net.IPAddress.TryParse(ipAddress, out var ip))
|
||||
sanBuilder.AddIpAddress(ip);
|
||||
request.CertificateExtensions.Add(sanBuilder.Build());
|
||||
|
||||
var notBefore = DateTimeOffset.UtcNow;
|
||||
var notAfter = notBefore.AddYears(2);
|
||||
|
||||
using var cert = request.CreateSelfSigned(notBefore, notAfter);
|
||||
|
||||
var separator = Path.DirectorySeparatorChar;
|
||||
|
||||
utility.CertificatePassword = _certificatePassword;
|
||||
utility.WriteCertificate(certificate, @$"{separator}user{separator}", _certificateName);
|
||||
var outputPath = string.Format("{0}user{1}{2}.pfx", separator, separator, _certificateName);
|
||||
|
||||
var pfxBytes = cert.Export(X509ContentType.Pfx, _certificatePassword);
|
||||
File.WriteAllBytes(outputPath, pfxBytes);
|
||||
|
||||
CrestronConsole.PrintLine(string.Format("CreateCert: Certificate written to {0}", outputPath));
|
||||
}
|
||||
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);
|
||||
CrestronConsole.PrintLine(string.Format("WSS CreateCert Failed: {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>
|
||||
/// <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)
|
||||
{
|
||||
@@ -133,119 +183,170 @@ public class DebugWebsocketSink : ILogEventSink, IKeyed
|
||||
var sw = new StringWriter();
|
||||
_textFormatter.Format(logEvent, sw);
|
||||
|
||||
_httpsServer.WebSocketServices[_path].Sessions.Broadcast(sw.ToString());
|
||||
_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>
|
||||
/// <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);
|
||||
Debug.LogInformation("Starting Websocket Server on port: {0}", port);
|
||||
|
||||
|
||||
Start(port, $"\\user\\{_certificateName}.pfx", _certificatePassword);
|
||||
Start(port, CertPath, _certificatePassword);
|
||||
}
|
||||
|
||||
private static X509Certificate2 LoadOrRecreateCert(string certPath, string certPassword)
|
||||
{
|
||||
try
|
||||
{
|
||||
// EphemeralKeySet is required on Linux/OpenSSL (Crestron 4-series) to avoid
|
||||
// key-container persistence failures, and avoids the private key export restriction.
|
||||
return new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.EphemeralKeySet);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Cert is stale or was generated by an incompatible library (e.g. old BouncyCastle output).
|
||||
// Delete it, regenerate with the BCL path, and retry once.
|
||||
CrestronConsole.PrintLine(string.Format("SSL cert load failed ({0}); regenerating...", ex.Message));
|
||||
try { File.Delete(certPath); } catch { }
|
||||
CreateCert();
|
||||
return new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.EphemeralKeySet);
|
||||
}
|
||||
}
|
||||
|
||||
private void Start(int port, string certPath = "", string certPassword = "")
|
||||
{
|
||||
try
|
||||
{
|
||||
_httpsServer = new HttpServer(port, true);
|
||||
_httpsServer = new HttpServer(port, true);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(certPath))
|
||||
{
|
||||
Debug.Console(0, "Assigning SSL Configuration");
|
||||
Debug.LogInformation("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.ServerCertificate = LoadOrRecreateCert(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");
|
||||
Debug.LogInformation("HTTPS ClientCerticateValidation Callback triggered");
|
||||
return true;
|
||||
};
|
||||
};
|
||||
}
|
||||
Debug.Console(0, "Adding Debug Client Service");
|
||||
Debug.LogInformation("Adding Debug Client Service");
|
||||
_httpsServer.AddWebSocketService<DebugClient>(_path);
|
||||
Debug.Console(0, "Assigning Log Info");
|
||||
Debug.LogInformation("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.Log.Output = WriteWebSocketInternalLog;
|
||||
Debug.LogInformation("Starting");
|
||||
|
||||
_httpsServer.Start();
|
||||
Debug.Console(0, "Ready");
|
||||
Debug.LogInformation("Ready");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Console(0, "WebSocket Failed to start {0}", ex.Message);
|
||||
Debug.LogError(ex, "WebSocket Failed to start {0}", ex.Message);
|
||||
Debug.LogVerbose("Stack Trace:\r{0}", ex.StackTrace);
|
||||
// Null out the server so callers can detect failure via IsRunning / Url null guards.
|
||||
_httpsServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the WebSocket server if it is currently running.
|
||||
/// <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()
|
||||
{
|
||||
Debug.Console(0, "Stopping Websocket Server");
|
||||
_httpsServer?.Stop();
|
||||
Debug.LogInformation("Stopping Websocket Server");
|
||||
|
||||
_httpsServer = null;
|
||||
try
|
||||
{
|
||||
if (_httpsServer == null || !_httpsServer.IsListening)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Prevent close-sequence internal websocket logs from re-entering the logging pipeline.
|
||||
_httpsServer.Log.Output = (d, s) => { };
|
||||
|
||||
var serviceHost = _httpsServer.WebSocketServices[_path];
|
||||
|
||||
if (serviceHost == null)
|
||||
{
|
||||
_httpsServer.Stop();
|
||||
_httpsServer = null;
|
||||
return;
|
||||
}
|
||||
|
||||
serviceHost.Sessions.Broadcast("Server is stopping");
|
||||
|
||||
foreach (var session in serviceHost.Sessions.Sessions)
|
||||
{
|
||||
if (session?.Context?.WebSocket != null && session.Context.WebSocket.IsAlive)
|
||||
{
|
||||
session.Context.WebSocket.Close(1001, "Server is stopping");
|
||||
}
|
||||
}
|
||||
|
||||
_httpsServer.Stop();
|
||||
|
||||
_httpsServer = null;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError(ex, "WebSocket Failed to stop gracefully {0}", ex.Message);
|
||||
Debug.LogVerbose("Stack Trace\r\n{0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteWebSocketInternalLog(LogData data, string supplemental)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var message = string.IsNullOrWhiteSpace(data.Message) ? "<none>" : data.Message;
|
||||
var details = string.IsNullOrWhiteSpace(supplemental) ? string.Empty : string.Format(" | details: {0}", supplemental);
|
||||
|
||||
// Use direct console output to avoid recursive log sink calls.
|
||||
CrestronConsole.PrintLine(string.Format("WS[{0}] {1} | message: {2}{3}", data.Level, data.Date, message, details));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Never throw from websocket log callback.
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the logger to write log events to a debug WebSocket sink.
|
||||
/// <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>
|
||||
/// <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,
|
||||
@@ -255,9 +356,9 @@ public static class DebugWebsocketSinkExtensions
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a WebSocket client for debugging purposes, providing connection lifecycle management and message
|
||||
/// handling functionality.
|
||||
/// <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
|
||||
@@ -266,8 +367,8 @@ public class DebugClient : WebSocketBehavior
|
||||
{
|
||||
private DateTime _connectionTime;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of time the WebSocket connection has been active.
|
||||
/// <summary>
|
||||
/// Gets the duration of time the WebSocket connection has been active.
|
||||
/// </summary>
|
||||
public TimeSpan ConnectedDuration
|
||||
{
|
||||
@@ -284,14 +385,12 @@ public class DebugClient : WebSocketBehavior
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DebugClient"/> class.
|
||||
/// <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");
|
||||
Debug.LogInformation("DebugClient Created");
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -300,7 +399,7 @@ public class DebugClient : WebSocketBehavior
|
||||
base.OnOpen();
|
||||
|
||||
var url = Context.WebSocket.Url;
|
||||
Debug.Console(0, Debug.ErrorLogLevel.Notice, "New WebSocket Connection from: {0}", url);
|
||||
Debug.LogInformation("New WebSocket Connection from: {0}", url);
|
||||
|
||||
_connectionTime = DateTime.Now;
|
||||
}
|
||||
@@ -310,7 +409,7 @@ public class DebugClient : WebSocketBehavior
|
||||
{
|
||||
base.OnMessage(e);
|
||||
|
||||
Debug.Console(0, "WebSocket UiClient Message: {0}", e.Data);
|
||||
Debug.LogVerbose("WebSocket UiClient Message: {0}", e.Data);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -318,8 +417,7 @@ public class DebugClient : WebSocketBehavior
|
||||
{
|
||||
base.OnClose(e);
|
||||
|
||||
Debug.Console(0, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Closing: {0} reason: {1}", e.Code, e.Reason);
|
||||
|
||||
Debug.LogDebug("WebSocket UiClient Closing: {0} reason: {1}", e.Code, e.Reason);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -327,6 +425,7 @@ public class DebugClient : WebSocketBehavior
|
||||
{
|
||||
base.OnError(e);
|
||||
|
||||
Debug.Console(2, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Error: {0} message: {1}", e.Exception, e.Message);
|
||||
Debug.LogError(e.Exception, "WebSocket UiClient Error: {0} message: {1}", e.Exception, e.Message);
|
||||
Debug.LogVerbose("Stack Trace:\r{0}", e.Exception.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,9 @@ namespace PepperDash.Core.PasswordManagement;
|
||||
/// Retrieve password by index
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <summary>
|
||||
/// GetPasswordByIndex method
|
||||
/// </summary>
|
||||
public void GetPasswordByIndex(ushort key)
|
||||
{
|
||||
OnUshrtChange((ushort)PasswordManager.Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
|
||||
@@ -81,6 +84,9 @@ namespace PepperDash.Core.PasswordManagement;
|
||||
/// Password validation method
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <summary>
|
||||
/// ValidatePassword method
|
||||
/// </summary>
|
||||
public void ValidatePassword(string password)
|
||||
{
|
||||
if (string.IsNullOrEmpty(password))
|
||||
@@ -99,6 +105,9 @@ namespace PepperDash.Core.PasswordManagement;
|
||||
/// password against the selected password when the length of the 2 are equal
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <summary>
|
||||
/// BuildPassword method
|
||||
/// </summary>
|
||||
public void BuildPassword(string data)
|
||||
{
|
||||
PasswordToValidate = String.Concat(PasswordToValidate, data);
|
||||
@@ -108,9 +117,9 @@ namespace PepperDash.Core.PasswordManagement;
|
||||
ValidatePassword(PasswordToValidate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the user entered password and resets the LEDs
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// ClearPassword method
|
||||
/// </summary>
|
||||
public void ClearPassword()
|
||||
{
|
||||
PasswordToValidate = "";
|
||||
|
||||
@@ -1,240 +1,252 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Crestron.SimplSharp;
|
||||
using System.Timers;
|
||||
|
||||
namespace PepperDash.Core.PasswordManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Allows passwords to be stored and managed
|
||||
/// </summary>
|
||||
public class PasswordManager
|
||||
public class PasswordManager
|
||||
{
|
||||
/// <summary>
|
||||
/// Public dictionary of known passwords
|
||||
/// </summary>
|
||||
public static Dictionary<uint, string> Passwords = new Dictionary<uint, string>();
|
||||
/// <summary>
|
||||
/// Private dictionary, used when passwords are updated
|
||||
/// </summary>
|
||||
private Dictionary<uint, string> _passwords = new Dictionary<uint, string>();
|
||||
|
||||
/// <summary>
|
||||
/// Timer used to wait until password changes have stopped before updating the dictionary
|
||||
/// </summary>
|
||||
Timer PasswordTimer;
|
||||
/// <summary>
|
||||
/// Timer length
|
||||
/// </summary>
|
||||
public long PasswordTimerElapsedMs = 5000;
|
||||
|
||||
/// <summary>
|
||||
/// Boolean event
|
||||
/// </summary>
|
||||
public event EventHandler<BoolChangeEventArgs> BoolChange;
|
||||
/// <summary>
|
||||
/// Ushort event
|
||||
/// </summary>
|
||||
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
|
||||
/// <summary>
|
||||
/// String event
|
||||
/// </summary>
|
||||
public event EventHandler<StringChangeEventArgs> StringChange;
|
||||
/// <summary>
|
||||
/// Event to notify clients of an updated password at the specified index (uint)
|
||||
/// </summary>
|
||||
public static event EventHandler<StringChangeEventArgs> PasswordChange;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public PasswordManager()
|
||||
{
|
||||
/// <summary>
|
||||
/// Public dictionary of known passwords
|
||||
/// </summary>
|
||||
public static Dictionary<uint, string> Passwords = new Dictionary<uint, string>();
|
||||
/// <summary>
|
||||
/// Private dictionary, used when passwords are updated
|
||||
/// </summary>
|
||||
private Dictionary<uint, string> _passwords = new Dictionary<uint, string>();
|
||||
|
||||
/// <summary>
|
||||
/// Timer used to wait until password changes have stopped before updating the dictionary
|
||||
/// </summary>
|
||||
CTimer PasswordTimer;
|
||||
/// <summary>
|
||||
/// Timer length
|
||||
/// </summary>
|
||||
public long PasswordTimerElapsedMs = 5000;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Boolean event
|
||||
/// </summary>
|
||||
public event EventHandler<BoolChangeEventArgs> BoolChange;
|
||||
/// <summary>
|
||||
/// Ushort event
|
||||
/// </summary>
|
||||
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
|
||||
/// <summary>
|
||||
/// String event
|
||||
/// </summary>
|
||||
public event EventHandler<StringChangeEventArgs> StringChange;
|
||||
/// <summary>
|
||||
/// Event to notify clients of an updated password at the specified index (uint)
|
||||
/// </summary>
|
||||
public static event EventHandler<StringChangeEventArgs> PasswordChange;
|
||||
/// <summary>
|
||||
/// Initialize password manager
|
||||
/// </summary>
|
||||
public void Initialize()
|
||||
{
|
||||
if (Passwords == null)
|
||||
Passwords = new Dictionary<uint, string>();
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public PasswordManager()
|
||||
if (_passwords == null)
|
||||
_passwords = new Dictionary<uint, string>();
|
||||
|
||||
OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates password stored in the dictonary
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <summary>
|
||||
/// UpdatePassword method
|
||||
/// </summary>
|
||||
public void UpdatePassword(ushort key, string password)
|
||||
{
|
||||
// validate the parameters
|
||||
if (key > 0 && string.IsNullOrEmpty(password))
|
||||
{
|
||||
|
||||
Debug.LogDebug("PasswordManager.UpdatePassword: key [{0}] or password are not valid", key, password);
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize password manager
|
||||
/// </summary>
|
||||
public void Initialize()
|
||||
try
|
||||
{
|
||||
if (Passwords == null)
|
||||
Passwords = new Dictionary<uint, string>();
|
||||
// if key exists, update the value
|
||||
if (_passwords.ContainsKey(key))
|
||||
_passwords[key] = password;
|
||||
// else add the key & value
|
||||
else
|
||||
_passwords.Add(key, password);
|
||||
|
||||
if (_passwords == null)
|
||||
_passwords = new Dictionary<uint, string>();
|
||||
Debug.LogDebug("PasswordManager.UpdatePassword: _password[{0}] = {1}", key, _passwords[key]);
|
||||
|
||||
OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates password stored in the dictonary
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="password"></param>
|
||||
public void UpdatePassword(ushort key, string password)
|
||||
{
|
||||
// validate the parameters
|
||||
if (key > 0 && string.IsNullOrEmpty(password))
|
||||
if (PasswordTimer == null)
|
||||
{
|
||||
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: key [{0}] or password are not valid", key, password));
|
||||
return;
|
||||
PasswordTimer = new Timer(PasswordTimerElapsedMs) { AutoReset = false };
|
||||
PasswordTimer.Elapsed += (s, e) => PasswordTimerElapsed(s, e);
|
||||
PasswordTimer.Start();
|
||||
Debug.LogDebug("PasswordManager.UpdatePassword: Timer Started");
|
||||
OnBoolChange(true, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// if key exists, update the value
|
||||
if(_passwords.ContainsKey(key))
|
||||
_passwords[key] = password;
|
||||
// else add the key & value
|
||||
else
|
||||
_passwords.Add(key, password);
|
||||
|
||||
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: _password[{0}] = {1}", key, _passwords[key]));
|
||||
|
||||
if (PasswordTimer == null)
|
||||
{
|
||||
PasswordTimer = new CTimer((o) => PasswordTimerElapsed(), PasswordTimerElapsedMs);
|
||||
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Started"));
|
||||
OnBoolChange(true, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
|
||||
}
|
||||
else
|
||||
{
|
||||
PasswordTimer.Reset(PasswordTimerElapsedMs);
|
||||
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Reset"));
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var msg = string.Format("PasswordManager.UpdatePassword key-value[{0}, {1}] failed:\r{2}", key, password, e);
|
||||
Debug.Console(1, msg);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CTimer callback function
|
||||
/// </summary>
|
||||
private void PasswordTimerElapsed()
|
||||
{
|
||||
try
|
||||
else
|
||||
{
|
||||
PasswordTimer.Stop();
|
||||
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: CTimer Stopped"));
|
||||
OnBoolChange(false, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
|
||||
foreach (var pw in _passwords)
|
||||
PasswordTimer.Interval = PasswordTimerElapsedMs;
|
||||
PasswordTimer.Start();
|
||||
Debug.LogDebug("PasswordManager.UpdatePassword: Timer Reset");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var msg = string.Format("PasswordManager.UpdatePassword key-value[{0}, {1}] failed:\r{2}", key, password, e);
|
||||
Debug.LogError(e, msg);
|
||||
Debug.LogVerbose("Stack Trace:\r{0}", e.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Timer callback function
|
||||
/// </summary>
|
||||
private void PasswordTimerElapsed(object sender, ElapsedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
PasswordTimer.Stop();
|
||||
Debug.LogDebug("PasswordManager.PasswordTimerElapsed: Timer Stopped");
|
||||
OnBoolChange(false, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
|
||||
foreach (var pw in _passwords)
|
||||
{
|
||||
// if key exists, continue
|
||||
if (Passwords.ContainsKey(pw.Key))
|
||||
{
|
||||
// if key exists, continue
|
||||
if (Passwords.ContainsKey(pw.Key))
|
||||
Debug.LogDebug("PasswordManager.PasswordTimerElapsed: pw.key[{0}] = {1}", pw.Key, pw.Value);
|
||||
if (Passwords[pw.Key] != _passwords[pw.Key])
|
||||
{
|
||||
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: pw.key[{0}] = {1}", pw.Key, pw.Value));
|
||||
if (Passwords[pw.Key] != _passwords[pw.Key])
|
||||
{
|
||||
Passwords[pw.Key] = _passwords[pw.Key];
|
||||
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: Updated Password[{0} = {1}", pw.Key, Passwords[pw.Key]));
|
||||
OnPasswordChange(Passwords[pw.Key], (ushort)pw.Key, PasswordManagementConstants.StringValueChange);
|
||||
}
|
||||
}
|
||||
// else add the key & value
|
||||
else
|
||||
{
|
||||
Passwords.Add(pw.Key, pw.Value);
|
||||
Passwords[pw.Key] = _passwords[pw.Key];
|
||||
Debug.LogDebug("PasswordManager.PasswordTimerElapsed: Updated Password[{0} = {1}", pw.Key, Passwords[pw.Key]);
|
||||
OnPasswordChange(Passwords[pw.Key], (ushort)pw.Key, PasswordManagementConstants.StringValueChange);
|
||||
}
|
||||
}
|
||||
OnUshrtChange((ushort)Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var msg = string.Format("PasswordManager.PasswordTimerElapsed failed:\r{0}", e);
|
||||
Debug.Console(1, msg);
|
||||
// else add the key & value
|
||||
else
|
||||
{
|
||||
Passwords.Add(pw.Key, pw.Value);
|
||||
}
|
||||
}
|
||||
OnUshrtChange((ushort)Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Method to change the default timer value, (default 5000ms/5s)
|
||||
/// </summary>
|
||||
/// <param name="time"></param>
|
||||
public void PasswordTimerMs(ushort time)
|
||||
catch (Exception ex)
|
||||
{
|
||||
PasswordTimerElapsedMs = Convert.ToInt64(time);
|
||||
var msg = string.Format("PasswordManager.PasswordTimerElapsed failed:\r{0}", ex.Message);
|
||||
Debug.LogError(ex, msg);
|
||||
Debug.LogVerbose("Stack Trace:\r{0}", ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper method for debugging to see what passwords are in the lists
|
||||
/// </summary>
|
||||
public void ListPasswords()
|
||||
{
|
||||
Debug.Console(0, "PasswordManager.ListPasswords:\r");
|
||||
foreach (var pw in Passwords)
|
||||
Debug.Console(0, "Passwords[{0}]: {1}\r", pw.Key, pw.Value);
|
||||
Debug.Console(0, "\n");
|
||||
foreach (var pw in _passwords)
|
||||
Debug.Console(0, "_passwords[{0}]: {1}\r", pw.Key, pw.Value);
|
||||
}
|
||||
/// <summary>
|
||||
/// Method to change the default timer value, (default 5000ms/5s)
|
||||
/// </summary>
|
||||
/// <param name="time"></param>
|
||||
/// <summary>
|
||||
/// PasswordTimerMs method
|
||||
/// </summary>
|
||||
public void PasswordTimerMs(ushort time)
|
||||
{
|
||||
PasswordTimerElapsedMs = Convert.ToInt64(time);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected boolean change event handler
|
||||
/// </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 args = new BoolChangeEventArgs(state, type);
|
||||
args.Index = index;
|
||||
BoolChange(this, args);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Helper method for debugging to see what passwords are in the lists
|
||||
/// </summary>
|
||||
public void ListPasswords()
|
||||
{
|
||||
Debug.LogInformation("PasswordManager.ListPasswords:\r");
|
||||
foreach (var pw in Passwords)
|
||||
Debug.LogInformation("Passwords[{0}]: {1}\r", pw.Key, pw.Value);
|
||||
Debug.LogInformation("\n");
|
||||
foreach (var pw in _passwords)
|
||||
Debug.LogInformation("_passwords[{0}]: {1}\r", pw.Key, pw.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected ushort change event handler
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnUshrtChange(ushort value, ushort index, ushort type)
|
||||
/// <summary>
|
||||
/// Protected boolean change event handler
|
||||
/// </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 = UshrtChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new UshrtChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
UshrtChange(this, args);
|
||||
}
|
||||
var args = new BoolChangeEventArgs(state, type);
|
||||
args.Index = index;
|
||||
BoolChange(this, args);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected string change event handler
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnStringChange(string value, ushort index, ushort type)
|
||||
/// <summary>
|
||||
/// Protected ushort change event handler
|
||||
/// </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 handler = StringChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new StringChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
StringChange(this, args);
|
||||
}
|
||||
var args = new UshrtChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
UshrtChange(this, args);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected password change event handler
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnPasswordChange(string value, ushort index, ushort type)
|
||||
/// <summary>
|
||||
/// Protected string change event handler
|
||||
/// </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 handler = PasswordChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new StringChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
PasswordChange(this, args);
|
||||
}
|
||||
var args = new StringChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
StringChange(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Protected password change event handler
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="type"></param>
|
||||
protected void OnPasswordChange(string value, ushort index, ushort type)
|
||||
{
|
||||
var handler = PasswordChange;
|
||||
if (handler != null)
|
||||
{
|
||||
var args = new StringChangeEventArgs(value, type);
|
||||
args.Index = index;
|
||||
PasswordChange(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user