diff --git a/.gitattributes b/.gitattributes index bdb0cab..e308246 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,6 +3,7 @@ # Custom for Visual Studio *.cs diff=csharp +*.sh text eol=lf # Standard to msysgit *.doc diff=astextplain diff --git a/.gitignore b/.gitignore index af54ad9..3cf2aac 100644 --- a/.gitignore +++ b/.gitignore @@ -1,233 +1,6 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -build/ -bld/ -[Bb]in/ -[Oo]bj/ -[Oo]utput/ -sbpackages/ -testrunner/ - -# Visual Studio 2015 cache/options directory .vs/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# DNX -project.lock.json +packages/ +bin/ +obj/ artifacts/ - -buildTemp/ - tools/ -Artifacts/ - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf -*.cachefile - -# Visual Studio profiler -*.psess -*.vsp -*.vspx - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -## TODO: Comment the next line if you want to checkin your -## web deploy settings but do note that will include unencrypted -## passwords -#*.pubxml - -*.publishproj - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config - -# Windows Azure Build Output -csx/ -*.build.csdef - -# Windows Store app package directory -AppPackages/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -[Ss]tyle[Cc]op.* -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.pfx -*.publishsettings -node_modules/ -orleans.codegen.cs - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# LightSwitch generated files -GeneratedArtifacts/ -_Pvt_Extensions/ -ModelManifest.xml -Sandcastle/Help/ -testfile.txt -networktables.ini -networktables.ini.bak -coverage.xml -*.project.lock.json -!src/FRC.NetworkTables.Core.DesktopLibraries/Libraries/frcnm.exe - -src/FRC.NetworkTables.Core.DesktopLibraries/Libraries/**/ - -.gradle/ - -.vscode/ -.settings/ -.project \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e557449..0000000 --- a/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -language: csharp -sudo: required -dist: trusty -env: - - CLI_VERSION=latest -addons: - apt: - sources: - - sourceline: 'deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ trusty main' - key_url: 'https://apt-mo.trafficmanager.net/keys/microsoft.asc' - packages: - - gettext - - libcurl4-openssl-dev - - libicu-dev - - libssl-dev - - libunwind8 - - zlib1g - - dotnet-dev-1.0.1 -mono: - - latest -os: - - linux - - osx -osx_image: xcode7.1 -branches: - only: - - master -before_install: - - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/; fi -script: - - ./build.sh - -before_cache: - - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock -cache: - directories: - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ diff --git a/.vscode/launch.json b/.vscode/launch.json index e464a79..4c86391 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,15 +1,20 @@ { - "version": "0.2.0", - "configurations": [ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ { "name": ".NET Core Launch (console)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceRoot}/bin/Debug//", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/src/FRC.NetworkTables.Dev/bin/Debug/netcoreapp2.1/FRC.NetworkTables.Dev.dll", "args": [], - "cwd": "${workspaceRoot}", - "externalConsole": false, + "cwd": "${workspaceFolder}/src/FRC.NetworkTables.Dev", + // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window + "console": "internalConsole", "stopAtEntry": false, "internalConsoleOptions": "openOnSessionStart" }, @@ -17,7 +22,7 @@ "name": ".NET Core Attach", "type": "coreclr", "request": "attach", - "processId": "${command.pickProcess}" + "processId": "${command:pickProcess}" } - ] + ,] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..2b425c4 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "omnisharp.path": "latest" +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c73077e..e79db9b 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,15 +1,14 @@ { - "version": "0.1.0", - "command": "dotnet", - "isShellCommand": true, - "args": [], + "version": "2.0.0", "tasks": [ { - "taskName": "build", + "label": "build", + "command": "dotnet", + "type": "process", "args": [ - "" + "build", + "${workspaceFolder}/src/FRC.NetworkTables.Dev/FRC.NetworkTables.Dev.csproj" ], - "isBuildCommand": true, "problemMatcher": "$msCompile" } ] diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 4d04eef..0000000 --- a/LICENSE.txt +++ /dev/null @@ -1,74 +0,0 @@ -RobotDotNet code license - -Copyright (c) 2015-2016 RobotDotNet - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of RobotDotNet nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY ROBOTDOTNET AND CONTRIBUTORS``AS IS'' AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY NONINFRINGEMENT AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ROBOTPY OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Code for WPILib was derived from code using the following license: - -* Copyright (c) 2008-2016 FIRST -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * Neither the name of the FIRST nor the -* names of its contributors may be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY FIRST AND CONTRIBUTORS``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY NONINFRINGEMENT AND FITNESS FOR A PARTICULAR -* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FIRST OR CONTRIBUTORS BE LIABLE FOR -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -The MIT License (MIT) - -Copyright (c) .NET Foundation and Contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/NetworkTables.sln b/NetworkTables.sln deleted file mode 100644 index fcfc574..0000000 --- a/NetworkTables.sln +++ /dev/null @@ -1,132 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26403.7 -MinimumVisualStudioVersion = 15.0.26124.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{9C2F4909-9BE2-437D-862C-4E23155C2A7A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables", "src\FRC.NetworkTables\FRC.NetworkTables.csproj", "{20D7E2A0-AA97-4613-B32C-8D3706FAF708}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables.Core", "src\FRC.NetworkTables.Core\FRC.NetworkTables.Core.csproj", "{E4577F32-D5E8-4191-8C29-124EBC15EFE9}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables.Core.DesktopLibraries", "src\FRC.NetworkTables.Core.DesktopLibraries\FRC.NetworkTables.Core.DesktopLibraries.csproj", "{EE176693-9FBA-43C6-B97A-D7A79DEE16B6}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{44BF4692-6DAD-4EEA-9A02-63920115AF2B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetworkTables.Core.Test", "test\NetworkTables.Core.Test\NetworkTables.Core.Test.csproj", "{070CCC8C-ECEE-4B59-A94A-A4BD1E330803}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetworkTables.Test", "test\NetworkTables.Test\NetworkTables.Test.csproj", "{06EBE437-BE46-4225-95DA-250472C7BEA3}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{88646071-EBE3-46F7-9DA6-64FF32464975}" - ProjectSection(SolutionItems) = preProject - src\Shared\ConnectionInfo.cs = src\Shared\ConnectionInfo.cs - src\Shared\Delegates.cs = src\Shared\Delegates.cs - src\Shared\EntryInfo.cs = src\Shared\EntryInfo.cs - src\Shared\Enumerations.cs = src\Shared\Enumerations.cs - src\Shared\Wire\FastBitConverterBE.cs = src\Shared\Wire\FastBitConverterBE.cs - src\Shared\Wire\FastBitConverterCache.cs = src\Shared\Wire\FastBitConverterCache.cs - src\Shared\Wire\FastBitConverterLE.cs = src\Shared\Wire\FastBitConverterLE.cs - src\Shared\Wire\IFastBitConverter.cs = src\Shared\Wire\IFastBitConverter.cs - src\Shared\Tables\IRemote.cs = src\Shared\Tables\IRemote.cs - src\Shared\Tables\IRemoteConnectionListener.cs = src\Shared\Tables\IRemoteConnectionListener.cs - src\Shared\Tables\ITable.cs = src\Shared\Tables\ITable.cs - src\Shared\Tables\ITableListener.cs = src\Shared\Tables\ITableListener.cs - src\Shared\Wire\Leb128.cs = src\Shared\Wire\Leb128.cs - src\Shared\ListStream.cs = src\Shared\ListStream.cs - src\Shared\NetworkTable.cs = src\Shared\NetworkTable.cs - src\Shared\NtCore.cs = src\Shared\NtCore.cs - src\Shared\NtIPAddress.cs = src\Shared\NtIPAddress.cs - src\Shared\NtType.cs = src\Shared\NtType.cs - src\Shared\Exceptions\PersistentException.cs = src\Shared\Exceptions\PersistentException.cs - src\Shared\RemoteProcedureCall.cs = src\Shared\RemoteProcedureCall.cs - src\Shared\RpcStructs.cs = src\Shared\RpcStructs.cs - src\Shared\StaticRemote.cs = src\Shared\StaticRemote.cs - src\Shared\Exceptions\TableKeyDifferentTypeException.cs = src\Shared\Exceptions\TableKeyDifferentTypeException.cs - src\Shared\Exceptions\TableKeyNotDefinedException.cs = src\Shared\Exceptions\TableKeyNotDefinedException.cs - src\Shared\Value.cs = src\Shared\Value.cs - src\Shared\Wire\WireDecoder.cs = src\Shared\Wire\WireDecoder.cs - src\Shared\Wire\WireEncoder.cs = src\Shared\Wire\WireEncoder.cs - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Debug|Any CPU.Build.0 = Debug|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Debug|x64.ActiveCfg = Debug|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Debug|x64.Build.0 = Debug|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Debug|x86.ActiveCfg = Debug|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Debug|x86.Build.0 = Debug|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Release|Any CPU.ActiveCfg = Release|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Release|Any CPU.Build.0 = Release|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Release|x64.ActiveCfg = Release|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Release|x64.Build.0 = Release|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Release|x86.ActiveCfg = Release|Any CPU - {20D7E2A0-AA97-4613-B32C-8D3706FAF708}.Release|x86.Build.0 = Release|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Debug|x64.ActiveCfg = Debug|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Debug|x64.Build.0 = Debug|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Debug|x86.ActiveCfg = Debug|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Debug|x86.Build.0 = Debug|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Release|Any CPU.Build.0 = Release|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Release|x64.ActiveCfg = Release|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Release|x64.Build.0 = Release|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Release|x86.ActiveCfg = Release|Any CPU - {E4577F32-D5E8-4191-8C29-124EBC15EFE9}.Release|x86.Build.0 = Release|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Debug|x64.ActiveCfg = Debug|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Debug|x64.Build.0 = Debug|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Debug|x86.ActiveCfg = Debug|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Debug|x86.Build.0 = Debug|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Release|Any CPU.Build.0 = Release|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Release|x64.ActiveCfg = Release|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Release|x64.Build.0 = Release|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Release|x86.ActiveCfg = Release|Any CPU - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6}.Release|x86.Build.0 = Release|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Debug|Any CPU.Build.0 = Debug|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Debug|x64.ActiveCfg = Debug|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Debug|x64.Build.0 = Debug|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Debug|x86.ActiveCfg = Debug|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Debug|x86.Build.0 = Debug|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Release|Any CPU.ActiveCfg = Release|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Release|Any CPU.Build.0 = Release|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Release|x64.ActiveCfg = Release|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Release|x64.Build.0 = Release|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Release|x86.ActiveCfg = Release|Any CPU - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803}.Release|x86.Build.0 = Release|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Debug|x64.ActiveCfg = Debug|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Debug|x64.Build.0 = Debug|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Debug|x86.ActiveCfg = Debug|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Debug|x86.Build.0 = Debug|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Release|Any CPU.Build.0 = Release|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Release|x64.ActiveCfg = Release|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Release|x64.Build.0 = Release|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Release|x86.ActiveCfg = Release|Any CPU - {06EBE437-BE46-4225-95DA-250472C7BEA3}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {20D7E2A0-AA97-4613-B32C-8D3706FAF708} = {9C2F4909-9BE2-437D-862C-4E23155C2A7A} - {E4577F32-D5E8-4191-8C29-124EBC15EFE9} = {9C2F4909-9BE2-437D-862C-4E23155C2A7A} - {EE176693-9FBA-43C6-B97A-D7A79DEE16B6} = {9C2F4909-9BE2-437D-862C-4E23155C2A7A} - {070CCC8C-ECEE-4B59-A94A-A4BD1E330803} = {44BF4692-6DAD-4EEA-9A02-63920115AF2B} - {06EBE437-BE46-4225-95DA-250472C7BEA3} = {44BF4692-6DAD-4EEA-9A02-63920115AF2B} - {88646071-EBE3-46F7-9DA6-64FF32464975} = {9C2F4909-9BE2-437D-862C-4E23155C2A7A} - EndGlobalSection -EndGlobal diff --git a/Readme.md b/Readme.md deleted file mode 100644 index 08efad7..0000000 --- a/Readme.md +++ /dev/null @@ -1,77 +0,0 @@ -**Build Status** - -| Windows | Linux/Mac | Code Coverage | NuGet | NuGet (Core) | NuGet (Core DesktopLibraries) | -| ------------------------|-------------------------|-----------------------|-----------------------|-----------------------|--------------------------------| -| [![Build status][1]][2] | [![Build Status][3]][4] | [![codecov][5]][6] | [![NuGet][7]][8] | [![NuGet][9]][10] | [![NuGet][11]][12] | - -[1]: https://ci.appveyor.com/api/projects/status/35aclclri0mf4juk/branch/master?svg=true -[2]: https://ci.appveyor.com/project/robotdotnet/networktables/branch/master -[3]: https://travis-ci.org/robotdotnet/NetworkTables.svg?branch=master -[4]: https://travis-ci.org/robotdotnet/NetworkTables -[5]: https://codecov.io/gh/robotdotnet/NetworkTables/branch/master/graph/badge.svg -[6]: https://codecov.io/gh/robotdotnet/NetworkTables -[7]: https://img.shields.io/nuget/vpre/FRC.NetworkTables.svg -[8]: https://www.nuget.org/packages/FRC.NetworkTables -[9]: https://img.shields.io/nuget/vpre/FRC.NetworkTables.Core.svg -[10]: https://www.nuget.org/packages/FRC.NetworkTables.Core -[11]: https://img.shields.io/nuget/vpre/FRC.NetworkTables.Core.DesktopLibraries.svg -[12]: https://www.nuget.org/packages/FRC.NetworkTables.Core.DesktopLibraries - -NetworkTables is a DotNet implementation of the NetworkTables protocol commonly used in FRC. Currently implements v3 of the NetworkTables spec. - -This repository contains two seperate release projects. - -The first is NetworkTables, which is a complete port of the ntcore library from C++ to DotNet. This library is recommended for any clients that you wish to create, as the dependancies are very low, and supported by most platforms. - -The second project is NetworkTables.Core. This is a wrapper around the official [ntcore](https://github.com/wpilibsuite/ntcore) library. This means that the networking code has been tested more by the community, and is recommended for running on an FRC robot as the server. - - - -Supported Platforms - NetworkTables ------------------------------------ -* All systems that support the frameworks listed below -* .NET 4.6 or higher -* .NET Standard 1.3 or higher: - * System.Net.NameResolution - * System.ComponentModel.EventBasedAsync - -Supported Platforms - NetworkTables.Core ----------------------------------------- -* .NET 4.5 or higher -* .NET Standard 1.5 -* Since this uses a native library, only the platforms listed below are supported - * Windows x86 and amd64 - * Linux x86 and amd64 - * Mac OS x86 and x86-64 - * RoboRio (Soft Float Arm v7) - Note to be used on Desktop, you must install the *FRC.NetworkTables.Core.DesktopLibraries* package as well. - -Installation ------------- -When you create a WPILib robot project using our VisualStudio extension, NetworkTables.Core will automatically be installed. - -For new installs, see the badges at the top for NuGet packages. - -Note that Xamarin requires 4.1.2 minimum in order to work directly from NuGet. If you require support for older versions, -you need to download and manually use the .NET 4.6 library, as Xamarin by default will attempt to use the Net Standard build and then error on build. -Note that only Android has been tested, but iOS should work without issue. - -Building --------- -* Windows - * Requires either .NET Core SDK (for command line building) or Visual Studio 2015 Update 3 with the .NET Core VS 2015 Tooling Preview, see https://www.microsoft.com/net/core#windows. - - -License -======= -See [LICENSE.txt](LICENSE.txt) - - -Contributors -============ - -Thad House (@thadhouse) - -[ntcore](https://github.com/wpilibsuite/ntcore) - -Peter Johnson (@peterjohnson) wrote the original ntcore library, which was heavily used to port to native diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 99d90fb..0000000 --- a/appveyor.yml +++ /dev/null @@ -1,37 +0,0 @@ -version: '{branch}-{build}' -pull_requests: - do_not_increment_build_number: true -skip_branch_with_pr: true -branches: - only: - - master -nuget: - disable_publish_on_pr: true - -build_script: -- ps: .\build.ps1 - -test: off - -artifacts: -# Store NuGet packages -- path: .\Artifacts\**\*.nupkg - name: NuGet - -cache: - - C:\Users\appveyor\.gradle - -deploy: -- provider: NuGet - api_key: - secure: f4XB8xaNhhhgmXZrsv5Yh+JjxgnAXOfBJtbUgPB623n4Z2t/gXcC7fCUg36DK69k - on: - branch: master - appveyor_repo_tag: true -- provider: GitHub - auth_token: - secure: fwCTagTAptB4QJnTt9RrLEvg3G0cEJxssYNxtYFMBKnqHqbGomBTZvvGjrHtt7l4 - artifact: /.*\.nupkg/ - on: - branch: master - appveyor_repo_tag: true diff --git a/azure-pipelines.yml b/azure-pipelines.yml new file mode 100644 index 0000000..ee68e54 --- /dev/null +++ b/azure-pipelines.yml @@ -0,0 +1,70 @@ +# Starter pipeline +# Start with a minimal pipeline that you can customize to build and deploy your code. +# Add steps that build, run tests, deploy, and more: +# https://aka.ms/yaml + +trigger: + tags: + include: + - v* + branches: + include: + - master + +jobs: + - job: Linux + pool: + vmImage: 'ubuntu-18.04' + + steps: + - script: ./build.sh + displayName: 'Build Artifacts' + + - task: CopyFiles@2 + inputs: + Contents: 'Artifacts/**/*.nupkg' + targetFolder: $(Build.ArtifactStagingDirectory) + displayName: "Copy Artifacts" + + - task: PublishBuildArtifacts@1 + inputs: + artifactName: 'NuGet' + + - task: PublishTestResults@2 + inputs: + testResultsFormat: 'VSTest' + testResultsFiles: '**/*.trx' + + - job: Windows + pool: + vmImage: 'windows-2019' + + steps: + - powershell: ./build.ps1 + displayName: 'Build Artifacts' + + - task: PublishTestResults@2 + inputs: + testResultsFormat: 'VSTest' + testResultsFiles: '**/*.trx' + + + - job: Mac + pool: + vmImage: 'macOS-10.14' + + steps: + - task: UseDotNet@2 + displayName: 'Use .NET Core sdk' + inputs: + packageType: sdk + version: 3.1.100 + installationPath: $(Agent.ToolsDirectory)/dotnet + - script: ./build.sh + displayName: 'Build Artifacts' + + - task: PublishTestResults@2 + inputs: + testResultsFormat: 'VSTest' + testResultsFiles: '**/*.trx' + diff --git a/build.cake b/build.cake index fd2720f..fd686f1 100644 --- a/build.cake +++ b/build.cake @@ -3,7 +3,7 @@ var target = Argument("Target", "Default"); // Configuration - The build configuration (Debug/Release) to use. // 1. If command line parameter parameter passed, use that. // 2. Otherwise if an Environment variable exists, use that. -var configuration = +var configuration = HasArgument("Configuration") ? Argument("Configuration") : EnvironmentVariable("Configuration") != null ? EnvironmentVariable("BuildNumber") : "Release"; // The build number to use in the version number of the built NuGet packages. @@ -17,19 +17,21 @@ var buildNumberInt = HasArgument("BuildNumber") ? Argument("BuildNumber") : AppVeyor.IsRunningOnAppVeyor ? AppVeyor.Environment.Build.Number : TravisCI.IsRunningOnTravisCI ? TravisCI.Environment.Build.BuildNumber : + TFBuild.IsRunningOnAzurePipelinesHosted ? 0 : EnvironmentVariable("BuildNumber") != null ? int.Parse(EnvironmentVariable("BuildNumber")) : 0; var buildNumber = buildNumberInt.ToString("D4"); var buildVersion = "1.0.0"; -var buildType = (AppVeyor.IsRunningOnAppVeyor || TravisCI.IsRunningOnTravisCI) ? "ci-" : "local-"; +var buildType = (AppVeyor.IsRunningOnAppVeyor || TravisCI.IsRunningOnTravisCI || TFBuild.IsRunningOnAzurePipelinesHosted) ? "ci-" : "local-"; buildType = buildType + buildNumber; -var tagName = EnvironmentVariable("APPVEYOR_REPO_TAG_NAME"); -if (tagName != null) { - // On AppVeyor +var tagName = EnvironmentVariable("BUILD_SOURCEBRANCH"); +if (tagName != null && tagName.StartsWith("refs/tags/v")) { + tagName = EnvironmentVariable("BUILD_SOURCEBRANCHNAME"); + // On Azure buildVersion = tagName.Substring(1); if (!tagName.Contains("-")) { // Building a full release @@ -47,9 +49,6 @@ Console.WriteLine("BuildNumber: " + msBuildVersionArgs); // A directory path to an Artifacts directory. var artifactsDirectory = Directory("./Artifacts"); -var current = MakeAbsolute(Directory(".")).ToString(); -Console.WriteLine(current); - // Deletes the contents of the Artifacts folder if it should contain anything from a previous build. Task("Clean") .Does(() => @@ -57,21 +56,6 @@ Task("Clean") CleanDirectory(artifactsDirectory); }); -Task("GradleRestore") - .IsDependentOn("Clean") - .Does(() => - { - int exitCode = 0; - if (System.IO.Path.DirectorySeparatorChar == '\\') { - exitCode = StartProcess(current + "/gradlew.bat", "build"); - } else { - exitCode = StartProcess(current + "\\gradlew", "build"); - } - if (exitCode != 0) { - throw new Exception("Failed to restore native dependencies"); - } - }); - // Run dotnet restore to restore all package references. Task("Restore") .IsDependentOn("Clean") @@ -79,16 +63,16 @@ Task("Restore") { DotNetCoreRestore(); }); - + // Find all crproj projects and build them using the build configuration specified as an argument. Task("Build") .IsDependentOn("Restore") - .IsDependentOn("GradleRestore") .Does(() => { - var projects = GetFiles("./**/*.csproj"); + var projects = GetFiles("./src/**/*.csproj").Concat(GetFiles("./test/**/*.csproj")); foreach(var project in projects) { + Console.WriteLine(project.FullPath); DotNetCoreBuild( project.GetDirectory().FullPath, new DotNetCoreBuildSettings() @@ -99,7 +83,7 @@ Task("Restore") }); } }); - + // Look under a 'Tests' folder and run dotnet test against all of those projects. // Then drop the XML test results file in the Artifacts folder at the root. Task("Test") @@ -117,26 +101,29 @@ Task("Test") { Configuration = configuration, NoBuild = true, - /* ArgumentCustomization = args => args - .Append("--logger trx;LogFileName="+ MakeAbsolute(artifactsDirectory).CombineWithFilePath(project.GetFilenameWithoutExtension()).FullPath + ".trx\"\"")*/ + .Append("--logger trx;LogFileName="+ MakeAbsolute(artifactsDirectory).CombineWithFilePath(project.GetFilenameWithoutExtension()).FullPath + ".trx\"\"") }); } }); - + // Run dotnet pack to produce NuGet packages from our projects. Versions the package -// using the build number argument on the script which is used as the revision number +// using the build number argument on the script which is used as the revision number // (Last number in 1.0.0.0). The packages are dropped in the Artifacts directory. Task("Pack") .IsDependentOn("Test") .Does(() => { - foreach (var project in GetFiles("./src/**/*.csproj")) + List matchers = new List + { + "./src/FRC.NetworkTables.Core/*.csproj", + "./src/FRC.NetworkTables.Core.DesktopLibraries/*.csproj", + "./src/FRC.NetworkTables.Core.Web/*.csproj" + }; + + foreach (var project in matchers.Select(x => GetFiles(x).First())) { - var sources = ""; - if (!project.FullPath.Contains("DesktopLibraries")) { - sources = "--include-source"; - } + var sources = "--include-source"; DotNetCorePack( project.GetDirectory().FullPath, new DotNetCorePackSettings() @@ -149,11 +136,11 @@ Task("Pack") }); } }); - + // The default task to run if none is explicitly specified. In this case, we want // to run everything starting from Clean, all the way up to Pack. Task("Default") .IsDependentOn("Pack"); - + // Executes the task specified in the target argument. -RunTarget(target); \ No newline at end of file +RunTarget(target); diff --git a/build.gradle b/build.gradle deleted file mode 100644 index ba59c25..0000000 --- a/build.gradle +++ /dev/null @@ -1,122 +0,0 @@ -plugins { - id 'net.ltgt.errorprone' version '0.0.8' - id 'edu.wpi.first.wpilib.versioning.WPILibVersioningPlugin' version '1.5.1' -} - -// Ensure that the WPILibVersioningPlugin is setup by setting the release type, if releaseType wasn't -// already specified on the command line -if (!hasProperty('releaseType')) { - WPILibVersion { - releaseType = 'dev' - } -} - -task downloadNtCoreArm() { - description = 'Downloads the ntcore arm maven dependency.' - group = 'WPILib' - def depFolder = "${project.buildDir}/dependencies" - def ntZip = file("${depFolder}/ntcorearm.zip") - outputs.file(ntZip) - def ntcore - - doFirst { - def ntDependency = project.dependencies.create("edu.wpi.first.wpilib.networktables.cpp:NetworkTables:+:arm@zip") - def ntConfig = project.configurations.detachedConfiguration(ntDependency) - ntConfig.setTransitive(false) - ntcore = ntConfig.files[0].canonicalFile - } - - doLast { - copy { - from ntcore - rename 'NetworkTables(.+)', 'ntcorearm.zip' - into depFolder - } - } -} - -task downloadNtCoreDT() { - description = 'Downloads the ntcore desktop maven dependency.' - group = 'WPILib' - def depFolder = "${project.buildDir}/dependencies" - def ntZip = file("${depFolder}/ntcoredt.zip") - outputs.file(ntZip) - def ntcore - - doFirst { - def ntDependency = project.dependencies.create("edu.wpi.first.wpilib.networktables.cpp:NetworkTables:+:desktop@zip") - def ntConfig = project.configurations.detachedConfiguration(ntDependency) - ntConfig.setTransitive(false) - ntcore = ntConfig.files[0].canonicalFile - } - - doLast { - copy { - from ntcore - rename 'NetworkTables(.+)', 'ntcoredt.zip' - into depFolder - } - } -} - -def netTablesArmUnzipLocation = "$buildDir/networktablesarm" -def netTablesDtUnzipLocation = "$buildDir/networktablesdt" - -// Create a task that will unzip the networktables files into a temporary build directory -task unzipNetworkTablesArm(type: Copy) { - description = 'Unzips the networktables arm maven dependency so that the include files and libraries can be used' - group = 'WPILib' - dependsOn downloadNtCoreArm - - from zipTree(downloadNtCoreArm.outputs.files.singleFile) - into netTablesArmUnzipLocation -} - -// Create a task that will unzip the networktables files into a temporary build directory -task unzipNetworkTablesDT(type: Copy) { - description = 'Unzips the networktables desktop maven dependency so that the include files and libraries can be used' - group = 'WPILib' - dependsOn downloadNtCoreDT - - from zipTree(downloadNtCoreDT.outputs.files.singleFile) - into netTablesDtUnzipLocation -} - -def nativeLibLocation = "src/FRC.NetworkTables.Core.DesktopLibraries/Libraries" - -task copyNetworkTablesArm(type: Copy) { - dependsOn unzipNetworkTablesArm - - from (netTablesArmUnzipLocation) - include "**/*.so" - exclude "include/" - into nativeLibLocation -} - -task copyNetworkTablesDT(type: Copy) { - dependsOn unzipNetworkTablesDT - - from (netTablesDtUnzipLocation) - include "**/*.so" - include "**/*.dll" - include "**/*.dylib" - exclude "include/" - into nativeLibLocation -} - -task build() { - -} - -task clean(type: Delete) { - description = "Deletes the build directory" - group = "Build" - delete buildDir -} - -build.dependsOn copyNetworkTablesArm -build.dependsOn copyNetworkTablesDT - -task wrapper(type: Wrapper) { - gradleVersion = '3.5' -} diff --git a/build.ps1 b/build.ps1 index 3a8ef5c..7f1f813 100644 --- a/build.ps1 +++ b/build.ps1 @@ -21,40 +21,52 @@ The build script target to run. The build configuration to use. .PARAMETER Verbosity Specifies the amount of information to be displayed. -.PARAMETER Experimental -Tells Cake to use the latest Roslyn release. -.PARAMETER WhatIf -Performs a dry run of the build script. -No tasks will be executed. -.PARAMETER Mono -Tells Cake to use the Mono scripting engine. +.PARAMETER ShowDescription +Shows description about tasks. +.PARAMETER DryRun +Performs a dry run. .PARAMETER SkipToolPackageRestore Skips restoring of packages. .PARAMETER ScriptArgs Remaining arguments are added here. .LINK -http://cakebuild.net +https://cakebuild.net #> [CmdletBinding()] Param( [string]$Script = "build.cake", - [string]$Target = "Default", - [ValidateSet("Release", "Debug")] - [string]$Configuration = "Release", + [string]$Target, + [string]$Configuration, [ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")] - [string]$Verbosity = "Verbose", - [switch]$Experimental, - [Alias("DryRun","Noop")] - [switch]$WhatIf, - [switch]$Mono, + [string]$Verbosity, + [switch]$ShowDescription, + [Alias("WhatIf", "Noop")] + [switch]$DryRun, [switch]$SkipToolPackageRestore, [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)] [string[]]$ScriptArgs ) +# Attempt to set highest encryption available for SecurityProtocol. +# PowerShell will not set this by default (until maybe .NET 4.6.x). This +# will typically produce a message for PowerShell v2 (just an info +# message though) +try { + # Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48) + # Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't + # exist in .NET 4.0, even though they are addressable if .NET 4.5+ is + # installed (.NET 4.5 is an in-place upgrade). + # PowerShell Core already has support for TLS 1.2 so we can skip this if running in that. + if (-not $IsCoreCLR) { + [System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -bor 48 + } + } catch { + Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3' + } + [Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null function MD5HashFile([string] $filePath) { @@ -80,6 +92,15 @@ function MD5HashFile([string] $filePath) } } +function GetProxyEnabledWebClient +{ + $wc = New-Object System.Net.WebClient + $proxy = [System.Net.WebRequest]::GetSystemWebProxy() + $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials + $wc.Proxy = $proxy + return $wc +} + Write-Host "Preparing to run build script..." if(!$PSScriptRoot){ @@ -87,42 +108,29 @@ if(!$PSScriptRoot){ } $TOOLS_DIR = Join-Path $PSScriptRoot "tools" +$ADDINS_DIR = Join-Path $TOOLS_DIR "Addins" +$MODULES_DIR = Join-Path $TOOLS_DIR "Modules" $NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe" $CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe" $NUGET_URL = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" $PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config" $PACKAGES_CONFIG_MD5 = Join-Path $TOOLS_DIR "packages.config.md5sum" - -# Should we use mono? -$UseMono = ""; -if($Mono.IsPresent) { - Write-Verbose -Message "Using the Mono based scripting engine." - $UseMono = "-mono" -} - -# Should we use the new Roslyn? -$UseExperimental = ""; -if($Experimental.IsPresent -and !($Mono.IsPresent)) { - Write-Verbose -Message "Using experimental version of Roslyn." - $UseExperimental = "-experimental" -} - -# Is this a dry run? -$UseDryRun = ""; -if($WhatIf.IsPresent) { - $UseDryRun = "-dryrun" -} +$ADDINS_PACKAGES_CONFIG = Join-Path $ADDINS_DIR "packages.config" +$MODULES_PACKAGES_CONFIG = Join-Path $MODULES_DIR "packages.config" # Make sure tools folder exists if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) { Write-Verbose -Message "Creating tools directory..." - New-Item -Path $TOOLS_DIR -Type directory | out-null + New-Item -Path $TOOLS_DIR -Type Directory | Out-Null } # Make sure that packages.config exist. if (!(Test-Path $PACKAGES_CONFIG)) { Write-Verbose -Message "Downloading packages.config..." - try { (New-Object System.Net.WebClient).DownloadFile("http://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG) } catch { + try { + $wc = GetProxyEnabledWebClient + $wc.DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG) + } catch { Throw "Could not download packages.config." } } @@ -142,14 +150,20 @@ if (!(Test-Path $NUGET_EXE)) { if (!(Test-Path $NUGET_EXE)) { Write-Verbose -Message "Downloading NuGet.exe..." try { - (New-Object System.Net.WebClient).DownloadFile($NUGET_URL, $NUGET_EXE) + $wc = GetProxyEnabledWebClient + $wc.DownloadFile($NUGET_URL, $NUGET_EXE) } catch { Throw "Could not download NuGet.exe." } } # Save nuget.exe path to environment to be available to child processed -$ENV:NUGET_EXE = $NUGET_EXE +$env:NUGET_EXE = $NUGET_EXE +$env:NUGET_EXE_INVOCATION = if ($IsLinux -or $IsMacOS) { + "mono `"$NUGET_EXE`"" +} else { + "`"$NUGET_EXE`"" +} # Restore tools from NuGet? if(-Not $SkipToolPackageRestore.IsPresent) { @@ -157,24 +171,61 @@ if(-Not $SkipToolPackageRestore.IsPresent) { Set-Location $TOOLS_DIR # Check for changes in packages.config and remove installed tools if true. - [string] $md5Hash = MD5HashFile($PACKAGES_CONFIG) + [string] $md5Hash = MD5HashFile $PACKAGES_CONFIG if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or - ($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) { + ($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) { Write-Verbose -Message "Missing or changed package.config hash..." - Remove-Item * -Recurse -Exclude packages.config,nuget.exe + Get-ChildItem -Exclude packages.config,nuget.exe,Cake.Bakery | + Remove-Item -Recurse } Write-Verbose -Message "Restoring tools from NuGet..." - $NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`"" + + $NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`"" if ($LASTEXITCODE -ne 0) { - Throw "An error occured while restoring NuGet tools." + Throw "An error occurred while restoring NuGet tools." } else { $md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII" } - Write-Verbose -Message ($NuGetOutput | out-string) + Write-Verbose -Message ($NuGetOutput | Out-String) + + Pop-Location +} + +# Restore addins from NuGet +if (Test-Path $ADDINS_PACKAGES_CONFIG) { + Push-Location + Set-Location $ADDINS_DIR + + Write-Verbose -Message "Restoring addins from NuGet..." + $NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$ADDINS_DIR`"" + + if ($LASTEXITCODE -ne 0) { + Throw "An error occurred while restoring NuGet addins." + } + + Write-Verbose -Message ($NuGetOutput | Out-String) + + Pop-Location +} + +# Restore modules from NuGet +if (Test-Path $MODULES_PACKAGES_CONFIG) { + Push-Location + Set-Location $MODULES_DIR + + Write-Verbose -Message "Restoring modules from NuGet..." + $NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$MODULES_DIR`"" + + if ($LASTEXITCODE -ne 0) { + Throw "An error occurred while restoring NuGet modules." + } + + Write-Verbose -Message ($NuGetOutput | Out-String) + Pop-Location } @@ -183,7 +234,23 @@ if (!(Test-Path $CAKE_EXE)) { Throw "Could not find Cake.exe at $CAKE_EXE" } +$CAKE_EXE_INVOCATION = if ($IsLinux -or $IsMacOS) { + "mono `"$CAKE_EXE`"" +} else { + "`"$CAKE_EXE`"" +} + + +# Build Cake arguments +$cakeArguments = @("$Script"); +if ($Target) { $cakeArguments += "-target=$Target" } +if ($Configuration) { $cakeArguments += "-configuration=$Configuration" } +if ($Verbosity) { $cakeArguments += "-verbosity=$Verbosity" } +if ($ShowDescription) { $cakeArguments += "-showdescription" } +if ($DryRun) { $cakeArguments += "-dryrun" } +$cakeArguments += $ScriptArgs + # Start Cake Write-Host "Running build script..." -Invoke-Expression "& `"$CAKE_EXE`" `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseMono $UseDryRun $UseExperimental $ScriptArgs" -exit $LASTEXITCODE \ No newline at end of file +Invoke-Expression "& $CAKE_EXE_INVOCATION $($cakeArguments -join " ")" +exit $LASTEXITCODE diff --git a/build.sh b/build.sh index 6e8f207..b9e1252 100755 --- a/build.sh +++ b/build.sh @@ -9,10 +9,14 @@ # Define directories. SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) TOOLS_DIR=$SCRIPT_DIR/tools +ADDINS_DIR=$TOOLS_DIR/Addins +MODULES_DIR=$TOOLS_DIR/Modules NUGET_EXE=$TOOLS_DIR/nuget.exe CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe PACKAGES_CONFIG=$TOOLS_DIR/packages.config PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum +ADDINS_PACKAGES_CONFIG=$ADDINS_DIR/packages.config +MODULES_PACKAGES_CONFIG=$MODULES_DIR/packages.config # Define md5sum or md5 depending on Linux/OSX MD5_EXE= @@ -24,24 +28,14 @@ fi # Define default arguments. SCRIPT="build.cake" -TARGET="Default" -CONFIGURATION="Release" -VERBOSITY="verbose" -DRYRUN= -SHOW_VERSION=false -SCRIPT_ARGUMENTS=() +CAKE_ARGUMENTS=() # Parse arguments. for i in "$@"; do case $1 in -s|--script) SCRIPT="$2"; shift ;; - -t|--target) TARGET="$2"; shift ;; - -c|--configuration) CONFIGURATION="$2"; shift ;; - -v|--verbosity) VERBOSITY="$2"; shift ;; - -d|--dryrun) DRYRUN="-dryrun" ;; - --version) SHOW_VERSION=true ;; - --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; - *) SCRIPT_ARGUMENTS+=("$1") ;; + --) shift; CAKE_ARGUMENTS+=("$@"); break ;; + *) CAKE_ARGUMENTS+=("$1") ;; esac shift done @@ -54,9 +48,9 @@ fi # Make sure that packages.config exist. if [ ! -f "$TOOLS_DIR/packages.config" ]; then echo "Downloading packages.config..." - curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + curl -Lsfo "$TOOLS_DIR/packages.config" https://cakebuild.net/download/bootstrapper/packages if [ $? -ne 0 ]; then - echo "An error occured while downloading packages.config." + echo "An error occurred while downloading packages.config." exit 1 fi fi @@ -66,27 +60,53 @@ if [ ! -f "$NUGET_EXE" ]; then echo "Downloading NuGet..." curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe if [ $? -ne 0 ]; then - echo "An error occured while downloading nuget.exe." + echo "An error occurred while downloading nuget.exe." exit 1 fi fi # Restore tools from NuGet. pushd "$TOOLS_DIR" >/dev/null -if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then - find . -type d ! -name . | xargs rm -rf +if [ ! -f "$PACKAGES_CONFIG_MD5" ] || [ "$( cat "$PACKAGES_CONFIG_MD5" | sed 's/\r$//' )" != "$( $MD5_EXE "$PACKAGES_CONFIG" | awk '{ print $1 }' )" ]; then + find . -type d ! -name . ! -name 'Cake.Bakery' | xargs rm -rf fi mono "$NUGET_EXE" install -ExcludeVersion if [ $? -ne 0 ]; then - echo "Could not restore NuGet packages." + echo "Could not restore NuGet tools." exit 1 fi -$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 +$MD5_EXE "$PACKAGES_CONFIG" | awk '{ print $1 }' >| "$PACKAGES_CONFIG_MD5" popd >/dev/null +# Restore addins from NuGet. +if [ -f "$ADDINS_PACKAGES_CONFIG" ]; then + pushd "$ADDINS_DIR" >/dev/null + + mono "$NUGET_EXE" install -ExcludeVersion + if [ $? -ne 0 ]; then + echo "Could not restore NuGet addins." + exit 1 + fi + + popd >/dev/null +fi + +# Restore modules from NuGet. +if [ -f "$MODULES_PACKAGES_CONFIG" ]; then + pushd "$MODULES_DIR" >/dev/null + + mono "$NUGET_EXE" install -ExcludeVersion + if [ $? -ne 0 ]; then + echo "Could not restore NuGet modules." + exit 1 + fi + + popd >/dev/null +fi + # Make sure that Cake has been installed. if [ ! -f "$CAKE_EXE" ]; then echo "Could not find Cake.exe at '$CAKE_EXE'." @@ -94,8 +114,4 @@ if [ ! -f "$CAKE_EXE" ]; then fi # Start Cake -if $SHOW_VERSION; then - exec mono "$CAKE_EXE" -version -else - exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -configuration=$CONFIGURATION -target=$TARGET $DRYRUN "${SCRIPT_ARGUMENTS[@]}" -fi \ No newline at end of file +exec mono "$CAKE_EXE" $SCRIPT "${CAKE_ARGUMENTS[@]}" diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 29c4fd9..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 12c9956..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Thu May 25 18:00:10 PDT 2017 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-bin.zip diff --git a/gradlew b/gradlew deleted file mode 100755 index 4453cce..0000000 --- a/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save ( ) { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index f955316..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/networktables.sln b/networktables.sln new file mode 100644 index 0000000..3cbf218 --- /dev/null +++ b/networktables.sln @@ -0,0 +1,119 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28803.156 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FCA2625C-F670-47C8-A57C-0CDDA75191D5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables.Core", "src\FRC.NetworkTables.Core\FRC.NetworkTables.Core.csproj", "{967E5110-A79D-4BBF-A039-29646474B141}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables.Dev", "src\FRC.NetworkTables.Dev\FRC.NetworkTables.Dev.csproj", "{3CE96B29-8A19-44E8-A90D-E104A2811C38}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables.Core.DesktopLibraries", "src\FRC.NetworkTables.Core.DesktopLibraries\FRC.NetworkTables.Core.DesktopLibraries.csproj", "{D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{540AC47D-3009-4CE1-8052-31639DF3E962}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables.Core.Test", "test\FRC.NetworkTables.Core.Test\FRC.NetworkTables.Core.Test.csproj", "{59184BE7-93CE-4416-94B8-F0CA32C1949B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetworkTablesAPI", "src\NetworkTablesAPI\NetworkTablesAPI.csproj", "{DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FRC.NetworkTables.Core.Web", "src\FRC.NetworkTables.Core.Web\FRC.NetworkTables.Core.Web.csproj", "{623E102A-8460-4237-B936-2C50177C527C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {967E5110-A79D-4BBF-A039-29646474B141}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Debug|Any CPU.Build.0 = Debug|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Debug|x64.ActiveCfg = Debug|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Debug|x64.Build.0 = Debug|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Debug|x86.ActiveCfg = Debug|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Debug|x86.Build.0 = Debug|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Release|Any CPU.ActiveCfg = Release|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Release|Any CPU.Build.0 = Release|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Release|x64.ActiveCfg = Release|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Release|x64.Build.0 = Release|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Release|x86.ActiveCfg = Release|Any CPU + {967E5110-A79D-4BBF-A039-29646474B141}.Release|x86.Build.0 = Release|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Debug|x64.ActiveCfg = Debug|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Debug|x64.Build.0 = Debug|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Debug|x86.ActiveCfg = Debug|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Debug|x86.Build.0 = Debug|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Release|Any CPU.Build.0 = Release|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Release|x64.ActiveCfg = Release|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Release|x64.Build.0 = Release|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Release|x86.ActiveCfg = Release|Any CPU + {3CE96B29-8A19-44E8-A90D-E104A2811C38}.Release|x86.Build.0 = Release|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Debug|x64.ActiveCfg = Debug|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Debug|x64.Build.0 = Debug|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Debug|x86.ActiveCfg = Debug|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Debug|x86.Build.0 = Debug|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Release|Any CPU.Build.0 = Release|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Release|x64.ActiveCfg = Release|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Release|x64.Build.0 = Release|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Release|x86.ActiveCfg = Release|Any CPU + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED}.Release|x86.Build.0 = Release|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Debug|x64.ActiveCfg = Debug|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Debug|x64.Build.0 = Debug|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Debug|x86.ActiveCfg = Debug|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Debug|x86.Build.0 = Debug|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Release|Any CPU.Build.0 = Release|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Release|x64.ActiveCfg = Release|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Release|x64.Build.0 = Release|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Release|x86.ActiveCfg = Release|Any CPU + {59184BE7-93CE-4416-94B8-F0CA32C1949B}.Release|x86.Build.0 = Release|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Debug|x64.ActiveCfg = Debug|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Debug|x64.Build.0 = Debug|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Debug|x86.ActiveCfg = Debug|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Debug|x86.Build.0 = Debug|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Release|Any CPU.Build.0 = Release|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Release|x64.ActiveCfg = Release|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Release|x64.Build.0 = Release|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Release|x86.ActiveCfg = Release|Any CPU + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0}.Release|x86.Build.0 = Release|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Debug|x64.ActiveCfg = Debug|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Debug|x64.Build.0 = Debug|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Debug|x86.ActiveCfg = Debug|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Debug|x86.Build.0 = Debug|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Release|Any CPU.Build.0 = Release|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Release|x64.ActiveCfg = Release|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Release|x64.Build.0 = Release|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Release|x86.ActiveCfg = Release|Any CPU + {623E102A-8460-4237-B936-2C50177C527C}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {967E5110-A79D-4BBF-A039-29646474B141} = {FCA2625C-F670-47C8-A57C-0CDDA75191D5} + {3CE96B29-8A19-44E8-A90D-E104A2811C38} = {FCA2625C-F670-47C8-A57C-0CDDA75191D5} + {D46FFFD8-BF31-48E4-830B-DC3AB705E8ED} = {FCA2625C-F670-47C8-A57C-0CDDA75191D5} + {59184BE7-93CE-4416-94B8-F0CA32C1949B} = {540AC47D-3009-4CE1-8052-31639DF3E962} + {DF4366DB-B3C3-4780-9E0C-AB7DEB6B20C0} = {FCA2625C-F670-47C8-A57C-0CDDA75191D5} + {623E102A-8460-4237-B936-2C50177C527C} = {FCA2625C-F670-47C8-A57C-0CDDA75191D5} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {EA46B082-AED4-4EA9-BAD9-924D6448AABE} + EndGlobalSection +EndGlobal diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/FRC.NetworkTables.Core.DesktopLibraries.csproj b/src/FRC.NetworkTables.Core.DesktopLibraries/FRC.NetworkTables.Core.DesktopLibraries.csproj index ef9cf8f..6d1747f 100644 --- a/src/FRC.NetworkTables.Core.DesktopLibraries/FRC.NetworkTables.Core.DesktopLibraries.csproj +++ b/src/FRC.NetworkTables.Core.DesktopLibraries/FRC.NetworkTables.Core.DesktopLibraries.csproj @@ -1,33 +1,37 @@ - - - - Native desktop libraries for NetworkTables - Copyright 2016 RobotDotNet - FRC NetworkTables.Core.DesktopLibraries - FRC NetworkTables.Core.DesktopLibraries - 3.0.0-local - RobotDotNet - net40;netstandard1.5 - $(DefineConstants);CORE - FRC.NetworkTables.Core.DesktopLibraries - FRC.NetworkTables.Core.DesktopLibraries - WPILib;FRC;FIRST;RoboRio - https://github.com/robotdotnet/NetworkTables - https://github.com/robotdotnet/NetworkTables/blob/master/LICENSE.txt - git - git://github.com/robotdotnet/NetworkTables - - - - - - - - - - - - - $(DefineConstants);NETSTANDARD - - + + + + Native desktop libraries for NetworkTables + Copyright 2018 RobotDotNet + FRC NetworkTables.Core.DesktopLibraries + FRC NetworkTables.Core.DesktopLibraries + 4.0.0 + RobotDotNet + netstandard2.0 + FRC.NetworkTables.Core.DesktopLibraries + FRC.NetworkTables.Core.DesktopLibraries + WPILib;FRC;FIRST;RoboRio + https://github.com/robotdotnet/NetworkTables + https://github.com/robotdotnet/NetworkTables/blob/master/LICENSE.txt + git + git://github.com/robotdotnet/NetworkTables + Library + + + + + + + + + + + + + + + + + + + diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/Libraries/frcnm.exe b/src/FRC.NetworkTables.Core.DesktopLibraries/Libraries/frcnm.exe deleted file mode 100644 index 92eef82..0000000 Binary files a/src/FRC.NetworkTables.Core.DesktopLibraries/Libraries/frcnm.exe and /dev/null differ diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/Natives.cs b/src/FRC.NetworkTables.Core.DesktopLibraries/Natives.cs index 55a68d2..925b27c 100644 --- a/src/FRC.NetworkTables.Core.DesktopLibraries/Natives.cs +++ b/src/FRC.NetworkTables.Core.DesktopLibraries/Natives.cs @@ -1,11 +1,11 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("FRC.NetworkTables.Core")] - -namespace NetworkTables.DesktopLibraries -{ - internal class Natives - { - - } -} \ No newline at end of file +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("FRC.NetworkTables.Core")] + +namespace FRC.NetworkTables.DesktopLibraries +{ + internal class Natives + { + + } +} diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/raspbian/libntcorejni.so b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/raspbian/libntcorejni.so new file mode 100644 index 0000000..a4fcba2 Binary files /dev/null and b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/raspbian/libntcorejni.so differ diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/raspbian/ntcorejni.hash b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/raspbian/ntcorejni.hash new file mode 100644 index 0000000..4b7173a --- /dev/null +++ b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/raspbian/ntcorejni.hash @@ -0,0 +1 @@ +d196632169b5db25389163a7a0c7fd67 \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/x86-64/libntcorejni.so b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/x86-64/libntcorejni.so new file mode 100644 index 0000000..d3d83a1 Binary files /dev/null and b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/x86-64/libntcorejni.so differ diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/x86-64/ntcorejni.hash b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/x86-64/ntcorejni.hash new file mode 100644 index 0000000..2113184 --- /dev/null +++ b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/linux/x86-64/ntcorejni.hash @@ -0,0 +1 @@ +46629dd8f95d6b7cf2eb509dde669bad \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/osx/x86-64/libntcorejni.dylib b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/osx/x86-64/libntcorejni.dylib new file mode 100644 index 0000000..0053268 Binary files /dev/null and b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/osx/x86-64/libntcorejni.dylib differ diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/osx/x86-64/ntcorejni.hash b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/osx/x86-64/ntcorejni.hash new file mode 100644 index 0000000..a49525c --- /dev/null +++ b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/osx/x86-64/ntcorejni.hash @@ -0,0 +1 @@ +94b2a8616534a92dff1d7886cb079a0d \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86-64/ntcorejni.dll b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86-64/ntcorejni.dll new file mode 100644 index 0000000..07d4cf1 Binary files /dev/null and b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86-64/ntcorejni.dll differ diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86-64/ntcorejni.hash b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86-64/ntcorejni.hash new file mode 100644 index 0000000..1082e36 --- /dev/null +++ b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86-64/ntcorejni.hash @@ -0,0 +1 @@ +d8855dae8c1e50058fdfa74c464b590c \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86/ntcorejni.dll b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86/ntcorejni.dll new file mode 100644 index 0000000..07e7c84 Binary files /dev/null and b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86/ntcorejni.dll differ diff --git a/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86/ntcorejni.hash b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86/ntcorejni.hash new file mode 100644 index 0000000..e187437 --- /dev/null +++ b/src/FRC.NetworkTables.Core.DesktopLibraries/libraries/windows/x86/ntcorejni.hash @@ -0,0 +1 @@ +d2c8a3ce1878ff83c94679e6bad5810e \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core.Web/FRC.NetworkTables.Core.Web.csproj b/src/FRC.NetworkTables.Core.Web/FRC.NetworkTables.Core.Web.csproj new file mode 100644 index 0000000..360575b --- /dev/null +++ b/src/FRC.NetworkTables.Core.Web/FRC.NetworkTables.Core.Web.csproj @@ -0,0 +1,21 @@ + + + + netstandard2.0 + + + + 8.0 + enable + + + + + + + + + + + + diff --git a/src/FRC.NetworkTables.Core.Web/NTHub.cs b/src/FRC.NetworkTables.Core.Web/NTHub.cs new file mode 100644 index 0000000..c86041d --- /dev/null +++ b/src/FRC.NetworkTables.Core.Web/NTHub.cs @@ -0,0 +1,51 @@ +using Microsoft.AspNetCore.SignalR; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace FRC.NetworkTables.Core.Web +{ + public class NTHub : Hub + { + private readonly NetworkTableInstance m_instance; + + public NTHub(NetworkTableInstance instance) + { + m_instance = instance; + } + + public EntryFlags GetFlags(string key) + { + return m_instance.GetEntry(key).GetEntryFlags(); + } + + public void SetFlags(string key, EntryFlags flags) + { + m_instance.GetEntry(key).SetFlags(flags); + } + + public object? GetValue(string key) + { + return m_instance.GetEntry(key).GetObjectValue(); + } + + public bool SetValue(string key, object value) + { + return m_instance.GetEntry(key).SetValue(value); + } + + public void ForceSetValue(string key, object value) + { + m_instance.GetEntry(key).ForceSetValue(value); + } + + public bool SetDefaultValue(string key, object value) + { + return m_instance.GetEntry(key).SetDefaultValue(value); + } + + + } +} diff --git a/src/FRC.NetworkTables.Core.Web/NetworkTablesMiddleware.cs b/src/FRC.NetworkTables.Core.Web/NetworkTablesMiddleware.cs new file mode 100644 index 0000000..84a043d --- /dev/null +++ b/src/FRC.NetworkTables.Core.Web/NetworkTablesMiddleware.cs @@ -0,0 +1,87 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables.Core.Web +{ + public static class NetworkTablesMiddleware + { + public static void AddNetworkTables(this IServiceCollection services, NetworkTableInstance ntInstance) + { + services.AddSignalR(); + services.AddSingleton(typeof(NetworkTableInstance), ntInstance); + } + + private static List HandleNTRequest(ReadOnlySpan remaining, HttpContext context, NetworkTableInstance nt) + { + var entries = nt.GetEntries(remaining, 0); + List responses = new List(); + foreach (var entry in entries) + { + responses.Add(new NtResponse() + { + Key = entry.GetEntryName(), + Flags = entry.GetEntryFlags(), + LastChange = entry.GetLastChange(), + Value = entry.GetObjectValue() + }); + } + return responses; + } + + public static void UseNetworkTables(this IApplicationBuilder app) + { + app.UseSignalR(routes => + { + routes.MapHub("/nthub"); + + }); + + var nt = app.ApplicationServices.GetService(); + nt.AddConnectionListener((in ConnectionNotification n) => + { + var hub = app.ApplicationServices.GetService>(); + hub.Clients.All.SendAsync("ConnectionNotification", n.Conn, n.Connected).Wait(); + }, false); + + _ = nt.AddEntryListener("", (in RefEntryNotification notification) => + { + var (Name, Value, Flags) = + ( + notification.Name.ToString(), + notification.Value.Value.GetValue(), + notification.Flags + ); + var hub = app.ApplicationServices.GetService>(); + hub.Clients.All.SendAsync("EntryNotification", Name, Value, Flags).Wait(); + }, (NotifyFlags)0xFFFFFFFFu); + + + + app.Use(async (context, next) => + { + var requestPath = context.Request.Path.ToString(); + if (requestPath.StartsWith("/nttable", StringComparison.InvariantCultureIgnoreCase)) + { + var remaining = requestPath.AsMemory().Slice(3); + if (context.Request.Method == "GET") + { + await context.Response.WriteAsync(JsonConvert.SerializeObject(HandleNTRequest(remaining.Span, context, app.ApplicationServices.GetService()))); + return; + } + else + { + context.Response.StatusCode = 404; + return; + } + } + await next.Invoke(); + }); + } + } +} diff --git a/src/FRC.NetworkTables.Core.Web/NtResponse.cs b/src/FRC.NetworkTables.Core.Web/NtResponse.cs new file mode 100644 index 0000000..1d5aaa3 --- /dev/null +++ b/src/FRC.NetworkTables.Core.Web/NtResponse.cs @@ -0,0 +1,12 @@ +using System; + +namespace FRC.NetworkTables.Core.Web +{ + public struct NtResponse + { + public string Key; + public object? Value; + public EntryFlags Flags; + public ulong LastChange; + } +} diff --git a/src/FRC.NetworkTables.Core/ConnectionInfo.cs b/src/FRC.NetworkTables.Core/ConnectionInfo.cs new file mode 100644 index 0000000..62ab802 --- /dev/null +++ b/src/FRC.NetworkTables.Core/ConnectionInfo.cs @@ -0,0 +1,39 @@ +using FRC.NetworkTables.Interop; + +namespace FRC.NetworkTables +{ + /// + /// This class contains all info needed for a given connection. + /// + public readonly struct ConnectionInfo + { + /// Gets the Remote Id of the Connection. + public readonly string RemoteId; + /// Gets the Remote IP Address of the Connection. + public readonly string RemoteIp; + /// Gets the Remote Port of the Connection. + public readonly int RemotePort; + /// Gets the last update time of the Connection. + public readonly long LastUpdate; + /// Gets the Protocol Version of the Connection. + public readonly int ProtocolVersion; + + internal unsafe ConnectionInfo(NtConnectionInfo* info) + { + RemoteId = UTF8String.ReadUTF8String(info->remote_id.str, info->remote_id.len); + RemoteIp = UTF8String.ReadUTF8String(info->remote_ip.str, info->remote_ip.len); + RemotePort = (int)info->remote_port; + LastUpdate = (long)info->last_update; + ProtocolVersion = (int)info->protocol_version; + } + + internal unsafe ConnectionInfo(in NtConnectionInfo info) + { + RemoteId = UTF8String.ReadUTF8String(info.remote_id.str, info.remote_id.len); + RemoteIp = UTF8String.ReadUTF8String(info.remote_ip.str, info.remote_ip.len); + RemotePort = (int)info.remote_port; + LastUpdate = (long)info.last_update; + ProtocolVersion = (int)info.protocol_version; + } + } +} diff --git a/src/FRC.NetworkTables.Core/ConnectionNotification.cs b/src/FRC.NetworkTables.Core/ConnectionNotification.cs new file mode 100644 index 0000000..b96d28f --- /dev/null +++ b/src/FRC.NetworkTables.Core/ConnectionNotification.cs @@ -0,0 +1,20 @@ +using FRC.NetworkTables.Interop; + +namespace FRC.NetworkTables +{ + public readonly struct ConnectionNotification + { + public readonly NtConnectionListener Listener; + public readonly bool Connected; + public readonly ConnectionInfo Conn; + public readonly NetworkTableInstance Instance; + + internal unsafe ConnectionNotification(NetworkTableInstance inst, in NtConnectionNotification notification) + { + this.Listener = notification.listener; + this.Connected = notification.connected.Get(); + this.Conn = new ConnectionInfo(notification.conn); + this.Instance = inst; + } + } +} diff --git a/src/FRC.NetworkTables.Core/EntryInfo.cs b/src/FRC.NetworkTables.Core/EntryInfo.cs new file mode 100644 index 0000000..0c36b9d --- /dev/null +++ b/src/FRC.NetworkTables.Core/EntryInfo.cs @@ -0,0 +1,35 @@ +using FRC; +using FRC.NetworkTables.Interop; +using System; + +namespace FRC.NetworkTables +{ + /// + /// This class contains all info for a given entry. + /// + public readonly struct EntryInfo + { + public readonly NtEntry EntryHandle; + /// Gets the Name of the entry. + public readonly string Name; + /// Gets the Type of the entry. + public readonly NtType Type; + /// Gets the Flags attached to the entry. + public readonly EntryFlags Flags; + /// Gets the last change time of the entry. + public readonly long LastChange; + /// Gets the entry object for this entry. + public NetworkTableEntry Entry => new NetworkTableEntry(m_instance, EntryHandle); + private readonly NetworkTableInstance m_instance; + + internal unsafe EntryInfo(NetworkTableInstance instance, NtEntryInfo* entryInfo) + { + EntryHandle = entryInfo->entry; + Type = (NtType)entryInfo->type; + Flags = (EntryFlags)entryInfo->flags; + LastChange = (long)entryInfo->last_change; + Name = UTF8String.ReadUTF8String(entryInfo->name.str, entryInfo->name.len); + m_instance = instance; + } + } +} diff --git a/src/FRC.NetworkTables.Core/EntryNotification.cs b/src/FRC.NetworkTables.Core/EntryNotification.cs new file mode 100644 index 0000000..1b0f811 --- /dev/null +++ b/src/FRC.NetworkTables.Core/EntryNotification.cs @@ -0,0 +1,25 @@ +using FRC.NetworkTables.Interop; + +namespace FRC.NetworkTables +{ + public readonly struct EntryNotification + { + public readonly NtEntryListener Listener; + public readonly NtEntry EntryHandle; + public readonly string Name; + public readonly NetworkTableValue Value; + public readonly NotifyFlags Flags; + public NetworkTableEntry Entry => new NetworkTableEntry(m_instance, EntryHandle); + private readonly NetworkTableInstance m_instance; + + internal unsafe EntryNotification(NetworkTableInstance inst, in RefEntryNotification entry) + { + Listener = entry.Listener; + EntryHandle = entry.EntryHandle; + Name = entry.Name.ToString(); + Value = new NetworkTableValue(entry.Value.Value); + Flags = entry.Flags; + m_instance = inst; + } + } +} diff --git a/src/FRC.NetworkTables.Core/Enumerations.cs b/src/FRC.NetworkTables.Core/Enumerations.cs new file mode 100644 index 0000000..2a416f2 --- /dev/null +++ b/src/FRC.NetworkTables.Core/Enumerations.cs @@ -0,0 +1,135 @@ +using System; + +namespace FRC.NetworkTables +{ + /// + /// An enumeration of all types allowed in the NetworkTables. + /// + [Flags] + public enum NtType : uint + { + /// + /// No type assigned + /// + Unassigned = 0, + /// + /// Boolean type + /// + Boolean = 0x01, + /// + /// Double type + /// + Double = 0x02, + /// + /// String type + /// + String = 0x04, + /// + /// Raw type + /// + Raw = 0x08, + /// + /// Boolean Array type + /// + BooleanArray = 0x10, + /// + /// Double Array type + /// + DoubleArray = 0x20, + /// + /// String Array type + /// + StringArray = 0x40, + /// + /// Rpc type + /// + Rpc = 0x80 + } + + /// + /// The flags avalible for TableListeners + /// + [Flags] + public enum NotifyFlags : uint + { + /// + /// Notify nobody + /// + None = 0x00, + /// + /// Initial listener addition + /// + Immediate = 0x01, + /// + /// Changed locally + /// + Local = 0x02, + /// + /// Newly created entry + /// + New = 0x04, + /// + /// Deleted entry + /// + Delete = 0x08, + /// + /// Value changed for entry + /// + Update = 0x10, + /// + /// Flags changed for entry + /// + FlagsChanged = 0x20 + }; + + /// + /// The flags avalible for Entries + /// + [Flags] + public enum EntryFlags : uint + { + /// + /// No flags + /// + None = 0x00, + /// + /// Set entry to be persistent + /// + Persistent = 0x01 + } + + /// + /// The log level to use for the NT logger + /// + public enum LogLevel : uint + { + /// + Critical = 50, + /// + Error = 40, + /// + Warning = 30, + /// + Info = 20, + /// + Debug = 10, + /// + Debug1 = 9, + /// + Debug2 = 8, + /// + Debug3 = 7, + /// + Debug4 = 6 + } + + public enum NetworkMode : uint + { + None = 0x00, /* not running */ + Server = 0x01, /* running in server mode */ + Client = 0x02, /* running in client mode */ + Starting = 0x04, /* flag for starting (either client or server) */ + Failure = 0x08, /* flag for failure (either client or server) */ + }; + +} \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core/FRC.NetworkTables.Core.csproj b/src/FRC.NetworkTables.Core/FRC.NetworkTables.Core.csproj index daaa059..0b3785e 100644 --- a/src/FRC.NetworkTables.Core/FRC.NetworkTables.Core.csproj +++ b/src/FRC.NetworkTables.Core/FRC.NetworkTables.Core.csproj @@ -1,52 +1,47 @@ - - - - NetworkTables using the ntcore library. - Copyright 2016 RobotDotNet - FRC NetworkTables.Core - FRC NetworkTables.Core - 3.0.0-local - RobotDotNet - net45;net40;netstandard1.5 - $(DefineConstants);CORE - true - FRC.NetworkTables.Core - FRC.NetworkTables.Core - WPILib;FRC;FIRST;RoboRio - https://github.com/robotdotnet/NetworkTables - https://github.com/robotdotnet/NetworkTables/blob/master/LICENSE.txt - git - git://github.com/robotdotnet/NetworkTables - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - $(DefineConstants);NET40 - - - - $(DefineConstants);NETSTANDARD - - + + + + Library + netstandard2.0 + + + NetworkTables using the ntcore library. + Copyright 2016 RobotDotNet + FRC NetworkTables.Core + FRC NetworkTables.Core + 4.0.3 + RobotDotNet + true + FRC.NetworkTables.Core + FRC.NetworkTables.Core + WPILib;FRC;FIRST;RoboRio + https://github.com/robotdotnet/NetworkTables + https://github.com/robotdotnet/NetworkTables/blob/master/LICENSE.txt + git + git://github.com/robotdotnet/NetworkTables + false + false + false + false + + + + true + 8.0 + FRC.NetworkTables + enable + + + + 1701;1702;1591 + + + + + + + + + + + diff --git a/src/FRC.NetworkTables.Core/Interop/Handles.cs b/src/FRC.NetworkTables.Core/Interop/Handles.cs new file mode 100644 index 0000000..e6d9769 --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/Handles.cs @@ -0,0 +1,1000 @@ +using System; +using System.Runtime.CompilerServices; + +namespace FRC.NetworkTables.Interop +{ + /// + /// Low level NT Core Handle + /// + public readonly struct NtHandle : IEquatable + { + private readonly int m_value; + + /// + /// Create a handle from an int. + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NtHandle(int value) + { + m_value = value; + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Get() + { + return m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool Equals(object obj) + { + if (obj is NtHandle v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(NtHandle other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator==(NtHandle lhs, NtHandle rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator!=(NtHandle lhs, NtHandle rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Instance Handle + /// + public readonly struct NtInst + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NtInst(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NtHandle(NtInst value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool Equals(object obj) + { + if (obj is NtInst v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(NtInst other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(NtInst lhs, NtInst rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtInst lhs, NtInst rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Entry Handle + /// + public readonly struct NtEntry : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtEntry(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtEntry value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtEntry v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtEntry other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtEntry lhs, NtEntry rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtEntry lhs, NtEntry rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Entry Listener Handle + /// + public readonly struct NtEntryListener : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtEntryListener(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtEntryListener value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtEntryListener v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtEntryListener other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtEntryListener lhs, NtEntryListener rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtEntryListener lhs, NtEntryListener rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Entry Poller Handle + /// + public readonly struct NtEntryListenerPoller : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtEntryListenerPoller(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtEntryListenerPoller value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtEntryListenerPoller v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtEntryListenerPoller other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtEntryListenerPoller lhs, NtEntryListenerPoller rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtEntryListenerPoller lhs, NtEntryListenerPoller rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Connection Listener Handle + /// + public readonly struct NtConnectionListener : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtConnectionListener(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtConnectionListener value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtConnectionListener v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtConnectionListener other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtConnectionListener lhs, NtConnectionListener rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtConnectionListener lhs, NtConnectionListener rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Connection Listener Poller Handle + /// + public readonly struct NtConnectionListenerPoller : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtConnectionListenerPoller(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtConnectionListenerPoller value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtConnectionListenerPoller v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtConnectionListenerPoller other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtConnectionListenerPoller lhs, NtConnectionListenerPoller rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtConnectionListenerPoller lhs, NtConnectionListenerPoller rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Logger Handle + /// + public readonly struct NtLogger : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtLogger(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtLogger value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtLogger v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtLogger other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtLogger lhs, NtLogger rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtLogger lhs, NtLogger rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Logger Poller Handle + /// + public readonly struct NtLoggerPoller : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtLoggerPoller(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtLoggerPoller value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtLoggerPoller v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtLoggerPoller other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtLoggerPoller lhs, NtLoggerPoller rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtLoggerPoller lhs, NtLoggerPoller rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Rpc Call Handle + /// + public readonly struct NtRpcCall : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtRpcCall(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtRpcCall value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtRpcCall v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtRpcCall other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtRpcCall lhs, NtRpcCall rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtRpcCall lhs, NtRpcCall rhs) + { + return lhs.m_value != rhs.m_value; + } + } + + /// + /// Low Level NT Core Rpc Call Poller Handle + /// + public readonly struct NtRpcCallPoller : IEquatable + { + private readonly NtHandle m_value; + + /// + /// Creates a new handle + /// + /// handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public NtRpcCallPoller(int value) + { + m_value = new NtHandle(value); + } + + /// + /// Gets the raw handle value + /// + /// The raw handle value + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Get() + { + return m_value.Get(); + } + + /// + /// Converts a handle to a base handle + /// + /// The current handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator NtHandle(NtRpcCallPoller value) + { + return value.m_value; + } + + /// + /// Checks equality between another object + /// + /// Object to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) + { + if (obj is NtRpcCallPoller v) + { + return Equals(v); + } + return false; + } + + /// + /// Checks equality between another Handle + /// + /// Handle to check + /// True if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(NtRpcCallPoller other) + { + return m_value == other.m_value; + } + + /// + /// Gets Hash Code of Handle + /// + /// Handle Value as Hash Code + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() + { + return m_value.GetHashCode(); + } + + /// + /// Gets if 2 handles are equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NtRpcCallPoller lhs, NtRpcCallPoller rhs) + { + return lhs.m_value == rhs.m_value; + } + + /// + /// Gets if 2 handles are not equal + /// + /// Left Hand Side + /// Right Hand Side + /// true if not equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NtRpcCallPoller lhs, NtRpcCallPoller rhs) + { + return lhs.m_value != rhs.m_value; + } + } +} diff --git a/src/FRC.NetworkTables.Core/Interop/INtCore.cs b/src/FRC.NetworkTables.Core/Interop/INtCore.cs new file mode 100644 index 0000000..1cd7217 --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/INtCore.cs @@ -0,0 +1,523 @@ +using System; + +namespace FRC.NetworkTables.Interop +{ + public interface INtCore + { + unsafe NtInst NT_GetDefaultInstance(); + unsafe NtInst NT_CreateInstance(); + unsafe void NT_DestroyInstance(NtInst inst); + unsafe NtInst NT_GetInstanceFromHandle(NtHandle handle); + unsafe NtEntry NT_GetEntry(NtInst inst, byte* name, UIntPtr name_len); + unsafe NtEntry* NT_GetEntries(NtInst inst, byte* prefix, UIntPtr prefix_len, uint types, UIntPtr* count); + unsafe byte* NT_GetEntryName(NtEntry entry, UIntPtr* name_len); + + + + + unsafe NtType NT_GetEntryType(NtEntry entry); + + + + + unsafe ulong NT_GetEntryLastChange(NtEntry entry); + + + + + unsafe void NT_GetEntryValue(NtEntry entry, NtValue* value); + + + + + unsafe NtBool NT_SetDefaultEntryValue(NtEntry entry, NtValue* default_value); + + + + + unsafe NtBool NT_SetEntryValue(NtEntry entry, NtValue* value); + + + + + unsafe void NT_SetEntryTypeValue(NtEntry entry, NtValue* value); + + + + + unsafe void NT_SetEntryFlags(NtEntry entry, uint flags); + + + + + unsafe uint NT_GetEntryFlags(NtEntry entry); + + + + + unsafe void NT_DeleteEntry(NtEntry entry); + + + + + unsafe void NT_DeleteAllEntries(NtInst inst); + + + + + unsafe NtEntryInfo* NT_GetEntryInfo(NtInst inst, byte* prefix, UIntPtr prefix_len, uint types, UIntPtr* count); + + + + + unsafe NtBool NT_GetEntryInfoHandle(NtEntry entry, NtEntryInfo* info); + + + + + unsafe NtEntryListenerPoller NT_CreateEntryListenerPoller(NtInst inst); + + + + + unsafe void NT_DestroyEntryListenerPoller(NtEntryListenerPoller poller); + + + + + unsafe NtEntryListener NT_AddPolledEntryListener(NtEntryListenerPoller poller, byte* prefix, UIntPtr prefix_len, uint flags); + + + + + unsafe NtEntryListener NT_AddPolledEntryListenerSingle(NtEntryListenerPoller poller, NtEntry entry, uint flags); + + + + + unsafe NtEntryNotification* NT_PollEntryListener(NtEntryListenerPoller poller, UIntPtr* len); + + + + + unsafe NtEntryNotification* NT_PollEntryListenerTimeout(NtEntryListenerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + + + + unsafe void NT_CancelPollEntryListener(NtEntryListenerPoller poller); + + + + + unsafe void NT_RemoveEntryListener(NtEntryListener entry_listener); + + + + + unsafe NtBool NT_WaitForEntryListenerQueue(NtInst inst, double timeout); + + + + + unsafe NtConnectionListenerPoller NT_CreateConnectionListenerPoller(NtInst inst); + + + + + unsafe void NT_DestroyConnectionListenerPoller(NtConnectionListenerPoller poller); + + + + + unsafe NtConnectionListener NT_AddPolledConnectionListener(NtConnectionListenerPoller poller, NtBool immediate_notify); + + + + + unsafe NtConnectionNotification* NT_PollConnectionListener(NtConnectionListenerPoller poller, UIntPtr* len); + + + + + unsafe NtConnectionNotification* NT_PollConnectionListenerTimeout(NtConnectionListenerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + + + + unsafe void NT_CancelPollConnectionListener(NtConnectionListenerPoller poller); + + + + + unsafe void NT_RemoveConnectionListener(NtConnectionListener conn_listener); + + + + + unsafe NtBool NT_WaitForConnectionListenerQueue(NtInst inst, double timeout); + + + + + unsafe NtRpcCallPoller NT_CreateRpcCallPoller(NtInst inst); + + + + + unsafe void NT_DestroyRpcCallPoller(NtRpcCallPoller poller); + + + + + unsafe void NT_CreatePolledRpc(NtEntry entry, byte* def, UIntPtr def_len, NtRpcCallPoller poller); + + + + + unsafe NtRpcAnswer* NT_PollRpc(NtRpcCallPoller poller, UIntPtr* len); + + + + + unsafe NtRpcAnswer* NT_PollRpcTimeout(NtRpcCallPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + + + + unsafe void NT_CancelPollRpc(NtRpcCallPoller poller); + + + + + unsafe NtBool NT_WaitForRpcCallQueue(NtInst inst, double timeout); + + + + + unsafe void NT_PostRpcResponse(NtEntry entry, NtRpcCall call, byte* result, UIntPtr result_len); + + + + + unsafe NtRpcCall NT_CallRpc(NtEntry entry, byte* @params, UIntPtr params_len); + + + + + unsafe byte* NT_GetRpcResult(NtEntry entry, NtRpcCall call, UIntPtr* result_len); + + + + + unsafe byte* NT_GetRpcResultTimeout(NtEntry entry, NtRpcCall call, UIntPtr* result_len, double timeout, NtBool* timed_out); + + + + + unsafe void NT_CancelRpcResult(NtEntry entry, NtRpcCall call); + + + + + unsafe byte* NT_PackRpcDefinition(NtRpcDefinition def, UIntPtr* packed_len); + + + + + unsafe NtBool NT_UnpackRpcDefinition(byte* packed, UIntPtr packed_len, NtRpcDefinition* def); + + + + + unsafe byte* NT_PackRpcValues(NtValue** values, UIntPtr values_len, UIntPtr* packed_len); + + + + + unsafe NtValue** NT_UnpackRpcValues(byte* packed, UIntPtr packed_len, NtType* types, UIntPtr types_len); + + + + + unsafe void NT_SetNetworkIdentity(NtInst inst, byte* name, UIntPtr name_len); + + + + + unsafe uint NT_GetNetworkMode(NtInst inst); + + + + + unsafe void NT_StartServer(NtInst inst, byte* persist_filename, byte* listen_address, uint port); + + + + + unsafe void NT_StopServer(NtInst inst); + + + + + unsafe void NT_StartClientNone(NtInst inst); + + + + + unsafe void NT_StartClient(NtInst inst, byte* server_name, uint port); + + + + + unsafe void NT_StartClientMulti(NtInst inst, UIntPtr count, byte** server_names, uint* ports); + + + + + unsafe void NT_StartClientTeam(NtInst inst, uint team, uint port); + + + + + unsafe void NT_StopClient(NtInst inst); + + + + + unsafe void NT_SetServer(NtInst inst, byte* server_name, uint port); + + + + + unsafe void NT_SetServerMulti(NtInst inst, UIntPtr count, byte** server_names, uint* ports); + + + + + unsafe void NT_SetServerTeam(NtInst inst, uint team, uint port); + + + + + unsafe void NT_StartDSClient(NtInst inst, uint port); + + + + + unsafe void NT_StopDSClient(NtInst inst); + + + + + unsafe void NT_SetUpdateRate(NtInst inst, double interval); + + + + + unsafe void NT_Flush(NtInst inst); + + + + + unsafe NtConnectionInfo* NT_GetConnections(NtInst inst, UIntPtr* count); + + + + + unsafe NtBool NT_IsConnected(NtInst inst); + + + + + unsafe byte* NT_SavePersistent(NtInst inst, byte* filename); + + + + + unsafe byte* NT_LoadPersistent(NtInst inst, byte* filename, IntPtr warnFunc); + + + + + unsafe byte* NT_SaveEntries(NtInst inst, byte* filename, byte* prefix, UIntPtr prefix_len); + + + + + unsafe byte* NT_LoadEntries(NtInst inst, byte* filename, byte* prefix, UIntPtr prefix_len, IntPtr warnFunc); + + + + + unsafe void NT_DisposeValue(NtValue* value); + + + + + unsafe void NT_InitValue(NtValue* value); + + + + + unsafe void NT_DisposeString(NtString* str); + + + + + unsafe void NT_InitString(NtString* str); + + + + + unsafe void NT_DisposeEntryArray(NtEntry* arr, UIntPtr count); + + + + + unsafe void NT_DisposeConnectionInfoArray(NtConnectionInfo* arr, UIntPtr count); + + + + + unsafe void NT_DisposeEntryInfoArray(NtEntryInfo* arr, UIntPtr count); + + + + + unsafe void NT_DisposeEntryInfo(NtEntryInfo* info); + + + + + unsafe void NT_DisposeRpcDefinition(NtRpcDefinition* def); + + + + + unsafe void NT_DisposeRpcAnswerArray(NtRpcAnswer* arr, UIntPtr count); + + + + + unsafe void NT_DisposeRpcAnswer(NtRpcAnswer* answer); + + + + + unsafe void NT_DisposeEntryNotificationArray(NtEntryNotification* arr, UIntPtr count); + + + + + unsafe void NT_DisposeEntryNotification(NtEntryNotification* info); + + + + + unsafe void NT_DisposeConnectionNotificationArray(NtConnectionNotification* arr, UIntPtr count); + + + + + unsafe void NT_DisposeConnectionNotification(NtConnectionNotification* info); + + + + + unsafe void NT_DisposeLogMessageArray(NtLogMessage* arr, UIntPtr count); + + + + + unsafe void NT_DisposeLogMessage(NtLogMessage* info); + + + + + unsafe ulong NT_Now(); + + + + + unsafe NtLoggerPoller NT_CreateLoggerPoller(NtInst inst); + + + + + unsafe void NT_DestroyLoggerPoller(NtLoggerPoller poller); + + + + + unsafe NtLogger NT_AddPolledLogger(NtLoggerPoller poller, uint min_level, uint max_level); + + + + + unsafe NtLogMessage* NT_PollLogger(NtLoggerPoller poller, UIntPtr* len); + + + + + unsafe NtLogMessage* NT_PollLoggerTimeout(NtLoggerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + + + + unsafe void NT_CancelPollLogger(NtLoggerPoller poller); + + + + + unsafe void NT_RemoveLogger(NtLogger logger); + + + + + unsafe NtBool NT_WaitForLoggerQueue(NtInst inst, double timeout); + + + + + unsafe byte* NT_AllocateCharArray(UIntPtr size); + + + + + unsafe NtBool* NT_AllocateBooleanArray(UIntPtr size); + + + + + unsafe double* NT_AllocateDoubleArray(UIntPtr size); + + + + + unsafe NtString* NT_AllocateStringArray(UIntPtr size); + + + + + unsafe void NT_FreeCharArray(byte* v_char); + + + + + unsafe void NT_FreeDoubleArray(double* v_double); + + + + + unsafe void NT_FreeBooleanArray(NtBool* v_boolean); + + + + + unsafe void NT_FreeStringArray(NtString* v_string, UIntPtr arr_size); + + + } +} + diff --git a/src/FRC.NetworkTables.Core/Interop/NtCore.cs b/src/FRC.NetworkTables.Core/Interop/NtCore.cs new file mode 100644 index 0000000..de4e655 --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/NtCore.cs @@ -0,0 +1,1329 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using FRC.NativeLibraryUtilities; + +[assembly: InternalsVisibleTo("FRC.NetworkTables.Core.Test")] + +namespace FRC.NetworkTables.Interop +{ + /// + /// Raw NT Core access function + /// + public static class NtCore + { + private static INtCore m_ntcore; + + private unsafe readonly static char* NullTerminator; + +#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. + static NtCore() +#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. + { + unsafe + { + NullTerminator = (char*)Marshal.AllocHGlobal(sizeof(char)); + *NullTerminator = '\0'; + } + + if (NtCoreHelper.LoadOnStaticInit) + { + var ntcore = NtCoreHelper.Load(); + m_ntcore = ntcore ?? throw new InvalidOperationException("Failed to load ntcore"); + } + } + + public static void ForceLoad() + { + if (m_ntcore == null) + { + var ntcore = NtCoreHelper.Load(); + m_ntcore = ntcore ?? throw new InvalidOperationException("Failed to load ntcore"); + } + } + + public static void ForceLoadDirect(string directPath) + { + if (m_ntcore != null) + { + throw new InvalidOperationException("Direct load not supported after implict load"); + } + + var nativeLoader = new NativeLibraryLoader(); + nativeLoader.LoadNativeLibrary(directPath, true); + var ntcore = nativeLoader.LoadNativeInterface(); + m_ntcore = ntcore ?? throw new Exception("Failed to load native interface?"); + } + + public static void LoadExisting(INtCore ntcore) + { + if (m_ntcore != null) + { + throw new InvalidOperationException("Direct load not supported after implict load"); + } + m_ntcore = ntcore; + } + + + private static Span GetSpanOrBuffer(Span store, int length) + { + return store.Length >= length ? store.Slice(0, length) : new T[length]; + } + + public static ulong Now() + { + return m_ntcore.NT_Now(); + } + + public static NtInst GetDefaultInstance() + { + return m_ntcore.NT_GetDefaultInstance(); + } + + public static NtInst CreateInstance() + { + return m_ntcore.NT_CreateInstance(); + } + + public static void DestroyInstance(NtInst inst) + { + m_ntcore.NT_DestroyInstance(inst); + } + + public static NtInst GetInstanceFromHandle(NtHandle handle) + { + return m_ntcore.NT_GetInstanceFromHandle(handle); + } + + public static unsafe NtEntry GetEntry(NtInst inst, ReadOnlySpan name) + { + fixed (char* p = name.IsEmpty ? new ReadOnlySpan(NullTerminator, 1) : name) + { + var dLen = Encoding.UTF8.GetByteCount(p, name.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, name.Length, d, dLen); + return m_ntcore.NT_GetEntry(inst, d, (UIntPtr)dLen); + } + } + } + + public static unsafe NtEntry GetEntry(NtInst inst, string name) + { + fixed (char* p = name) + { + var dLen = Encoding.UTF8.GetByteCount(p, name.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, name.Length, d, dLen); + return m_ntcore.NT_GetEntry(inst, d, (UIntPtr)dLen); + } + } + } + + public static unsafe int GetEntryCount(NtInst inst, ReadOnlySpan prefix, NtType types) + { + fixed (char* p = prefix.IsEmpty ? new ReadOnlySpan(NullTerminator, 1) : prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntries(inst, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + m_ntcore.NT_DisposeEntryArray(data, count); + return len; + } + } + } + + public static unsafe int GetEntryCount(NtInst inst, string prefix, NtType types) + { + fixed (char* p = prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntries(inst, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + m_ntcore.NT_DisposeEntryArray(data, count); + return len; + } + } + } + + public static unsafe ReadOnlySpan GetEntries(NtInst inst, ReadOnlySpan prefix, NtType types, Span store) + { + fixed (char* p = prefix.IsEmpty ? new ReadOnlySpan(NullTerminator, 1) : prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntries(inst, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + Span entries = GetSpanOrBuffer(store, len); + new Span(data, len).CopyTo(entries); + m_ntcore.NT_DisposeEntryArray(data, count); + return entries; + } + } + } + + public static unsafe ReadOnlySpan GetEntries(NtInst inst, string prefix, NtType types, Span store) + { + fixed (char* p = prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntries(inst, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + Span entries = GetSpanOrBuffer(store, len); + new Span(data, len).CopyTo(entries); + m_ntcore.NT_DisposeEntryArray(data, count); + return entries; + } + } + } + + public static unsafe ReadOnlySpan GetEntriesManaged(NetworkTableInstance inst, ReadOnlySpan prefix, NtType types, Span store) + { + fixed (char* p = prefix.IsEmpty ? new ReadOnlySpan(NullTerminator, 1) : prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntries(inst.Handle, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + Span entries = GetSpanOrBuffer(store, len); + for (int i = 0; i < entries.Length; i++) + { + entries[i] = new NetworkTableEntry(inst, data[i]); + } + m_ntcore.NT_DisposeEntryArray(data, count); + return entries; + } + } + } + + public static unsafe ReadOnlySpan GetEntriesManaged(NetworkTableInstance inst, string prefix, NtType types, Span store) + { + fixed (char* p = prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntries(inst.Handle, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + Span entries = GetSpanOrBuffer(store, len); + for (int i = 0; i < entries.Length; i++) + { + entries[i] = new NetworkTableEntry(inst, data[i]); + } + m_ntcore.NT_DisposeEntryArray(data, count); + return entries; + } + } + } + + public static unsafe string GetEntryName(NtEntry entry) + { + UIntPtr len = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntryName(entry, &len); + string ret = UTF8String.ReadUTF8String(data, len); + m_ntcore.NT_FreeCharArray(data); + return ret; + } + + public static NtType GetEntryType(NtEntry entry) + { + return m_ntcore.NT_GetEntryType(entry); + } + + public static ulong GetEntryLastChange(NtEntry entry) + { + return m_ntcore.NT_GetEntryLastChange(entry); + } + + public static unsafe ManagedValue GetEntryValue(NtEntry entry) + { + NtValue value = new NtValue(); + m_ntcore.NT_GetEntryValue(entry, &value); + var ret = new ManagedValue(&value); + m_ntcore.NT_DisposeValue(&value); + return ret; + } + + internal static unsafe bool SetDefaultEntryValue(NtEntry entry, in ManagedValue value) + { + NtValue v = new NtValue + { + type = value.Type + }; + + switch (value.Type) + { + case NtType.Boolean: + v.data.v_boolean = value.Data.VBoolean; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + case NtType.Double: + v.data.v_double = value.Data.VDouble; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + case NtType.String: + fixed (char* p = value.Data.VString.AsSpan()) + { + var dLen = Encoding.UTF8.GetByteCount(p, value.Data.VString!.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, value.Data.VString.Length, d, dLen); + v.data.v_string.str = d; + v.data.v_string.len = (UIntPtr)dLen; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + case NtType.Raw: + case NtType.Rpc: + fixed (byte* p = value.Data.VRaw.AsSpan()) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw!.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + case NtType.BooleanArray: + fixed (bool* p = value.Data.VBooleanArray.AsSpan()) + { + var len = value.Data.VBooleanArray!.Length; + Span dSpan = len <= 256 ? stackalloc NtBool[len == 0 ? 1 : 0] : new NtBool[len]; + fixed (NtBool* d = dSpan) + { + v.data.arr_boolean.arr = d; + v.data.arr_boolean.len = (UIntPtr)len; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + case NtType.DoubleArray: + fixed (byte* p = value.Data.VRaw.AsSpan()) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw!.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + case NtType.StringArray: + v.data.arr_string.arr = (NtString*)Marshal.AllocHGlobal(value.Data.VStringArray!.Length * sizeof(NtString)); + v.data.arr_string.len = (UIntPtr)value.Data.VStringArray.Length; + var sSpan = value.Data.VStringArray.AsSpan(); + for (int i = 0; i < sSpan.Length; i++) + { + Utilities.CreateNtString(sSpan[i], &v.data.arr_string.arr[i]); + } + var ret = m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + int sLen = (int)v.data.arr_string.len; + for (int i = 0; i < sLen; i++) + { + Utilities.DisposeNtString(&v.data.arr_string.arr[i]); + } + Marshal.FreeHGlobal((IntPtr)v.data.arr_string.arr); + return ret; + default: + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + + public static unsafe bool SetEntryValue(NtEntry entry, in ManagedValue value) + { + NtValue v = new NtValue + { + type = value.Type + }; + + switch (value.Type) + { + case NtType.Boolean: + v.data.v_boolean = value.Data.VBoolean; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + case NtType.Double: + v.data.v_double = value.Data.VDouble; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + case NtType.String: + fixed (char* p = value.Data.VString.AsSpan()) + { + var dLen = Encoding.UTF8.GetByteCount(p, value.Data.VString!.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, value.Data.VString.Length, d, dLen); + v.data.v_string.str = d; + v.data.v_string.len = (UIntPtr)dLen; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + } + case NtType.Raw: + case NtType.Rpc: + fixed (byte* p = value.Data.VRaw.AsSpan()) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw!.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + case NtType.BooleanArray: + fixed (bool* p = value.Data.VBooleanArray.AsSpan()) + { + var len = value.Data.VBooleanArray!.Length; + Span dSpan = len <= 256 ? stackalloc NtBool[len == 0 ? 1 : 0] : new NtBool[len]; + fixed (NtBool* d = dSpan) + { + v.data.arr_boolean.arr = d; + v.data.arr_boolean.len = (UIntPtr)len; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + } + case NtType.DoubleArray: + fixed (byte* p = value.Data.VRaw.AsSpan()) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw!.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + case NtType.StringArray: + v.data.arr_string.arr = (NtString*)Marshal.AllocHGlobal(value.Data.VStringArray!.Length * sizeof(NtString)); + v.data.arr_string.len = (UIntPtr)value.Data.VStringArray.Length; + var sSpan = value.Data.VStringArray.AsSpan(); + for (int i = 0; i < sSpan.Length; i++) + { + Utilities.CreateNtString(sSpan[i], &v.data.arr_string.arr[i]); + } + var ret = m_ntcore.NT_SetEntryValue(entry, &v).Get(); + int sLen = (int)v.data.arr_string.len; + for (int i = 0; i < sLen; i++) + { + Utilities.DisposeNtString(&v.data.arr_string.arr[i]); + } + Marshal.FreeHGlobal((IntPtr)v.data.arr_string.arr); + return ret; + default: + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + + internal static unsafe void SetEntryTypeValue(NtEntry entry, in ManagedValue value) + { + NtValue v = new NtValue + { + type = value.Type + }; + + switch (value.Type) + { + case NtType.Boolean: + v.data.v_boolean = value.Data.VBoolean; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + case NtType.Double: + v.data.v_double = value.Data.VDouble; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + case NtType.String: + fixed (char* p = value.Data.VString.AsSpan()) + { + var dLen = Encoding.UTF8.GetByteCount(p, value.Data.VString!.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, value.Data.VString.Length, d, dLen); + v.data.v_string.str = d; + v.data.v_string.len = (UIntPtr)dLen; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + } + case NtType.Raw: + case NtType.Rpc: + fixed (byte* p = value.Data.VRaw.AsSpan()) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw!.Length; + v.data.v_raw.str = p; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + case NtType.BooleanArray: + fixed (bool* p = value.Data.VBooleanArray.AsSpan()) + { + var len = value.Data.VBooleanArray!.Length; + Span dSpan = len <= 256 ? stackalloc NtBool[len == 0 ? 1 : 0] : new NtBool[len]; + fixed (NtBool* d = dSpan) + { + v.data.arr_boolean.arr = d; + v.data.arr_boolean.len = (UIntPtr)len; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + } + case NtType.DoubleArray: + fixed (byte* p = value.Data.VRaw.AsSpan()) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw!.Length; + v.data.v_raw.str = p; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + case NtType.StringArray: + v.data.arr_string.arr = (NtString*)Marshal.AllocHGlobal(value.Data.VStringArray!.Length * sizeof(NtString)); + v.data.arr_string.len = (UIntPtr)value.Data.VStringArray.Length; + var sSpan = value.Data.VStringArray.AsSpan(); + for (int i = 0; i < sSpan.Length; i++) + { + Utilities.CreateNtString(sSpan[i], &v.data.arr_string.arr[i]); + } + m_ntcore.NT_SetEntryTypeValue(entry, &v); + int sLen = (int)v.data.arr_string.len; + for (int i = 0; i < sLen; i++) + { + Utilities.DisposeNtString(&v.data.arr_string.arr[i]); + } + Marshal.FreeHGlobal((IntPtr)v.data.arr_string.arr); + break; + default: + m_ntcore.NT_SetDefaultEntryValue(entry, &v); + break; + } + } + + + internal static unsafe bool SetDefaultEntryValue(NtEntry entry, in RefManagedValue value) + { + NtValue v = new NtValue + { + type = value.Type + }; + + switch (value.Type) + { + case NtType.Boolean: + v.data.v_boolean = value.Data.VBoolean; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + case NtType.Double: + v.data.v_double = value.Data.VDouble; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + case NtType.String: + fixed (char* p = value.Data.VString) + { + var dLen = Encoding.UTF8.GetByteCount(p, value.Data.VString.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, value.Data.VString.Length, d, dLen); + v.data.v_string.str = d; + v.data.v_string.len = (UIntPtr)dLen; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + case NtType.Raw: + case NtType.Rpc: + fixed(byte* p = value.Data.VRaw) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + case NtType.BooleanArray: + fixed (bool* p = value.Data.VBooleanArray) + { + var len = value.Data.VBooleanArray.Length; + Span dSpan = len <= 256 ? stackalloc NtBool[len == 0 ? 1 : 0] : new NtBool[len]; + fixed(NtBool* d = dSpan) + { + v.data.arr_boolean.arr = d; + v.data.arr_boolean.len = (UIntPtr)len; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + case NtType.DoubleArray: + fixed (byte* p = value.Data.VRaw) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + case NtType.StringArray: + v.data.arr_string.arr = (NtString*)Marshal.AllocHGlobal(value.Data.VStringArray.Length * sizeof(NtString)); + v.data.arr_string.len = (UIntPtr)value.Data.VStringArray.Length; + var sSpan = value.Data.VStringArray; + for (int i = 0; i < sSpan.Length; i++) + { + Utilities.CreateNtString(sSpan[i], &v.data.arr_string.arr[i]); + } + var ret = m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + int sLen = (int)v.data.arr_string.len; + for (int i = 0; i < sLen; i++) + { + Utilities.DisposeNtString(&v.data.arr_string.arr[i]); + } + Marshal.FreeHGlobal((IntPtr)v.data.arr_string.arr); + return ret; + default: + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + + internal static unsafe bool SetEntryValue(NtEntry entry, in RefManagedValue value) + { + NtValue v = new NtValue + { + type = value.Type + }; + + switch (value.Type) + { + case NtType.Boolean: + v.data.v_boolean = value.Data.VBoolean; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + case NtType.Double: + v.data.v_double = value.Data.VDouble; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + case NtType.String: + fixed (char* p = value.Data.VString) + { + if (p == null) + { + v.data.v_string.str = null; + v.data.v_string.len = (UIntPtr)0; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + var dLen = Encoding.UTF8.GetByteCount(p, value.Data.VString.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, value.Data.VString.Length, d, dLen); + v.data.v_string.str = d; + v.data.v_string.len = (UIntPtr)dLen; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + } + case NtType.Raw: + case NtType.Rpc: + fixed (byte* p = value.Data.VRaw) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + case NtType.BooleanArray: + fixed (bool* p = value.Data.VBooleanArray) + { + var len = value.Data.VBooleanArray.Length; + Span dSpan = len <= 256 ? stackalloc NtBool[len == 0 ? 1 : 0] : new NtBool[len]; + fixed (NtBool* d = dSpan) + { + v.data.arr_boolean.arr = d; + v.data.arr_boolean.len = (UIntPtr)len; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + } + case NtType.DoubleArray: + fixed (byte* p = value.Data.VRaw) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw.Length; + v.data.v_raw.str = p; + return m_ntcore.NT_SetEntryValue(entry, &v).Get(); + } + case NtType.StringArray: + v.data.arr_string.arr = (NtString*)Marshal.AllocHGlobal(value.Data.VStringArray.Length * sizeof(NtString)); + v.data.arr_string.len = (UIntPtr)value.Data.VStringArray.Length; + var sSpan = value.Data.VStringArray; + for (int i = 0; i < sSpan.Length; i++) + { + Utilities.CreateNtString(sSpan[i], &v.data.arr_string.arr[i]); + } + var ret = m_ntcore.NT_SetEntryValue(entry, &v).Get(); + int sLen = (int)v.data.arr_string.len; + for (int i = 0; i < sLen; i++) + { + Utilities.DisposeNtString(&v.data.arr_string.arr[i]); + } + Marshal.FreeHGlobal((IntPtr)v.data.arr_string.arr); + return ret; + default: + return m_ntcore.NT_SetDefaultEntryValue(entry, &v).Get(); + } + } + + internal static unsafe void SetEntryTypeValue(NtEntry entry, in RefManagedValue value) + { + NtValue v = new NtValue + { + type = value.Type + }; + + switch (value.Type) + { + case NtType.Boolean: + v.data.v_boolean = value.Data.VBoolean; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + case NtType.Double: + v.data.v_double = value.Data.VDouble; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + case NtType.String: + fixed (char* p = value.Data.VString) + { + if (p == null) + { + v.data.v_string.str = null; + v.data.v_string.len = (UIntPtr)0; + m_ntcore.NT_SetEntryValue(entry, &v).Get(); + return; + } + var dLen = Encoding.UTF8.GetByteCount(p, value.Data.VString.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, value.Data.VString.Length, d, dLen); + v.data.v_string.str = d; + v.data.v_string.len = (UIntPtr)dLen; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + } + case NtType.Raw: + case NtType.Rpc: + fixed (byte* p = value.Data.VRaw) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw.Length; + v.data.v_raw.str = p; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + case NtType.BooleanArray: + fixed (bool* p = value.Data.VBooleanArray) + { + var len = value.Data.VBooleanArray.Length; + Span dSpan = len <= 256 ? stackalloc NtBool[len == 0 ? 1 : 0] : new NtBool[len]; + fixed (NtBool* d = dSpan) + { + v.data.arr_boolean.arr = d; + v.data.arr_boolean.len = (UIntPtr)len; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + } + case NtType.DoubleArray: + fixed (byte* p = value.Data.VRaw) + { + v.data.v_raw.len = (UIntPtr)value.Data.VRaw.Length; + v.data.v_raw.str = p; + m_ntcore.NT_SetEntryTypeValue(entry, &v); + break; + } + case NtType.StringArray: + v.data.arr_string.arr = (NtString*)Marshal.AllocHGlobal(value.Data.VStringArray.Length * sizeof(NtString)); + v.data.arr_string.len = (UIntPtr)value.Data.VStringArray.Length; + var sSpan = value.Data.VStringArray; + for (int i = 0; i < sSpan.Length; i++) + { + Utilities.CreateNtString(sSpan[i], &v.data.arr_string.arr[i]); + } + m_ntcore.NT_SetEntryTypeValue(entry, &v); + int sLen = (int)v.data.arr_string.len; + for (int i = 0; i < sLen; i++) + { + Utilities.DisposeNtString(&v.data.arr_string.arr[i]); + } + Marshal.FreeHGlobal((IntPtr)v.data.arr_string.arr); + break; + default: + m_ntcore.NT_SetDefaultEntryValue(entry, &v); + break; + } + } + + public static void SetEntryFlags(NtEntry entry, EntryFlags flags) + { + m_ntcore.NT_SetEntryFlags(entry, (uint)flags); + } + + public static EntryFlags GetEntryFlags(NtEntry entry) + { + return (EntryFlags)m_ntcore.NT_GetEntryFlags(entry); + } + + public static void DeleteEntry(NtEntry entry) + { + m_ntcore.NT_DeleteEntry(entry); + } + + public static void DeleteAllEntries(NtInst inst) + { + m_ntcore.NT_DeleteAllEntries(inst); + } + + public static unsafe ReadOnlySpan GetEntryInfo(NetworkTableInstance inst, ReadOnlySpan prefix, NtType types, Span store) + { + fixed (char* p = prefix.IsEmpty ? new ReadOnlySpan(NullTerminator, 1) : prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntryInfo(inst.Handle, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + Span entries = GetSpanOrBuffer(store, len); + for (int i = 0; i < entries.Length; i++) + { + entries[i] = new EntryInfo(inst, &data[i]); + } + m_ntcore.NT_DisposeEntryInfoArray(data, count); + return entries; + } + } + } + + public static unsafe ReadOnlySpan GetEntryInfo(NetworkTableInstance inst, string prefix, NtType types, Span store) + { + fixed (char* p = prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + UIntPtr count = UIntPtr.Zero; + var data = m_ntcore.NT_GetEntryInfo(inst.Handle, d, (UIntPtr)dLen, (uint)types, &count); + int len = (int)count; + Span entries = GetSpanOrBuffer(store, len); + for (int i = 0; i < entries.Length; i++) + { + entries[i] = new EntryInfo(inst, &data[i]); + } + m_ntcore.NT_DisposeEntryInfoArray(data, count); + return entries; + } + } + } + + public static unsafe EntryInfo? GetEntryInfoHandle(NetworkTableInstance inst, NtEntry entry) + { + NtEntryInfo info = new NtEntryInfo(); + var ret = m_ntcore.NT_GetEntryInfoHandle(entry, &info); + if (!ret.Get()) + { + m_ntcore.NT_DisposeEntryInfo(&info); + return null; + } + EntryInfo infoM = new EntryInfo(inst, &info); + m_ntcore.NT_DisposeEntryInfo(&info); + return infoM; + } + + public static NtEntryListenerPoller CreateEntryListenerPoller(NtInst inst) + { + return m_ntcore.NT_CreateEntryListenerPoller(inst); + } + + internal static unsafe PointerSpan PollEntryListener(NtEntryListenerPoller poller) + { + UIntPtr length = UIntPtr.Zero; + NtEntryNotification* notifications = m_ntcore.NT_PollEntryListener(poller, &length); + return new PointerSpan(notifications, (int)length); + } + + internal static unsafe PointerSpan PollEntryListenerTimeout(NtEntryListenerPoller poller, double timeout, out bool timedOut) + { + UIntPtr length = UIntPtr.Zero; + NtBool timedOutNt = false; + NtEntryNotification* notifications = m_ntcore.NT_PollEntryListenerTimeout(poller, &length, timeout, &timedOutNt); + timedOut = timedOutNt.Get(); + return new PointerSpan(notifications, (int)length); + } + + internal static unsafe void DisposeEntryListenerSpan(PointerSpan listeners) + { + m_ntcore.NT_DisposeEntryNotificationArray(listeners.Pointer, (UIntPtr)listeners.Length); + } + + public static unsafe NtEntryListener AddPolledEntryListener(NtEntryListenerPoller poller, string prefix, NotifyFlags flags) + { + fixed (char* p = prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + return m_ntcore.NT_AddPolledEntryListener(poller, d, (UIntPtr)dLen, (uint)flags); + } + } + + } + + public static unsafe NtEntryListener AddPolledEntryListener(NtEntryListenerPoller poller, ReadOnlySpan prefix, NotifyFlags flags) + { + fixed (char* p = prefix.IsEmpty ? new ReadOnlySpan(NullTerminator, 1) : prefix) + { + var dLen = Encoding.UTF8.GetByteCount(p, prefix.Length); + Span dSpan = dLen <= 256 ? stackalloc byte[dLen == 0 ? 1 : dLen] : new byte[dLen]; + fixed (byte* d = dSpan) + { + Encoding.UTF8.GetBytes(p, prefix.Length, d, dLen); + return m_ntcore.NT_AddPolledEntryListener(poller, d, (UIntPtr)dLen, (uint)flags); + } + } + + } + + public static unsafe NtEntryListener AddPolledEntryListener(NtEntryListenerPoller poller, NetworkTableEntry entry, NotifyFlags flags) + { + return m_ntcore.NT_AddPolledEntryListenerSingle(poller, entry.Handle, (uint)flags); + } + + public static unsafe void RemoveEntryListener(NtEntryListener listener) + { + m_ntcore.NT_RemoveEntryListener(listener); + } + + public static unsafe bool WaitForEntryListenerQueue(NtInst inst, double timeout) + { + return m_ntcore.NT_WaitForEntryListenerQueue(inst, timeout).Get(); + } + + public static unsafe void CancelPollEntryListener(NtEntryListenerPoller poller) + { + m_ntcore.NT_CancelPollEntryListener(poller); + } + + public static void DestroyEntryListenerPoller(NtEntryListenerPoller poller) + { + m_ntcore.NT_DestroyEntryListenerPoller(poller); + } + + public static NtConnectionListenerPoller CreateConnectionListenerPoller(NtInst inst) + { + return m_ntcore.NT_CreateConnectionListenerPoller(inst); + } + + internal static unsafe PointerSpan PollConnectionListener(NtConnectionListenerPoller poller) + { + UIntPtr length = UIntPtr.Zero; + NtConnectionNotification* notifications = m_ntcore.NT_PollConnectionListener(poller, &length); + return new PointerSpan(notifications, (int)length); + } + + internal static unsafe PointerSpan PollConnectionListenerTimeout(NtConnectionListenerPoller poller, double timeout, out bool timedOut) + { + UIntPtr length = UIntPtr.Zero; + NtBool timedOutNt = false; + NtConnectionNotification* notifications = m_ntcore.NT_PollConnectionListenerTimeout(poller, &length, timeout, &timedOutNt); + timedOut = timedOutNt.Get(); + return new PointerSpan(notifications, (int)length); + } + + internal static unsafe void DisposeConnectionListenerSpan(PointerSpan listeners) + { + m_ntcore.NT_DisposeConnectionNotificationArray(listeners.Pointer, (UIntPtr)listeners.Length); + } + + public static unsafe NtConnectionListener AddPolledConnectionListener(NtConnectionListenerPoller poller, bool immediateNotify) + { + return m_ntcore.NT_AddPolledConnectionListener(poller, immediateNotify); + } + + public static unsafe void RemoveConnectionListener(NtConnectionListener listener) + { + m_ntcore.NT_RemoveConnectionListener(listener); + } + + public static unsafe bool WaitForConnectionListenerQueue(NtInst inst, double timeout) + { + return m_ntcore.NT_WaitForConnectionListenerQueue(inst, timeout).Get(); + } + + public static unsafe void CancelPollConnectionListener(NtConnectionListenerPoller poller) + { + m_ntcore.NT_CancelPollConnectionListener(poller); + } + + public static void DestroyConnectionListenerPoller(NtConnectionListenerPoller poller) + { + m_ntcore.NT_DestroyConnectionListenerPoller(poller); + } + + public static NtRpcCallPoller CreateRpcCallPoller(NtInst inst) + { + return m_ntcore.NT_CreateRpcCallPoller(inst); + } + + internal static unsafe PointerSpan PollRpc(NtRpcCallPoller poller) + { + UIntPtr length = UIntPtr.Zero; + NtRpcAnswer* notifications = m_ntcore.NT_PollRpc(poller, &length); + return new PointerSpan(notifications, (int)length); + } + + internal static unsafe void DisposeRpcAnswerSpan(PointerSpan answers) + { + m_ntcore.NT_DisposeRpcAnswerArray(answers.Pointer, (UIntPtr)answers.Length); + } + + internal static unsafe PointerSpan PollRpcTimeout(NtRpcCallPoller poller, double timeout, out bool timedOut) + { + UIntPtr length = UIntPtr.Zero; + NtBool timedOutNt = false; + NtRpcAnswer* notifications = m_ntcore.NT_PollRpcTimeout(poller, &length, timeout, &timedOutNt); + timedOut = timedOutNt.Get(); + return new PointerSpan(notifications, (int)length); + } + + public static unsafe void CreatePolledRpc(NtEntry entry, ReadOnlySpan def, NtRpcCallPoller poller) + { + fixed (byte* p = def) + { + m_ntcore.NT_CreatePolledRpc(entry, p, (UIntPtr)def.Length, poller); + } + } + + public static unsafe bool WaitForRpcCallQueue(NtInst inst, double timeout) + { + return m_ntcore.NT_WaitForRpcCallQueue(inst, timeout).Get(); + } + + public static unsafe void CancelPollRpc(NtRpcCallPoller poller) + { + m_ntcore.NT_CancelPollRpc(poller); + } + + public static void DestroyRpcCallPoller(NtRpcCallPoller poller) + { + m_ntcore.NT_DestroyRpcCallPoller(poller); + } + + + public static NtLoggerPoller CreateLoggerPoller(NtInst inst) + { + return m_ntcore.NT_CreateLoggerPoller(inst); + } + + internal static unsafe PointerSpan PollLogger(NtLoggerPoller poller) + { + UIntPtr length = UIntPtr.Zero; + NtLogMessage* notifications = m_ntcore.NT_PollLogger(poller, &length); + return new PointerSpan(notifications, (int)length); + } + + internal static unsafe PointerSpan PollLoggerTimeout(NtLoggerPoller poller, double timeout, out bool timedOut) + { + UIntPtr length = UIntPtr.Zero; + NtBool timedOutNt = false; + NtLogMessage* notifications = m_ntcore.NT_PollLoggerTimeout(poller, &length, timeout, &timedOutNt); + timedOut = timedOutNt.Get(); + return new PointerSpan(notifications, (int)length); + } + + internal static unsafe void DisposeLoggerSpan(PointerSpan listeners) + { + m_ntcore.NT_DisposeLogMessageArray(listeners.Pointer, (UIntPtr)listeners.Length); + } + + public static unsafe NtLogger AddPolledLogger(NtLoggerPoller poller, int minLevel, int maxLevel) + { + return m_ntcore.NT_AddPolledLogger(poller, (uint)minLevel, (uint)maxLevel); + } + + public static unsafe void RemoveLogger(NtLogger logger) + { + m_ntcore.NT_RemoveLogger(logger); + } + + public static unsafe bool WaitForLoggerQueue(NtInst inst, double timeout) + { + return m_ntcore.NT_WaitForLoggerQueue(inst, timeout).Get(); + } + + public static unsafe void CancelPollLogger(NtLoggerPoller poller) + { + m_ntcore.NT_CancelPollLogger(poller); + } + + public static void DestroyLoggerPoller(NtLoggerPoller poller) + { + m_ntcore.NT_DestroyLoggerPoller(poller); + } + + + public static unsafe void PostRpcResponse(NtEntry entry, NtRpcCall call, ReadOnlySpan result) + { + fixed (byte* p = result) + { + UIntPtr len = (UIntPtr)result.Length; + m_ntcore.NT_PostRpcResponse(entry, call, p, len); + } + } + + public static unsafe ReadOnlySpan GetRpcResult(NtEntry entry, NtRpcCall call, Span store) + { + UIntPtr length = UIntPtr.Zero; + byte* res = m_ntcore.NT_GetRpcResult(entry, call, &length); + int len = (int)length; + Span retVal = GetSpanOrBuffer(store, len); + new Span(res, len).CopyTo(retVal); + m_ntcore.NT_FreeCharArray(res); + return retVal; + } + + public static unsafe ReadOnlySpan GetRpcResult(NtEntry entry, NtRpcCall call, double timeout, Span store) + { + UIntPtr length = UIntPtr.Zero; + NtBool timedOut = false; + byte* res = m_ntcore.NT_GetRpcResultTimeout(entry, call, &length, timeout, &timedOut); + if (timedOut.Get()) + { + return null; + } + int len = (int)length; + Span retVal = GetSpanOrBuffer(store, len); + new Span(res, len).CopyTo(retVal); + m_ntcore.NT_FreeCharArray(res); + return retVal; + } + + public static unsafe void CancelRpcResult(NtEntry entry, NtRpcCall call) + { + m_ntcore.NT_CancelRpcResult(entry, call); + } + + public static unsafe NtRpcCall CallRpc(NtEntry entry, Span @params) + { + fixed (byte* b = @params ) + { + return m_ntcore.NT_CallRpc(entry, b, (UIntPtr)@params.Length); + } + } + + public static unsafe void SetNetworkIdentity(NtInst inst, String name) + { + using var str = UTF8String.CreateUTF8DisposableString(name); + m_ntcore.NT_SetNetworkIdentity(inst, str.Buffer, str.Length); + } + + public static unsafe NetworkMode GetNetworkMode(NtInst inst) + { + return (NetworkMode)m_ntcore.NT_GetNetworkMode(inst); + } + + public static unsafe void StartServer(NtInst inst, string persistFilename, string listenAddress, int port) + { + using var pStr = UTF8String.CreateUTF8DisposableString(persistFilename); + using var lStr = UTF8String.CreateUTF8DisposableString(listenAddress); + m_ntcore.NT_StartServer(inst, pStr.Buffer, lStr.Buffer, (uint)port); + } + + public static unsafe void StopServer(NtInst inst) + { + m_ntcore.NT_StopServer(inst); + } + + public static unsafe void StartClient(NtInst inst) + { + m_ntcore.NT_StartClientNone(inst); + } + + public static unsafe void StartClient(NtInst inst, string serverName, int port) + { + using var str = UTF8String.CreateUTF8DisposableString(serverName); + m_ntcore.NT_StartClient(inst, str.Buffer, (uint)port); + } + + public static unsafe void StartClient(NtInst inst, ReadOnlySpan servers) + { + var serverStrs = stackalloc byte*[servers.Length]; + var serverPorts = stackalloc uint[servers.Length]; + for (int i = 0; i < servers.Length; i++) + { + serverPorts[i] = (uint)servers[i].Port; + string vStr = servers[i].Server; + fixed (char* str = vStr) + { + var encoding = Encoding.UTF8; + int bytes = encoding.GetByteCount(str, vStr.Length); + serverStrs[i] = (byte*)Marshal.AllocHGlobal((bytes + 1) * sizeof(byte)); + encoding.GetBytes(str, vStr.Length, serverStrs[i], bytes); + serverStrs[i][bytes] = 0; + } + } + m_ntcore.NT_StartClientMulti(inst, (UIntPtr)servers.Length, serverStrs, serverPorts); + + for (int i = 0; i < servers.Length; i++) + { + Marshal.FreeHGlobal((IntPtr)serverStrs[i]); + } + } + + public static unsafe void StartClientTeam(NtInst inst, int team, int port) + { + m_ntcore.NT_StartClientTeam(inst, (uint)team, (uint)port); + } + + public static unsafe void StopClient(NtInst inst) + { + m_ntcore.NT_StopClient(inst); + } + + public static unsafe void SetServer(NtInst inst, string serverName, int port) + { + using var str = UTF8String.CreateUTF8DisposableString(serverName); + m_ntcore.NT_SetServer(inst, str.Buffer, (uint)port); + } + + public static unsafe void SetServer(NtInst inst, ReadOnlySpan servers) + { + var serverStrs = stackalloc byte*[servers.Length]; + var serverPorts = stackalloc uint[servers.Length]; + for (int i = 0; i < servers.Length; i++) + { + serverPorts[i] = (uint)servers[i].Port; + string vStr = servers[i].Server; + fixed (char* str = vStr) + { + var encoding = Encoding.UTF8; + int bytes = encoding.GetByteCount(str, vStr.Length); + serverStrs[i] = (byte*)Marshal.AllocHGlobal((bytes + 1) * sizeof(byte)); + encoding.GetBytes(str, vStr.Length, serverStrs[i], bytes); + serverStrs[i][bytes] = 0; + } + } + m_ntcore.NT_SetServerMulti(inst, (UIntPtr)servers.Length, serverStrs, serverPorts); + + for (int i = 0; i < servers.Length; i++) + { + Marshal.FreeHGlobal((IntPtr)serverStrs[i]); + } + } + + public static unsafe void SetServerTeam(NtInst inst, int team, int port) + { + m_ntcore.NT_SetServerTeam(inst, (uint)team, (uint)port); + } + + public static unsafe void StartDSClient(NtInst inst, int port) + { + m_ntcore.NT_StartDSClient(inst, (uint)port); + } + + public static void StopDSClient(NtInst inst) + { + m_ntcore.NT_StopDSClient(inst); + } + + public static unsafe void SetUpdateRate(NtInst inst, double interval) + { + m_ntcore.NT_SetUpdateRate(inst, interval); + } + + public static unsafe void Flush(NtInst inst) + { + m_ntcore.NT_Flush(inst); + } + + public static unsafe ReadOnlySpan GetConnections(NtInst inst, Span store) + { + UIntPtr count = UIntPtr.Zero; + var conns = m_ntcore.NT_GetConnections(inst, &count); + int len = (int)count; + Span retConns = GetSpanOrBuffer(store, len); + for (int i = 0; i < retConns.Length; i++) + { + retConns[i] = new ConnectionInfo(&conns[i]); + } + m_ntcore.NT_DisposeConnectionInfoArray(conns, count); + return retConns; + } + + public static unsafe bool IsConnected(NtInst inst) + { + return m_ntcore.NT_IsConnected(inst).Get(); + } + + public static unsafe void SavePersistent(NtInst inst, string filename) + { + using var f = UTF8String.CreateUTF8DisposableString(filename); + var error = m_ntcore.NT_SavePersistent(inst, f.Buffer); + if (error != null) + { + throw new PersistentException(UTF8String.ReadUTF8String(error)); + } + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate void WarnFunc(UIntPtr line, byte* messsage); + + public static unsafe List LoadPersistent(NtInst inst, string filename) + { + using var f = UTF8String.CreateUTF8DisposableString(filename); + List warns = new List(4); + var fp = Marshal.GetFunctionPointerForDelegate((UIntPtr line, byte* message) => + { + warns.Add($"{(int)line} : {UTF8String.ReadUTF8String(message)}"); + }); + var error = m_ntcore.NT_LoadPersistent(inst, f.Buffer, fp); + if (error != null) + { + throw new PersistentException(UTF8String.ReadUTF8String(error)); + } + return warns; + } + + public static unsafe void SaveEntries(NtInst inst, string filename, string prefix) + { + using var f = UTF8String.CreateUTF8DisposableString(filename); + using var p = UTF8String.CreateUTF8DisposableString(prefix); + var error = m_ntcore.NT_SaveEntries(inst, f.Buffer, p.Buffer, p.Length); + if (error != null) + { + throw new PersistentException(UTF8String.ReadUTF8String(error)); + } + } + + public static unsafe List LoadEntries(NtInst inst, string filename, string prefix) + { + using var f = UTF8String.CreateUTF8DisposableString(filename); + using var p = UTF8String.CreateUTF8DisposableString(prefix); + List warns = new List(4); + var fp = Marshal.GetFunctionPointerForDelegate((UIntPtr line, byte* message) => + { + warns.Add($"{(int)line} : {UTF8String.ReadUTF8String(message)}"); + }); + var error = m_ntcore.NT_LoadEntries(inst, f.Buffer, p.Buffer, p.Length, fp); + if (error != null) + { + throw new PersistentException(UTF8String.ReadUTF8String(error)); + } + return warns; + } + + + } +} diff --git a/src/FRC.NetworkTables.Core/Interop/NtCoreHelper.cs b/src/FRC.NetworkTables.Core/Interop/NtCoreHelper.cs new file mode 100644 index 0000000..9b1ac77 --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/NtCoreHelper.cs @@ -0,0 +1,57 @@ +using FRC.NativeLibraryUtilities; +using System; +using System.IO; + +namespace FRC.NetworkTables.Interop +{ + public static class NtCoreHelper + { + public static bool LoadOnStaticInit { get; set;} = true; + + public static INtCore? Load() + { + var nativeLoader = new NativeLibraryLoader(); + + string[] commandArgs = Environment.GetCommandLineArgs(); + foreach (var commandArg in commandArgs) + { + //search for a line with the prefix "-ntcore:" + if (commandArg.ToLower().Contains("-ntcore:")) + { + //Split line to get the library. + int splitLoc = commandArg.IndexOf(':'); + string file = commandArg.Substring(splitLoc + 1); + + //If the file exists, just return it so dlopen can load it. + if (File.Exists(file)) + { + nativeLoader.LoadNativeLibrary(file, true); + return nativeLoader.LoadNativeInterface(); + } + } + } + + if (nativeLoader.TryLoadNativeLibraryPath("ntcorejni")) + { + return nativeLoader.LoadNativeInterface(); + } + + const string resourceRoot = "FRC.NetworkTables.Core.DesktopLibraries.libraries."; + + nativeLoader.AddLibraryLocation(OsType.Windows32, + resourceRoot + "windows.x86.ntcorejni.dll"); + nativeLoader.AddLibraryLocation(OsType.Windows64, + resourceRoot + "windows.x86_64.ntcorejni.dll"); + nativeLoader.AddLibraryLocation(OsType.Linux64, + resourceRoot + "linux.x86_64.libntcorejni.so"); + nativeLoader.AddLibraryLocation(OsType.MacOs64, + resourceRoot + "osx.x86_64.libntcorejni.dylib"); + nativeLoader.AddLibraryLocation(OsType.roboRIO, "ntcore"); + + nativeLoader.LoadNativeLibraryFromReflectedAssembly("FRC.NetworkTables.Core.DesktopLibraries"); + return nativeLoader.LoadNativeInterface(); + } + + + } +} diff --git a/src/FRC.NetworkTables.Core/Interop/NtCorePInvoke.cs b/src/FRC.NetworkTables.Core/Interop/NtCorePInvoke.cs new file mode 100644 index 0000000..9fa03e0 --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/NtCorePInvoke.cs @@ -0,0 +1,873 @@ +using System; +using System.Runtime.InteropServices; + +namespace FRC.NetworkTables.Interop +{ + public unsafe class NtCorePInvoke : INtCore + { + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeEntryNotificationArray")] + private static extern void Native_NT_DisposeEntryNotificationArray(NtEntryNotification* arr, UIntPtr count); + + public void NT_DisposeEntryNotificationArray(NtEntryNotification* arr, UIntPtr count) + { + Native_NT_DisposeEntryNotificationArray(arr, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeEntryNotification")] + private static extern void Native_NT_DisposeEntryNotification(NtEntryNotification* info); + + public void NT_DisposeEntryNotification(NtEntryNotification* info) + { + Native_NT_DisposeEntryNotification(info); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeConnectionNotificationArray")] + private static extern void Native_NT_DisposeConnectionNotificationArray(NtConnectionNotification* arr, UIntPtr count); + + public void NT_DisposeConnectionNotificationArray(NtConnectionNotification* arr, UIntPtr count) + { + Native_NT_DisposeConnectionNotificationArray(arr, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeConnectionNotification")] + private static extern void Native_NT_DisposeConnectionNotification(NtConnectionNotification* info); + + public void NT_DisposeConnectionNotification(NtConnectionNotification* info) + { + Native_NT_DisposeConnectionNotification(info); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeLogMessageArray")] + private static extern void Native_NT_DisposeLogMessageArray(NtLogMessage* arr, UIntPtr count); + + public void NT_DisposeLogMessageArray(NtLogMessage* arr, UIntPtr count) + { + Native_NT_DisposeLogMessageArray(arr, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeLogMessage")] + private static extern void Native_NT_DisposeLogMessage(NtLogMessage* info); + + public void NT_DisposeLogMessage(NtLogMessage* info) + { + Native_NT_DisposeLogMessage(info); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_Now")] + private static extern ulong Native_NT_Now(); + + public ulong NT_Now() + { + return Native_NT_Now(); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CreateLoggerPoller")] + private static extern NtLoggerPoller Native_NT_CreateLoggerPoller(NtInst inst); + + public NtLoggerPoller NT_CreateLoggerPoller(NtInst inst) + { + return Native_NT_CreateLoggerPoller(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DestroyLoggerPoller")] + private static extern void Native_NT_DestroyLoggerPoller(NtLoggerPoller poller); + + public void NT_DestroyLoggerPoller(NtLoggerPoller poller) + { + Native_NT_DestroyLoggerPoller(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AddPolledLogger")] + private static extern NtLogger Native_NT_AddPolledLogger(NtLoggerPoller poller, uint min_level, uint max_level); + + public NtLogger NT_AddPolledLogger(NtLoggerPoller poller, uint min_level, uint max_level) + { + return Native_NT_AddPolledLogger(poller, min_level, max_level); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollLogger")] + private static extern NtLogMessage* Native_NT_PollLogger(NtLoggerPoller poller, UIntPtr* len); + + public NtLogMessage* NT_PollLogger(NtLoggerPoller poller, UIntPtr* len) + { + return Native_NT_PollLogger(poller, len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollLoggerTimeout")] + private static extern NtLogMessage* Native_NT_PollLoggerTimeout(NtLoggerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + public NtLogMessage* NT_PollLoggerTimeout(NtLoggerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out) + { + return Native_NT_PollLoggerTimeout(poller, len, timeout, timed_out); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CancelPollLogger")] + private static extern void Native_NT_CancelPollLogger(NtLoggerPoller poller); + + public void NT_CancelPollLogger(NtLoggerPoller poller) + { + Native_NT_CancelPollLogger(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_RemoveLogger")] + private static extern void Native_NT_RemoveLogger(NtLogger logger); + + public void NT_RemoveLogger(NtLogger logger) + { + Native_NT_RemoveLogger(logger); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_WaitForLoggerQueue")] + private static extern NtBool Native_NT_WaitForLoggerQueue(NtInst inst, double timeout); + + public NtBool NT_WaitForLoggerQueue(NtInst inst, double timeout) + { + return Native_NT_WaitForLoggerQueue(inst, timeout); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AllocateCharArray")] + private static extern byte* Native_NT_AllocateCharArray(UIntPtr size); + + public byte* NT_AllocateCharArray(UIntPtr size) + { + return Native_NT_AllocateCharArray(size); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AllocateBooleanArray")] + private static extern NtBool* Native_NT_AllocateBooleanArray(UIntPtr size); + + public NtBool* NT_AllocateBooleanArray(UIntPtr size) + { + return Native_NT_AllocateBooleanArray(size); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AllocateDoubleArray")] + private static extern double* Native_NT_AllocateDoubleArray(UIntPtr size); + + public double* NT_AllocateDoubleArray(UIntPtr size) + { + return Native_NT_AllocateDoubleArray(size); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AllocateStringArray")] + private static extern NtString* Native_NT_AllocateStringArray(UIntPtr size); + + public NtString* NT_AllocateStringArray(UIntPtr size) + { + return Native_NT_AllocateStringArray(size); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_FreeCharArray")] + private static extern void Native_NT_FreeCharArray(byte* v_char); + + public void NT_FreeCharArray(byte* v_char) + { + Native_NT_FreeCharArray(v_char); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_FreeDoubleArray")] + private static extern void Native_NT_FreeDoubleArray(double* v_double); + + public void NT_FreeDoubleArray(double* v_double) + { + Native_NT_FreeDoubleArray(v_double); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_FreeBooleanArray")] + private static extern void Native_NT_FreeBooleanArray(NtBool* v_boolean); + + public void NT_FreeBooleanArray(NtBool* v_boolean) + { + Native_NT_FreeBooleanArray(v_boolean); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_FreeStringArray")] + private static extern void Native_NT_FreeStringArray(NtString* v_string, UIntPtr arr_size); + + public void NT_FreeStringArray(NtString* v_string, UIntPtr arr_size) + { + Native_NT_FreeStringArray(v_string, arr_size); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetDefaultInstance")] + private static extern NtInst Native_NT_GetDefaultInstance(); + + public NtInst NT_GetDefaultInstance() + { + return Native_NT_GetDefaultInstance(); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CreateInstance")] + private static extern NtInst Native_NT_CreateInstance(); + + public NtInst NT_CreateInstance() + { + return Native_NT_CreateInstance(); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DestroyInstance")] + private static extern void Native_NT_DestroyInstance(NtInst inst); + + public void NT_DestroyInstance(NtInst inst) + { + Native_NT_DestroyInstance(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetInstanceFromHandle")] + private static extern NtInst Native_NT_GetInstanceFromHandle(NtHandle handle); + + public NtInst NT_GetInstanceFromHandle(NtHandle handle) + { + return Native_NT_GetInstanceFromHandle(handle); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntry")] + private static extern NtEntry Native_NT_GetEntry(NtInst inst, byte* name, UIntPtr name_len); + + public NtEntry NT_GetEntry(NtInst inst, byte* name, UIntPtr name_len) + { + return Native_NT_GetEntry(inst, name, name_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntries")] + private static extern NtEntry* Native_NT_GetEntries(NtInst inst, byte* prefix, UIntPtr prefix_len, uint types, UIntPtr* count); + + public NtEntry* NT_GetEntries(NtInst inst, byte* prefix, UIntPtr prefix_len, uint types, UIntPtr* count) + { + return Native_NT_GetEntries(inst, prefix, prefix_len, types, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntryName")] + private static extern byte* Native_NT_GetEntryName(NtEntry entry, UIntPtr* name_len); + + public byte* NT_GetEntryName(NtEntry entry, UIntPtr* name_len) + { + return Native_NT_GetEntryName(entry, name_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntryType")] + private static extern NtType Native_NT_GetEntryType(NtEntry entry); + + public NtType NT_GetEntryType(NtEntry entry) + { + return Native_NT_GetEntryType(entry); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntryLastChange")] + private static extern ulong Native_NT_GetEntryLastChange(NtEntry entry); + + public ulong NT_GetEntryLastChange(NtEntry entry) + { + return Native_NT_GetEntryLastChange(entry); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntryValue")] + private static extern void Native_NT_GetEntryValue(NtEntry entry, NtValue* value); + + public void NT_GetEntryValue(NtEntry entry, NtValue* value) + { + Native_NT_GetEntryValue(entry, value); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetDefaultEntryValue")] + private static extern NtBool Native_NT_SetDefaultEntryValue(NtEntry entry, NtValue* default_value); + + public NtBool NT_SetDefaultEntryValue(NtEntry entry, NtValue* default_value) + { + return Native_NT_SetDefaultEntryValue(entry, default_value); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetEntryValue")] + private static extern NtBool Native_NT_SetEntryValue(NtEntry entry, NtValue* value); + + public NtBool NT_SetEntryValue(NtEntry entry, NtValue* value) + { + return Native_NT_SetEntryValue(entry, value); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetEntryTypeValue")] + private static extern void Native_NT_SetEntryTypeValue(NtEntry entry, NtValue* value); + + public void NT_SetEntryTypeValue(NtEntry entry, NtValue* value) + { + Native_NT_SetEntryTypeValue(entry, value); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetEntryFlags")] + private static extern void Native_NT_SetEntryFlags(NtEntry entry, uint flags); + + public void NT_SetEntryFlags(NtEntry entry, uint flags) + { + Native_NT_SetEntryFlags(entry, flags); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntryFlags")] + private static extern uint Native_NT_GetEntryFlags(NtEntry entry); + + public uint NT_GetEntryFlags(NtEntry entry) + { + return Native_NT_GetEntryFlags(entry); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DeleteEntry")] + private static extern void Native_NT_DeleteEntry(NtEntry entry); + + public void NT_DeleteEntry(NtEntry entry) + { + Native_NT_DeleteEntry(entry); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DeleteAllEntries")] + private static extern void Native_NT_DeleteAllEntries(NtInst inst); + + public void NT_DeleteAllEntries(NtInst inst) + { + Native_NT_DeleteAllEntries(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntryInfo")] + private static extern NtEntryInfo* Native_NT_GetEntryInfo(NtInst inst, byte* prefix, UIntPtr prefix_len, uint types, UIntPtr* count); + + public NtEntryInfo* NT_GetEntryInfo(NtInst inst, byte* prefix, UIntPtr prefix_len, uint types, UIntPtr* count) + { + return Native_NT_GetEntryInfo(inst, prefix, prefix_len, types, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetEntryInfoHandle")] + private static extern NtBool Native_NT_GetEntryInfoHandle(NtEntry entry, NtEntryInfo* info); + + public NtBool NT_GetEntryInfoHandle(NtEntry entry, NtEntryInfo* info) + { + return Native_NT_GetEntryInfoHandle(entry, info); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CreateEntryListenerPoller")] + private static extern NtEntryListenerPoller Native_NT_CreateEntryListenerPoller(NtInst inst); + + public NtEntryListenerPoller NT_CreateEntryListenerPoller(NtInst inst) + { + return Native_NT_CreateEntryListenerPoller(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DestroyEntryListenerPoller")] + private static extern void Native_NT_DestroyEntryListenerPoller(NtEntryListenerPoller poller); + + public void NT_DestroyEntryListenerPoller(NtEntryListenerPoller poller) + { + Native_NT_DestroyEntryListenerPoller(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AddPolledEntryListener")] + private static extern NtEntryListener Native_NT_AddPolledEntryListener(NtEntryListenerPoller poller, byte* prefix, UIntPtr prefix_len, uint flags); + + public NtEntryListener NT_AddPolledEntryListener(NtEntryListenerPoller poller, byte* prefix, UIntPtr prefix_len, uint flags) + { + return Native_NT_AddPolledEntryListener(poller, prefix, prefix_len, flags); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AddPolledEntryListenerSingle")] + private static extern NtEntryListener Native_NT_AddPolledEntryListenerSingle(NtEntryListenerPoller poller, NtEntry entry, uint flags); + + public NtEntryListener NT_AddPolledEntryListenerSingle(NtEntryListenerPoller poller, NtEntry entry, uint flags) + { + return Native_NT_AddPolledEntryListenerSingle(poller, entry, flags); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollEntryListener")] + private static extern NtEntryNotification* Native_NT_PollEntryListener(NtEntryListenerPoller poller, UIntPtr* len); + + public NtEntryNotification* NT_PollEntryListener(NtEntryListenerPoller poller, UIntPtr* len) + { + return Native_NT_PollEntryListener(poller, len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollEntryListenerTimeout")] + private static extern NtEntryNotification* Native_NT_PollEntryListenerTimeout(NtEntryListenerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + public NtEntryNotification* NT_PollEntryListenerTimeout(NtEntryListenerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out) + { + return Native_NT_PollEntryListenerTimeout(poller, len, timeout, timed_out); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CancelPollEntryListener")] + private static extern void Native_NT_CancelPollEntryListener(NtEntryListenerPoller poller); + + public void NT_CancelPollEntryListener(NtEntryListenerPoller poller) + { + Native_NT_CancelPollEntryListener(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_RemoveEntryListener")] + private static extern void Native_NT_RemoveEntryListener(NtEntryListener entry_listener); + + public void NT_RemoveEntryListener(NtEntryListener entry_listener) + { + Native_NT_RemoveEntryListener(entry_listener); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_WaitForEntryListenerQueue")] + private static extern NtBool Native_NT_WaitForEntryListenerQueue(NtInst inst, double timeout); + + public NtBool NT_WaitForEntryListenerQueue(NtInst inst, double timeout) + { + return Native_NT_WaitForEntryListenerQueue(inst, timeout); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CreateConnectionListenerPoller")] + private static extern NtConnectionListenerPoller Native_NT_CreateConnectionListenerPoller(NtInst inst); + + public NtConnectionListenerPoller NT_CreateConnectionListenerPoller(NtInst inst) + { + return Native_NT_CreateConnectionListenerPoller(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DestroyConnectionListenerPoller")] + private static extern void Native_NT_DestroyConnectionListenerPoller(NtConnectionListenerPoller poller); + + public void NT_DestroyConnectionListenerPoller(NtConnectionListenerPoller poller) + { + Native_NT_DestroyConnectionListenerPoller(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_AddPolledConnectionListener")] + private static extern NtConnectionListener Native_NT_AddPolledConnectionListener(NtConnectionListenerPoller poller, NtBool immediate_notify); + + public NtConnectionListener NT_AddPolledConnectionListener(NtConnectionListenerPoller poller, NtBool immediate_notify) + { + return Native_NT_AddPolledConnectionListener(poller, immediate_notify); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollConnectionListener")] + private static extern NtConnectionNotification* Native_NT_PollConnectionListener(NtConnectionListenerPoller poller, UIntPtr* len); + + public NtConnectionNotification* NT_PollConnectionListener(NtConnectionListenerPoller poller, UIntPtr* len) + { + return Native_NT_PollConnectionListener(poller, len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollConnectionListenerTimeout")] + private static extern NtConnectionNotification* Native_NT_PollConnectionListenerTimeout(NtConnectionListenerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + public NtConnectionNotification* NT_PollConnectionListenerTimeout(NtConnectionListenerPoller poller, UIntPtr* len, double timeout, NtBool* timed_out) + { + return Native_NT_PollConnectionListenerTimeout(poller, len, timeout, timed_out); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CancelPollConnectionListener")] + private static extern void Native_NT_CancelPollConnectionListener(NtConnectionListenerPoller poller); + + public void NT_CancelPollConnectionListener(NtConnectionListenerPoller poller) + { + Native_NT_CancelPollConnectionListener(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_RemoveConnectionListener")] + private static extern void Native_NT_RemoveConnectionListener(NtConnectionListener conn_listener); + + public void NT_RemoveConnectionListener(NtConnectionListener conn_listener) + { + Native_NT_RemoveConnectionListener(conn_listener); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_WaitForConnectionListenerQueue")] + private static extern NtBool Native_NT_WaitForConnectionListenerQueue(NtInst inst, double timeout); + + public NtBool NT_WaitForConnectionListenerQueue(NtInst inst, double timeout) + { + return Native_NT_WaitForConnectionListenerQueue(inst, timeout); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CreateRpcCallPoller")] + private static extern NtRpcCallPoller Native_NT_CreateRpcCallPoller(NtInst inst); + + public NtRpcCallPoller NT_CreateRpcCallPoller(NtInst inst) + { + return Native_NT_CreateRpcCallPoller(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DestroyRpcCallPoller")] + private static extern void Native_NT_DestroyRpcCallPoller(NtRpcCallPoller poller); + + public void NT_DestroyRpcCallPoller(NtRpcCallPoller poller) + { + Native_NT_DestroyRpcCallPoller(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CreatePolledRpc")] + private static extern void Native_NT_CreatePolledRpc(NtEntry entry, byte* def, UIntPtr def_len, NtRpcCallPoller poller); + + public void NT_CreatePolledRpc(NtEntry entry, byte* def, UIntPtr def_len, NtRpcCallPoller poller) + { + Native_NT_CreatePolledRpc(entry, def, def_len, poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollRpc")] + private static extern NtRpcAnswer* Native_NT_PollRpc(NtRpcCallPoller poller, UIntPtr* len); + + public NtRpcAnswer* NT_PollRpc(NtRpcCallPoller poller, UIntPtr* len) + { + return Native_NT_PollRpc(poller, len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PollRpcTimeout")] + private static extern NtRpcAnswer* Native_NT_PollRpcTimeout(NtRpcCallPoller poller, UIntPtr* len, double timeout, NtBool* timed_out); + + public NtRpcAnswer* NT_PollRpcTimeout(NtRpcCallPoller poller, UIntPtr* len, double timeout, NtBool* timed_out) + { + return Native_NT_PollRpcTimeout(poller, len, timeout, timed_out); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CancelPollRpc")] + private static extern void Native_NT_CancelPollRpc(NtRpcCallPoller poller); + + public void NT_CancelPollRpc(NtRpcCallPoller poller) + { + Native_NT_CancelPollRpc(poller); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_WaitForRpcCallQueue")] + private static extern NtBool Native_NT_WaitForRpcCallQueue(NtInst inst, double timeout); + + public NtBool NT_WaitForRpcCallQueue(NtInst inst, double timeout) + { + return Native_NT_WaitForRpcCallQueue(inst, timeout); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PostRpcResponse")] + private static extern void Native_NT_PostRpcResponse(NtEntry entry, NtRpcCall call, byte* result, UIntPtr result_len); + + public void NT_PostRpcResponse(NtEntry entry, NtRpcCall call, byte* result, UIntPtr result_len) + { + Native_NT_PostRpcResponse(entry, call, result, result_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CallRpc")] + private static extern NtRpcCall Native_NT_CallRpc(NtEntry entry, byte* @params, UIntPtr params_len); + + public NtRpcCall NT_CallRpc(NtEntry entry, byte* @params, UIntPtr params_len) + { + return Native_NT_CallRpc(entry, @params, params_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetRpcResult")] + private static extern byte* Native_NT_GetRpcResult(NtEntry entry, NtRpcCall call, UIntPtr* result_len); + + public byte* NT_GetRpcResult(NtEntry entry, NtRpcCall call, UIntPtr* result_len) + { + return Native_NT_GetRpcResult(entry, call, result_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetRpcResultTimeout")] + private static extern byte* Native_NT_GetRpcResultTimeout(NtEntry entry, NtRpcCall call, UIntPtr* result_len, double timeout, NtBool* timed_out); + + public byte* NT_GetRpcResultTimeout(NtEntry entry, NtRpcCall call, UIntPtr* result_len, double timeout, NtBool* timed_out) + { + return Native_NT_GetRpcResultTimeout(entry, call, result_len, timeout, timed_out); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_CancelRpcResult")] + private static extern void Native_NT_CancelRpcResult(NtEntry entry, NtRpcCall call); + + public void NT_CancelRpcResult(NtEntry entry, NtRpcCall call) + { + Native_NT_CancelRpcResult(entry, call); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PackRpcDefinition")] + private static extern byte* Native_NT_PackRpcDefinition(NtRpcDefinition def, UIntPtr* packed_len); + + public byte* NT_PackRpcDefinition(NtRpcDefinition def, UIntPtr* packed_len) + { + return Native_NT_PackRpcDefinition(def, packed_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_UnpackRpcDefinition")] + private static extern NtBool Native_NT_UnpackRpcDefinition(byte* packed, UIntPtr packed_len, NtRpcDefinition* def); + + public NtBool NT_UnpackRpcDefinition(byte* packed, UIntPtr packed_len, NtRpcDefinition* def) + { + return Native_NT_UnpackRpcDefinition(packed, packed_len, def); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_PackRpcValues")] + private static extern byte* Native_NT_PackRpcValues(NtValue** values, UIntPtr values_len, UIntPtr* packed_len); + + public byte* NT_PackRpcValues(NtValue** values, UIntPtr values_len, UIntPtr* packed_len) + { + return Native_NT_PackRpcValues(values, values_len, packed_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_UnpackRpcValues")] + private static extern NtValue** Native_NT_UnpackRpcValues(byte* packed, UIntPtr packed_len, NtType* types, UIntPtr types_len); + + public NtValue** NT_UnpackRpcValues(byte* packed, UIntPtr packed_len, NtType* types, UIntPtr types_len) + { + return Native_NT_UnpackRpcValues(packed, packed_len, types, types_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetNetworkIdentity")] + private static extern void Native_NT_SetNetworkIdentity(NtInst inst, byte* name, UIntPtr name_len); + + public void NT_SetNetworkIdentity(NtInst inst, byte* name, UIntPtr name_len) + { + Native_NT_SetNetworkIdentity(inst, name, name_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetNetworkMode")] + private static extern uint Native_NT_GetNetworkMode(NtInst inst); + + public uint NT_GetNetworkMode(NtInst inst) + { + return Native_NT_GetNetworkMode(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StartServer")] + private static extern void Native_NT_StartServer(NtInst inst, byte* persist_filename, byte* listen_address, uint port); + + public void NT_StartServer(NtInst inst, byte* persist_filename, byte* listen_address, uint port) + { + Native_NT_StartServer(inst, persist_filename, listen_address, port); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StopServer")] + private static extern void Native_NT_StopServer(NtInst inst); + + public void NT_StopServer(NtInst inst) + { + Native_NT_StopServer(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StartClientNone")] + private static extern void Native_NT_StartClientNone(NtInst inst); + + public void NT_StartClientNone(NtInst inst) + { + Native_NT_StartClientNone(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StartClient")] + private static extern void Native_NT_StartClient(NtInst inst, byte* server_name, uint port); + + public void NT_StartClient(NtInst inst, byte* server_name, uint port) + { + Native_NT_StartClient(inst, server_name, port); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StartClientMulti")] + private static extern void Native_NT_StartClientMulti(NtInst inst, UIntPtr count, byte** server_names, uint* ports); + + public void NT_StartClientMulti(NtInst inst, UIntPtr count, byte** server_names, uint* ports) + { + Native_NT_StartClientMulti(inst, count, server_names, ports); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StartClientTeam")] + private static extern void Native_NT_StartClientTeam(NtInst inst, uint team, uint port); + + public void NT_StartClientTeam(NtInst inst, uint team, uint port) + { + Native_NT_StartClientTeam(inst, team, port); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StopClient")] + private static extern void Native_NT_StopClient(NtInst inst); + + public void NT_StopClient(NtInst inst) + { + Native_NT_StopClient(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetServer")] + private static extern void Native_NT_SetServer(NtInst inst, byte* server_name, uint port); + + public void NT_SetServer(NtInst inst, byte* server_name, uint port) + { + Native_NT_SetServer(inst, server_name, port); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetServerMulti")] + private static extern void Native_NT_SetServerMulti(NtInst inst, UIntPtr count, byte** server_names, uint* ports); + + public void NT_SetServerMulti(NtInst inst, UIntPtr count, byte** server_names, uint* ports) + { + Native_NT_SetServerMulti(inst, count, server_names, ports); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetServerTeam")] + private static extern void Native_NT_SetServerTeam(NtInst inst, uint team, uint port); + + public void NT_SetServerTeam(NtInst inst, uint team, uint port) + { + Native_NT_SetServerTeam(inst, team, port); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StartDSClient")] + private static extern void Native_NT_StartDSClient(NtInst inst, uint port); + + public void NT_StartDSClient(NtInst inst, uint port) + { + Native_NT_StartDSClient(inst, port); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_StopDSClient")] + private static extern void Native_NT_StopDSClient(NtInst inst); + + public void NT_StopDSClient(NtInst inst) + { + Native_NT_StopDSClient(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SetUpdateRate")] + private static extern void Native_NT_SetUpdateRate(NtInst inst, double interval); + + public void NT_SetUpdateRate(NtInst inst, double interval) + { + Native_NT_SetUpdateRate(inst, interval); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_Flush")] + private static extern void Native_NT_Flush(NtInst inst); + + public void NT_Flush(NtInst inst) + { + Native_NT_Flush(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_GetConnections")] + private static extern NtConnectionInfo* Native_NT_GetConnections(NtInst inst, UIntPtr* count); + + public NtConnectionInfo* NT_GetConnections(NtInst inst, UIntPtr* count) + { + return Native_NT_GetConnections(inst, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_IsConnected")] + private static extern NtBool Native_NT_IsConnected(NtInst inst); + + public NtBool NT_IsConnected(NtInst inst) + { + return Native_NT_IsConnected(inst); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SavePersistent")] + private static extern byte* Native_NT_SavePersistent(NtInst inst, byte* filename); + + public byte* NT_SavePersistent(NtInst inst, byte* filename) + { + return Native_NT_SavePersistent(inst, filename); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_LoadPersistent")] + private static extern byte* Native_NT_LoadPersistent(NtInst inst, byte* filename, IntPtr warnFunc); + + public byte* NT_LoadPersistent(NtInst inst, byte* filename, IntPtr warnFunc) + { + return Native_NT_LoadPersistent(inst, filename, warnFunc); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_SaveEntries")] + private static extern byte* Native_NT_SaveEntries(NtInst inst, byte* filename, byte* prefix, UIntPtr prefix_len); + + public byte* NT_SaveEntries(NtInst inst, byte* filename, byte* prefix, UIntPtr prefix_len) + { + return Native_NT_SaveEntries(inst, filename, prefix, prefix_len); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_LoadEntries")] + private static extern byte* Native_NT_LoadEntries(NtInst inst, byte* filename, byte* prefix, UIntPtr prefix_len, IntPtr warnFunc); + + public byte* NT_LoadEntries(NtInst inst, byte* filename, byte* prefix, UIntPtr prefix_len, IntPtr warnFunc) + { + return Native_NT_LoadEntries(inst, filename, prefix, prefix_len, warnFunc); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeValue")] + private static extern void Native_NT_DisposeValue(NtValue* value); + + public void NT_DisposeValue(NtValue* value) + { + Native_NT_DisposeValue(value); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_InitValue")] + private static extern void Native_NT_InitValue(NtValue* value); + + public void NT_InitValue(NtValue* value) + { + Native_NT_InitValue(value); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeString")] + private static extern void Native_NT_DisposeString(NtString* str); + + public void NT_DisposeString(NtString* str) + { + Native_NT_DisposeString(str); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_InitString")] + private static extern void Native_NT_InitString(NtString* str); + + public void NT_InitString(NtString* str) + { + Native_NT_InitString(str); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeEntryArray")] + private static extern void Native_NT_DisposeEntryArray(NtEntry* arr, UIntPtr count); + + public void NT_DisposeEntryArray(NtEntry* arr, UIntPtr count) + { + Native_NT_DisposeEntryArray(arr, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeConnectionInfoArray")] + private static extern void Native_NT_DisposeConnectionInfoArray(NtConnectionInfo* arr, UIntPtr count); + + public void NT_DisposeConnectionInfoArray(NtConnectionInfo* arr, UIntPtr count) + { + Native_NT_DisposeConnectionInfoArray(arr, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeEntryInfoArray")] + private static extern void Native_NT_DisposeEntryInfoArray(NtEntryInfo* arr, UIntPtr count); + + public void NT_DisposeEntryInfoArray(NtEntryInfo* arr, UIntPtr count) + { + Native_NT_DisposeEntryInfoArray(arr, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeEntryInfo")] + private static extern void Native_NT_DisposeEntryInfo(NtEntryInfo* info); + + public void NT_DisposeEntryInfo(NtEntryInfo* info) + { + Native_NT_DisposeEntryInfo(info); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeRpcDefinition")] + private static extern void Native_NT_DisposeRpcDefinition(NtRpcDefinition* def); + + public void NT_DisposeRpcDefinition(NtRpcDefinition* def) + { + Native_NT_DisposeRpcDefinition(def); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeRpcAnswerArray")] + private static extern void Native_NT_DisposeRpcAnswerArray(NtRpcAnswer* arr, UIntPtr count); + + public void NT_DisposeRpcAnswerArray(NtRpcAnswer* arr, UIntPtr count) + { + Native_NT_DisposeRpcAnswerArray(arr, count); + } + + [DllImport("ntcorejni", CallingConvention = CallingConvention.Cdecl, EntryPoint = "NT_DisposeRpcAnswer")] + private static extern void Native_NT_DisposeRpcAnswer(NtRpcAnswer* answer); + + public void NT_DisposeRpcAnswer(NtRpcAnswer* answer) + { + Native_NT_DisposeRpcAnswer(answer); + } + + } +} diff --git a/src/FRC.NetworkTables.Core/Interop/PointerSpan.cs b/src/FRC.NetworkTables.Core/Interop/PointerSpan.cs new file mode 100644 index 0000000..7d7d9da --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/PointerSpan.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables.Interop +{ + internal unsafe readonly ref struct PointerSpan where T : unmanaged + { + internal readonly T* Pointer; + internal readonly int Length; + + internal PointerSpan(T* pointer, int length) + { + Pointer = pointer; + Length = length; + } + } +} diff --git a/src/FRC.NetworkTables.Core/Interop/Structs.cs b/src/FRC.NetworkTables.Core/Interop/Structs.cs new file mode 100644 index 0000000..9dde6e1 --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/Structs.cs @@ -0,0 +1,389 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace FRC.NetworkTables.Interop +{ + /// + /// NT Bool for interop + /// + public readonly struct NtBool + { + private readonly int m_value; + + /// + /// Creates an NT Bool from an int + /// + /// value + public NtBool(int value) + { + this.m_value = value; + } + + /// + /// Creates an NT Bool from a bool + /// + /// + public NtBool(bool value) + { + this.m_value = value ? 1 : 0; + } + + /// + /// Gets the value + /// + /// value + public bool Get() + { + return m_value != 0; + } + + /// + /// Converts a bool to an NT Bool + /// + /// bool balue + public static implicit operator NtBool(bool value) + { + return new NtBool(value); + } + } + + /// + /// NT String + /// + public unsafe struct NtString + { + /// + /// String Pointer + /// + public byte* str; + /// + /// String Length + /// + public UIntPtr len; + } + + /// + /// NT Boolean Array + /// + public unsafe struct BoolArr + { + /// + /// Array Pointer + /// + public NtBool* arr; + /// + /// Array Length + /// + public UIntPtr len; + } + + + /// + /// NT Double Array + /// + public unsafe struct DoubleArr + { + /// + /// Array Pointer + /// + public double* arr; + /// + /// Array Length + /// + public UIntPtr len; + } + + /// + /// NT String Array + /// + public unsafe struct StringArr + { + /// + /// Array Pointer + /// + public NtString* arr; + /// + /// Array Length + /// + public UIntPtr len; + } + + /// + /// NT Entry Data Union + /// + [StructLayout(LayoutKind.Explicit)] + public struct DataUnion + { + /// + /// Boolean Value + /// + [FieldOffset(0)] + public NtBool v_boolean; + /// + /// Double Value + /// + [FieldOffset(0)] + public double v_double; + /// + /// String Value + /// + [FieldOffset(0)] + public NtString v_string; + /// + /// Raw Value + /// + [FieldOffset(0)] + public NtString v_raw; + /// + /// Boolean Array Value + /// + [FieldOffset(0)] + public BoolArr arr_boolean; + /// + /// Double Array Value + /// + [FieldOffset(0)] + public DoubleArr arr_double; + /// + /// String Array Value + /// + [FieldOffset(0)] + public StringArr arr_string; + } + + /// + /// NT Value + /// + public struct NtValue + { + /// + /// Value Type + /// + public NtType type; + /// + /// Value Last Change + /// + public ulong last_change; + /// + /// Value Data + /// + public DataUnion data; + } + + /// + /// NT Entry Info + /// + public struct NtEntryInfo + { + /// + /// Entry Handle + /// + public NtEntry entry; + /// + /// Name + /// + public NtString name; + /// + /// Entry Type + /// + public NtType type; + /// + /// Entry Flags + /// + public uint flags; + /// + /// Last Entry Change + /// + public ulong last_change; + } + + /// + /// NT Connection Info + /// + public struct NtConnectionInfo + { + /// + /// Remote ID + /// + public NtString remote_id; + /// + /// Remote IP + /// + public NtString remote_ip; + /// + /// Remote Port + /// + public uint remote_port; + /// + /// Last Update + /// + public ulong last_update; + /// + /// NT Protocol Version + /// + public uint protocol_version; + } + + /// + /// NT Rpc Parameter Definition + /// + public struct NtRpcParamDef + { + /// + /// Parameter Name + /// + public NtString name; + /// + /// Parameter Type + /// + public NtType type; + } + + /// + /// NT Rpc Result Definition + /// + public struct NtRpcResultDef + { + /// + /// Result Name + /// + public NtString name; + /// + /// Result Type + /// + public NtType type; + } + + /// + /// NT Rpc Definition + /// + public unsafe struct NtRpcDefinition + { + /// + /// Definition Version + /// + public uint version; + /// + /// Rpc Name + /// + public NtString name; + /// + /// Number of Parameters + /// + public UIntPtr num_params; + /// + /// Array of Parameter Definitions + /// + public NtRpcParamDef* @params; + /// + /// Number of Results + /// + public UIntPtr num_results; + /// + /// Array of Result Definitions + /// + public NtRpcResultDef* results; + } + + /// + /// NT Rpc Answer Version 1 + /// + public struct NtRpcAnswer + { + /// + /// Rpc Entry Handle + /// + public NtEntry entry; + /// + /// Rpc Call Handle + /// + public NtRpcCall call; + /// + /// Rpc Name + /// + public NtString name; + /// + /// Rpc Parameters + /// + public NtString @params; + /// + /// Rpc Connection + /// + public NtConnectionInfo conn; + } + + /// + /// NT Entry Notification + /// + public struct NtEntryNotification + { + /// + /// Entry Listener Handle + /// + public NtEntryListener listener; + /// + /// Entry Handle + /// + public NtEntry entry; + /// + /// Entry Name + /// + public NtString name; + /// + /// Entry Value + /// + public NtValue value; + /// + /// Notification Flags + /// + public uint flags; + } + + /// + /// NT Connection Notification + /// + public struct NtConnectionNotification + { + /// + /// Listener Handle + /// + public NtConnectionListener listener; + /// + /// Connected or Disconnected + /// + public NtBool connected; + /// + /// Connection Info + /// + public NtConnectionInfo conn; + } + + /// + /// NT Log Message + /// + public unsafe struct NtLogMessage + { + /// + /// Logger Handle + /// + public NtLogger logger; + /// + /// Log Level + /// + public uint level; + /// + /// Filename + /// + public byte* filename; + /// + /// Line + /// + public uint line; + /// + /// Message + /// + public byte* message; + } +} diff --git a/src/FRC.NetworkTables.Core/Interop/Utilities.cs b/src/FRC.NetworkTables.Core/Interop/Utilities.cs new file mode 100644 index 0000000..86bc6ba --- /dev/null +++ b/src/FRC.NetworkTables.Core/Interop/Utilities.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace FRC.NetworkTables.Interop +{ + internal static class Utilities + { + internal static unsafe void CreateNtString(ReadOnlySpan vStr, NtString* nStr) + { + fixed (char* str = vStr) + { + var encoding = Encoding.UTF8; + int bytes = encoding.GetByteCount(str, vStr.Length); + nStr->str = (byte*)Marshal.AllocHGlobal((bytes) * sizeof(byte)); + nStr->len = (UIntPtr)bytes; + encoding.GetBytes(str, vStr.Length, nStr->str, bytes); + } + } + + internal static unsafe void CreateNtString(ReadOnlyMemory vStr, NtString* nStr) + { + fixed (char* str = vStr.Span) + { + var encoding = Encoding.UTF8; + int bytes = encoding.GetByteCount(str, vStr.Length); + nStr->str = (byte*)Marshal.AllocHGlobal((bytes) * sizeof(byte)); + nStr->len = (UIntPtr)bytes; + encoding.GetBytes(str, vStr.Length, nStr->str, bytes); + } + } + + internal static unsafe void CreateNtString(string vStr, NtString* nStr) + { + fixed (char* str = vStr) + { + var encoding = Encoding.UTF8; + int bytes = encoding.GetByteCount(str, vStr.Length); + nStr->str = (byte*)Marshal.AllocHGlobal((bytes) * sizeof(byte)); + nStr->len = (UIntPtr)bytes; + encoding.GetBytes(str, vStr.Length, nStr->str, bytes); + } + } + + + internal static unsafe void DisposeNtString(NtString* str) + { + Marshal.FreeHGlobal((IntPtr)str->str); + } + } +} diff --git a/src/FRC.NetworkTables.Core/LogMessage.cs b/src/FRC.NetworkTables.Core/LogMessage.cs new file mode 100644 index 0000000..afa0e1c --- /dev/null +++ b/src/FRC.NetworkTables.Core/LogMessage.cs @@ -0,0 +1,27 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables +{ + public readonly struct LogMessage + { + public readonly NtLogger Logger; + public readonly LogLevel Level; + public readonly string Filename; + public readonly int Line; + public readonly string Message; + internal NetworkTableInstance Instance { get; } + + internal unsafe LogMessage(NetworkTableInstance inst, in NtLogMessage log) + { + Instance = inst; + Logger = log.logger; + Level = (LogLevel)log.level; + Filename = UTF8String.ReadUTF8String(log.filename); + Line = (int)log.line; + Message = UTF8String.ReadUTF8String(log.message); + } + } +} diff --git a/src/FRC.NetworkTables.Core/ManagedValue.cs b/src/FRC.NetworkTables.Core/ManagedValue.cs new file mode 100644 index 0000000..fef8789 --- /dev/null +++ b/src/FRC.NetworkTables.Core/ManagedValue.cs @@ -0,0 +1,451 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Runtime.InteropServices; + +namespace FRC.NetworkTables +{ + public readonly struct ManagedValue : IEquatable + { + public readonly NtType Type; + public readonly ulong LastChange; + public readonly EntryUnion Data; + + public override int GetHashCode() + { + unchecked + { + int hash = 13; + hash = (hash * 7) + Type.GetHashCode(); + switch (Type) + { + case NtType.Boolean: + hash = (hash * 7) + Data.VBoolean.GetHashCode(); + break; + case NtType.Double: + hash = (hash * 7) + Data.VDouble.GetHashCode(); + break; + case NtType.String: + hash = (hash * 7) + Data.VString!.GetHashCode(); + break; + case NtType.Rpc: + case NtType.Raw: + hash = (hash * 7) + Data.VRaw!.GetHashCode(); + break; + case NtType.BooleanArray: + hash = (hash * 7) + Data.VBooleanArray!.GetHashCode(); + break; + case NtType.DoubleArray: + hash = (hash * 7) + Data.VDoubleArray!.GetHashCode(); + break; + case NtType.StringArray: + hash = (hash * 7) + Data.VStringArray!.GetHashCode(); + break; + } + return hash; + } + } + + public override bool Equals(object obj) + { + if (obj is ManagedValue v) + { + return Equals(v); + } + return false; + } + + public bool Equals(ManagedValue other) + { + if (Type != other.Type) return false; + switch (Type) + { + case NtType.Unassigned: + return true; + case NtType.Boolean: + return Data.VBoolean == other.Data.VBoolean; + case NtType.Double: + return Data.VDouble == other.Data.VDouble; + case NtType.String: + return Data.VString.AsSpan().SequenceEqual(other.Data.VString.AsSpan()); + case NtType.Raw: + case NtType.Rpc: + return Data.VRaw.AsSpan().SequenceEqual(other.Data.VRaw.AsSpan()); + case NtType.BooleanArray: + return Data.VBooleanArray.AsSpan().SequenceEqual(other.Data.VBooleanArray.AsSpan()); + case NtType.DoubleArray: + return Data.VDoubleArray.AsSpan().SequenceEqual(other.Data.VDoubleArray.AsSpan()); + case NtType.StringArray: + return Data.VStringArray.AsSpan().SequenceEqual(other.Data.VStringArray.AsSpan()); + default: + return false; + } + } + + public object? GetValue() + { + switch (Type) + { + case NtType.Boolean: + return Data.VBoolean; + case NtType.Double: + return Data.VDouble; + case NtType.String: + return Data.VString!.ToString(); + case NtType.Rpc: + case NtType.Raw: + return Data.VRaw.AsSpan().ToArray(); + case NtType.BooleanArray: + return Data.VBooleanArray.AsSpan().ToArray(); + case NtType.DoubleArray: + return Data.VDoubleArray.AsSpan().ToArray(); + case NtType.StringArray: + return Data.VStringArray.AsSpan().ToArray(); + default: + return null; + } + } + + internal unsafe ManagedValue(NtValue* v) + { + LastChange = v->last_change; + Type = v->type; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(in RefManagedValue v) + { + LastChange = v.LastChange; + Type = v.Type; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(bool v, ulong t) + { + LastChange = t; + Type = NtType.Boolean; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(double v, ulong t) + { + LastChange = t; + Type = NtType.Double; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.String; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.Raw; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(ReadOnlySpan v, ulong t, bool r) + { + LastChange = t; + Type = r ? NtType.Rpc : NtType.Raw; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.BooleanArray; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.DoubleArray; + Data = new EntryUnion(v); + } + + internal unsafe ManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.StringArray; + Data = new EntryUnion(v); + } + } + + [StructLayout(LayoutKind.Explicit)] + public readonly struct EntryUnion + { + [FieldOffset(0)] + public readonly bool VBoolean; + [FieldOffset(0)] + public readonly double VDouble; + [FieldOffset(8)] + public readonly string? VString; + [FieldOffset(8)] + public readonly byte[]? VRaw; + [FieldOffset(8)] + public readonly bool[]? VBooleanArray; + [FieldOffset(8)] + public readonly double[]? VDoubleArray; + [FieldOffset(8)] + public readonly string[]? VStringArray; + + internal EntryUnion(bool v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VBoolean = v; + } + + internal EntryUnion(double v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VDouble = v; + } + + internal EntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VString = v.ToString(); + } + + internal EntryUnion(string v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VString = v; + } + + internal EntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VRaw = v.ToArray(); + } + + internal EntryUnion(byte[] v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VRaw = v; + } + + internal EntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VBooleanArray = v.ToArray(); + } + + internal EntryUnion(bool[] v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VBooleanArray = v; + } + + internal EntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VDoubleArray = v.ToArray(); + } + + internal EntryUnion(double[] v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VDoubleArray = v; + } + + internal EntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VStringArray = v.ToArray(); + } + + internal EntryUnion(string[] v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VStringArray = v; + } + + internal unsafe EntryUnion(NtValue* v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + switch (v->type) + { + case NtType.Unassigned: + break; + case NtType.Boolean: + VBoolean = v->data.v_boolean.Get(); + break; + case NtType.Double: + VDouble = v->data.v_double; + break; + case NtType.String: + VString = UTF8String.ReadUTF8String(v->data.v_string.str, v->data.v_string.len); + break; + case NtType.Rpc: + case NtType.Raw: + var raw = new byte[(int)v->data.v_raw.len]; + for (int i = 0; i < raw.Length; i++) + { + raw[i] = v->data.v_raw.str[i]; + } + VRaw = raw; + break; + case NtType.BooleanArray: + var barr = new bool[(int)v->data.arr_boolean.len]; + for (int i = 0; i < barr.Length; i++) + { + barr[i] = v->data.arr_boolean.arr[i].Get(); + } + VBooleanArray = barr; + break; + case NtType.DoubleArray: + var darr = new double[(int)v->data.arr_double.len]; + for (int i = 0; i < darr.Length; i++) + { + darr[i] = v->data.arr_double.arr[i]; + } + VDoubleArray = darr; + break; + case NtType.StringArray: + var sarr = new string[(int)v->data.arr_string.len]; + for (int i = 0; i < sarr.Length; i++) + { + sarr[i] = UTF8String.ReadUTF8String(v->data.arr_string.arr[i].str, v->data.arr_string.arr[i].len); + } + VStringArray = sarr; + break; + } + } + + internal EntryUnion(in RefManagedValue v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + switch (v.Type) + { + case NtType.Unassigned: + break; + case NtType.Boolean: + VBoolean = v.Data.VBoolean; + break; + case NtType.Double: + VDouble = v.Data.VDouble; + break; + case NtType.String: + VString = v.Data.VString.ToString(); + break; + case NtType.Rpc: + case NtType.Raw: + VRaw = v.Data.VRaw.ToArray(); + break; + case NtType.BooleanArray: + VBooleanArray = v.Data.VBooleanArray.ToArray(); + break; + case NtType.DoubleArray: + VDoubleArray = v.Data.VDoubleArray.ToArray(); + break; + case NtType.StringArray: + VStringArray = v.Data.VStringArray.ToArray(); + break; + } + } + } +} diff --git a/src/FRC.NetworkTables.Core/Native/CoreMethods.cs b/src/FRC.NetworkTables.Core/Native/CoreMethods.cs deleted file mode 100644 index 4751f6c..0000000 --- a/src/FRC.NetworkTables.Core/Native/CoreMethods.cs +++ /dev/null @@ -1,1108 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using NetworkTables.Exceptions; -using System.Linq; -using FRC; -using static FRC.UTF8String; - -namespace NetworkTables.Core.Native -{ - /// - /// This class contains all the methods to interface with the native library. - /// - /// - /// This is the equivelent of the NetworkTablesJNI.cpp class in the official library. It is the - /// bridge between the native methods called via P/Invoke and the NetworkTables classes. - /// Most of these are internal, however some of them can be used publicly, so the class is public, - /// and specific methods are public. - /// - internal static class CoreMethods - { - #region SetDefault - - internal static bool SetDefaultEntryValue(string name, Value value) - { - switch (value.Type) - { - case NtType.Boolean: - return SetDefaultEntryBoolean(name, value.GetBoolean()); - case NtType.Double: - return SetDefaultEntryDouble(name, value.GetDouble()); - case NtType.String: - return SetDefaultEntryString(name, value.GetString()); - case NtType.Raw: - return SetDefaultEntryRaw(name, value.GetRpc()); - case NtType.BooleanArray: - return SetDefaultEntryBooleanArray(name, value.GetBooleanArray()); - case NtType.DoubleArray: - return SetDefaultEntryDoubleArray(name, value.GetDoubleArray()); - case NtType.StringArray: - return SetDefaultEntryStringArray(name, value.GetStringArray()); - default: - return false; - } - } - - internal static bool SetDefaultEntryBoolean(string name, bool value) - { - var namePtr = CreateCachedUTF8String(name); - int retVal = Interop.NT_SetDefaultEntryBoolean(namePtr.Buffer, namePtr.Length, value ? 1 : 0); - return retVal != 0; - } - - internal static bool SetDefaultEntryDouble(string name, double value) - { - var namePtr = CreateCachedUTF8String(name); - int retVal = Interop.NT_SetDefaultEntryDouble(namePtr.Buffer, namePtr.Length, value); - return retVal != 0; - } - - internal static bool SetDefaultEntryString(string name, string value) - { - var namePtr = CreateCachedUTF8String(name); - byte[] stringPtr = CreateUTF8String(value); - int retVal = Interop.NT_SetDefaultEntryString(namePtr.Buffer, namePtr.Length, stringPtr, (UIntPtr)(stringPtr.Length - 1)); - return retVal != 0; - } - - internal static bool SetDefaultEntryRaw(string name, IList value) - { - var namePtr = CreateCachedUTF8String(name); - byte[] arr = value as byte[]; - int retVal = Interop.NT_SetDefaultEntryRaw(namePtr.Buffer, namePtr.Length, arr ?? value.ToArray(), (UIntPtr)value.Count); - return retVal != 0; - } - - internal static bool SetDefaultEntryBooleanArray(string name, IList value) - { - if (value == null) throw new ArgumentNullException(nameof(value), "Value array cannot be null"); - var namePtr = CreateCachedUTF8String(name); - - int[] valueIntArr = new int[value.Count]; - for (int i = 0; i < value.Count; i++) - { - valueIntArr[i] = value[i] ? 1 : 0; - } - - int retVal = Interop.NT_SetDefaultEntryBooleanArray(namePtr.Buffer, namePtr.Length, valueIntArr, (UIntPtr)valueIntArr.Length); - - return retVal != 0; - } - - internal static bool SetDefaultEntryDoubleArray(string name, IList value) - { - var namePtr = CreateCachedUTF8String(name); - double[] arr = value as double[]; - int retVal = Interop.NT_SetDefaultEntryDoubleArray(namePtr.Buffer, namePtr.Length, arr ?? value.ToArray(), (UIntPtr)value.Count); - - return retVal != 0; - } - - internal static bool SetDefaultEntryStringArray(string name, IList value) - { - if (value == null) throw new ArgumentNullException(nameof(value), "Value array cannot be null"); - var namePtr = CreateCachedUTF8String(name); - - DisposableNativeString[] ntStrings = new DisposableNativeString[value.Count]; - for (int i = 0; i < value.Count; i++) - { - ntStrings[i] = new DisposableNativeString(value[i]); - } - - int retVal = Interop.NT_SetDefaultEntryStringArray(namePtr.Buffer, namePtr.Length, ntStrings, (UIntPtr)ntStrings.Length); - - foreach (var ntString in ntStrings) - { - ntString.Dispose(); - } - - return retVal != 0; - } - - #endregion - - #region Setters - - internal static bool SetEntryValue(string name, Value value, bool force = false) - { - switch (value.Type) - { - case NtType.Boolean: - return SetEntryBoolean(name, value.GetBoolean(), force); - case NtType.Double: - return SetEntryDouble(name, value.GetDouble(), force); - case NtType.String: - return SetEntryString(name, value.GetString(), force); - case NtType.Raw: - return SetEntryRaw(name, value.GetRpc(), force); - case NtType.BooleanArray: - return SetEntryBooleanArray(name, value.GetBooleanArray(), force); - case NtType.DoubleArray: - return SetEntryDoubleArray(name, value.GetDoubleArray(), force); - case NtType.StringArray: - return SetEntryStringArray(name, value.GetStringArray(), force); - default: - return false; - } - } - - internal static bool SetEntryBoolean(string name, bool value, bool force = false) - { - var namePtr = CreateCachedUTF8String(name); - int retVal = Interop.NT_SetEntryBoolean(namePtr.Buffer, namePtr.Length, value ? 1 : 0, force ? 1 : 0); - return retVal != 0; - } - - internal static bool SetEntryDouble(string name, double value, bool force = false) - { - var namePtr = CreateCachedUTF8String(name); - int retVal = Interop.NT_SetEntryDouble(namePtr.Buffer, namePtr.Length, value, force ? 1 : 0); - return retVal != 0; - } - - internal static bool SetEntryString(string name, string value, bool force = false) - { - var namePtr = CreateCachedUTF8String(name); - byte[] stringPtr = CreateUTF8String(value); - int retVal = Interop.NT_SetEntryString(namePtr.Buffer, namePtr.Length, stringPtr, (UIntPtr)(stringPtr.Length - 1), force ? 1 : 0); - return retVal != 0; - } - - internal static bool SetEntryRaw(string name, IList value, bool force = false) - { - var namePtr = CreateCachedUTF8String(name); - byte[] arr = value as byte[]; - int retVal = Interop.NT_SetEntryRaw(namePtr.Buffer, namePtr.Length, arr ?? value.ToArray(), (UIntPtr)value.Count, force ? 1 : 0); - return retVal != 0; - } - - internal static bool SetEntryBooleanArray(string name, IList value, bool force = false) - { - if (value == null) throw new ArgumentNullException(nameof(value), "Value array cannot be null"); - var namePtr = CreateCachedUTF8String(name); - - int[] valueIntArr = new int[value.Count]; - for (int i = 0; i < value.Count; i++) - { - valueIntArr[i] = value[i] ? 1 : 0; - } - - int retVal = Interop.NT_SetEntryBooleanArray(namePtr.Buffer, namePtr.Length, valueIntArr, (UIntPtr)valueIntArr.Length, force ? 1 : 0); - - return retVal != 0; - } - - internal static bool SetEntryDoubleArray(string name, IList value, bool force = false) - { - var namePtr = CreateCachedUTF8String(name); - double[] arr = value as double[]; - int retVal = Interop.NT_SetEntryDoubleArray(namePtr.Buffer, namePtr.Length, arr ?? value.ToArray(), (UIntPtr)value.Count, force ? 1 : 0); - - return retVal != 0; - } - - internal static bool SetEntryStringArray(string name, IList value, bool force = false) - { - if (value == null) throw new ArgumentNullException(nameof(value), "Value array cannot be null"); - var namePtr = CreateCachedUTF8String(name); - - DisposableNativeString[] ntStrings = new DisposableNativeString[value.Count]; - for (int i = 0; i < value.Count; i++) - { - ntStrings[i] = new DisposableNativeString(value[i]); - } - - int retVal = Interop.NT_SetEntryStringArray(namePtr.Buffer, namePtr.Length, ntStrings, (UIntPtr)ntStrings.Length, force ? 1 : 0); - - foreach (var ntString in ntStrings) - { - ntString.Dispose(); - } - - return retVal != 0; - } - - #endregion - - #region DefaultGetters - - internal static bool GetEntryBoolean(string name, bool defaultValue) - { - var namePtr = CreateCachedUTF8String(name); - int boolean = 0; - ulong lc = 0; - int status = Interop.NT_GetEntryBoolean(namePtr.Buffer, namePtr.Length, ref lc, ref boolean); - if (status == 0) - { - return defaultValue; - } - return boolean != 0; - } - - internal static double GetEntryDouble(string name, double defaultValue) - { - var namePtr = CreateCachedUTF8String(name); - double retVal = 0; - ulong lastChange = 0; - int status = Interop.NT_GetEntryDouble(namePtr.Buffer, namePtr.Length, ref lastChange, ref retVal); - if (status == 0) - { - return defaultValue; - } - return retVal; - } - - internal static string GetEntryString(string name, string defaultValue) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr stringSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr ret = Interop.NT_GetEntryString(namePtr.Buffer, namePtr.Length, ref lastChange, ref stringSize); - if (ret == IntPtr.Zero) - { - return defaultValue; - } - else - { - string str = ReadUTF8String(ret, stringSize); - Interop.NT_FreeCharArray(ret); - return str; - } - } - - internal static byte[] GetEntryRaw(string name, byte[] defaultValue) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr stringSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr ret = Interop.NT_GetEntryRaw(namePtr.Buffer, namePtr.Length, ref lastChange, ref stringSize); - if (ret == IntPtr.Zero) - { - return defaultValue; - } - byte[] arr = GetRawDataFromPtr(ret, stringSize); - Interop.NT_FreeCharArray(ret); - return arr; - } - - internal static double[] GetEntryDoubleArray(string name, double[] defaultValue) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr arrSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr arrPtr = Interop.NT_GetEntryDoubleArray(namePtr.Buffer, namePtr.Length, ref lastChange, ref arrSize); - if (arrPtr == IntPtr.Zero) - { - return defaultValue; - } - double[] arr = GetDoubleArrayFromPtr(arrPtr, arrSize); - Interop.NT_FreeDoubleArray(arrPtr); - return arr; - } - - internal static bool[] GetEntryBooleanArray(string name, bool[] defaultValue) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr arrSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr arrPtr = Interop.NT_GetEntryBooleanArray(namePtr.Buffer, namePtr.Length, ref lastChange, ref arrSize); - if (arrPtr == IntPtr.Zero) - { - return defaultValue; - } - bool[] arr = GetBooleanArrayFromPtr(arrPtr, arrSize); - Interop.NT_FreeBooleanArray(arrPtr); - return arr; - } - - internal static string[] GetEntryStringArray(string name, string[] defaultValue) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr arrSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr arrPtr = Interop.NT_GetEntryStringArray(namePtr.Buffer, namePtr.Length, ref lastChange, ref arrSize); - if (arrPtr == IntPtr.Zero) - { - return defaultValue; - } - string[] arr = GetStringArrayFromPtr(arrPtr, arrSize); - Interop.NT_FreeStringArray(arrPtr, arrSize); - return arr; - } - - #endregion - - #region Getters - - internal static Value GetEntryValue(string name) - { - NtType type = GetType(name); - try - { - switch (type) - { - case NtType.Boolean: - return Value.MakeBoolean(GetEntryBoolean(name)); - case NtType.Double: - return Value.MakeDouble(GetEntryDouble(name)); - case NtType.String: - return Value.MakeString(GetEntryString(name)); - case NtType.Raw: - return Value.MakeRaw(GetEntryRaw(name)); - case NtType.BooleanArray: - return Value.MakeBooleanArray(GetEntryBooleanArray(name)); - case NtType.DoubleArray: - return Value.MakeDoubleArray(GetEntryDoubleArray(name)); - case NtType.StringArray: - return Value.MakeStringArray(GetEntryStringArray(name)); - default: - return null; - } - } - catch (InvalidOperationException) - { - return null; - } - } - - private static void ThrowException(string name, IntPtr namePtr, UIntPtr size, NtType requestedType) - { - NtType typeInTable = Interop.NT_GetType(namePtr, size); - if (typeInTable == NtType.Unassigned) - { - throw new TableKeyNotDefinedException(name); - } - else - { - throw new TableKeyDifferentTypeException(name, requestedType, typeInTable); - } - } - - internal static bool GetEntryBoolean(string name) - { - var namePtr = CreateCachedUTF8String(name); - int boolean = 0; - ulong lc = 0; - int status = Interop.NT_GetEntryBoolean(namePtr.Buffer, namePtr.Length, ref lc, ref boolean); - if (status == 0) - { - ThrowException(name, namePtr.Buffer, namePtr.Length, NtType.Boolean); - } - return boolean != 0; - } - - internal static double GetEntryDouble(string name) - { - var namePtr = CreateCachedUTF8String(name); - double retVal = 0; - ulong lastChange = 0; - int status = Interop.NT_GetEntryDouble(namePtr.Buffer, namePtr.Length, ref lastChange, ref retVal); - if (status == 0) - { - ThrowException(name, namePtr.Buffer, namePtr.Length, NtType.Double); - } - return retVal; - } - - internal static string GetEntryString(string name) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr stringSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr ret = Interop.NT_GetEntryString(namePtr.Buffer, namePtr.Length, ref lastChange, ref stringSize); - if (ret == IntPtr.Zero) - { - ThrowException(name, namePtr.Buffer, namePtr.Length, NtType.String); - } - string str = ReadUTF8String(ret, stringSize); - Interop.NT_FreeCharArray(ret); - return str; - } - - internal static byte[] GetEntryRaw(string name) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr stringSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr ret = Interop.NT_GetEntryRaw(namePtr.Buffer, namePtr.Length, ref lastChange, ref stringSize); - if (ret == IntPtr.Zero) - { - ThrowException(name, namePtr.Buffer, namePtr.Length, NtType.Raw); - } - byte[] data = GetRawDataFromPtr(ret, stringSize); - Interop.NT_FreeCharArray(ret); - return data; - } - - internal static double[] GetEntryDoubleArray(string name) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr arrSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr arrPtr = Interop.NT_GetEntryDoubleArray(namePtr.Buffer, namePtr.Length, ref lastChange, ref arrSize); - if (arrPtr == IntPtr.Zero) - { - ThrowException(name, namePtr.Buffer, namePtr.Length, NtType.DoubleArray); - } - double[] arr = GetDoubleArrayFromPtr(arrPtr, arrSize); - Interop.NT_FreeDoubleArray(arrPtr); - return arr; - } - - internal static bool[] GetEntryBooleanArray(string name) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr arrSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr arrPtr = Interop.NT_GetEntryBooleanArray(namePtr.Buffer, namePtr.Length, ref lastChange, ref arrSize); - if (arrPtr == IntPtr.Zero) - { - ThrowException(name, namePtr.Buffer, namePtr.Length, NtType.BooleanArray); - } - bool[] arr = GetBooleanArrayFromPtr(arrPtr, arrSize); - Interop.NT_FreeBooleanArray(arrPtr); - return arr; - } - - internal static string[] GetEntryStringArray(string name) - { - var namePtr = CreateCachedUTF8String(name); - UIntPtr arrSize = UIntPtr.Zero; - ulong lastChange = 0; - IntPtr arrPtr = Interop.NT_GetEntryStringArray(namePtr.Buffer, namePtr.Length, ref lastChange, ref arrSize); - if (arrPtr == IntPtr.Zero) - { - ThrowException(name, namePtr.Buffer, namePtr.Length, NtType.StringArray); - } - string[] arr = GetStringArrayFromPtr(arrPtr, arrSize); - Interop.NT_FreeStringArray(arrPtr, arrSize); - return arr; - } - - #endregion - - #region EntryInfo - - internal static List GetEntryInfo(string prefix, NtType types) - { - byte[] str = CreateUTF8String(prefix); - UIntPtr arrSize = UIntPtr.Zero; - IntPtr arr = Interop.NT_GetEntryInfo(str, (UIntPtr)(str.Length - 1), (uint)types, ref arrSize); -#pragma warning disable CS0618 - int entryInfoSize = Marshal.SizeOf(typeof(NtEntryInfo)); -#pragma warning restore CS0618 - int arraySize = (int)arrSize.ToUInt64(); - List entryArray = new List(arraySize); - - for (int i = 0; i < arraySize; i++) - { - IntPtr data = new IntPtr(arr.ToInt64() + entryInfoSize * i); -#pragma warning disable CS0618 - NtEntryInfo info = (NtEntryInfo)Marshal.PtrToStructure(data, typeof(NtEntryInfo)); -#pragma warning restore CS0618 - entryArray.Add(new EntryInfo(info.name.ToString(), info.type, (EntryFlags)info.flags, (long)info.last_change)); - } - Interop.NT_DisposeEntryInfoArray(arr, arrSize); - return entryArray; - } - - #endregion - - #region ConnectionInfo - - internal static List GetConnections() - { - UIntPtr count = UIntPtr.Zero; - IntPtr connections = Interop.NT_GetConnections(ref count); -#pragma warning disable CS0618 - int connectionInfoSize = Marshal.SizeOf(typeof(NtConnectionInfo)); -#pragma warning restore CS0618 - int arraySize = (int)count.ToUInt64(); - - List connectionsArray = new List(arraySize); - - for (int i = 0; i < arraySize; i++) - { - IntPtr data = new IntPtr(connections.ToInt64() + connectionInfoSize * i); -#pragma warning disable CS0618 - var con = (NtConnectionInfo)Marshal.PtrToStructure(data, typeof(NtConnectionInfo)); -#pragma warning restore CS0618 - connectionsArray.Add(new ConnectionInfo(con.RemoteId.ToString(), con.RemoteIp.ToString(), (int)con.RemotePort, (long)con.LastUpdate, (int)con.ProtocolVersion)); - } - Interop.NT_DisposeConnectionInfoArray(connections, count); - return connectionsArray; - } - - #endregion - - #region EntryListeners - - private static readonly Dictionary s_entryCallbacks = new Dictionary(); - - internal static int AddEntryListener(string prefix, EntryListenerCallback listener, NotifyFlags flags) - { - // ReSharper disable once InconsistentNaming - Interop.NT_EntryListenerCallback modCallback = (uid, data, name, len, value, flags_) => - { - NtType type = Interop.NT_GetValueType(value); - Value obj; - ulong lastChange = 0; - UIntPtr size = UIntPtr.Zero; - IntPtr ptr; - switch (type) - { - case NtType.Unassigned: - obj = null; - break; - case NtType.Boolean: - int boolean = 0; - Interop.NT_GetValueBoolean(value, ref lastChange, ref boolean); - obj = Value.MakeBoolean(boolean != 0); - break; - case NtType.Double: - double val = 0; - Interop.NT_GetValueDouble(value, ref lastChange, ref val); - obj = Value.MakeDouble(val); - break; - case NtType.String: - ptr = Interop.NT_GetValueString(value, ref lastChange, ref size); - obj = Value.MakeString(ReadUTF8String(ptr, size)); - break; - case NtType.Raw: - ptr = Interop.NT_GetValueRaw(value, ref lastChange, ref size); - obj = Value.MakeRaw(GetRawDataFromPtr(ptr, size)); - break; - case NtType.BooleanArray: - ptr = Interop.NT_GetValueBooleanArray(value, ref lastChange, ref size); - obj = Value.MakeBooleanArray(GetBooleanArrayFromPtr(ptr, size)); - break; - case NtType.DoubleArray: - ptr = Interop.NT_GetValueDoubleArray(value, ref lastChange, ref size); - obj = Value.MakeDoubleArray(GetDoubleArrayFromPtr(ptr, size)); - break; - case NtType.StringArray: - ptr = Interop.NT_GetValueStringArray(value, ref lastChange, ref size); - obj = Value.MakeStringArray(GetStringArrayFromPtr(ptr, size)); - break; - case NtType.Rpc: - ptr = Interop.NT_GetValueRaw(value, ref lastChange, ref size); - obj = Value.MakeRpc(GetRawDataFromPtr(ptr, size)); - break; - default: - obj = null; - break; - } - string key = ReadUTF8String(name, len); - listener((int)uid, key, obj, (NotifyFlags)flags_); - }; - byte[] prefixStr = CreateUTF8String(prefix); - int retVal = (int)Interop.NT_AddEntryListener(prefixStr, (UIntPtr)(prefixStr.Length - 1), IntPtr.Zero, modCallback, (uint)flags); - s_entryCallbacks.Add(retVal, modCallback); - return retVal; - } - - internal static void RemoveEntryListener(int uid) - { - Interop.NT_RemoveEntryListener((uint)uid); - if (s_entryCallbacks.ContainsKey(uid)) - { - s_entryCallbacks.Remove(uid); - } - } - - #endregion - - #region Connection Listeners - - private static readonly Dictionary s_connectionCallbacks = new Dictionary(); - - internal static int AddConnectionListener(ConnectionListenerCallback callback, bool immediateNotify) - { - Interop.NT_ConnectionListenerCallback modCallback = (uint uid, IntPtr data, int connected, ref NtConnectionInfo conn) => - { - ConnectionInfo info = new ConnectionInfo(conn.RemoteId.ToString(), conn.RemoteIp.ToString(), (int)conn.RemotePort, (long)conn.LastUpdate, (int)conn.ProtocolVersion); - callback((int)uid, connected != 0, info); - }; - - int retVal = (int)Interop.NT_AddConnectionListener(IntPtr.Zero, modCallback, immediateNotify ? 1 : 0); - s_connectionCallbacks.Add(retVal, modCallback); - return retVal; - } - - internal static void RemoveConnectionListener(int uid) - { - Interop.NT_RemoveConnectionListener((uint)uid); - if (s_connectionCallbacks.ContainsKey(uid)) - { - s_connectionCallbacks.Remove(uid); - } - } - - #endregion - - #region Server and Client Methods - - internal static void SetNetworkIdentity(string name) - { - byte[] namePtr = CreateUTF8String(name); - Interop.NT_SetNetworkIdentity(namePtr, (UIntPtr)(namePtr.Length - 1)); - } - - internal static void StartClient() - { - Interop.NT_StartClientNone(); - } - - internal static void StartClient(string serverName, uint port) - { - if (serverName == null) - { - throw new ArgumentNullException(nameof(serverName), "Server cannot be null"); - } - byte[] serverNamePtr = CreateUTF8String(serverName); - Interop.NT_StartClient(serverNamePtr, port); - } - - internal static void StartClient(IList servers) - { - uint[] uPorts = new uint[servers.Count]; - for (int i = 0; i < uPorts.Length; i++) - { - uPorts[i] = (uint)servers[i].Port; - } - IntPtr[] serv = new IntPtr[servers.Count]; - DisposableNativeString[] servHolder = new DisposableNativeString[servers.Count]; - UIntPtr len; - for (int i = 0; i < serv.Length; i++) - { - servHolder[i] = new DisposableNativeString(servers[i].IpAddress); - serv[i] = servHolder[i].Buffer; - } - len = (UIntPtr)servers.Count; - Interop.NT_StartClientMulti(len, serv, uPorts); - foreach (var s in servHolder) - { - s.Dispose(); - } - } - - internal static void SetServer(string serverName, int port) - { - if (serverName == null) - { - throw new ArgumentNullException(nameof(serverName), "Server cannot be null"); - } - byte[] serverNamePtr = CreateUTF8String(serverName); - Interop.NT_SetServer(serverNamePtr, (uint)port); - } - - internal static void SetServer(IList servers) - { - uint[] uPorts = new uint[servers.Count]; - for (int i = 0; i < uPorts.Length; i++) - { - uPorts[i] = (uint)servers[i].Port; - } - IntPtr[] serv = new IntPtr[servers.Count]; - DisposableNativeString[] servHolder = new DisposableNativeString[servers.Count]; - UIntPtr len; - for (int i = 0; i < serv.Length; i++) - { - servHolder[i] = new DisposableNativeString(servers[i].IpAddress); - serv[i] = servHolder[i].Buffer; - } - len = (UIntPtr)servers.Count; - Interop.NT_SetServerMulti(len, serv, uPorts); - foreach (var s in servHolder) - { - s.Dispose(); - } - } - - internal static void StartDSClient(int port) - { - Interop.NT_StartDSClient((uint)port); - } - - internal static void StopDSClient() - { - Interop.NT_StopDSClient(); - } - - internal static void StartServer(string fileName, string listenAddress, int port) - { - var fileNamePtr = string.IsNullOrEmpty(fileName) ? new[] { (byte)0 } : CreateUTF8String(fileName); - var listenAddressPtr = string.IsNullOrEmpty(fileName) ? new[] { (byte)0 } : CreateUTF8String(listenAddress); - Interop.NT_StartServer(fileNamePtr, listenAddressPtr, (uint)port); - } - - internal static void StopClient() - { - Interop.NT_StopClient(); - } - - internal static void StopServer() - { - Interop.NT_StopServer(); - } - - internal static void StopNotifier() - { - Interop.NT_StopNotifier(); - //Clear callback dictionaries - s_entryCallbacks.Clear(); - s_connectionCallbacks.Clear(); - } - - internal static void StopRpcServer() - { - Interop.NT_StopRpcServer(); - // Clear callback dictionaries - s_rpcCallbacks.Clear(); - } - - internal static void SetUpdateRate(double interval) - { - Interop.NT_SetUpdateRate(interval); - } - - #endregion - - #region Persistent - - internal static string SavePersistent(string filename) - { - byte[] name = CreateUTF8String(filename); - IntPtr err = Interop.NT_SavePersistent(name); - if (err != IntPtr.Zero) - { - return ReadUTF8String(err); - } - else - { - return null; - } - } - - internal static string LoadPersistent(string filename, Action warn) - { - byte[] name = CreateUTF8String(filename); - IntPtr err = Interop.NT_LoadPersistent(name, (line, msg) => { warn((int)line, ReadUTF8String(msg)); }); - if (err != IntPtr.Zero) - { - return ReadUTF8String(err); - } - else - { - return null; - } - } - - #endregion - - #region Flags - - internal static void SetEntryFlags(string name, EntryFlags flags) - { - var str = CreateCachedUTF8String(name); - Interop.NT_SetEntryFlags(str.Buffer, str.Length, (uint)flags); - } - - internal static EntryFlags GetEntryFlags(string name) - { - var str = CreateCachedUTF8String(name); - uint flags = Interop.NT_GetEntryFlags(str.Buffer, str.Length); - return (EntryFlags)flags; - } - - #endregion - - #region Utility - - internal static void DeleteEntry(string name) - { - var str = CreateCachedUTF8String(name); - Interop.NT_DeleteEntry(str.Buffer, str.Length); - } - - internal static void DeleteAllEntries() - { - Interop.NT_DeleteAllEntries(); - } - - internal static void Flush() - { - Interop.NT_Flush(); - } - - internal static bool NotifierDestroyed() - { - return Interop.NT_NotifierDestroyed() != 0; - } - - internal static NtType GetType(string name) - { - var str = CreateCachedUTF8String(name); - NtType retVal = Interop.NT_GetType(str.Buffer, str.Length); - return retVal; - } - - internal static bool ContainsEntry(string name) - { - NtType val = GetType(name); - return val != NtType.Unassigned; - } - - internal static long Now() - { - return (long)Interop.NT_Now(); - } - - #endregion - - #region Logger - - private static Interop.NT_LogFunc s_nativeLog; - - /// - /// Assigns a method to be called whenever a log statement occurs in the internal - /// network table library. - /// - /// The log function to assign. - /// The minimum level to log. - public static void SetLogger(LogFunc func, LogLevel minLevel) - { - s_nativeLog = (level, file, line, msg) => - { - string message = ReadUTF8String(msg); - string fileName = ReadUTF8String(file); - - func((LogLevel)level, fileName, (int)line, message); - }; - - Interop.NT_SetLogger(s_nativeLog, (uint)minLevel); - } - - #endregion - - #region IntPtr to Array Conversions - - private static double[] GetDoubleArrayFromPtr(IntPtr ptr, UIntPtr size) - { - double[] arr = new double[size.ToUInt64()]; - Marshal.Copy(ptr, arr, 0, arr.Length); - return arr; - } - - internal static byte[] GetRawDataFromPtr(IntPtr ptr, UIntPtr size) - { - int len = (int)size.ToUInt64(); - byte[] data = new byte[len]; - Marshal.Copy(ptr, data, 0, len); - return data; - } - - private static bool[] GetBooleanArrayFromPtr(IntPtr ptr, UIntPtr size) - { - int iSize = (int)size.ToUInt64(); - - bool[] bArr = new bool[iSize]; - for (int i = 0; i < iSize; i++) - { - bArr[i] = Marshal.ReadInt32(ptr, sizeof(int) * i) != 0; - } - return bArr; - } - - private static string[] GetStringArrayFromPtr(IntPtr ptr, UIntPtr size) - { -#pragma warning disable CS0618 - int ntStringSize = Marshal.SizeOf(typeof(NtStringRead)); -#pragma warning restore CS0618 - int arraySize = (int)size.ToUInt64(); - string[] strArray = new string[arraySize]; - - for (int i = 0; i < arraySize; i++) - { - IntPtr data = new IntPtr(ptr.ToInt64() + ntStringSize * i); -#pragma warning disable CS0618 - strArray[i] = Marshal.PtrToStructure(data, typeof(NtStringRead)).ToString(); -#pragma warning restore CS0618 - } - return strArray; - } - - #endregion - - #region Rpc - // Never queried because it is only used to save for the GC - // ReSharper disable once CollectionNeverQueried.Global - internal static readonly List s_rpcCallbacks = new List(); - - internal static void CreateRpc(string name, IList def, RpcCallback callback) - { - Interop.NT_RPCCallback modCallback = - (IntPtr data, IntPtr ptr, UIntPtr len, IntPtr intPtr, UIntPtr paramsLen, out UIntPtr resultsLen, ref NtConnectionInfo connInfo) => - { - string retName = ReadUTF8String(ptr, len); - byte[] param = GetRawDataFromPtr(intPtr, paramsLen); - IList cb = callback(retName, param, connInfo.ToManaged()); - resultsLen = (UIntPtr)cb.Count; - IntPtr retPtr = Interop.NT_AllocateCharArray(resultsLen); - if (cb is byte[]) - { - Marshal.Copy((byte[])cb, 0, retPtr, cb.Count); - } - else - { - for (int i = 0; i < cb.Count; i++) - { - // Must do a slow write if not a byte[] - Marshal.WriteByte(retPtr, i, cb[i]); - } - } - - return retPtr; - }; - var nameB = CreateCachedUTF8String(name); - if (def is byte[] bArr) - { - Interop.NT_CreateRpc(nameB.Buffer, nameB.Length, bArr, (UIntPtr)def.Count, IntPtr.Zero, modCallback); - } - else - { - Interop.NT_CreateRpc(nameB.Buffer, nameB.Length, def.ToArray(), (UIntPtr)def.Count, IntPtr.Zero, modCallback); - } - - s_rpcCallbacks.Add(modCallback); - } - - internal static void CreatePolledRpc(string name, IList def) - { - var nameB = CreateCachedUTF8String(name); - if (def is byte[] bArr) - { - Interop.NT_CreatePolledRpc(nameB.Buffer, nameB.Length, bArr, (UIntPtr)def.Count); - } - else - { - Interop.NT_CreatePolledRpc(nameB.Buffer, nameB.Length, def.ToArray(), (UIntPtr)def.Count); - } - } - - internal static bool PollRpc(bool blocking, TimeSpan timeout, out RpcCallInfo callInfo) - { - if (Interop.NT_PollRpcTimeout(blocking ? 1 : 0, timeout.TotalSeconds, out NtRpcCallInfo nativeInfo) == 0) - { - callInfo = new RpcCallInfo(); - return false; - } - callInfo = nativeInfo.ToManaged(); - return true; - } - - internal static bool PollRpc(bool blocking, out RpcCallInfo callInfo) - { - int retVal = Interop.NT_PollRpc(blocking ? 1 : 0, out var nativeInfo); - if (retVal == 0) - { - callInfo = new RpcCallInfo(); - return false; - } - callInfo = nativeInfo.ToManaged(); - return true; - } - - internal static void PostRpcResponse(long rpcId, long callUid, IList result) - { - if (result is byte[] bArr) - { - Interop.NT_PostRpcResponse((uint)rpcId, (uint)callUid, bArr, (UIntPtr)result.Count); - } - else - { - Interop.NT_PostRpcResponse((uint)rpcId, (uint)callUid, result.ToArray(), (UIntPtr)result.Count); - } - } - - internal static long CallRpc(string name, IList param) - { - var nameB = CreateCachedUTF8String(name); - if (param is byte[] bArr) - { - return Interop.NT_CallRpc(nameB.Buffer, nameB.Length, bArr, (UIntPtr)param.Count); - } - else - { - return Interop.NT_CallRpc(nameB.Buffer, nameB.Length, param.ToArray(), (UIntPtr)param.Count); - } - } - -#if !NET40 - internal static async Task GetRpcResultAsync(long callUid, CancellationToken token) - { - token.Register(() => - { - // must use a delegate to cancel the call. - Interop.NT_CancelBlockingRpcResult((uint)callUid); - }); - try - { - var result = await Task.Run(() => - { - bool success = GetRpcResult(true, callUid, out byte[] results); - if (success) - { - return results; - } - else - { - return null; - } - }, token).ConfigureAwait(false); - return result; - } - catch (OperationCanceledException) - { - return null; - } - } -#endif //NET40 - internal static bool GetRpcResult(bool blocking, long callUid, TimeSpan timeout, out byte[] result) - { - UIntPtr size = UIntPtr.Zero; - IntPtr retVal = Interop.NT_GetRpcResultTimeout(blocking ? 1 : 0, (uint)callUid, timeout.TotalSeconds, ref size); - if (retVal == IntPtr.Zero) - { - result = null; - return false; - } - result = GetRawDataFromPtr(retVal, size); - return true; - } - - internal static bool GetRpcResult(bool blocking, long callUid, out byte[] result) - { - UIntPtr size = UIntPtr.Zero; - IntPtr retVal = Interop.NT_GetRpcResult(blocking ? 1 : 0, (uint)callUid, ref size); - if (retVal == IntPtr.Zero) - { - result = null; - return false; - } - result = GetRawDataFromPtr(retVal, size); - return true; - } - - #endregion - - #region IntPtrs To String Conversions - - #endregion - } -} diff --git a/src/FRC.NetworkTables.Core/Native/Interop.cs b/src/FRC.NetworkTables.Core/Native/Interop.cs deleted file mode 100644 index 6e5c829..0000000 --- a/src/FRC.NetworkTables.Core/Native/Interop.cs +++ /dev/null @@ -1,402 +0,0 @@ -using System; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security; -using FRC.NativeLibraryUtilities; -using NetworkTables.Tables; -using FRC; - -// ReSharper disable InconsistentNaming -// ReSharper disable NotAccessedField.Global - -namespace NetworkTables.Core.Native -{ - internal class ExcludeFromCodeCoverageAttribute : Attribute - { - - } -#if !NETSTANDARD - [SuppressUnmanagedCodeSecurity] -#endif - [ExcludeFromCodeCoverage] - internal class Interop - { - private static readonly bool s_libraryLoaded; - // ReSharper disable PrivateFieldCanBeConvertedToLocalVariable - internal static NativeLibraryLoader NativeLoader { get; } - private static readonly string s_libraryLocation; - private static readonly bool s_useCommandLineFile; - // ReSharper restore PrivateFieldCanBeConvertedToLocalVariable - private static readonly bool s_runFinalizer; - - // private constructor. Only used for our unload finalizer - private Interop() { } - private void Ping() { } // Used to force compilation - // static variable used only for interop purposes - private static readonly Interop finalizeInterop = new Interop(); - ~Interop() - { - // If we did not successfully get constructed, we don't need to destruct - if (!s_runFinalizer) return; - //Sets logger to null so no logger gets called back. - NT_SetLogger(null, 0); - - NT_StopDSClient(); - NT_StopClient(); - NT_StopServer(); - NT_StopRpcServer(); - NT_StopNotifier(); - - NativeLoader.LibraryLoader.UnloadLibrary(); - - try - { - //Don't delete file if we are using a specified file. - if (!s_useCommandLineFile && File.Exists(s_libraryLocation)) - { - File.Delete(s_libraryLocation); - } - } - catch - { - //Any errors just ignore. - } - } - - - static Interop() - { - if (!s_libraryLoaded) - { - try - { - finalizeInterop.Ping(); - string[] commandArgs = Environment.GetCommandLineArgs(); - foreach (var commandArg in commandArgs) - { - //search for a line with the prefix "-ntcore:" - if (commandArg.ToLower().Contains("-ntcore:")) - { - //Split line to get the library. - int splitLoc = commandArg.IndexOf(':'); - string file = commandArg.Substring(splitLoc + 1); - - //If the file exists, just return it so dlopen can load it. - if (File.Exists(file)) - { - s_libraryLocation = file; - s_useCommandLineFile = true; - } - } - } - - const string resourceRoot = "FRC.NetworkTables.Core.DesktopLibraries.Libraries."; - - NativeLoader = new NativeLibraryLoader(); - NativeLoader.AddLibraryLocation(OsType.Windows32, - resourceRoot + "Windows.x86.ntcore.dll"); - NativeLoader.AddLibraryLocation(OsType.Windows64, - resourceRoot + "Windows.amd64.ntcore.dll"); - NativeLoader.AddLibraryLocation(OsType.Linux32, - resourceRoot + "Linux.x86.libntcore.so"); - NativeLoader.AddLibraryLocation(OsType.Linux64, - resourceRoot + "Linux.amd64.libntcore.so"); - NativeLoader.AddLibraryLocation(OsType.MacOs32, - resourceRoot + "Mac_OS_X.x86.libntcore.dylib"); - NativeLoader.AddLibraryLocation(OsType.MacOs64, - resourceRoot + "Mac_OS_X.x86_64.libntcore.dylib"); - NativeLoader.AddLibraryLocation(OsType.roboRIO, "libntcore.so"); - - if (s_useCommandLineFile) - { - NativeLoader.LoadNativeLibrary(s_libraryLocation, true); - } - else - { - NativeLoader.LoadNativeLibraryFromReflectedAssembly("FRC.NetworkTables.Core.DesktopLibraries"); - s_libraryLocation = NativeLoader.LibraryLocation; - } - - NativeDelegateInitializer.SetupNativeDelegates(NativeLoader); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - Console.WriteLine(e.StackTrace); - Environment.Exit(1); - } - s_runFinalizer = true; - s_libraryLoaded = true; - } - } - - //Callback Typedefs - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void NT_EntryListenerCallback( - uint uid, IntPtr data, IntPtr name, UIntPtr name_len, IntPtr value, uint flags); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void NT_ConnectionListenerCallback( - uint uid, IntPtr data, int connected, ref NtConnectionInfo conn); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void NT_LogFunc(uint level, IntPtr file, uint line, IntPtr msg); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void WarmFunction(UIntPtr line, IntPtr msg); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate IntPtr NT_RPCCallback( - IntPtr data, IntPtr name, UIntPtr name_len, IntPtr param, UIntPtr params_len, out UIntPtr results_len, ref NtConnectionInfo conn); - - - //Interup Functions - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_SetEntryFlagsDelegate(IntPtr name, UIntPtr name_len, uint flags); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate uint NT_GetEntryFlagsDelegate(IntPtr name, UIntPtr name_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DeleteEntryDelegate(IntPtr name, UIntPtr name_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DeleteAllEntriesDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetEntryInfoDelegate(byte[] prefix, UIntPtr prefix_len, uint types, ref UIntPtr count); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_FlushDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate uint NT_AddEntryListenerDelegate(byte[] prefix, UIntPtr prefix_len, IntPtr data, NT_EntryListenerCallback callback, uint flags); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_RemoveEntryListenerDelegate(uint entry_listener_uid); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate uint NT_AddConnectionListenerDelegate(IntPtr data, NT_ConnectionListenerCallback callback, int immediate_notify); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_RemoveConnectionListenerDelegate(uint conn_listener_uid); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_SetNetworkIdentityDelegate(byte[] name, UIntPtr name_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StartServerDelegate(byte[] persist_filename, byte[] listen_address, uint port); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StopServerDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StartClientNoneDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StartClientDelegate(byte[] server_name, uint port); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StartClientMultiDelegate(UIntPtr count, IntPtr[] server_names, uint[] port); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StopClientDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_SetServerDelegate(byte[] server_name, uint port); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_SetServerMultiDelegate(UIntPtr count, IntPtr[] server_names, uint[] ports); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StartDSClientDelegate(uint port); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_StopDSClientDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate uint NT_StopRpcServerDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_StopNotifierDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_NotifierDestroyedDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_SetUpdateRateDelegate(double interval); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetConnectionsDelegate(ref UIntPtr count); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_SavePersistentDelegate(byte[] filename); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_LoadPersistentDelegate(byte[] filename, WarmFunction warn); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DisposeValueDelegate(IntPtr value); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_InitValueDelegate(IntPtr value); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DisposeStringDelegate(ref NtStringRead str); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate NtType NT_GetTypeDelegate(IntPtr name, UIntPtr name_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DisposeConnectionInfoArrayDelegate(IntPtr arr, UIntPtr count); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DisposeEntryInfoArrayDelegate(IntPtr arr, UIntPtr count); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate ulong NT_NowDelegate(); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_SetLoggerDelegate(NT_LogFunc funct, uint min_level); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_AllocateCharArrayDelegate(UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_FreeBooleanArrayDelegate(IntPtr arr); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_FreeDoubleArrayDelegate(IntPtr arr); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_FreeCharArrayDelegate(IntPtr arr); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_FreeStringArrayDelegate(IntPtr arr, UIntPtr arr_size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate NtType NT_GetValueTypeDelegate(IntPtr value); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_GetValueBooleanDelegate(IntPtr value, ref ulong last_change, ref int v_boolean); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_GetValueDoubleDelegate(IntPtr value, ref ulong last_change, ref double v_double); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetValueStringDelegate(IntPtr value, ref ulong last_change, ref UIntPtr string_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetValueRawDelegate(IntPtr value, ref ulong last_change, ref UIntPtr raw_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetValueBooleanArrayDelegate(IntPtr value, ref ulong last_change, ref UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetValueDoubleArrayDelegate(IntPtr value, ref ulong last_change, ref UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetValueStringArrayDelegate(IntPtr value, ref ulong last_change, ref UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_GetEntryBooleanDelegate(IntPtr name, UIntPtr name_len, ref ulong last_change, ref int v_boolean); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_GetEntryDoubleDelegate(IntPtr name, UIntPtr name_len, ref ulong last_change, ref double v_double); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetEntryStringDelegate(IntPtr name, UIntPtr name_len, ref ulong last_change, ref UIntPtr string_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetEntryRawDelegate(IntPtr name, UIntPtr name_len, ref ulong last_change, ref UIntPtr raw_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetEntryBooleanArrayDelegate(IntPtr name, UIntPtr name_len, ref ulong last_change, ref UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetEntryDoubleArrayDelegate(IntPtr name, UIntPtr name_len, ref ulong last_change, ref UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetEntryStringArrayDelegate(IntPtr name, UIntPtr name_len, ref ulong last_change, ref UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetEntryBooleanDelegate(IntPtr name, UIntPtr name_len, int v_boolean, int force); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetEntryDoubleDelegate(IntPtr name, UIntPtr name_len, double v_double, int force); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetEntryStringDelegate(IntPtr name, UIntPtr name_len, byte[] v_string, UIntPtr string_len, int force); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetEntryRawDelegate(IntPtr name, UIntPtr name_len, byte[] raw, UIntPtr raw_len, int force); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetEntryBooleanArrayDelegate(IntPtr name, UIntPtr name_len, int[] arr, UIntPtr size, int force); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetEntryDoubleArrayDelegate(IntPtr name, UIntPtr name_len, double[] arr, UIntPtr size, int force); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetEntryStringArrayDelegate(IntPtr name, UIntPtr name_len, DisposableNativeString[] arr, UIntPtr size, int force); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetDefaultEntryBooleanDelegate(IntPtr name, UIntPtr name_len, int v_boolean); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetDefaultEntryDoubleDelegate(IntPtr name, UIntPtr name_len, double v_double); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetDefaultEntryStringDelegate(IntPtr name, UIntPtr name_len, byte[] v_string, UIntPtr string_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetDefaultEntryRawDelegate(IntPtr name, UIntPtr name_len, byte[] raw, UIntPtr raw_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetDefaultEntryBooleanArrayDelegate(IntPtr name, UIntPtr name_len, int[] arr, UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetDefaultEntryDoubleArrayDelegate(IntPtr name, UIntPtr name_len, double[] arr, UIntPtr size); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_SetDefaultEntryStringArrayDelegate(IntPtr name, UIntPtr name_len, DisposableNativeString[] arr, UIntPtr size); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_CreateRpcDelegate(IntPtr name, UIntPtr name_len, byte[] def, UIntPtr def_len, IntPtr data, NT_RPCCallback callback); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_CreatePolledRpcDelegate(IntPtr name, UIntPtr name_len, byte[] def, UIntPtr def_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_PollRpcTimeoutDelegate(int blocking, double time_out, out NtRpcCallInfo call_info); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int NT_PollRpcDelegate(int blocking, out NtRpcCallInfo call_info); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_PostRpcResponseDelegate(uint rpc_id, uint call_uid, byte[] result, UIntPtr result_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate uint NT_CallRpcDelegate(IntPtr name, UIntPtr name_len, byte[] param, UIntPtr params_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetRpcResultDelegate(int blocking, uint call_uid, ref UIntPtr result_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetRpcResultTimeoutDelegate(int blocking, uint call_uid, double time_out, ref UIntPtr result_len); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_CancelBlockingRpcResultDelegate(uint call_uid); - - - [NativeDelegate] internal static NT_SetEntryFlagsDelegate NT_SetEntryFlags; - [NativeDelegate] internal static NT_GetEntryFlagsDelegate NT_GetEntryFlags; - [NativeDelegate] internal static NT_DeleteEntryDelegate NT_DeleteEntry; - [NativeDelegate] internal static NT_DeleteAllEntriesDelegate NT_DeleteAllEntries; - [NativeDelegate] internal static NT_GetEntryInfoDelegate NT_GetEntryInfo; - [NativeDelegate] internal static NT_FlushDelegate NT_Flush; - [NativeDelegate] internal static NT_AddEntryListenerDelegate NT_AddEntryListener; - [NativeDelegate] internal static NT_RemoveEntryListenerDelegate NT_RemoveEntryListener; - [NativeDelegate] internal static NT_AddConnectionListenerDelegate NT_AddConnectionListener; - [NativeDelegate] internal static NT_RemoveConnectionListenerDelegate NT_RemoveConnectionListener; - [NativeDelegate] internal static NT_SetNetworkIdentityDelegate NT_SetNetworkIdentity; - [NativeDelegate] internal static NT_StartServerDelegate NT_StartServer; - [NativeDelegate] internal static NT_StopServerDelegate NT_StopServer; - [NativeDelegate] internal static NT_StartClientNoneDelegate NT_StartClientNone; - [NativeDelegate] internal static NT_StartClientDelegate NT_StartClient; - [NativeDelegate] internal static NT_StartClientMultiDelegate NT_StartClientMulti; - [NativeDelegate] internal static NT_StopClientDelegate NT_StopClient; - [NativeDelegate] - internal static NT_SetServerDelegate NT_SetServer; - [NativeDelegate] - internal static NT_SetServerMultiDelegate NT_SetServerMulti; - [NativeDelegate] - internal static NT_StartDSClientDelegate NT_StartDSClient; - [NativeDelegate] - internal static NT_StopDSClientDelegate NT_StopDSClient; - [NativeDelegate] internal static NT_StopRpcServerDelegate NT_StopRpcServer; - [NativeDelegate] internal static NT_StopNotifierDelegate NT_StopNotifier; - [NativeDelegate] internal static NT_NotifierDestroyedDelegate NT_NotifierDestroyed; - [NativeDelegate] internal static NT_SetUpdateRateDelegate NT_SetUpdateRate; - [NativeDelegate] internal static NT_GetConnectionsDelegate NT_GetConnections; - [NativeDelegate] internal static NT_SavePersistentDelegate NT_SavePersistent; - [NativeDelegate] internal static NT_LoadPersistentDelegate NT_LoadPersistent; - [NativeDelegate] internal static NT_DisposeValueDelegate NT_DisposeValue; - [NativeDelegate] internal static NT_InitValueDelegate NT_InitValue; - [NativeDelegate] internal static NT_DisposeStringDelegate NT_DisposeString; - [NativeDelegate] internal static NT_GetTypeDelegate NT_GetType; - [NativeDelegate] internal static NT_DisposeConnectionInfoArrayDelegate NT_DisposeConnectionInfoArray; - [NativeDelegate] internal static NT_DisposeEntryInfoArrayDelegate NT_DisposeEntryInfoArray; - [NativeDelegate] internal static NT_NowDelegate NT_Now; - [NativeDelegate] internal static NT_SetLoggerDelegate NT_SetLogger; - [NativeDelegate] internal static NT_AllocateCharArrayDelegate NT_AllocateCharArray; - [NativeDelegate] internal static NT_FreeBooleanArrayDelegate NT_FreeBooleanArray; - [NativeDelegate] internal static NT_FreeDoubleArrayDelegate NT_FreeDoubleArray; - [NativeDelegate] internal static NT_FreeCharArrayDelegate NT_FreeCharArray; - [NativeDelegate] internal static NT_FreeStringArrayDelegate NT_FreeStringArray; - [NativeDelegate] internal static NT_GetValueTypeDelegate NT_GetValueType; - [NativeDelegate] internal static NT_GetValueBooleanDelegate NT_GetValueBoolean; - [NativeDelegate] internal static NT_GetValueDoubleDelegate NT_GetValueDouble; - [NativeDelegate] internal static NT_GetValueStringDelegate NT_GetValueString; - [NativeDelegate] internal static NT_GetValueRawDelegate NT_GetValueRaw; - [NativeDelegate] internal static NT_GetValueBooleanArrayDelegate NT_GetValueBooleanArray; - [NativeDelegate] internal static NT_GetValueDoubleArrayDelegate NT_GetValueDoubleArray; - [NativeDelegate] internal static NT_GetValueStringArrayDelegate NT_GetValueStringArray; - [NativeDelegate] internal static NT_GetEntryBooleanDelegate NT_GetEntryBoolean; - [NativeDelegate] internal static NT_GetEntryDoubleDelegate NT_GetEntryDouble; - [NativeDelegate] internal static NT_GetEntryStringDelegate NT_GetEntryString; - [NativeDelegate] internal static NT_GetEntryRawDelegate NT_GetEntryRaw; - [NativeDelegate] internal static NT_GetEntryBooleanArrayDelegate NT_GetEntryBooleanArray; - [NativeDelegate] internal static NT_GetEntryDoubleArrayDelegate NT_GetEntryDoubleArray; - [NativeDelegate] internal static NT_GetEntryStringArrayDelegate NT_GetEntryStringArray; - [NativeDelegate] internal static NT_SetEntryBooleanDelegate NT_SetEntryBoolean; - [NativeDelegate] internal static NT_SetEntryDoubleDelegate NT_SetEntryDouble; - [NativeDelegate] internal static NT_SetEntryStringDelegate NT_SetEntryString; - [NativeDelegate] internal static NT_SetEntryRawDelegate NT_SetEntryRaw; - [NativeDelegate] internal static NT_SetEntryBooleanArrayDelegate NT_SetEntryBooleanArray; - [NativeDelegate] internal static NT_SetEntryDoubleArrayDelegate NT_SetEntryDoubleArray; - [NativeDelegate] internal static NT_SetEntryStringArrayDelegate NT_SetEntryStringArray; - - [NativeDelegate] internal static NT_SetDefaultEntryBooleanDelegate NT_SetDefaultEntryBoolean; - [NativeDelegate] internal static NT_SetDefaultEntryDoubleDelegate NT_SetDefaultEntryDouble; - [NativeDelegate] internal static NT_SetDefaultEntryStringDelegate NT_SetDefaultEntryString; - [NativeDelegate] internal static NT_SetDefaultEntryRawDelegate NT_SetDefaultEntryRaw; - [NativeDelegate] internal static NT_SetDefaultEntryBooleanArrayDelegate NT_SetDefaultEntryBooleanArray; - [NativeDelegate] internal static NT_SetDefaultEntryDoubleArrayDelegate NT_SetDefaultEntryDoubleArray; - [NativeDelegate] internal static NT_SetDefaultEntryStringArrayDelegate NT_SetDefaultEntryStringArray; - - [NativeDelegate] internal static NT_CreateRpcDelegate NT_CreateRpc; - [NativeDelegate] internal static NT_CreatePolledRpcDelegate NT_CreatePolledRpc; - [NativeDelegate] internal static NT_PollRpcDelegate NT_PollRpc; - [NativeDelegate] internal static NT_PollRpcTimeoutDelegate NT_PollRpcTimeout; - [NativeDelegate] internal static NT_PostRpcResponseDelegate NT_PostRpcResponse; - [NativeDelegate] internal static NT_CallRpcDelegate NT_CallRpc; - [NativeDelegate] internal static NT_GetRpcResultDelegate NT_GetRpcResult; - [NativeDelegate] internal static NT_GetRpcResultTimeoutDelegate NT_GetRpcResultTimeout; - [NativeDelegate] internal static NT_CancelBlockingRpcResultDelegate NT_CancelBlockingRpcResult; - } -} diff --git a/src/FRC.NetworkTables.Core/Native/Structs.cs b/src/FRC.NetworkTables.Core/Native/Structs.cs deleted file mode 100644 index b569c02..0000000 --- a/src/FRC.NetworkTables.Core/Native/Structs.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Text; -using FRC; - -namespace NetworkTables.Core.Native -{ - [StructLayout(LayoutKind.Sequential)] - internal struct NtStringRead - { - private readonly IntPtr str; - private readonly UIntPtr len; - - internal NtStringRead(IntPtr str, UIntPtr len) - { - this.str = str; - this.len = len; - } - - public override string ToString() - { - byte[] arr = new byte[len.ToUInt64()]; - Marshal.Copy(str, arr, 0, (int)len.ToUInt64()); - return Encoding.UTF8.GetString(arr); - } - - public byte[] ToRpcArray() - { - byte[] arr = new byte[len.ToUInt64()]; - Marshal.Copy(str, arr, 0, (int)len.ToUInt64()); - return arr; - } - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NtEntryInfo - { - public NtStringRead name; - // ReSharper disable FieldCanBeMadeReadOnly.Global - public NtType type; - public uint flags; - public ulong last_change; - // ReSharper restore FieldCanBeMadeReadOnly.Global - } - - - //Looks like this will always be created for us by the library, so we do not have to write it. - // - [StructLayout(LayoutKind.Sequential)] - internal struct NtConnectionInfo - { -#pragma warning disable 649 - public readonly NtStringRead RemoteId; - public readonly NtStringRead RemoteIp; - public readonly uint RemotePort; - public readonly ulong LastUpdate; - public readonly uint ProtocolVersion; -#pragma warning restore 649 - - internal NtConnectionInfo(NtStringRead remoteId, NtStringRead remoteIp, uint port, ulong update, uint proto) - { - RemoteId = remoteId; - RemoteIp = remoteIp; - RemotePort = port; - LastUpdate = update; - ProtocolVersion = proto; - } - - public ConnectionInfo ToManaged() - { - return new ConnectionInfo(RemoteId.ToString(), RemoteIp.ToString(), (int)RemotePort, (long)LastUpdate, (int)ProtocolVersion); - } - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NtRpcCallInfo - { -#pragma warning disable 649 - public readonly uint RpcId; - public readonly uint CallUid; - public readonly NtStringRead Name; - public readonly NtStringRead Param; -#pragma warning restore 649 - - internal NtRpcCallInfo(NtStringRead name, NtStringRead param, uint rpcId, uint callUid) - { - Name = name; - Param = param; - RpcId = rpcId; - CallUid = callUid; - } - - public RpcCallInfo ToManaged() - { - // ReSharper disable once ImpureMethodCallOnReadonlyValueField - return new RpcCallInfo(RpcId, CallUid, Name.ToString(), Param.ToRpcArray()); - } - } - - -} diff --git a/src/FRC.NetworkTables.Core/NetworkTable.cs b/src/FRC.NetworkTables.Core/NetworkTable.cs new file mode 100644 index 0000000..4ad6b66 --- /dev/null +++ b/src/FRC.NetworkTables.Core/NetworkTable.cs @@ -0,0 +1,255 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Generic; + +namespace FRC.NetworkTables +{ + public class NetworkTable : IEquatable + { + public static readonly char PathSeparator = '/'; + private readonly string m_pathWithSep; + + public static string BasenameKey(string key) + { + int slash = key.LastIndexOf(PathSeparator); + if (slash == -1) + { + return key; + } + return key.Substring(slash + 1); + } + + internal NetworkTable(NetworkTableInstance inst, ReadOnlySpan path) + { + var str = path.ToString(); + Path = str; + m_pathWithSep = str + PathSeparator; + Instance = inst; + } + + public NetworkTableInstance Instance { get; } + + public override string ToString() + { + return $"NetworkTable: {Path}"; + } + + public NetworkTableEntry GetEntry(string key) + { + return Instance.GetEntry(m_pathWithSep + key); + } + + public NetworkTableEntry GetEntry(ReadOnlySpan key) + { + return Instance.GetEntry(m_pathWithSep + key.ToString()); + } + + public NtEntryListener AddEntryListener(TableEntryListener listener, NotifyFlags flags) + { + int prefixLen = Path.Length + 1; + return Instance.AddEntryListener(m_pathWithSep, (in RefEntryNotification evnt) => + { + ReadOnlySpan relativeKey = evnt.Name.AsSpan().Slice(prefixLen); + if (relativeKey.IndexOf(PathSeparator) != -1) + { + return; + } + listener(this, relativeKey, evnt.Entry, evnt.Value, evnt.Flags); + }, flags); + } + + public NtEntryListener AddEntryListener(ReadOnlySpan key, TableEntryListener listener, NotifyFlags flags) + { + var entry = GetEntry(key); + int prefixLen = Path.Length + 1; + return Instance.AddEntryListener(entry, (in RefEntryNotification evnt) => + { + ReadOnlySpan relativeKey = evnt.Name.AsSpan().Slice(prefixLen); + listener(this, relativeKey, evnt.Entry, evnt.Value, evnt.Flags); + }, flags); + } + + public NtEntryListener AddEntryListener(string key, TableEntryListener listener, NotifyFlags flags) + { + var entry = GetEntry(key); + return Instance.AddEntryListener(entry, (in RefEntryNotification evnt) => + { + listener(this, key.AsSpan(), evnt.Entry, evnt.Value, evnt.Flags); + }, flags); + } + + public void RemoveEntryListener(NtEntryListener listener) + { + Instance.RemoveEntryListener(listener); + } + + public NtEntryListener AddSubTableListener(TableListener listener, bool localNotify) + { + NotifyFlags flags = NotifyFlags.New | NotifyFlags.Immediate; + if (localNotify) + { + flags |= NotifyFlags.Local; + } + + int prefixLen = Path.Length + 1; + HashSet notifiedTable = new HashSet(); + + return Instance.AddEntryListener(m_pathWithSep, (in RefEntryNotification evnt) => + { + ReadOnlySpan relativeKey = evnt.Name.AsSpan().Slice(prefixLen); + int endSubTable = relativeKey.IndexOf(PathSeparator); + if (endSubTable == -1) + { + return; + } + relativeKey.Slice(0, endSubTable).ToString(); + ReadOnlySpan subTableKeySpan = relativeKey.Slice(0, endSubTable); + string subTableKeyStr = subTableKeySpan.ToString(); + if (notifiedTable.Contains(subTableKeyStr)) + { + return; + } + notifiedTable.Add(subTableKeyStr); + listener(this, subTableKeySpan, evnt.Flags); + }, flags); + } + + public void RemoveTableListener(NtEntryListener listener) + { + Instance.RemoveEntryListener(listener); + } + + public NetworkTable GetSubTable(string key) + { + return new NetworkTable(Instance, (m_pathWithSep + key).AsSpan()); + } + + public NetworkTable GetSubTable(ReadOnlySpan key) + { + return new NetworkTable(Instance, (m_pathWithSep + key.ToString()).AsSpan()); + } + + public bool ContainsKey(string key) + { + return !(string.IsNullOrWhiteSpace(key)) && GetEntry(key).Exists(); + } + + public bool ContainsKey(ReadOnlySpan key) + { + return !key.IsEmpty && GetEntry(key).Exists(); + } + + public bool ContainsSubTable(string key) + { + return NtCore.GetEntryCount(Instance.Handle, m_pathWithSep + key + PathSeparator, 0) != 0; + } + + public bool ContainsSubTable(ReadOnlySpan key) + { + return NtCore.GetEntryCount(Instance.Handle, m_pathWithSep + key.ToString() + PathSeparator, 0) != 0; + } + + + public HashSet GetKeys(NtType types) + { + HashSet keys = new HashSet(); + int prefixLen = -Path.Length + 1; + foreach(var info in Instance.GetEntryInfo(m_pathWithSep, types)) + { + var relativeKey = info.Name.AsSpan().Slice(prefixLen); + if (relativeKey.IndexOf(PathSeparator) != -1) + { + continue; + } + string rKey = relativeKey.ToString(); + keys.Add(rKey); + } + return keys; + } + + public HashSet GetKeys() + { + return GetKeys(0); + } + + public HashSet GetSubTables() + { + HashSet keys = new HashSet(); + int prefixLen = Path.Length + 1; + foreach (EntryInfo info in Instance.GetEntryInfo(m_pathWithSep, 0)) + { + var relativeKey = info.Name.AsSpan().Slice(prefixLen); + int endSubTable = relativeKey.IndexOf(PathSeparator); + if (endSubTable == 1) + { + continue; + } + keys.Add(relativeKey.Slice(0, endSubTable).ToString()); + } + return keys; + } + + public void Delete(string key) + { + GetEntry(key).Delete(); + } + + public void Delete(ReadOnlySpan key) + { + GetEntry(key).Delete(); + } + + internal NetworkTableValue GetValue(string key) + { + return GetEntry(key).GetValue(); + } + + public string Path { get; } + + public void SaveEntries(string filename) + { + Instance.SaveEntries(filename, m_pathWithSep); + } + + public List LoadEntries(string filename) + { + return Instance.LoadEntries(filename, m_pathWithSep); + } + + public bool Equals(NetworkTable other) + { + return Path.Equals(other.Path) && Instance.Equals(other.Instance); + } + + public override bool Equals(object obj) + { + if (obj is NetworkTable v) + { + return Equals(v); + } + return false; + } + + public override int GetHashCode() + { + unchecked + { + int hash = 13; + hash = (hash * 7) + Path.GetHashCode(); + hash = (hash * 7) + Instance.GetHashCode(); + return hash; + } + } + + public static bool operator==(NetworkTable lhs, NetworkTable rhs) + { + return lhs?.Equals(rhs) ?? false; + } + + public static bool operator !=(NetworkTable lhs, NetworkTable rhs) + { + return !lhs?.Equals(rhs) ?? true; + } + + } +} diff --git a/src/FRC.NetworkTables.Core/NetworkTableEntry.cs b/src/FRC.NetworkTables.Core/NetworkTableEntry.cs new file mode 100644 index 0000000..69cad96 --- /dev/null +++ b/src/FRC.NetworkTables.Core/NetworkTableEntry.cs @@ -0,0 +1,424 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables +{ + public readonly struct NetworkTableEntry + { + public const int kPersistent = 0x01; + + public NetworkTableEntry(NetworkTableInstance inst, NtEntry handle) + { + Instance = inst; + Handle = handle; + } + + public bool IsValid => Handle.Get() != 0; + + public readonly NtEntry Handle; + + public readonly NetworkTableInstance Instance; + + public bool Exists() => GetEntryType() != NtType.Unassigned; + + public string GetEntryName() => NtCore.GetEntryName(Handle); + + public NtType GetEntryType() => NtCore.GetEntryType(Handle); + + public EntryFlags GetEntryFlags() => NtCore.GetEntryFlags(Handle); + + public ulong GetLastChange() => NtCore.GetEntryLastChange(Handle); + + public EntryInfo? GetEntryInfo() + { + return NtCore.GetEntryInfoHandle(Instance, Handle); + } + + public NetworkTableValue GetValue() + { + return new NetworkTableValue(NtCore.GetEntryValue(Handle)); + } + + public object? GetObjectValue() + { + var v = NtCore.GetEntryValue(Handle); + return v.GetValue(); + } + + public bool GetBoolean(bool defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.Boolean) + { + return entry.Data.VBoolean; + } + return defaultValue; + } + + public double GetDouble(double defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.Double) + { + return entry.Data.VDouble; + } + return defaultValue; + } + + public string GetString(string defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.String) + { + return entry.Data.VString!; + } + return defaultValue; + } + + public ReadOnlySpan GetString(ReadOnlySpan defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.String) + { + return entry.Data.VString.AsSpan(); + } + return defaultValue; + } + + public ReadOnlySpan GetRaw(ReadOnlySpan defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.Raw) + { + return entry.Data.VRaw.AsSpan(); + } + return defaultValue; + } + + public ReadOnlySpan GetBooleanArray(ReadOnlySpan defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.BooleanArray) + { + return entry.Data.VBooleanArray.AsSpan(); + } + return defaultValue; + } + + public ReadOnlySpan GetDoubleArray(ReadOnlySpan defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.DoubleArray) + { + return entry.Data.VDoubleArray.AsSpan(); + } + return defaultValue; + } + + public ReadOnlySpan GetStringArray(ReadOnlySpan defaultValue) + { + var entry = NtCore.GetEntryValue(Handle); + if (entry.Type == NtType.StringArray) + { + return entry.Data.VStringArray.AsSpan(); + } + return defaultValue; + } + + private double? GetAsDouble(T value) + { + return value switch + { + double v => v, + int v => v, + short v => v, + byte v => v, + long v => v, + float v => v, + ushort v => v, + uint v => v, + ulong v => v, + sbyte v => v, + decimal v => (double)v, + _ => default(double?), + }; + } + + public bool SetDefaultValue(in NetworkTableValue value) + { + return NtCore.SetDefaultEntryValue(Handle, value.Value); + } + + public bool SetDefaultValue(T defaultValue) + { + switch(defaultValue) + { + case bool v: + return SetDefaultBoolean(v); + case string v: + return SetDefaultString(v.AsSpan()); + case byte[] v: + return SetDefaultRaw(v); + case bool[] v: + return SetDefaultBooleanArray(v); + case double[] v: + return SetDefaultDoubleArray(v); + case string[] v: + return SetDefaultStringArray(v); + default: + var d = GetAsDouble(defaultValue); + if (d != null) + { + return SetDefaultDouble(d.Value); + } + throw new InvalidOperationException($"Value of type {typeof(T).Name} cannot be put into a table"); + + } + } + + public bool SetDefaultBoolean(bool defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue, 0)); + } + + public bool SetDefaultDouble(double defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue, 0)); + } + + public bool SetDefaultString(string defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue.AsSpan(), 0)); + } + + public bool SetDefaultString(ReadOnlySpan defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue, 0)); + } + + public bool SetDefaultRaw(ReadOnlySpan defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue, 0)); + } + + public bool SetDefaultBooleanArray(ReadOnlySpan defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue, 0)); + } + + public bool SetDefaultDoubleArray(ReadOnlySpan defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue, 0)); + } + + public bool SetDefaultStringArray(ReadOnlySpan defaultValue) + { + return NtCore.SetDefaultEntryValue(Handle, new RefManagedValue(defaultValue, 0)); + } + + public bool SetValue(in NetworkTableValue value) + { + return NtCore.SetEntryValue(Handle, value.Value); + } + + public bool SetValue(T value) + { + switch (value) + { + case bool v: + return SetBoolean(v); + case string v: + return SetString(v.AsSpan()); + case byte[] v: + return SetRaw(v); + case bool[] v: + return SetBooleanArray(v); + case double[] v: + return SetDoubleArray(v); + case string[] v: + return SetStringArray(v); + default: + var d = GetAsDouble(value); + if (d != null) + { + return SetDouble(d.Value); + } + throw new InvalidOperationException($"Value of type {typeof(T).Name} cannot be put into a table"); + + } + } + + public bool SetBoolean(bool value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value, 0)); + } + + public bool SetDouble(double value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value, 0)); + } + + public bool SetString(string value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value.AsSpan(), 0)); + } + + public bool SetString(ReadOnlySpan value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value, 0)); + } + + public bool SetRaw(ReadOnlySpan value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value, 0)); + } + + public bool SetBooleanArray(ReadOnlySpan value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value, 0)); + } + + public bool SetDoubleArray(ReadOnlySpan value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value, 0)); + } + + public bool SetStringArray(ReadOnlySpan value) + { + return NtCore.SetEntryValue(Handle, new RefManagedValue(value, 0)); + } + + public void ForceSetValue(in NetworkTableValue value) + { + NtCore.SetDefaultEntryValue(Handle, value.Value); + } + + public void ForceSetValue(T value) + { + switch (value) + { + case bool v: + ForceSetBoolean(v); + break; + case string v: + ForceSetString(v.AsSpan()); + break; + case byte[] v: + ForceSetRaw(v); + break; + case bool[] v: + ForceSetBooleanArray(v); + break; + case double[] v: + ForceSetDoubleArray(v); + break; + case string[] v: + ForceSetStringArray(v); + break; + default: + var d = GetAsDouble(value); + if (d != null) + { + ForceSetDouble(d.Value); + break; + } + throw new InvalidOperationException($"Value of type {typeof(T).Name} cannot be put into a table"); + + } + } + + public void ForceSetBoolean(bool value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value, 0)); + } + + public void ForceSetDouble(double value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value, 0)); + } + + public void ForceSetString(string value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value.AsSpan(), 0)); + } + + public void ForceSetString(ReadOnlySpan value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value, 0)); + } + + public void ForceSetRaw(ReadOnlySpan value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value, 0)); + } + + public void ForceSetBooleanArray(ReadOnlySpan value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value, 0)); + } + + public void ForceSetDoubleArray(ReadOnlySpan value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value, 0)); + } + + public void ForceSetStringArray(ReadOnlySpan value) + { + NtCore.SetEntryTypeValue(Handle, new RefManagedValue(value, 0)); + } + + public void SetFlags(EntryFlags flags) + { + NtCore.SetEntryFlags(Handle, GetEntryFlags() | flags); + } + + public void ClearFlags(EntryFlags flags) + { + NtCore.SetEntryFlags(Handle, GetEntryFlags() & ~flags); + } + + public void SetPersistent() + { + SetFlags(EntryFlags.Persistent); + } + + public void ClearPersistent() + { + ClearFlags(EntryFlags.Persistent); + } + + public bool IsPersistent() + { + return (GetEntryFlags() & EntryFlags.Persistent) != 0; + } + + public void Delete() + { + NtCore.DeleteEntry(Handle); + } + + public void CreateRpc(RpcAnswerDelegate callback) + { + Instance.CreateRpc(this, callback); + } + + public RpcCall CallRpc(Span @params) + { + return new RpcCall(this, NtCore.CallRpc(Handle, @params)); + } + + public NtEntryListener AddListener(EntryNotificationDelegate listener, NotifyFlags flags) + { + return Instance.AddEntryListener(this, listener, flags); + } + + public void RemoveListener(NtEntryListener listener) + { + Instance.RemoveEntryListener(listener); + } + + //TODO : Equals + } +} diff --git a/src/FRC.NetworkTables.Core/NetworkTableInstance.cs b/src/FRC.NetworkTables.Core/NetworkTableInstance.cs new file mode 100644 index 0000000..a353f9d --- /dev/null +++ b/src/FRC.NetworkTables.Core/NetworkTableInstance.cs @@ -0,0 +1,299 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; + +namespace FRC.NetworkTables +{ + public partial class NetworkTableInstance : IDisposable, IEquatable + { + public const int DefaultPort = 1735; + private bool m_owned; + + private NetworkTableInstance(NtInst handle) + { + m_entryListenerToken = new Lazy(CreateEntryListenerThread); + m_connectionListenerToken = new Lazy(CreateConnectionListenerThread); + m_rpcListenerToken = new Lazy(CreateRpcListenerThread); + m_loggerListenerToken = new Lazy(CreateLoggerThread); + m_owned = false; + Handle = handle; + } + + public void Dispose() + { + if (m_owned && Handle.Get() != 0) + { + NtCore.DestroyInstance(Handle); + Handle = new NtInst(); + } + } + + public bool IsValid() => Handle.Get() != 0; + + private static readonly Lazy s_defaultInstance = new Lazy(() => + { + return new NetworkTableInstance(NtCore.GetDefaultInstance()); + }); + + public static NetworkTableInstance Default => s_defaultInstance.Value; + + public static NetworkTableInstance Create() + { + var inst = new NetworkTableInstance(NtCore.CreateInstance()) + { + m_owned = true + }; + return inst; + } + + public NtInst Handle { get; private set; } + + public NetworkTableEntry GetEntry(string name) + { + return new NetworkTableEntry(this, NtCore.GetEntry(Handle, name)); + } + + public ReadOnlySpan GetEntries(string prefix, NtType types) + { + return NtCore.GetEntriesManaged(this, prefix, types, Span.Empty); + } + + public ReadOnlySpan GetEntryInfo(string prefix, NtType types) + { + return NtCore.GetEntryInfo(this, prefix, types, Span.Empty); + } + + public ReadOnlySpan GetEntries(string prefix, NtType types, Span store) + { + return NtCore.GetEntriesManaged(this, prefix, types, store); + } + + public ReadOnlySpan GetEntryInfo(string prefix, NtType types, Span store) + { + return NtCore.GetEntryInfo(this, prefix, types, store); + } + + public NetworkTableEntry GetEntry(ReadOnlySpan name) + { + return new NetworkTableEntry(this, NtCore.GetEntry(Handle, name)); + } + + public ReadOnlySpan GetEntries(ReadOnlySpan prefix, NtType types) + { + return NtCore.GetEntriesManaged(this, prefix, types, Span.Empty); + } + + public ReadOnlySpan GetEntryInfo(ReadOnlySpan prefix, NtType types) + { + return NtCore.GetEntryInfo(this, prefix, types, Span.Empty); + } + + public ReadOnlySpan GetEntries(ReadOnlySpan prefix, NtType types, Span store) + { + return NtCore.GetEntriesManaged(this, prefix, types, store); + } + + public ReadOnlySpan GetEntryInfo(ReadOnlySpan prefix, NtType types, Span store) + { + return NtCore.GetEntryInfo(this, prefix, types, store); + } + + private readonly ConcurrentDictionary m_tables = new ConcurrentDictionary(); + + public NetworkTable GetTable(string key) + { + string theKey; + if (string.IsNullOrWhiteSpace(key) || key.Equals("")) + { + theKey = ""; + } + else if (key[0] == NetworkTable.PathSeparator) + { + theKey = key; + } + else + { + theKey = NetworkTable.PathSeparator + key; + } + + NetworkTable table = m_tables.GetOrAdd(theKey, (s) => + { + return new NetworkTable(this, s.AsSpan()); + }); + return table; + } + + public void DeleteAllEntries() + { + NtCore.DeleteAllEntries(Handle); + } + + public void SetNetworkIdentity(string name) + { + NtCore.SetNetworkIdentity(Handle, name); + } + + public NetworkMode GetNetworkMode() + { + return NtCore.GetNetworkMode(Handle); + } + + public void StartServer(string persistFilename = "networktables.ini", + string listenAddress = "", int port = DefaultPort) + { + NtCore.StartServer(Handle, persistFilename, listenAddress, port); + } + + public void StopServer() + { + NtCore.StopServer(Handle); + } + + public void StartClient() + { + NtCore.StartClient(Handle); + } + + public void StartClient(string serverName, int port = DefaultPort) + { + NtCore.StartClient(Handle, serverName, port); + } + + public void StartClient(ReadOnlySpan serverNames, int port = DefaultPort) + { + Span servers = new ServerPortPair[serverNames.Length]; + for (int i = 0; i < serverNames.Length; i++) + { + servers[i] = new ServerPortPair(serverNames[i], port); + } + StartClient(serverNames); + } + + public void StartClient(ReadOnlySpan servers) + { + NtCore.StartClient(Handle, servers); + } + + public void StartClientTeam(int team, int port = DefaultPort) + { + NtCore.StartClientTeam(Handle, team, port); + } + + public void StopClient() + { + NtCore.StopClient(Handle); + } + + public void SetServer(string serverName, int port = DefaultPort) + { + NtCore.SetServer(Handle, serverName, port); + } + + public void SetServer(ReadOnlySpan serverNames, int port = DefaultPort) + { + Span servers = new ServerPortPair[serverNames.Length]; + for (int i = 0; i < serverNames.Length; i++) + { + servers[i] = new ServerPortPair(serverNames[i], port); + } + SetServer(serverNames); + } + + public void SetServer(ReadOnlySpan servers) + { + NtCore.SetServer(Handle, servers); + } + + public void SetServerTeam(int team, int port = DefaultPort) + { + NtCore.SetServerTeam(Handle, team, port); + } + + public void StartDSClient(int port = DefaultPort) + { + NtCore.StartDSClient(Handle, port); + } + + public void StopDSClient() + { + NtCore.StopDSClient(Handle); + } + + public void SetUpdateRate(double interval) + { + NtCore.SetUpdateRate(Handle, interval); + } + + public void Flush() + { + NtCore.Flush(Handle); + } + + public ReadOnlySpan GetConnections() + { + Span store = Span.Empty; + return NtCore.GetConnections(Handle, store); + } + + public ReadOnlySpan GetConnections(Span store) + { + return NtCore.GetConnections(Handle, store); + } + + public bool IsConnected() + { + return NtCore.IsConnected(Handle); + } + + public void SavePersistent(string filename) + { + NtCore.SavePersistent(Handle, filename); + } + + public List LoadPersistent(string filename) + { + return NtCore.LoadPersistent(Handle, filename); + } + + public void SaveEntries(string filename, string prefix) + { + NtCore.SaveEntries(Handle, filename, prefix); + } + + public List LoadEntries(string filename, string prefix) + { + return NtCore.LoadEntries(Handle, filename, prefix); + } + + public override bool Equals(object obj) + { + if (obj is NetworkTableInstance v) + { + return Equals(v); + } + return false; + } + + public bool Equals(NetworkTableInstance other) + { + return Handle.Get() == other.Handle.Get(); + } + + public override int GetHashCode() + { + return Handle.Get().GetHashCode(); + } + + public static bool operator==(in NetworkTableInstance lhs, in NetworkTableInstance rhs) + { + return lhs.Equals(rhs); + } + + public static bool operator!=(in NetworkTableInstance lhs, in NetworkTableInstance rhs) + { + return !lhs.Equals(rhs); + } + } +} diff --git a/src/FRC.NetworkTables.Core/NetworkTableInstancePollers.cs b/src/FRC.NetworkTables.Core/NetworkTableInstancePollers.cs new file mode 100644 index 0000000..fe151ef --- /dev/null +++ b/src/FRC.NetworkTables.Core/NetworkTableInstancePollers.cs @@ -0,0 +1,517 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; + +namespace FRC.NetworkTables +{ + public unsafe partial class NetworkTableInstance + { + private readonly object m_entryListenerLock = new object(); + private readonly Dictionary m_entryListeners = new Dictionary(); + private readonly Lazy m_entryListenerToken; + private Thread? m_entryListenerThread; + private NtEntryListenerPoller m_entryListenerPoller; + private readonly object m_entryListenerWaitQueueLock = new object(); + private bool m_entryListenerWaitQueue = false; + + private CancellationTokenSource CreateEntryListenerThread() + { + m_entryListenerPoller = NtCore.CreateEntryListenerPoller(Handle); + CancellationTokenSource source = new CancellationTokenSource(); + var ret = new Thread(() => + { + bool wasInterrupted = false; + var token = source.Token; + token.Register(() => + { + NtCore.CancelPollEntryListener(m_entryListenerPoller); + }); + while (!token.IsCancellationRequested) + { + var events = NtCore.PollEntryListener(m_entryListenerPoller); + if (token.IsCancellationRequested) + { + NtCore.DisposeEntryListenerSpan(events); + break; + } + if (events.Length == 0) + { + NtCore.DisposeEntryListenerSpan(events); + lock (m_entryListenerWaitQueueLock) + { + if (m_entryListenerWaitQueue) + { + m_entryListenerWaitQueue = false; + Monitor.PulseAll(m_entryListenerWaitQueueLock); + continue; + } + } + wasInterrupted = true; + break; + } + for (int i = 0; i < events.Length; i++) + { + EntryNotificationDelegate? listener; + lock (m_entryListenerLock) { + m_entryListeners.TryGetValue(events.Pointer[i].listener, out listener); + } + if (listener != null) + { + listener(new RefEntryNotification(this, events.Pointer[i])); + if (token.IsCancellationRequested) + { + break; + } + } + } + NtCore.DisposeEntryListenerSpan(events); + } + lock (m_entryListenerWaitQueueLock) + { + if (!wasInterrupted) + { + NtCore.DestroyEntryListenerPoller(m_entryListenerPoller); + } + m_entryListenerPoller = new NtEntryListenerPoller(); + } + }) + { + Name = "NTEntryListener", + IsBackground = true + }; + ret.Start(); + m_entryListenerThread = ret; + return source; + } + + public NtEntryListener AddEntryListener(string prefix, EntryNotificationDelegate listener, NotifyFlags flags) + { + var token = m_entryListenerToken.Value; + lock (m_entryListenerLock) { + var handle = NtCore.AddPolledEntryListener(m_entryListenerPoller, prefix, flags); + m_entryListeners.Add(handle, listener); + return handle; + } + } + + public NtEntryListener AddEntryListener(in NetworkTableEntry entry, EntryNotificationDelegate listener, NotifyFlags flags) + { + var token = m_entryListenerToken.Value; + lock (m_entryListenerLock) { + var handle = NtCore.AddPolledEntryListener(m_entryListenerPoller, entry, flags); + m_entryListeners.Add(handle, listener); + return handle; + } + } + + public void RemoveEntryListener(NtEntryListener listener) + { + NtCore.RemoveEntryListener(listener); + lock (m_entryListenerLock) { + m_entryListeners.Remove(listener); + } + } + + public bool WaitForEntryListenerQueue(double timeout) + { + if (!NtCore.WaitForEntryListenerQueue(Handle, timeout)) + { + return false; + } + lock (m_entryListenerWaitQueueLock) + { + if (m_entryListenerPoller.Get() == 0) return true; + m_entryListenerWaitQueue = true; + NtCore.CancelPollEntryListener(m_entryListenerPoller); + while (m_entryListenerWaitQueue) + { + if (timeout < 0) + { + Monitor.Wait(m_entryListenerWaitQueueLock); + } + else + { + return Monitor.Wait(m_entryListenerWaitQueueLock, TimeSpan.FromSeconds(timeout)); + } + } + } + return true; + } + + + + private readonly object m_connectionListenerLock = new object(); + private readonly Dictionary m_connectionListeners = new Dictionary(); + private readonly Lazy m_connectionListenerToken; + private Thread? m_connectionListenerThread; + private NtConnectionListenerPoller m_connectionListenerPoller; + private readonly object m_connectionListenerWaitQueueLock = new object(); + private bool m_connectionListenerWaitQueue = false; + + private CancellationTokenSource CreateConnectionListenerThread() + { + m_connectionListenerPoller = NtCore.CreateConnectionListenerPoller(Handle); + CancellationTokenSource source = new CancellationTokenSource(); + var ret = new Thread(() => + { + bool wasInterrupted = false; + var token = source.Token; + token.Register(() => + { + NtCore.CancelPollConnectionListener(m_connectionListenerPoller); + }); + while (!token.IsCancellationRequested) + { + var events = NtCore.PollConnectionListener(m_connectionListenerPoller); + if (token.IsCancellationRequested) + { + NtCore.DisposeConnectionListenerSpan(events); + break; + } + if (events.Length == 0) + { + NtCore.DisposeConnectionListenerSpan(events); + lock (m_connectionListenerWaitQueueLock) + { + if (m_entryListenerWaitQueue) + { + m_entryListenerWaitQueue = false; + Monitor.PulseAll(m_connectionListenerWaitQueueLock); + continue; + } + } + wasInterrupted = true; + break; + } + for (int i = 0; i < events.Length; i++) + { + ConnectionNotificationDelegate? listener; + lock (m_connectionListenerLock) { + m_connectionListeners.TryGetValue(events.Pointer[i].listener, out listener); + } + if (listener != null) + { + listener(new ConnectionNotification(this, events.Pointer[i])); + if (token.IsCancellationRequested) + { + break; + } + } + } + NtCore.DisposeConnectionListenerSpan(events); + } + lock (m_connectionListenerWaitQueueLock) + { + if (!wasInterrupted) + { + NtCore.DestroyConnectionListenerPoller(m_connectionListenerPoller); + } + m_connectionListenerPoller = new NtConnectionListenerPoller(); + } + }) + { + Name = "NTConnectionListener", + IsBackground = true + }; + ret.Start(); + m_connectionListenerThread = ret; + return source; + } + + public NtConnectionListener AddConnectionListener(ConnectionNotificationDelegate listener, bool immediateNotify) + { + var token = m_connectionListenerToken.Value; + lock (m_connectionListenerLock) { + var handle = NtCore.AddPolledConnectionListener(m_connectionListenerPoller, immediateNotify); + m_connectionListeners.Add(handle, listener); + return handle; + } + } + + public void RemoveConnectionListener(NtConnectionListener listener) + { + NtCore.RemoveConnectionListener(listener); + lock (m_connectionListenerLock) { + m_connectionListeners.Remove(listener); + } + } + + public bool WaitForConnectionListenerQueue(double timeout) + { + if (!NtCore.WaitForConnectionListenerQueue(Handle, timeout)) + { + return false; + } + lock (m_connectionListenerWaitQueueLock) + { + if (m_connectionListenerPoller.Get() == 0) return true; + m_connectionListenerWaitQueue = true; + NtCore.CancelPollConnectionListener(m_connectionListenerPoller); + while (m_connectionListenerWaitQueue) + { + if (timeout < 0) + { + Monitor.Wait(m_connectionListenerWaitQueueLock); + } + else + { + return Monitor.Wait(m_connectionListenerWaitQueueLock, TimeSpan.FromSeconds(timeout)); + } + } + } + return true; + } + + private readonly object m_rpcCallLock = new object(); + private readonly Dictionary m_rpcCalls = new Dictionary(); + private readonly Lazy m_rpcListenerToken; + private Thread? m_rpcListenerThread; + private NtRpcCallPoller m_rpcListenerPoller; + private readonly object m_rpcListenerWaitQueueLock = new object(); + private bool m_rpcListenerWaitQueue = false; + + private CancellationTokenSource CreateRpcListenerThread() + { + m_rpcListenerPoller = NtCore.CreateRpcCallPoller(Handle); + CancellationTokenSource source = new CancellationTokenSource(); + var ret = new Thread(() => + { + bool wasInterrupted = false; + var token = source.Token; + token.Register(() => + { + NtCore.CancelPollRpc(m_rpcListenerPoller); + }); + Span respondedStore = stackalloc bool[1] { false }; + while (!token.IsCancellationRequested) + { + var events = NtCore.PollRpc(m_rpcListenerPoller); + if (token.IsCancellationRequested) + { + NtCore.DisposeRpcAnswerSpan(events); + break; + } + if (events.Length == 0) + { + NtCore.DisposeRpcAnswerSpan(events); + lock (m_rpcListenerWaitQueueLock) + { + if (m_entryListenerWaitQueue) + { + m_entryListenerWaitQueue = false; + Monitor.PulseAll(m_rpcListenerWaitQueueLock); + continue; + } + } + wasInterrupted = true; + break; + } + for (int i = 0; i < events.Length; i++) + { + RpcAnswerDelegate? listener; + lock (m_rpcCallLock) { + m_rpcCalls.TryGetValue(events.Pointer[i].entry, out listener); + } + if (listener != null) + { + respondedStore[0] = false; + var evnt = new RpcAnswer(this, events.Pointer[i], respondedStore); + listener(evnt); + if (!respondedStore[0]) + { + evnt.PostResponse(Span.Empty); + } + + if (token.IsCancellationRequested) + { + break; + } + } + } + NtCore.DisposeRpcAnswerSpan(events); + } + lock (m_rpcListenerWaitQueueLock) + { + if (!wasInterrupted) + { + NtCore.DestroyRpcCallPoller(m_rpcListenerPoller); + } + m_rpcListenerPoller = new NtRpcCallPoller(); + } + }) + { + Name = "NTRpcCall", + IsBackground = true + }; + ret.Start(); + m_rpcListenerThread = ret; + return source; + } + + public void CreateRpc(in NetworkTableEntry entry, RpcAnswerDelegate callback) + { + var token = m_rpcListenerToken.Value; + Span def = stackalloc byte[1]{ 0 }; + lock (m_rpcCallLock) { + NtCore.CreatePolledRpc(entry.Handle, def, m_rpcListenerPoller); + m_rpcCalls.Add(entry.Handle, callback); + } + } + + public bool WaitForRpcCallQueue(double timeout) + { + if (!NtCore.WaitForRpcCallQueue(Handle, timeout)) + { + return false; + } + lock (m_rpcListenerWaitQueueLock) + { + if (m_rpcListenerPoller.Get() == 0) return true; + m_rpcListenerWaitQueue = true; + NtCore.CancelPollRpc(m_rpcListenerPoller); + while (m_rpcListenerWaitQueue) + { + if (timeout < 0) + { + Monitor.Wait(m_rpcListenerWaitQueueLock); + } + else + { + return Monitor.Wait(m_rpcListenerWaitQueueLock, TimeSpan.FromSeconds(timeout)); + } + } + } + return true; + } + + + + + + + private readonly object m_loggerListenerLock = new object(); + private readonly Dictionary m_loggerListeners = new Dictionary(); + private readonly Lazy m_loggerListenerToken; + private Thread? m_loggerListenerThread; + private NtLoggerPoller m_loggerListenerPoller; + private readonly object m_loggerListenerWaitQueueLock = new object(); + private bool m_loggerListenerWaitQueue = false; + + private CancellationTokenSource CreateLoggerThread() + { + m_loggerListenerPoller = NtCore.CreateLoggerPoller(Handle); + CancellationTokenSource source = new CancellationTokenSource(); + var ret = new Thread(() => + { + bool wasInterrupted = false; + var token = source.Token; + token.Register(() => + { + NtCore.CancelPollLogger(m_loggerListenerPoller); + }); + while (!token.IsCancellationRequested) + { + var events = NtCore.PollLogger(m_loggerListenerPoller); + if (token.IsCancellationRequested) + { + NtCore.DisposeLoggerSpan(events); + break; + } + if (events.Length == 0) + { + NtCore.DisposeLoggerSpan(events); + lock (m_loggerListenerWaitQueueLock) + { + if (m_entryListenerWaitQueue) + { + m_entryListenerWaitQueue = false; + Monitor.PulseAll(m_loggerListenerWaitQueueLock); + continue; + } + } + wasInterrupted = true; + break; + } + for (int i = 0; i < events.Length; i++) + { + LogMessageDelegate? listener; + lock (m_loggerListenerLock) { + m_loggerListeners.TryGetValue(events.Pointer[i].logger, out listener); + } + if (listener != null) + { + listener(new LogMessage(this, events.Pointer[i])); + if (token.IsCancellationRequested) + { + break; + } + } + } + NtCore.DisposeLoggerSpan(events); + } + lock (m_loggerListenerWaitQueueLock) + { + if (!wasInterrupted) + { + NtCore.DestroyLoggerPoller(m_loggerListenerPoller); + } + m_loggerListenerPoller = new NtLoggerPoller(); + } + }) + { + Name = "NTLogger", + IsBackground = true + }; + ret.Start(); + m_loggerListenerThread = ret; + return source; + } + + public NtLogger AddLogger(LogMessageDelegate listener, int minLevel, int maxLevel) + { + var token = m_loggerListenerToken.Value; + lock (m_loggerListenerLock) { + var handle = NtCore.AddPolledLogger(m_loggerListenerPoller, minLevel, maxLevel); + m_loggerListeners.Add(handle, listener); + return handle; + } + } + + public void RemoveLogger(NtLogger listener) + { + NtCore.RemoveLogger(listener); + lock (m_loggerListenerLock) { + m_loggerListeners.Remove(listener); + } + + } + + public bool WaitForLoggerQueue(double timeout) + { + if (!NtCore.WaitForLoggerQueue(Handle, timeout)) + { + return false; + } + lock (m_loggerListenerWaitQueueLock) + { + if (m_loggerListenerPoller.Get() == 0) return true; + m_loggerListenerWaitQueue = true; + NtCore.CancelPollLogger(m_loggerListenerPoller); + while (m_loggerListenerWaitQueue) + { + if (timeout < 0) + { + Monitor.Wait(m_loggerListenerWaitQueueLock); + } + else + { + return Monitor.Wait(m_loggerListenerWaitQueueLock, TimeSpan.FromSeconds(timeout)); + } + } + } + return true; + } + } +} diff --git a/src/FRC.NetworkTables.Core/NetworkTableRefValue.cs b/src/FRC.NetworkTables.Core/NetworkTableRefValue.cs new file mode 100644 index 0000000..b9c32cb --- /dev/null +++ b/src/FRC.NetworkTables.Core/NetworkTableRefValue.cs @@ -0,0 +1,259 @@ +using FRC.NetworkTables.Interop; +using System; + +namespace FRC.NetworkTables +{ + public readonly ref struct RefNetworkTableValue + { + public NtType Type => Value.Type; + public readonly RefManagedValue Value; + public bool IsValid => Type != NtType.Unassigned; + + internal RefNetworkTableValue(in RefManagedValue value) + { + this.Value = value; + } + + public NetworkTableValue ToValue() + { + return new NetworkTableValue(Value); + } + + /// + /// Gets if the type is boolean + /// + /// True if the type is boolean + public bool IsBoolean() => Type == NtType.Boolean; + /// + /// Gets if the type is double + /// + /// True if the type is double + public bool IsDouble() => Type == NtType.Double; + /// + /// Gets if the type is string + /// + /// True if the type is string + public bool IsString() => Type == NtType.String; + + /// + /// Gets if the type is raw + /// + /// True if the type is raw + public bool IsRaw() => Type == NtType.Raw; + + /// + /// Gets if the type is Rpc + /// + /// True if the type is Rpc + public bool IsRpc() => Type == NtType.Rpc; + + /// + /// Gets if the type is boolean array + /// + /// True if the type is a boolean array + public bool IsBooleanArray() => Type == NtType.BooleanArray; + + /// + /// Gets if the type is double array + /// + /// True if the type is a double array + public bool IsDoubleArray() => Type == NtType.DoubleArray; + + /// + /// Gets if the type is string array + /// + /// True if the type is a string array + public bool IsStringArray() => Type == NtType.StringArray; + + /// + /// Gets the boolean value from the type + /// + /// boolean contained in type + /// Thrown if + /// type is not boolean. + public bool GetBoolean() + { + if (Type != NtType.Boolean) + { + throw new InvalidCastException($"cannot convert {Type} to boolean"); + } + return Value.Data.VBoolean; + } + /// + /// Gets the double value from the type + /// + /// double contained in type + /// Thrown if + /// type is not double. + public double GetDouble() + { + if (Type != NtType.Double) + { + throw new InvalidCastException($"cannot convert {Type} to double"); + } + return Value.Data.VDouble; + } + + /// + /// Gets the string value from the type + /// + /// string contained in type + /// Thrown if + /// type is not string. + public ReadOnlySpan GetString() + { + if (Type != NtType.String) + { + throw new InvalidCastException($"cannot convert {Type} to string"); + } + return Value.Data.VString; + } + + //For reference types (other then strings) return copies; + + /// + /// Gets the raw value from the type + /// + /// raw byte array contained in type + /// Thrown if + /// type is not raw. + public ReadOnlySpan GetRaw() + { + if (Type != NtType.Raw) + { + throw new InvalidCastException($"cannot convert {Type} to raw"); + } + return Value.Data.VRaw; + } + + /// + /// Gets the rpc value from the type + /// + /// rpc byte array contained in type + /// Thrown if + /// type is not rpc. + public ReadOnlySpan GetRpc() + { + if (Type != NtType.Rpc) + { + throw new InvalidCastException($"cannot convert {Type} to Rpc"); + } + return Value.Data.VRaw; + } + + /// + /// Gets the boolean array value from the type + /// + /// boolean array contained in type + /// Thrown if + /// type is not boolean array. + public ReadOnlySpan GetBooleanArray() + { + if (Type != NtType.BooleanArray) + { + throw new InvalidCastException($"cannot convert {Type} to boolean array"); + } + return Value.Data.VBooleanArray; + } + + /// + /// Gets the double array value from the type + /// + /// double array contained in type + /// Thrown if + /// type is not double array. + public ReadOnlySpan GetDoubleArray() + { + if (Type != NtType.DoubleArray) + { + throw new InvalidCastException($"cannot convert {Type} to double array"); + } + return Value.Data.VDoubleArray; + } + + /// + /// Gets the string array value from the type + /// + /// string array contained in type + /// Thrown if + /// type is not string arrya. + public ReadOnlySpan GetStringArray() + { + if (Type != NtType.StringArray) + { + throw new InvalidCastException($"cannot convert {Type} to string array"); + } + return Value.Data.VStringArray; + } + + public static RefNetworkTableValue MakeBoolean(bool value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now())); + } + + public static RefNetworkTableValue MakeDouble(double value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now())); + } + + public static RefNetworkTableValue MakeString(string value) + { + return new RefNetworkTableValue(new RefManagedValue(value.AsSpan(), NtCore.Now())); + } + + public static RefNetworkTableValue MakeString(ReadOnlySpan value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now())); + } + + public static RefNetworkTableValue MakeRaw(ReadOnlySpan value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now())); + } + + public static RefNetworkTableValue MakeRpc(ReadOnlySpan value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now(), true)); + } + + public static RefNetworkTableValue MakeBooleanArray(ReadOnlySpan value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now())); + } + + public static RefNetworkTableValue MakeDoubleArray(ReadOnlySpan value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now())); + } + + public static RefNetworkTableValue MakeStringArray(ReadOnlySpan value) + { + return new RefNetworkTableValue(new RefManagedValue(value, NtCore.Now())); + } + + public override bool Equals(object obj) + { + return false; + } + + public override int GetHashCode() + { + return Value.GetHashCode(); + } + + public bool Equals(RefNetworkTableValue other) + { + return Value.Equals(other.Value); + } + + public static bool operator ==(RefNetworkTableValue lhs, RefNetworkTableValue rhs) + { + return lhs.Equals(rhs); + } + + public static bool operator !=(RefNetworkTableValue lhs, RefNetworkTableValue rhs) + { + return !lhs.Equals(rhs); + } + } +} \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core/NetworkTableValue.cs b/src/FRC.NetworkTables.Core/NetworkTableValue.cs new file mode 100644 index 0000000..af7556d --- /dev/null +++ b/src/FRC.NetworkTables.Core/NetworkTableValue.cs @@ -0,0 +1,268 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace FRC.NetworkTables +{ + public readonly struct NetworkTableValue : IEquatable + { + public NtType Type => Value.Type; + public readonly ManagedValue Value; + public bool IsValid => Type != NtType.Unassigned; + + internal NetworkTableValue(in ManagedValue value) + { + this.Value = value; + } + + internal NetworkTableValue(in RefManagedValue value) + { + Value = new ManagedValue(value); + } + + /// + /// Gets if the type is boolean + /// + /// True if the type is boolean + public bool IsBoolean() => Type == NtType.Boolean; + /// + /// Gets if the type is double + /// + /// True if the type is double + public bool IsDouble() => Type == NtType.Double; + /// + /// Gets if the type is string + /// + /// True if the type is string + public bool IsString() => Type == NtType.String; + + /// + /// Gets if the type is raw + /// + /// True if the type is raw + public bool IsRaw() => Type == NtType.Raw; + + /// + /// Gets if the type is Rpc + /// + /// True if the type is Rpc + public bool IsRpc() => Type == NtType.Rpc; + + /// + /// Gets if the type is boolean array + /// + /// True if the type is a boolean array + public bool IsBooleanArray() => Type == NtType.BooleanArray; + + /// + /// Gets if the type is double array + /// + /// True if the type is a double array + public bool IsDoubleArray() => Type == NtType.DoubleArray; + + /// + /// Gets if the type is string array + /// + /// True if the type is a string array + public bool IsStringArray() => Type == NtType.StringArray; + + /// + /// Gets the boolean value from the type + /// + /// boolean contained in type + /// Thrown if + /// type is not boolean. + public bool GetBoolean() + { + if (Type != NtType.Boolean) + { + throw new InvalidCastException($"cannot convert {Type} to boolean"); + } + return Value.Data.VBoolean; + } + /// + /// Gets the double value from the type + /// + /// double contained in type + /// Thrown if + /// type is not double. + public double GetDouble() + { + if (Type != NtType.Double) + { + throw new InvalidCastException($"cannot convert {Type} to double"); + } + return Value.Data.VDouble; + } + + /// + /// Gets the string value from the type + /// + /// string contained in type + /// Thrown if + /// type is not string. + public string GetString() + { + if (Type != NtType.String) + { + throw new InvalidCastException($"cannot convert {Type} to string"); + } + return Value.Data.VString!; + } + + //For reference types (other then strings) return copies; + + /// + /// Gets the raw value from the type + /// + /// raw byte array contained in type + /// Thrown if + /// type is not raw. + public byte[] GetRaw() + { + if (Type != NtType.Raw) + { + throw new InvalidCastException($"cannot convert {Type} to raw"); + } + return Value.Data.VRaw!; + } + + /// + /// Gets the rpc value from the type + /// + /// rpc byte array contained in type + /// Thrown if + /// type is not rpc. + public byte[] GetRpc() + { + if (Type != NtType.Rpc) + { + throw new InvalidCastException($"cannot convert {Type} to Rpc"); + } + return Value.Data.VRaw!; + } + + /// + /// Gets the boolean array value from the type + /// + /// boolean array contained in type + /// Thrown if + /// type is not boolean array. + public bool[] GetBooleanArray() + { + if (Type != NtType.BooleanArray) + { + throw new InvalidCastException($"cannot convert {Type} to boolean array"); + } + return Value.Data.VBooleanArray!; + } + + /// + /// Gets the double array value from the type + /// + /// double array contained in type + /// Thrown if + /// type is not double array. + public double[] GetDoubleArray() + { + if (Type != NtType.DoubleArray) + { + throw new InvalidCastException($"cannot convert {Type} to double array"); + } + return Value.Data.VDoubleArray!; + } + + /// + /// Gets the string array value from the type + /// + /// string array contained in type + /// Thrown if + /// type is not string arrya. + public string[] GetStringArray() + { + if (Type != NtType.StringArray) + { + throw new InvalidCastException($"cannot convert {Type} to string array"); + } + return Value.Data.VStringArray!; + } + + public static NetworkTableValue MakeBoolean(bool value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now())); + } + + public static NetworkTableValue MakeDouble(double value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now())); + } + + public static NetworkTableValue MakeString(string value) + { + return new NetworkTableValue(new ManagedValue(value.AsSpan(), NtCore.Now())); + } + + public static NetworkTableValue MakeString(ReadOnlySpan value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now())); + } + + public static NetworkTableValue MakeRaw(ReadOnlySpan value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now())); + } + + public static NetworkTableValue MakeRpc(ReadOnlySpan value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now(), true)); + } + + public static NetworkTableValue MakeBooleanArray(ReadOnlySpan value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now())); + } + + public static NetworkTableValue MakeDoubleArray(ReadOnlySpan value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now())); + } + + public static NetworkTableValue MakeStringArray(ReadOnlySpan value) + { + return new NetworkTableValue(new ManagedValue(value, NtCore.Now())); + } + + public override bool Equals(object obj) + { + if (obj is NetworkTableValue v) + { + return Equals(v); + } + return false; + } + + public override int GetHashCode() + { + return Value.GetHashCode(); + } + + public bool Equals(NetworkTableValue other) + { + return Value.Equals(other.Value); + } + + public static bool operator==(NetworkTableValue lhs, NetworkTableValue rhs) + { + return lhs.Equals(rhs); + } + + public static bool operator!=(NetworkTableValue lhs, NetworkTableValue rhs) + { + return !lhs.Equals(rhs); + } + + + } +} \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core/PersistentException.cs b/src/FRC.NetworkTables.Core/PersistentException.cs new file mode 100644 index 0000000..f2fbf4f --- /dev/null +++ b/src/FRC.NetworkTables.Core/PersistentException.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace FRC.NetworkTables +{ + public sealed class PersistentException : IOException + { + public PersistentException(string message) : base(message) + { + + } + } +} diff --git a/src/FRC.NetworkTables.Core/Properties/AssemblyInfo.cs b/src/FRC.NetworkTables.Core/Properties/AssemblyInfo.cs deleted file mode 100644 index ec73701..0000000 --- a/src/FRC.NetworkTables.Core/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("FRC.NetworkTables.Core")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyVersion("3.0.0.0")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("41be202a-b37e-4aba-8c90-3d1d2e1b1a0e")] - -[assembly: InternalsVisibleTo("NetworkTables.Core.Test")] \ No newline at end of file diff --git a/src/FRC.NetworkTables.Core/RefDelegates.cs b/src/FRC.NetworkTables.Core/RefDelegates.cs new file mode 100644 index 0000000..f8e0815 --- /dev/null +++ b/src/FRC.NetworkTables.Core/RefDelegates.cs @@ -0,0 +1,7 @@ +namespace FRC.NetworkTables +{ + public delegate void RpcAnswerDelegate(in RpcAnswer answer); + public delegate void EntryNotificationDelegate(in RefEntryNotification notification); + public delegate void ConnectionNotificationDelegate(in ConnectionNotification notification); + public delegate void LogMessageDelegate(in LogMessage log); +} diff --git a/src/FRC.NetworkTables.Core/RefEntryNotification.cs b/src/FRC.NetworkTables.Core/RefEntryNotification.cs new file mode 100644 index 0000000..1a0e1ef --- /dev/null +++ b/src/FRC.NetworkTables.Core/RefEntryNotification.cs @@ -0,0 +1,30 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables +{ + public readonly ref struct RefEntryNotification + { + public readonly NtEntryListener Listener; + public readonly NtEntry EntryHandle; + public readonly string Name; + public readonly RefNetworkTableValue Value; + public readonly NotifyFlags Flags; + public NetworkTableEntry Entry => new NetworkTableEntry(m_instance, EntryHandle); + private readonly NetworkTableInstance m_instance; + + public EntryNotification CopyNotification => new EntryNotification(m_instance, this); + + internal unsafe RefEntryNotification(NetworkTableInstance inst, in NtEntryNotification entry) + { + Listener = entry.listener; + EntryHandle = entry.entry; + Name = UTF8String.ReadUTF8String(entry.name.str, entry.name.len); + Value = new RefNetworkTableValue(new RefManagedValue(entry.value)); + Flags = (NotifyFlags)entry.flags; + m_instance = inst; + } + } +} diff --git a/src/FRC.NetworkTables.Core/RefManagedValue.cs b/src/FRC.NetworkTables.Core/RefManagedValue.cs new file mode 100644 index 0000000..5fee30b --- /dev/null +++ b/src/FRC.NetworkTables.Core/RefManagedValue.cs @@ -0,0 +1,322 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Runtime.InteropServices; + +namespace FRC.NetworkTables +{ + public readonly ref struct RefManagedValue + { + public readonly NtType Type; + public readonly ulong LastChange; + public readonly RefEntryUnion Data; + + public override int GetHashCode() + { + unchecked + { + int hash = 13; + hash = (hash * 7) + Type.GetHashCode(); + switch (Type) + { + case NtType.Boolean: + hash = (hash * 7) + Data.VBoolean.GetHashCode(); + break; + case NtType.Double: + hash = (hash * 7) + Data.VDouble.GetHashCode(); + break; + case NtType.String: + hash = (hash * 7) + Data.VString.GetHashCode(); + break; + case NtType.Rpc: + case NtType.Raw: + hash = (hash * 7) + Data.VRaw.GetHashCode(); + break; + case NtType.BooleanArray: + hash = (hash * 7) + Data.VBooleanArray.GetHashCode(); + break; + case NtType.DoubleArray: + hash = (hash * 7) + Data.VDoubleArray.GetHashCode(); + break; + case NtType.StringArray: + hash = (hash * 7) + Data.VStringArray.GetHashCode(); + break; + } + return hash; + } + } + + public override bool Equals(object obj) + { + return false; + } + + public bool Equals(RefManagedValue other) + { + if (Type != other.Type) return false; + switch (Type) + { + case NtType.Unassigned: + return true; + case NtType.Boolean: + return Data.VBoolean == other.Data.VBoolean; + case NtType.Double: + return Data.VDouble == other.Data.VDouble; + case NtType.String: + return Data.VString.SequenceEqual(other.Data.VString); + case NtType.Raw: + case NtType.Rpc: + return Data.VRaw.SequenceEqual(other.Data.VRaw); + case NtType.BooleanArray: + return Data.VBooleanArray.SequenceEqual(other.Data.VBooleanArray); + case NtType.DoubleArray: + return Data.VDoubleArray.SequenceEqual(other.Data.VDoubleArray); + case NtType.StringArray: + return Data.VStringArray.SequenceEqual(other.Data.VStringArray); + default: + return false; + } + } + + public object? GetValue() + { + switch (Type) + { + case NtType.Boolean: + return Data.VBoolean; + case NtType.Double: + return Data.VDouble; + case NtType.String: + return Data.VString.ToString(); + case NtType.Rpc: + case NtType.Raw: + return Data.VRaw.ToArray(); + case NtType.BooleanArray: + return Data.VBooleanArray.ToArray(); + case NtType.DoubleArray: + return Data.VDoubleArray.ToArray(); + case NtType.StringArray: + return Data.VStringArray.ToArray(); + default: + return null; + } + } + + internal unsafe RefManagedValue(in NtValue v) + { + LastChange = v.last_change; + Type = v.type; + Data = new RefEntryUnion(v); + + } + + internal unsafe RefManagedValue(bool v, ulong t) + { + LastChange = t; + Type = NtType.Boolean; + Data = new RefEntryUnion(v); + } + + internal unsafe RefManagedValue(double v, ulong t) + { + LastChange = t; + Type = NtType.Double; + Data = new RefEntryUnion(v); + } + + internal unsafe RefManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.String; + Data = new RefEntryUnion(v); + } + + internal unsafe RefManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.Raw; + Data = new RefEntryUnion(v); + } + + internal unsafe RefManagedValue(ReadOnlySpan v, ulong t, bool r) + { + LastChange = t; + Type = r ? NtType.Rpc : NtType.Raw; + Data = new RefEntryUnion(v); + } + + internal unsafe RefManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.BooleanArray; + Data = new RefEntryUnion(v); + } + + internal unsafe RefManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.DoubleArray; + Data = new RefEntryUnion(v); + } + + internal unsafe RefManagedValue(ReadOnlySpan v, ulong t) + { + LastChange = t; + Type = NtType.StringArray; + Data = new RefEntryUnion(v); + } + } + + [StructLayout(LayoutKind.Explicit)] + public readonly ref struct RefEntryUnion + { + [FieldOffset(0)] + public readonly bool VBoolean; + [FieldOffset(0)] + public readonly double VDouble; + [FieldOffset(8)] + public readonly ReadOnlySpan VString; + [FieldOffset(8)] + public readonly ReadOnlySpan VRaw; + [FieldOffset(8)] + public readonly ReadOnlySpan VBooleanArray; + [FieldOffset(8)] + public readonly ReadOnlySpan VDoubleArray; + [FieldOffset(8)] + public readonly ReadOnlySpan VStringArray; + + internal RefEntryUnion(bool v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VBoolean = v; + } + + internal RefEntryUnion(double v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VDouble = v; + } + + internal RefEntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VString = v; + } + + internal RefEntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VRaw = v; + } + + internal RefEntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VBooleanArray = v; + } + + internal RefEntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VDoubleArray = v; + } + + internal RefEntryUnion(ReadOnlySpan v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + VStringArray = v; + } + + internal unsafe RefEntryUnion(in NtValue v) + { + VBoolean = false; + VDouble = 0; + VString = null; + VRaw = null; + VBooleanArray = null; + VDoubleArray = null; + VStringArray = null; + + switch (v.type) + { + case NtType.Unassigned: + break; + case NtType.Boolean: + VBoolean = v.data.v_boolean.Get(); + break; + case NtType.Double: + VDouble = v.data.v_double; + break; + case NtType.String: + VString = UTF8String.ReadUTF8String(v.data.v_string.str, v.data.v_string.len).AsSpan(); + break; + case NtType.Rpc: + case NtType.Raw: + VRaw = new ReadOnlySpan(v.data.v_raw.str, (int)v.data.v_raw.len); + break; + case NtType.BooleanArray: + VBooleanArray = new ReadOnlySpan(v.data.arr_boolean.arr, (int)v.data.arr_boolean.len); + break; + case NtType.DoubleArray: + VDoubleArray = new ReadOnlySpan(v.data.arr_double.arr, (int)v.data.arr_double.len); + break; + case NtType.StringArray: + var sarr = new string[(int)v.data.arr_string.len]; + for (int i = 0; i < sarr.Length; i++) + { + sarr[i] = UTF8String.ReadUTF8String(v.data.arr_string.arr[i].str, v.data.arr_string.arr[i].len); + } + VStringArray = sarr; + break; + } + } + } +} diff --git a/src/FRC.NetworkTables.Core/RpcAnswer.cs b/src/FRC.NetworkTables.Core/RpcAnswer.cs new file mode 100644 index 0000000..ef9d62d --- /dev/null +++ b/src/FRC.NetworkTables.Core/RpcAnswer.cs @@ -0,0 +1,36 @@ +using FRC.NetworkTables.Interop; +using System; + +namespace FRC.NetworkTables +{ + public readonly ref struct RpcAnswer + { + public readonly NtEntry EntryHandle; + public readonly NtRpcCall Call; + public readonly string Name; + public readonly ReadOnlySpan Params; + public readonly ConnectionInfo Conn; + private readonly Span m_wasRespondedTo; + public NetworkTableEntry Entry => new NetworkTableEntry(m_instance, EntryHandle); + private readonly NetworkTableInstance m_instance; + + internal unsafe RpcAnswer(NetworkTableInstance inst, in NtRpcAnswer answer, Span respondedTo) + { + EntryHandle = answer.entry; + Call = answer.call; + Name = UTF8String.ReadUTF8String(answer.name.str, answer.name.len); + Params = new Span(answer.@params.str, (int)answer.@params.len); + Conn = new ConnectionInfo(answer.conn); + m_wasRespondedTo = respondedTo; + m_instance = inst; + } + + public bool IsValid => m_wasRespondedTo[0] == false; + + public void PostResponse(ReadOnlySpan result) + { + NtCore.PostRpcResponse(EntryHandle, Call, result); + m_wasRespondedTo[0] = true; + } + } +} diff --git a/src/FRC.NetworkTables.Core/RpcCall.cs b/src/FRC.NetworkTables.Core/RpcCall.cs new file mode 100644 index 0000000..ccc6883 --- /dev/null +++ b/src/FRC.NetworkTables.Core/RpcCall.cs @@ -0,0 +1,73 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace FRC.NetworkTables +{ + public readonly struct RpcCall : IDisposable + { + public RpcCall(NetworkTableEntry entry, NtRpcCall call) + { + Handle = call; + Entry = entry; + } + + public readonly NtRpcCall Handle; + public readonly NetworkTableEntry Entry; + + public bool IsValid => Handle.Get() != 0; + + public void Dispose() + { + if (IsValid) + { + CancelResult(); + } + } + + public ReadOnlySpan GetResult() + { + Span store = Span.Empty; + var result = NtCore.GetRpcResult(Entry.Handle, Handle, store); + return result; + } + + public ReadOnlySpan GetResult(Span store) + { + var result = NtCore.GetRpcResult(Entry.Handle, Handle, store); + return result; + } + + public ReadOnlySpan GetResult(double timeout) + { + Span store = Span.Empty; + var result = NtCore.GetRpcResult(Entry.Handle, Handle, timeout, store); + return result; + } + + public ReadOnlySpan GetResult(double timeout, Span store) + { + var result = NtCore.GetRpcResult(Entry.Handle, Handle, timeout, store); + return result; + } + + public Task GetResultAsync(CancellationToken token = default) + { + NtEntry handle = Entry.Handle; + Interop.NtRpcCall call = Handle; + token.Register(() => { + NtCore.CancelRpcResult(handle, call); + }); + return Task.Run(() => + { + return NtCore.GetRpcResult(handle, call, Span.Empty).ToArray(); + }); + } + + public void CancelResult() + { + NtCore.CancelRpcResult(Entry.Handle, Handle); + } + } +} diff --git a/src/FRC.NetworkTables.Core/ServerPortPair.cs b/src/FRC.NetworkTables.Core/ServerPortPair.cs new file mode 100644 index 0000000..de89e0f --- /dev/null +++ b/src/FRC.NetworkTables.Core/ServerPortPair.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables +{ + public readonly struct ServerPortPair + { + public readonly string Server; + public readonly int Port; + public ServerPortPair(string server, int port) + { + Server = server; + Port = port; + } + } +} diff --git a/src/FRC.NetworkTables.Core/Support/Timestamp.cs b/src/FRC.NetworkTables.Core/Support/Timestamp.cs deleted file mode 100644 index 3b7ab7c..0000000 --- a/src/FRC.NetworkTables.Core/Support/Timestamp.cs +++ /dev/null @@ -1,14 +0,0 @@ -using NetworkTables.Core.Native; - -// ReSharper disable once CheckNamespace -namespace NetworkTables.Support -{ - internal static class Timestamp - { - public static long Now() - { - // Gets a consistent timestamp that we can use for checking if data is new. - return CoreMethods.Now(); - } - } -} diff --git a/src/FRC.NetworkTables.Core/TableEntryListener.cs b/src/FRC.NetworkTables.Core/TableEntryListener.cs new file mode 100644 index 0000000..46e4f3d --- /dev/null +++ b/src/FRC.NetworkTables.Core/TableEntryListener.cs @@ -0,0 +1,6 @@ +using System; + +namespace FRC.NetworkTables +{ + public delegate void TableEntryListener(NetworkTable table, ReadOnlySpan key, in NetworkTableEntry entry, in RefNetworkTableValue value, NotifyFlags flags); +} diff --git a/src/FRC.NetworkTables.Core/TableListener.cs b/src/FRC.NetworkTables.Core/TableListener.cs new file mode 100644 index 0000000..67fd8c1 --- /dev/null +++ b/src/FRC.NetworkTables.Core/TableListener.cs @@ -0,0 +1,8 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables +{ + public delegate void TableListener(NetworkTable parent, ReadOnlySpan name, NotifyFlags flags); +} diff --git a/src/FRC.NetworkTables.Dev/FRC.NetworkTables.Dev.csproj b/src/FRC.NetworkTables.Dev/FRC.NetworkTables.Dev.csproj new file mode 100644 index 0000000..3f7caaf --- /dev/null +++ b/src/FRC.NetworkTables.Dev/FRC.NetworkTables.Dev.csproj @@ -0,0 +1,21 @@ + + + + Exe + netcoreapp3.0 + + + + 8.0 + enable + x64 + true + true + + + + + + + + diff --git a/src/FRC.NetworkTables.Dev/Program.cs b/src/FRC.NetworkTables.Dev/Program.cs new file mode 100644 index 0000000..50bd03a --- /dev/null +++ b/src/FRC.NetworkTables.Dev/Program.cs @@ -0,0 +1,20 @@ +using FRC.NetworkTables.Interop; +using System; + +namespace FRC.NetworkTables.Dev +{ + class Program + { + static void Main(string[] args) + { + + NetworkTableInstance inst = NetworkTableInstance.Default; + foreach (var s in inst.GetTable("SmartDashboard").GetSubTables()) + { + ; + } + + Console.WriteLine("Hello World!"); + } + } +} diff --git a/src/FRC.NetworkTables/DSClient.cs b/src/FRC.NetworkTables/DSClient.cs deleted file mode 100644 index 6d9c0ea..0000000 --- a/src/FRC.NetworkTables/DSClient.cs +++ /dev/null @@ -1,245 +0,0 @@ -using NetworkTables.Logging; -using System; -using System.Threading; -using System.Threading.Tasks; -using System.Net.Sockets; -using System.IO; -using System.Text; -using static NetworkTables.Logging.Logger; -using System.Net; -using Nito.AsyncEx; -using Nito.AsyncEx.Synchronous; - -namespace NetworkTables -{ - internal class DsClient : IDisposable - { - private static DsClient s_instance; - - public static DsClient Instance - { - get - { - if (s_instance == null) - { - DsClient d = new DsClient(); - Interlocked.CompareExchange(ref s_instance, d, null); - } - return s_instance; - } - } - - //private IServerOverridable m_serverOverridable; - - public DsClient(/*IServerOverridable serverOverridable*/) - { - //m_serverOverridable = serverOverridable; - } - - private int m_port; - - private Task m_task; - private CancellationTokenSource m_tokenSource; - - public void Dispose() - { - Stop(); - } - - public void Stop() - { - m_tokenSource?.Cancel(); - m_task?.WaitAndUnwrapException(); - m_task = null; - m_tokenSource = null; - } - - public void Start(int port) - { - Interlocked.Exchange(ref m_port, port); - if (m_task == null) - { - if (m_tokenSource == null || m_tokenSource.IsCancellationRequested) - { - m_tokenSource = new CancellationTokenSource(); - } - m_task = Task.Factory.StartNew(ThreadMain, m_tokenSource.Token, TaskCreationOptions.LongRunning); - } - } - - public void ThreadMain(object token) - { - - if (token is CancellationToken) - { - try - { - AsyncContext.Run(async () => - { - await ThreadMainAsync((CancellationToken)token); - }); - } - catch (OperationCanceledException) - { - // Ignore operation cancelled - } - } - } - - public async Task ThreadMainAsync(CancellationToken token) - { - uint oldIp = 0; - try - { - while (!token.IsCancellationRequested) - { - int port; - - using (TcpClient client = new TcpClient()) - { - Task connection = client.ConnectAsync("127.0.0.1", 1742); - Task delayTask = Task.Delay(2000, token); - - try - { - var finished = await Task.WhenAny(connection, delayTask); - if (finished == delayTask) - { - // Timed Out - continue; - } - if (!finished.IsCompleted || finished.IsFaulted || finished.IsCanceled) - { - continue; - } - } - - catch (OperationCanceledException) - { - goto done; - } - - if (token.IsCancellationRequested) - { - goto done; - } - - Logger.Debug3(Logger.Instance, "Connected to DS"); - Stream stream = client.GetStream(); - - while (!token.IsCancellationRequested && stream.CanRead) - { - StringBuilder json = new StringBuilder(); - int chars = 0; - byte[] ch = new byte[1]; - do - { - chars = 0; - try - { - chars = await stream.ReadAsync(ch, 0, 1, token); - } - catch (OperationCanceledException) - { - goto done; - } - if (chars != 1) break; - if (token.IsCancellationRequested) goto done; - } while (ch[0] != (byte)'{'); - json.Append('{'); - - if (!stream.CanRead || !client.Connected || chars != 1) - { - break; - } - - do - { - chars = 0; - try - { - chars = await stream.ReadAsync(ch, 0, 1, token); - if (chars != 1) break; - if (token.IsCancellationRequested) goto done; - json.Append((char)ch[0]); - } - catch (OperationCanceledException) - { - goto done; - } - } while (ch[0] != (byte)'}'); - - if (!stream.CanRead || !client.Connected || chars != 1) - { - break; - } - - string jsonString = json.ToString(); - Debug3(Logger.Instance, $"json={jsonString}"); - - // Look for "robotIP":12345, and get 12345 portion - int pos = jsonString.IndexOf("\"robotIP\""); - if (pos < 0) continue; // could not find? - pos += 9; - pos = jsonString.IndexOf(':', pos); - if (pos < 0) continue; // could not find? - // Find first not of - int endpos = -1; - for (int i = pos + 1; i < jsonString.Length; i++) - { - if (jsonString[i] < '0' || jsonString[i] > '9') - { - endpos = i; - break; - } - } - string ipString = jsonString.Substring(pos + 1, endpos - (pos + 1)); - Debug3(Logger.Instance, $"found robotIP={ipString}"); - - // Parse into number - if (!uint.TryParse(ipString, out uint ip)) continue; - - if (BitConverter.IsLittleEndian) - { - ip = (uint)IPAddress.NetworkToHostOrder((int)ip); - } - - if (ip == 0) - { - //m_serverOverridable.ClearServerOverride(); - Dispatcher.Instance.ClearServerOverride(); - oldIp = 0; - continue; - } - - if (ip == oldIp) continue; - oldIp = ip; - - json.Clear(); - - IPAddress address = new IPAddress(oldIp); - Info(Logger.Instance, $"client: DS overriding server IP to {address.ToString()}"); - port = Interlocked.CompareExchange(ref m_port, 0, 0); - //m_serverOverridable.SetServerOverride(address, port); - Dispatcher.Instance.SetServerOverride(address, port); - } - } - - Dispatcher.Instance.ClearServerOverride(); - //m_serverOverridable.ClearServerOverride(); - oldIp = 0; - } - } - catch (ObjectDisposedException) - { - } - catch (NullReferenceException) - { - } - - done: - Dispatcher.Instance.ClearServerOverride(); - //m_serverOverridable.ClearServerOverride(); - } - } -} diff --git a/src/FRC.NetworkTables/Dispatcher.cs b/src/FRC.NetworkTables/Dispatcher.cs deleted file mode 100644 index 1600dd3..0000000 --- a/src/FRC.NetworkTables/Dispatcher.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Collections.Generic; -using System.Net; -using System.Threading; -using NetworkTables.Interfaces; -using NetworkTables.TcpSockets; -using NetworkTables.Logging; - -namespace NetworkTables -{ - internal class Dispatcher : DispatcherBase, IServerOverridable - { - private static Dispatcher s_instance; - - private Dispatcher() : this(Storage.Instance, Notifier.Instance) - { - } - - public Dispatcher(Storage storage, Notifier notifier) - : base(storage, notifier) - { - - } - - /// - /// Gets the local instance of Dispatcher - /// - public static Dispatcher Instance - { - get - { - if (s_instance == null) - { - Dispatcher d = new Dispatcher(); - Interlocked.CompareExchange(ref s_instance, d, null); - } - return s_instance; - } - } - - public void StartServer(string persistentFilename, string listenAddress, int port) - { - StartServer(persistentFilename, new TcpAcceptor(port, listenAddress)); - } - - - public void SetServer(string serverName, int port) - { - SetConnector(() => TcpConnector.Connect(serverName, port, Logger.Instance, 1)); - } - - public void SetServer(IList servers) - { - List connectors = new List(); - foreach (var server in servers) - { - connectors.Add(() => TcpConnector.Connect(server.IpAddress, server.Port, Logger.Instance, 1)); - } - SetConnector(connectors); - } - - public void SetServerOverride(IPAddress address, int port) - { - SetConnectorOverride(() => TcpConnector.Connect(address.ToString(), port, Logger.Instance, 1)); - } - - public void ClearServerOverride() - { - ClearConnectorOverride(); - } - } -} diff --git a/src/FRC.NetworkTables/DispatcherBase.cs b/src/FRC.NetworkTables/DispatcherBase.cs deleted file mode 100644 index a5d4512..0000000 --- a/src/FRC.NetworkTables/DispatcherBase.cs +++ /dev/null @@ -1,660 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using NetworkTables.TcpSockets; -using static NetworkTables.Logging.Logger; -using NetworkTables.Extensions; -using System.Net; -using System.Threading.Tasks; -using Nito.AsyncEx.Synchronous; -using NetworkTables.Logging; - -namespace NetworkTables -{ - internal class DispatcherBase : IDisposable - { - public delegate NtTcpClient Connector(); - - public const double MinimumUpdateTime = 0.01; //100ms - public const double MaximumUpdateTime = 1.0; //1 second - - private static readonly TimeSpan s_saveDeltaTime = TimeSpan.FromSeconds(1); - private readonly AutoResetEvent m_flushCv = new AutoResetEvent(false); - - private readonly object m_flushMutex = new object(); - private readonly Notifier m_notifier; - - private readonly AutoResetEvent m_reconnectCv = new AutoResetEvent(false); - - private readonly Storage m_storage; - - private readonly object m_userMutex = new object(); - - private bool m_active; - private Task m_clientServerThread; - private List m_connections = new List(); - private Task m_dispatchThread; - private bool m_doFlush; - private bool m_doReconnect = true; - private string m_identity = ""; - - private IList m_clientConnectors = new List(); - - private DateTime m_lastFlush; - - private string m_persistFilename; - private int m_reconnectProtoRev = 0x0300; - - private bool m_server; - - private INetworkAcceptor m_serverAccepter; - private double m_updateRate; - - private Connector m_clientConnectorOverride; - - protected DispatcherBase(Storage storage, Notifier notifier) - { - m_storage = storage; - m_notifier = notifier; - m_active = false; - m_updateRate = MinimumUpdateTime; - } - - public bool Active => m_active; - - public double UpdateRate - { - get { return m_updateRate; } - set - { - //Don't allow update rates faster the 100ms or slower then 1 second - if (value < MinimumUpdateTime) - value = MinimumUpdateTime; - else if (value > MaximumUpdateTime) - value = MaximumUpdateTime; - m_updateRate = value; - } - } - - public string Identity - { - get - { - lock (m_userMutex) - { - return m_identity; - } - } - set - { - lock (m_userMutex) - { - m_identity = value; - } - } - } - - //Disposable - public void Dispose() - { - Instance.SetDefaultLogger(); - Stop(); - } - - public void StartServer(string persistentFilename, INetworkAcceptor acceptor) - { - lock (m_userMutex) - { - if (m_active) return; - m_active = true; - } - m_server = true; - m_persistFilename = persistentFilename; - m_serverAccepter = acceptor; - - //Load persistent file, and ignore erros but pass along warnings. - if (!string.IsNullOrEmpty(persistentFilename)) - { - bool first = true; - m_storage.LoadPersistent(persistentFilename, (line, msg) => - { - if (first) - { - first = false; - Warning(Logger.Instance, $"When reading initial persistent values from \" {persistentFilename} \":"); - } - Warning(Logger.Instance, $"{persistentFilename} : {line.ToString()} : {msg}"); - }); - } - - //Bind SetOutgoing - m_storage.SetOutgoing(QueueOutgoing, m_server); - - //Start our tasks - m_dispatchThread = Task.Factory.StartNew(DispatchThreadMain, TaskCreationOptions.LongRunning); - m_clientServerThread = Task.Factory.StartNew(ServerThreadMain, TaskCreationOptions.LongRunning); - } - - public void StartClient() - { - lock (m_userMutex) - { - if (m_active) return; - m_active = true; - } - m_server = false; - - //Bind SetOutgoing - m_storage.SetOutgoing(QueueOutgoing, m_server); - - //Start our tasks - m_dispatchThread = Task.Factory.StartNew(DispatchThreadMain, TaskCreationOptions.LongRunning); - m_clientServerThread = Task.Factory.StartNew(ClientThreadMain, TaskCreationOptions.LongRunning); - } - - public void SetConnector(Connector connector) - { - SetConnector(new List() { connector }); - } - - public void SetConnector(IList connectors) - { - lock (m_userMutex) - { - m_clientConnectors = connectors; - } - } - - public void SetConnectorOverride(Connector connector) - { - lock (m_userMutex) - { - m_clientConnectorOverride = connector; - } - } - - public void ClearConnectorOverride() - { - lock (m_userMutex) - { - m_clientConnectorOverride = null; - } - } - - public void Stop() - { - m_active = false; - - // Wake up dispatch thread with a flush - m_flushCv.Set(); - - //Wake up client thread with a reconnect - lock (m_userMutex) - { - m_clientConnectors.Clear(); - } - ClientReconnect(); - - //Wake up server thread by a socket shutdown - m_serverAccepter?.Shutdown(); - - //Join our dispatch thread. - m_dispatchThread?.WaitAndUnwrapException(); - //Join our Client Server Thread - m_clientServerThread?.WaitAndUnwrapException(); - - List conns = new List(); - lock (m_userMutex) - { - var tmp = m_connections; - m_connections = conns; - conns = tmp; - } - - //Dispose and close all connections - foreach (var networkConnection in conns) - { - networkConnection.Dispose(); - } - - m_connections.Clear(); - } - - public void Flush() - { - var now = DateTime.UtcNow; - lock (m_flushMutex) - { - if (now - m_lastFlush < TimeSpan.FromSeconds(MinimumUpdateTime)) - { - return; - } - - m_lastFlush = now; - m_doFlush = true; - } - m_flushCv.Set(); - } - - public List GetConnections() - { - List conns = new List(); - if (!m_active) return conns; - - lock (m_userMutex) - { - foreach (var networkConnection in m_connections) - { - if (networkConnection.GetState() != NetworkConnection.State.Active) continue; - conns.Add(networkConnection.GetConnectionInfo()); - } - } - - return conns; - } - - public void NotifyConnections(ConnectionListenerCallback callback) - { - lock (m_userMutex) - { - - foreach (var conn in m_connections) - { - conn.NotifyIfActive(callback); - } - } - } - - private void DispatchThreadMain() - { - var timeoutTime = DateTime.UtcNow; - - var nextSaveTime = timeoutTime + s_saveDeltaTime; - - int count = 0; - - bool lockEntered = false; - try - { - while (m_active) - { - //Handle loop taking too long - var start = DateTime.UtcNow; - if (start > timeoutTime) - timeoutTime = start; - //Wait for periodic or when flushed - timeoutTime += TimeSpan.FromSeconds(m_updateRate); - TimeSpan waitTime = timeoutTime - start; - Monitor.Enter(m_flushMutex, ref lockEntered); - m_flushCv.WaitTimeout(m_flushMutex, ref lockEntered, waitTime, - () => !m_active || m_doFlush); - m_doFlush = false; - Monitor.Exit(m_flushMutex); - lockEntered = false; - if (!m_active) break; //in case we were woken up to terminate - - if (m_server && !string.IsNullOrEmpty(m_persistFilename) && start > nextSaveTime) - { - nextSaveTime += s_saveDeltaTime; - //Handle loop taking too long - if (start > nextSaveTime) nextSaveTime = start + s_saveDeltaTime; - string err = m_storage.SavePersistent(m_persistFilename, true); - if (err != null) - { - Warning(Logger.Instance, $"periodic persistent save: {err}"); - } - } - - lock (m_userMutex) - { - bool reconnect = false; - - if (++count > 10) - { - Debug(Logger.Instance, $"dispatch running {m_connections.Count.ToString()} connections"); - count = 0; - } - - foreach (var conn in m_connections) - { - //Post outgoing messages if connection is active - //only send keep-alives on client - if (conn.GetState() == NetworkConnection.State.Active) - conn.PostOutgoing(!m_server); - - //if client, reconnect if connection died - if (!m_server && conn.GetState() == NetworkConnection.State.Dead) - reconnect = true; - } - - //reconnect if we disconnected and a reconnect is not in progress - if (reconnect && !m_doReconnect) - { - m_doReconnect = true; - m_reconnectCv.Set(); - } - } - } - } - finally - { - if (lockEntered) Monitor.Exit(m_flushMutex); - } - } - - private void ServerThreadMain() - { - if (m_serverAccepter.Start() != 0) - { - m_active = false; - return; - } - - while (m_active) - { - var stream = m_serverAccepter.Accept(); - if (stream == null) - { - m_active = false; - return; - } - if (!m_active) return; - - if (stream.RemoteEndPoint is IPEndPoint ipEp) - { - Debug(Logger.Instance, $"server: client connection from {ipEp.Address} port {ipEp.Port.ToString()}"); - } - else - { - Warning(Logger.Instance, "server: client connection from unknown IP address and Port"); - } - - var conn = new NetworkConnection(stream, m_notifier, ServerHandshake, m_storage.GetEntryType); - conn.SetProcessIncoming(((msg, connection) => - { - m_storage.ProcessIncoming(msg, connection, new WeakReference(connection)); - })); - - lock (m_userMutex) - { - bool placed = false; - for (int i = 0; i < m_connections.Count; i++) - { - var c = m_connections[i]; - if (c.GetState() == NetworkConnection.State.Dead) - { - m_connections[i] = conn; - placed = true; - break; - } - } - - if (!placed) m_connections.Add(conn); - conn.Start(); - } - } - } - - private void ClientThreadMain() - { - int i = 0; - while (m_active) - { - //Sleep between retries - Task.Delay(TimeSpan.FromMilliseconds(250)).Wait(); - - Connector connect; - - lock (m_userMutex) - { - if (m_clientConnectorOverride != null) - { - connect = m_clientConnectorOverride; - } - else - { - if (m_clientConnectors.Count == 0) continue; - if (i >= m_clientConnectors.Count) i = 0; - connect = m_clientConnectors[i++]; - } - } - - Debug(Logger.Instance, "client trying to connect"); - var stream = connect(); - if (stream == null) continue; //keep retrying - Debug(Logger.Instance, "client connected"); - - bool lockEntered = false; - try - { - Monitor.Enter(m_userMutex, ref lockEntered); - var conn = new NetworkConnection(stream, m_notifier, ClientHandshake, m_storage.GetEntryType); - conn.SetProcessIncoming((msg, connection) => - { - m_storage.ProcessIncoming(msg, connection, new WeakReference(connection)); - }); - foreach (var s in m_connections) //Disconnect any current - { - s.Dispose(); - } - - m_connections.Clear(); - - m_connections.Add(conn); - - conn.ProtoRev = m_reconnectProtoRev; - - conn.Start(); - - // reconnect the next time starting with latest protocol revision - m_reconnectProtoRev = 0x0300; - - m_doReconnect = false; - m_reconnectCv.Wait(m_userMutex, ref lockEntered, () => !m_active || m_doReconnect); - } - finally - { - if (lockEntered) Monitor.Exit(m_userMutex); - } - } - } - - private bool ClientHandshake(NetworkConnection conn, Func getMsg, Action> sendMsgs) - { - string selfId; - lock (m_userMutex) - { - selfId = m_identity; - } - - Debug(Logger.Instance, "client: sending hello"); - sendMsgs(new List { Message.ClientHello(selfId) }); - - var msg = getMsg(); - if (msg == null) - { - //Disconnected - Debug(Logger.Instance, "client: server disconnected before first response"); - return false; - } - - if (msg.Is(Message.MsgType.ProtoUnsup)) - { - if (msg.Id == 0x0200) ClientReconnect(0x0200); - return false; - } - - bool newServer = true; - if (conn.ProtoRev >= 0x0300) - { - if (!msg.Is(Message.MsgType.ServerHello)) return false; - conn.RemoteId = msg.Str; - if ((msg.Flags & 1) != 0) newServer = false; - msg = getMsg(); - } - - List incoming = new List(); - - for (;;) - { - if (msg == null) - { - //disconnected, retry - Debug(Logger.Instance, "client: server disconnected during initial entries"); - return false; - } - Debug4(Logger.Instance, $"received init str={msg.Str} id={msg.Id.ToString()} seqNum={msg.SeqNumUid.ToString()}"); - - if (msg.Is(Message.MsgType.ServerHelloDone)) break; - if (msg.Is(Message.MsgType.KeepAlive)) - { - msg = getMsg(); - continue; - } - if (!msg.Is(Message.MsgType.EntryAssign)) - { - //Unexpected - Debug(Logger.Instance, - $"client: received message ({msg.Type.GetString()}) other then entry assignment during initial handshake"); - return false; - } - - incoming.Add(msg); - - msg = getMsg(); - } - - List outgoing = new List(); - m_storage.ApplyInitialAssignments(conn, incoming.ToArray(), newServer, outgoing); - - if (conn.ProtoRev >= 0x0300) - { - outgoing.Add(Message.ClientHelloDone()); - } - - if (outgoing.Count != 0) sendMsgs(outgoing); - - Info(Logger.Instance, $"client: CONNECTED to server {conn.PeerIP} port {conn.PeerPort.ToString()}"); - - return true; - } - - private bool ServerHandshake(NetworkConnection conn, Func getMsg, Action> sendMsgs) - { - var msg = getMsg(); - - if (msg == null) - { - Debug(Logger.Instance, "server: client disconnected before sending hello"); - return false; - } - - if (!msg.Is(Message.MsgType.ClientHello)) - { - Debug(Logger.Instance, "server: client initial message was not client hello"); - return false; - } - - int protoRev = (int)msg.Id; - - if (protoRev > 0x0300) - { - Debug(Logger.Instance, "server: client requested proto > 0x0300"); - sendMsgs(new List { Message.ProtoUnsup() }); - return false; - } - - if (protoRev >= 0x0300) conn.RemoteId = msg.Str; - - Debug(Logger.Instance, $"server: client protocol {protoRev.ToString()}"); - conn.ProtoRev = protoRev; - - List outgoing = new List(); - - if (protoRev >= 0x0300) - { - lock (m_userMutex) - { - outgoing.Add(Message.ServerHello(0, m_identity)); - } - } - - m_storage.GetInitialAssignments(conn, outgoing); - - outgoing.Add(Message.ServerHelloDone()); - - Debug(Logger.Instance, "server: sending initial assignments"); - sendMsgs(outgoing); - - if (protoRev >= 0x0300) - { - List incoming = new List(); - - msg = getMsg(); - - for (;;) - { - if (msg == null) - { - //Disconnected Retry - Debug(Logger.Instance, "server: disconnected waiting for initial entries"); - return false; - } - - if (msg.Is(Message.MsgType.ClientHelloDone)) break; - if (msg.Is(Message.MsgType.KeepAlive)) - { - msg = getMsg(); - continue; - } - if (!msg.Is(Message.MsgType.EntryAssign)) - { - Debug(Logger.Instance, - $"server: received message ({msg.Type.GetString()}) other than entry assignment during initial handshake"); - return false; - } - - incoming.Add(msg); - - msg = getMsg(); - } - - foreach (var m in incoming) - { - m_storage.ProcessIncoming(m, conn, new WeakReference(conn)); - } - } - - Info(Logger.Instance, $"server: client CONNECTED: {conn.PeerIP} port {conn.PeerPort.ToString()}"); - return true; - } - - private void ClientReconnect(int protoRev = 0x0300) - { - if (m_server) return; - lock (m_userMutex) - { - m_reconnectProtoRev = protoRev; - m_doReconnect = true; - } - - m_reconnectCv.Set(); - } - - private void QueueOutgoing(Message msg, NetworkConnection only, NetworkConnection except) - { - lock (m_userMutex) - { - foreach (var conn in m_connections) - { - if (conn == except) continue; - if (only != null && conn != only) continue; - var state = conn.GetState(); - if (state != NetworkConnection.State.Synchronized && - state != NetworkConnection.State.Active) continue; - conn.QueueOutgoing(msg); - } - } - } - } -} diff --git a/src/FRC.NetworkTables/Extensions/AutoResetEventExtensions.cs b/src/FRC.NetworkTables/Extensions/AutoResetEventExtensions.cs deleted file mode 100644 index a77050e..0000000 --- a/src/FRC.NetworkTables/Extensions/AutoResetEventExtensions.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Threading; - -namespace NetworkTables.Extensions -{ - internal static class AutoResetEventExtensions - { - /// - /// Extension for AutoReset that takes a mutex and a ref entered bool, - /// and unlocks the mutex before waiting for the specified timeout. - /// The predicate checks if something goes wrong. - /// - /// - /// - /// - /// - /// - /// - public static bool WaitTimeout(this AutoResetEvent e, object mutex, - ref bool lockEntered, TimeSpan timeout, Func pred) - { - //Throw if thread currently doesn't own the lock - if (!Monitor.IsEntered(mutex)) - { - throw new SynchronizationLockException(); - } - if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan) - timeout = TimeSpan.Zero; - //While pred is false. - // ReSharper disable once LoopVariableIsNeverChangedInsideLoop - while (!pred()) - { - Monitor.Exit(mutex); - lockEntered = false; - if (!e.WaitOne(timeout)) - { - //Timed out - Monitor.Enter(mutex, ref lockEntered); - return pred(); - } - Monitor.Enter(mutex, ref lockEntered); - } - - return true; - } - - public static bool WaitTimeout(this AutoResetEvent e, object mutex, ref bool lockEntered, TimeSpan timeout) - { - //Throw if thread currently doesn't own the lock - if (!Monitor.IsEntered(mutex)) - { - throw new SynchronizationLockException(); - } - if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan) - timeout = TimeSpan.Zero; - Monitor.Exit(mutex); - lockEntered = false; - if (!e.WaitOne(timeout)) - { - //Timed out - Monitor.Enter(mutex, ref lockEntered); - return false; - } - Monitor.Enter(mutex, ref lockEntered); - return true; - } - - public static void Wait(this AutoResetEvent e, object mutex, ref bool lockEntered, Func pred) - { - //Throw if thread currently doesn't own the lock - if (!Monitor.IsEntered(mutex)) - { - throw new SynchronizationLockException(); - } - //While pred is false. - // ReSharper disable once LoopVariableIsNeverChangedInsideLoop - while (!pred()) - { - Monitor.Exit(mutex); - lockEntered = false; - e.WaitOne(); - Monitor.Enter(mutex, ref lockEntered); - } - } - - public static void Wait(this AutoResetEvent e, object mutex, ref bool lockEntered) - { - //Throw if thread currently doesn't own the lock - if (!Monitor.IsEntered(mutex)) - { - throw new SynchronizationLockException(); - } - Monitor.Exit(mutex); - lockEntered = false; - e.WaitOne(); - Monitor.Enter(mutex, ref lockEntered); - } - } -} diff --git a/src/FRC.NetworkTables/FRC.NetworkTables.csproj b/src/FRC.NetworkTables/FRC.NetworkTables.csproj deleted file mode 100644 index 95d03be..0000000 --- a/src/FRC.NetworkTables/FRC.NetworkTables.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - A Managed version of the NetworkTables3 Protocol. - Copyright 2016 RobotDotNet - FRC NetworkTables - FRC NetworkTables - 3.0.0-local - RobotDotNet - net46;netstandard1.3 - true - FRC.NetworkTables - FRC.NetworkTables - WPILib;FRC;FIRST;RoboRio - https://github.com/robotdotnet/NetworkTables - https://github.com/robotdotnet/NetworkTables/blob/master/LICENSE.txt - git - git://github.com/robotdotnet/NetworkTables - false - false - false - false - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/FRC.NetworkTables/Independent/IndependentNetworkTable.cs b/src/FRC.NetworkTables/Independent/IndependentNetworkTable.cs deleted file mode 100644 index 8b92695..0000000 --- a/src/FRC.NetworkTables/Independent/IndependentNetworkTable.cs +++ /dev/null @@ -1,760 +0,0 @@ -using System; -using System.Collections.Generic; -using NetworkTables.Exceptions; -using NetworkTables.Tables; - -namespace NetworkTables.Independent -{ - /// - /// This class is the Main Class for interfacing with NetworkTables. - /// - /// For most users, this will be the only class that will be needed. - /// Any interfaces needed to work with this can be found in the - /// namespace. - /// - /// The static , and - /// all run using the same backend library. This means you cannot have both a client and a server running - /// in the same user program. The - /// , and - /// get around this restriction, and allow multiple clients and servers in the same user program. Note that this is - /// not supported by NetworkTables.Core. - public class IndependentNetworkTable : ITable, IRemote - { - private readonly IndependentNtCore m_ntCore; - /// - public const char PathSeperatorChar = NetworkTable.PathSeperatorChar; - internal const string PathSeperatorCharString = NetworkTable.PathSeperatorCharString; - private readonly string m_path; - private readonly string m_pathWithSeperator; - - /// - /// Creates a new NetworkTable object from an NtCore object - /// - /// The NtCore object to use - /// The root path for this table - public IndependentNetworkTable(IndependentNtCore ntCore, string path) - { - if (path == "" || path[0] == PathSeperatorChar) - m_path = path; - else - { - m_path = PathSeperatorCharString + path; - } - m_ntCore = ntCore; - m_pathWithSeperator = m_path + PathSeperatorCharString; - } - - /// - public override string ToString() - { - return $"NetworkTable: {m_path}"; - } - - /// - /// Checkts the table and tells if it contains the specified key. - /// - /// The key to be checked. - /// True if the table contains the key, otherwise false. - public bool ContainsKey(string key) - { - return m_ntCore.ContainsEntry(m_pathWithSeperator + key); - } - - /// - /// Checks the table and tells if if contains the specified sub-table. - /// - /// The sub-table to check for - /// True if the table contains the sub-table, otherwise false - public bool ContainsSubTable(string key) - { - return m_ntCore.GetEntryInfo(m_pathWithSeperator + key + PathSeperatorChar, 0).Count != 0; - } - - /// - /// Gets a set of all the keys contained in the table with the specified type. - /// - /// Bitmask of types to check for; 0 is treated as a "don't care". - /// A set of all keys currently in the table. - public HashSet GetKeys(NtType types) - { - HashSet keys = new HashSet(); - int prefixLen = m_path.Length + 1; - foreach (EntryInfo entry in m_ntCore.GetEntryInfo(m_pathWithSeperator, types)) - { - string relativeKey = entry.Name.Substring(prefixLen); - if (relativeKey.IndexOf(PathSeperatorChar) != -1) - continue; - keys.Add(relativeKey); - } - return keys; - } - - /// - /// Gets a set of all the keys contained in the table. - /// - /// A set of all keys currently in the table. - public HashSet GetKeys() - { - return GetKeys(0); - } - - /// - /// Gets a set of all the sub-tables contained in the table. - /// - /// A set of all subtables currently contained in the table. - public HashSet GetSubTables() - { - HashSet keys = new HashSet(); - int prefixLen = m_path.Length + 1; - foreach (EntryInfo entry in m_ntCore.GetEntryInfo(m_pathWithSeperator, 0)) - { - string relativeKey = entry.Name.Substring(prefixLen); - int endSubTable = relativeKey.IndexOf(PathSeperatorChar); - if (endSubTable == -1) - continue; - keys.Add(relativeKey.Substring(0, endSubTable)); - } - return keys; - } - - /// - /// Returns the at the specified key. If there is no - /// table at the specified key, it will create a new table. - /// - /// The key name. - /// The to be returned. - public ITable GetSubTable(string key) - { - return new IndependentNetworkTable(m_ntCore, m_pathWithSeperator + key); - } - - /// - /// Makes a key's value persistent through program restarts. - /// - /// The key name (cannot be null). - public void SetPersistent(string key) - { - SetFlags(key, EntryFlags.Persistent); - } - - /// - /// Stop making a key's value persistent through program restarts. - /// - /// The key name (cannot be null). - public void ClearPersistent(string key) - { - ClearFlags(key, EntryFlags.Persistent); - } - - /// - /// Returns whether a value is persistent through program restarts. - /// - /// The key name (cannot be null). - /// True if the value is persistent. - public bool IsPersistent(string key) - { - return GetFlags(key).HasFlag(EntryFlags.Persistent); - } - - /// - /// Sets flags on the specified key in this table. - /// - /// The key name. - /// The flags to set. (Bitmask) - public void SetFlags(string key, EntryFlags flags) - { - m_ntCore.SetEntryFlags(m_pathWithSeperator + key, GetFlags(key) | flags); - } - - /// - /// Clears flags on the specified key in this table. - /// - /// The key name. - /// The flags to clear. (Bitmask) - public void ClearFlags(string key, EntryFlags flags) - { - m_ntCore.SetEntryFlags(m_pathWithSeperator + key, GetFlags(key) & ~flags); - } - - /// - /// Returns the flags for the specified key. - /// - /// The key name. - /// The flags attached to the key. - public EntryFlags GetFlags(string key) - { - return m_ntCore.GetEntryFlags(m_pathWithSeperator + key); - } - - /// - /// Deletes the specifed key in this table. - /// - /// The key name. - public void Delete(string key) - { - m_ntCore.DeleteEntry(m_pathWithSeperator + key); - } - - /// - /// Flushes all updated values immediately to the network. - /// - /// - /// Note that this is rate-limited to protect the network from flooding. - /// This is primarily useful for synchronizing network updates with user code. - /// - public void Flush() - { - m_ntCore.Flush(); - } - - /// - /// Saves persistent keys to a file. The server does this automatically. - /// - /// The file name. - /// Thrown if there is an error - /// saving the file. - public void SavePersistent(string filename) - { - m_ntCore.SavePersistent(filename); - } - - /// - /// Loads persistent keys from a file. The server does this automatically. - /// - /// The file name. - /// A List of warnings (errors result in an exception instead.) - /// Thrown if there is an error - /// loading the file. - public IList LoadPersistent(string filename) - { - return m_ntCore.LoadPersistent(filename); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public Value GetValue(string key) - { - string localPath = m_pathWithSeperator + key; - var v = m_ntCore.GetEntryValue(localPath); - if (v == null) throw new TableKeyNotDefinedException(localPath); - return v; - } - - /// - public Value GetValue(string key, Value defaultValue) - { - string localPath = m_pathWithSeperator + key; - var v = m_ntCore.GetEntryValue(localPath); - if (v == null) return defaultValue; - return v; - } - - /// - public bool PutValue(string key, Value value) - { - key = m_pathWithSeperator + key; - return m_ntCore.SetEntryValue(key, value); - } - - /// - public bool PutNumber(string key, double value) - { - - return m_ntCore.SetEntryDouble(m_pathWithSeperator + key, value); - } - - /// - public double GetNumber(string key, double defaultValue) - { - - return m_ntCore.GetEntryDouble(m_pathWithSeperator + key, defaultValue); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public double GetNumber(string key) - { - - return m_ntCore.GetEntryDouble(m_pathWithSeperator + key); - } - - /// - public bool PutString(string key, string value) - { - - return m_ntCore.SetEntryString(m_pathWithSeperator + key, value); - } - - /// - public string GetString(string key, string defaultValue) - { - - return m_ntCore.GetEntryString(m_pathWithSeperator + key, defaultValue); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public string GetString(string key) - { - - return m_ntCore.GetEntryString(m_pathWithSeperator + key); - } - - /// - public bool PutBoolean(string key, bool value) - { - - return m_ntCore.SetEntryBoolean(m_pathWithSeperator + key, value); - } - - /// - public bool GetBoolean(string key, bool defaultValue) - { - - return m_ntCore.GetEntryBoolean(m_pathWithSeperator + key, defaultValue); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public bool GetBoolean(string key) - { - - return m_ntCore.GetEntryBoolean(m_pathWithSeperator + key); - } - - /// - public bool PutStringArray(string key, IList value) - { - - return m_ntCore.SetEntryStringArray(m_pathWithSeperator + key, value); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public string[] GetStringArray(string key) - { - - return m_ntCore.GetEntryStringArray(m_pathWithSeperator + key); - } - - /// - public string[] GetStringArray(string key, string[] defaultValue) - { - - return m_ntCore.GetEntryStringArray(m_pathWithSeperator + key, defaultValue); - - } - - /// - public bool PutNumberArray(string key, IList value) - { - - return m_ntCore.SetEntryDoubleArray(m_pathWithSeperator + key, value); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public double[] GetNumberArray(string key) - { - - return m_ntCore.GetEntryDoubleArray(m_pathWithSeperator + key); - } - - /// - public double[] GetNumberArray(string key, double[] defaultValue) - { - - return m_ntCore.GetEntryDoubleArray(m_pathWithSeperator + key, defaultValue); - } - - /// - public bool PutBooleanArray(string key, IList value) - { - - return m_ntCore.SetEntryBooleanArray(m_pathWithSeperator + key, value); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public bool[] GetBooleanArray(string key) - { - - return m_ntCore.GetEntryBooleanArray(m_pathWithSeperator + key); - } - - /// - public bool PutRaw(string key, IList value) - { - - return m_ntCore.SetEntryRaw(m_pathWithSeperator + key, value); - } - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public byte[] GetRaw(string key) - { - - return m_ntCore.GetEntryRaw(m_pathWithSeperator + key); - } - /// - public byte[] GetRaw(string key, byte[] defaultValue) - { - - return m_ntCore.GetEntryRaw(m_pathWithSeperator + key, defaultValue); - } - - /// - public bool[] GetBooleanArray(string key, bool[] defaultValue) - { - - return m_ntCore.GetEntryBooleanArray(m_pathWithSeperator + key, defaultValue); - } - - private readonly Dictionary> m_listenerMap = new Dictionary>(); - - private readonly Dictionary, List> m_actionListenerMap = new Dictionary, List>(); - - /// - public void AddTableListenerEx(ITableListener listener, NotifyFlags flags) - { - if (!m_listenerMap.TryGetValue(listener, out List adapters)) - { - adapters = new List(); - m_listenerMap.Add(listener, adapters); - } - - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - if (relativeKey.IndexOf(PathSeperatorChar) != -1) - { - return; - } - listener.ValueChanged(this, relativeKey, value, flags_); - }; - - int id = m_ntCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - - /// - public void AddTableListenerEx(string key, ITableListener listener, NotifyFlags flags) - { - if (!m_listenerMap.TryGetValue(listener, out List adapters)) - { - adapters = new List(); - m_listenerMap.Add(listener, adapters); - } - string fullKey = m_pathWithSeperator + key; - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, funcKey, value, flags_) => - { - if (!funcKey.Equals(fullKey)) - return; - listener.ValueChanged(this, key, value, flags_); - }; - - int id = m_ntCore.AddEntryListener(fullKey, func, flags); - - adapters.Add(id); - } - - /// - public void AddSubTableListener(ITableListener listener, bool localNotify) - { - if (!m_listenerMap.TryGetValue(listener, out List adapters)) - { - adapters = new List(); - m_listenerMap.Add(listener, adapters); - } - HashSet notifiedTables = new HashSet(); - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - int endSubTable = relativeKey.IndexOf(PathSeperatorChar); - if (endSubTable == -1) - return; - string subTableKey = relativeKey.Substring(0, endSubTable); - if (notifiedTables.Contains(subTableKey)) - return; - notifiedTables.Add(subTableKey); - listener.ValueChanged(this, subTableKey, null, flags_); - }; - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (localNotify) - flags |= NotifyFlags.NotifyLocal; - int id = m_ntCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - - /// - public void AddTableListener(ITableListener listener, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(listener, flags); - } - - /// - public void AddTableListener(string key, ITableListener listener, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(key, listener, flags); - } - - /// - public void AddSubTableListener(ITableListener listener) - { - AddSubTableListener(listener, false); - } - - /// - public void RemoveTableListener(ITableListener listener) - { - if (m_listenerMap.TryGetValue(listener, out List adapters)) - { - foreach (int t in adapters) - { - m_ntCore.RemoveEntryListener(t); - } - adapters.Clear(); - } - } - - - /// - public void AddTableListenerEx(Action listenerDelegate, NotifyFlags flags) - { - if (!m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - adapters = new List(); - m_actionListenerMap.Add(listenerDelegate, adapters); - } - - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - if (relativeKey.IndexOf(PathSeperatorChar) != -1) - { - return; - } - listenerDelegate(this, relativeKey, value, flags_); - }; - - int id = m_ntCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - - /// - public void AddTableListenerEx(string key, Action listenerDelegate, NotifyFlags flags) - { - if (!m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - adapters = new List(); - m_actionListenerMap.Add(listenerDelegate, adapters); - } - string fullKey = m_pathWithSeperator + key; - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, funcKey, value, flags_) => - { - if (!funcKey.Equals(fullKey)) - return; - listenerDelegate(this, key, value, flags_); - }; - - int id = m_ntCore.AddEntryListener(fullKey, func, flags); - - adapters.Add(id); - } - - /// - public void AddSubTableListener(Action listenerDelegate, bool localNotify) - { - if (!m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - adapters = new List(); - m_actionListenerMap.Add(listenerDelegate, adapters); - } - HashSet notifiedTables = new HashSet(); - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - int endSubTable = relativeKey.IndexOf(PathSeperatorChar); - if (endSubTable == -1) - return; - string subTableKey = relativeKey.Substring(0, endSubTable); - if (notifiedTables.Contains(subTableKey)) - return; - notifiedTables.Add(subTableKey); - listenerDelegate(this, subTableKey, null, flags_); - }; - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (localNotify) - flags |= NotifyFlags.NotifyLocal; - int id = m_ntCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - - /// - public void AddTableListener(Action listenerDelegate, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(listenerDelegate, flags); - } - - /// - public void AddTableListener(string key, Action listenerDelegate, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(key, listenerDelegate, flags); - } - - /// - public void AddSubTableListener(Action listenerDelegate) - { - AddSubTableListener(listenerDelegate, false); - } - - /// - public void RemoveTableListener(Action listenerDelegate) - { - if (m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - foreach (int t in adapters) - { - m_ntCore.RemoveEntryListener(t); - } - adapters.Clear(); - } - } - - private readonly Dictionary m_connectionListenerMap = - new Dictionary(); - - private readonly Dictionary, int> m_actionConnectionListenerMap - = new Dictionary, int>(); - - /// - public void AddConnectionListener(IRemoteConnectionListener listener, bool immediateNotify) - { - - if (m_connectionListenerMap.ContainsKey(listener)) - { - throw new ArgumentException("Cannot add the same listener twice", nameof(listener)); - } - - ConnectionListenerCallback func = (uid, connected, conn) => - { - if (connected) listener.Connected(this, conn); - else listener.Disconnected(this, conn); - }; - int id = m_ntCore.AddConnectionListener(func, immediateNotify); - m_connectionListenerMap.Add(listener, id); - - } - - /// - public void RemoveConnectionListener(IRemoteConnectionListener listener) - { - if (m_connectionListenerMap.TryGetValue(listener, out int val)) - { - m_ntCore.RemoveConnectionListener(val); - } - } - - /// - public void AddConnectionListener(Action listener, bool immediateNotify) - { - if (m_actionConnectionListenerMap.ContainsKey(listener)) - { - throw new ArgumentException("Cannot add the same listener twice", nameof(listener)); - } - - ConnectionListenerCallback func = (uid, connected, conn) => - { - listener(this, conn, connected); - }; - int id = m_ntCore.AddConnectionListener(func, immediateNotify); - m_actionConnectionListenerMap.Add(listener, id); - } - - /// - public void RemoveConnectionListener(Action listener) - { - if (m_actionConnectionListenerMap.TryGetValue(listener, out int val)) - { - m_ntCore.RemoveConnectionListener(val); - } - } - - /// - /// Gets if the NetworkTables is connected to a client or server. - /// - public bool IsConnected - { - get - { - var conns = m_ntCore.GetConnections(); - return conns.Count > 0; - } - } - - /// - public bool SetDefaultValue(string key, Value defaultValue) - { - return m_ntCore.SetDefaultEntryValue(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultNumber(string key, double defaultValue) - { - return m_ntCore.SetDefaultEntryDouble(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultBoolean(string key, bool defaultValue) - { - return m_ntCore.SetDefaultEntryBoolean(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultString(string key, string defaultValue) - { - return m_ntCore.SetDefaultEntryString(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultRaw(string key, IList defaultValue) - { - return m_ntCore.SetDefaultEntryRaw(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultBooleanArray(string key, IList defaultValue) - { - return m_ntCore.SetDefaultEntryBooleanArray(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultNumberArray(string key, IList defaultValue) - { - return m_ntCore.SetDefaultEntryDoubleArray(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultStringArray(string key, IList defaultValue) - { - return m_ntCore.SetDefaultEntryStringArray(m_pathWithSeperator + key, defaultValue); - } - - /// - public bool IsServer => !m_ntCore.Client; - } -} diff --git a/src/FRC.NetworkTables/Independent/IndependentNtCore.cs b/src/FRC.NetworkTables/Independent/IndependentNtCore.cs deleted file mode 100644 index 9abd4b9..0000000 --- a/src/FRC.NetworkTables/Independent/IndependentNtCore.cs +++ /dev/null @@ -1,599 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NetworkTables.Exceptions; -using NetworkTables.Logging; - -namespace NetworkTables.Independent -{ - /// - /// This class contains all NtCore methods exposed by the underlying library, running in an independent state - /// - /// The static , and - /// all run using the same backend library. This means you cannot have both a client and a server running - /// in the same user program. The - /// , and - /// get around this restriction, and allow multiple clients and servers in the same user program. Note that this is - /// not supported by NetworkTables.Core. - public class IndependentNtCore : IDisposable - { - /// - public const int DefaultPort = NetworkTable.DefaultPort; - - internal readonly Storage m_storage; - internal readonly Notifier m_notifier; - internal readonly Dispatcher m_dispatcher; - internal readonly RpcServer m_rpcServer; - - private readonly object m_lockObject = new object(); - - /// - /// Creates a new NtCore object to run independently of all other NtCore objects - /// - public IndependentNtCore() - { - m_notifier = new Notifier(); - m_rpcServer = new RpcServer(); - m_storage = new Storage(m_notifier, m_rpcServer); - m_dispatcher = new Dispatcher(m_storage, m_notifier); - } - - /// - public void Dispose() - { - StopClient(); - StopServer(); - StopNotifier(); - StopRpcServer(); - m_dispatcher.Dispose(); - m_storage.Dispose(); - m_rpcServer.Dispose(); - m_notifier.Dispose(); - } - - /// - public bool SetDefaultEntryBoolean(string name, bool value) - { - return m_storage.SetDefaultEntryValue(name, Value.MakeBoolean(value)); - } - - /// - public bool SetDefaultEntryDouble(string name, double value) - { - return m_storage.SetDefaultEntryValue(name, Value.MakeDouble(value)); - } - - /// - public bool SetDefaultEntryString(string name, string value) - { - return m_storage.SetDefaultEntryValue(name, Value.MakeString(value)); - } - - /// - public bool SetDefaultEntryBooleanArray(string name, IList value) - { - return m_storage.SetDefaultEntryValue(name, Value.MakeBooleanArray(value)); - } - - /// - public bool SetDefaultEntryDoubleArray(string name, IList value) - { - return m_storage.SetDefaultEntryValue(name, Value.MakeDoubleArray(value)); - } - - /// - public bool SetDefaultEntryStringArray(string name, IList value) - { - return m_storage.SetDefaultEntryValue(name, Value.MakeStringArray(value)); - } - - /// - public bool SetDefaultEntryRaw(string name, IList value) - { - return m_storage.SetDefaultEntryValue(name, Value.MakeRaw(value)); - } - - /// - public bool SetEntryBoolean(string name, bool value, bool force = false) - { - if (force) - { - m_storage.SetEntryTypeValue(name, Value.MakeBoolean(value)); - return true; - } - return m_storage.SetEntryValue(name, Value.MakeBoolean(value)); - } - - /// - public bool SetEntryDouble(string name, double value, bool force = false) - { - if (force) - { - m_storage.SetEntryTypeValue(name, Value.MakeDouble(value)); - return true; - } - return m_storage.SetEntryValue(name, Value.MakeDouble(value)); - - } - - /// - public bool SetEntryString(string name, string value, bool force = false) - { - if (force) - { - m_storage.SetEntryTypeValue(name, Value.MakeString(value)); - return true; - } - return m_storage.SetEntryValue(name, Value.MakeString(value)); - - } - - /// - public bool SetEntryBooleanArray(string name, IList value, bool force = false) - { - if (force) - { - m_storage.SetEntryTypeValue(name, Value.MakeBooleanArray(value)); - return true; - } - return m_storage.SetEntryValue(name, Value.MakeBooleanArray(value)); - - } - - /// - public bool SetEntryDoubleArray(string name, IList value, bool force = false) - { - if (force) - { - m_storage.SetEntryTypeValue(name, Value.MakeDoubleArray(value)); - return true; - } - return m_storage.SetEntryValue(name, Value.MakeDoubleArray(value)); - - } - - /// - public bool SetEntryStringArray(string name, IList value, bool force = false) - { - if (force) - { - m_storage.SetEntryTypeValue(name, Value.MakeStringArray(value)); - return true; - } - return m_storage.SetEntryValue(name, Value.MakeStringArray(value)); - - } - - /// - public bool SetEntryRaw(string name, IList value, bool force = false) - { - if (force) - { - m_storage.SetEntryTypeValue(name, Value.MakeRaw(value)); - return true; - } - return m_storage.SetEntryValue(name, Value.MakeRaw(value)); - - } - - - - #region ThrowingGetters - - /// - public bool GetEntryBoolean(string name) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsBoolean()) throw NtCore.GetValueException(name, v, NtType.Boolean); - return v.GetBoolean(); - - } - - /// - public double GetEntryDouble(string name) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsDouble()) throw NtCore.GetValueException(name, v, NtType.Double); - return v.GetDouble(); - - } - - /// - public string GetEntryString(string name) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsString()) throw NtCore.GetValueException(name, v, NtType.String); - return v.GetString(); - - } - - /// - public bool[] GetEntryBooleanArray(string name) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsBooleanArray()) throw NtCore.GetValueException(name, v, NtType.BooleanArray); - return v.GetBooleanArray(); - - } - - /// - public double[] GetEntryDoubleArray(string name) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsDoubleArray()) throw NtCore.GetValueException(name, v, NtType.DoubleArray); - return v.GetDoubleArray(); - - } - - /// - public string[] GetEntryStringArray(string name) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsStringArray()) throw NtCore.GetValueException(name, v, NtType.StringArray); - return v.GetStringArray(); - - } - - /// - public byte[] GetEntryRaw(string name) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsRaw()) throw NtCore.GetValueException(name, v, NtType.Raw); - return v.GetRaw(); - - } - - #endregion - - #region DefaultGetters - - /// - public bool GetEntryBoolean(string name, bool defaultValue) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsBoolean()) return defaultValue; - return v.GetBoolean(); - - } - - /// - public double GetEntryDouble(string name, double defaultValue) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsDouble()) return defaultValue; - return v.GetDouble(); - - } - - /// - public string GetEntryString(string name, string defaultValue) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsString()) return defaultValue; - return v.GetString(); - - } - - /// - public bool[] GetEntryBooleanArray(string name, bool[] defaultValue) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsBooleanArray()) - { - return defaultValue; - } - return v.GetBooleanArray(); - - } - - /// - public double[] GetEntryDoubleArray(string name, double[] defaultValue) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsDoubleArray()) - { - - return defaultValue; - } - return v.GetDoubleArray(); - - } - - /// - public string[] GetEntryStringArray(string name, string[] defaultValue) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsStringArray()) - { - return defaultValue; - } - return v.GetStringArray(); - - } - - /// - public byte[] GetEntryRaw(string name, byte[] defaultValue) - { - var v = m_storage.GetEntryValue(name); - if (v == null || !v.IsRaw()) - { - return defaultValue; - } - return v.GetRaw(); - - } - #endregion - - /// - public Value GetEntryValue(string name) - { - return m_storage.GetEntryValue(name); - } - - /// - public bool SetEntryValue(string name, Value value) - { - return m_storage.SetEntryValue(name, value); - } - - /// - public bool SetDefaultEntryValue(string name, Value value) - { - return m_storage.SetDefaultEntryValue(name, value); - } - - /// - public void SetEntryTypeValue(string name, Value value) - { - m_storage.SetEntryTypeValue(name, value); - } - - /// - public void SetEntryFlags(string name, EntryFlags flags) - { - m_storage.SetEntryFlags(name, flags); - } - - /// - public EntryFlags GetEntryFlags(string name) - { - return m_storage.GetEntryFlags(name); - } - - /// - public void DeleteEntry(string name) - { - m_storage.DeleteEntry(name); - } - - /// - public void DeleteAllEntries() - { - m_storage.DeleteAllEntries(); - } - - /// - public List GetEntryInfo(string prefix, NtType types) - { - return m_storage.GetEntryInfo(prefix, types); - } - - /// - public NtType GetType(string name) - { - var v = GetEntryValue(name); - if (v == null) return NtType.Unassigned; - return v.Type; - } - - /// - public bool ContainsEntry(string name) - { - return GetType(name) != NtType.Unassigned; - } - - /// - public void Flush() - { - m_dispatcher.Flush(); - } - - /// - public int AddEntryListener(string prefix, EntryListenerCallback callback, NotifyFlags flags) - { - Notifier notifier = m_notifier; - int uid = notifier.AddEntryListener(prefix, callback, flags); - notifier.Start(); - if ((flags & NotifyFlags.NotifyImmediate) != 0) - m_storage.NotifyEntries(prefix, callback); - return uid; - } - - /// - public void RemoveEntryListener(int uid) - { - m_notifier.RemoveEntryListener(uid); - } - - /// - public int AddConnectionListener(ConnectionListenerCallback callback, bool immediateNotify) - { - Notifier notifier = m_notifier; - int uid = notifier.AddConnectionListener(callback); - notifier.Start(); - if (immediateNotify) m_dispatcher.NotifyConnections(callback); - return uid; - } - - /// - public void RemoveConnectionListener(int uid) - { - m_notifier.RemoveConnectionListener(uid); - } - - /// - public bool NotifierDestroyed() - { - return m_notifier.Destroyed(); - } - - /// - public void StartClient(IList servers) - { - - lock (m_lockObject) - { - CheckInit(); - Client = true; - Running = true; - } - - m_dispatcher.StartClient(); - m_dispatcher.SetServer(servers); - } - - /// - public void StartServer(string persistFilename, string listenAddress, int port) - { - lock (m_lockObject) - { - CheckInit(); - Client = false; - Running = true; - } - m_dispatcher.StartServer(persistFilename, listenAddress, port); - } - - /// - public void StopServer() - { - lock (m_lockObject) - { - Running = false; - } - m_dispatcher.Stop(); - } - - /// - /// Gets or sets the remote name for this table - /// - public string RemoteName - { - get - { - return m_dispatcher.Identity; - } - set - { - CheckInit(); - m_dispatcher.Identity = value; - } - } - - /// - /// Gets if this table is a client - /// - public bool Client { get; private set; } - /// - /// Gets if this table is running - /// - public bool Running { get; private set; } - - private void CheckInit() - { - lock (m_lockObject) - { - if (Running) - throw new InvalidOperationException("Operation cannot be completed while NtCore is running"); - } - } - - /// - public void StartClient(string serverName, int port) - { - lock (m_lockObject) - { - CheckInit(); - Client = true; - Running = true; - m_dispatcher.StartClient(); - m_dispatcher.SetServer(serverName, port); - } - } - - /// - public void StopClient() - { - lock (m_lockObject) - { - Running = false; - m_dispatcher.Stop(); - } - } - - /// - public void StopRpcServer() - { - m_rpcServer.Stop(); - } - - /// - public void StopNotifier() - { - m_notifier.Stop(); - } - - /// - /// Gets or sets the update rate for this table (seconds) - /// - public double UpdateRate - { - get { return m_dispatcher.UpdateRate; } - set { m_dispatcher.UpdateRate = value; } - } - - /// - public List GetConnections() - { - return m_dispatcher.GetConnections(); - } - - /// - public string SavePersistent(string filename) - { - return m_storage.SavePersistent(filename, false); - } - - /// - public string LoadPersistent(string filename, Action warn) - { - return m_storage.LoadPersistent(filename, warn); - } - - /// - public long Now() - { - return Support.Timestamp.Now(); - } - - /// - public void SetLogger(LogFunc func, LogLevel minLevel) - { - Logger logger = Logger.Instance; - logger.SetLogger(func); - logger.MinLevel = minLevel; - } - - /// - public List LoadPersistent(string filename) - { - List warns = new List(); - var err = LoadPersistent(filename, (i, s) => - { - warns.Add($"{i}: {s}"); - }); - if (err != null) throw new PersistentException($"Load Persistent Failed: {err}"); - return warns; - } - } -} diff --git a/src/FRC.NetworkTables/Independent/IndependentRemoteProcedureCall.cs b/src/FRC.NetworkTables/Independent/IndependentRemoteProcedureCall.cs deleted file mode 100644 index 0fbafd6..0000000 --- a/src/FRC.NetworkTables/Independent/IndependentRemoteProcedureCall.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace NetworkTables.Independent -{ - /// - /// A RemoteProcedureCall class that can be run without the static NetworkTables implmentation - /// - public class IndependentRemoteProcedureCall - { - private readonly IndependentNtCore m_ntCore; - - /// - /// Creates a new object from a object - /// - /// The object to use - public IndependentRemoteProcedureCall(IndependentNtCore ntCore) - { - m_ntCore = ntCore; - } - - /// - public void CreateRpc(string name, IList def, RpcCallback callback) - { - m_ntCore.m_storage.CreateRpc(name, def, callback); - } - - /// - public void CreateRpc(string name, RpcDefinition def, RpcCallback callback) - { - m_ntCore.m_storage.CreateRpc(name, PackRpcDefinition(def), callback); - } - - /// - public void CreatePolledRpc(string name, IList def) - { - m_ntCore.m_storage.CreatePolledRpc(name, def); - } - - /// - public void CreatePolledRpc(string name, RpcDefinition def) - { - m_ntCore.m_storage.CreatePolledRpc(name, PackRpcDefinition(def)); - } - - /// - public async Task PollRpcAsync(CancellationToken token) - { - return await m_ntCore.m_rpcServer.PollRpcAsync(token); - } - - /// - public bool PollRpc(bool blocking, TimeSpan timeout, out RpcCallInfo callInfo) - { - return m_ntCore.m_rpcServer.PollRpc(blocking, timeout, out callInfo); - } - - /// - public bool PollRpc(bool blocking, out RpcCallInfo callInfo) - { - return m_ntCore.m_rpcServer.PollRpc(blocking, out callInfo); - } - - /// - public void PostRpcResponse(long rpcId, long callUid, IList result) - { - m_ntCore.m_rpcServer.PostRpcResponse(rpcId, callUid, result); - } - - /// - public long CallRpc(string name, IList param) - { - return m_ntCore.m_storage.CallRpc(name, param); - } - - /// - public long CallRpc(string name, IList param) - { - return m_ntCore.m_storage.CallRpc(name, PackRpcValues(param)); - } - - /// - public async Task> GetRpcResultAsync(long callUid, CancellationToken token) - { - return await m_ntCore.m_storage.GetRpcResultAsync(callUid, token); - } - - /// - public async Task> CallRpcWithResultAsync(string name, CancellationToken token, IList param) - { - long id = CallRpc(name, param); - return await GetRpcResultAsync(id, token).ConfigureAwait(false); - } - - /// - public async Task> CallRpcWithResultAsync(string name, CancellationToken token, IList param) - { - long id = CallRpc(name, param); - return await GetRpcResultAsync(id, token).ConfigureAwait(false); - } - - /// - public bool GetRpcResult(bool blocking, long callUid, TimeSpan timeout, out byte[] result) - { - return m_ntCore.m_storage.GetRpcResult(blocking, callUid, timeout, out result); - } - - /// - public bool GetRpcResult(bool blocking, long callUid, out byte[] result) - { - return m_ntCore.m_storage.GetRpcResult(blocking, callUid, out result); - } - - /// - public byte[] PackRpcDefinition(RpcDefinition def) - { - return RemoteProcedureCall.PackRpcDefinition(def); - } - - /// - public bool UnpackRpcDefinition(IList packed, ref RpcDefinition def) - { - return RemoteProcedureCall.UnpackRpcDefinition(packed, ref def); - } - - /// - public byte[] PackRpcValues(IList values) - { - return RemoteProcedureCall.PackRpcValues(values); - } - - /// - public List UnpackRpcValues(IList packed, IList types) - { - return RemoteProcedureCall.UnpackRpcValues(packed, types); - } - } -} diff --git a/src/FRC.NetworkTables/Interfaces/IServerOverridable.cs b/src/FRC.NetworkTables/Interfaces/IServerOverridable.cs deleted file mode 100644 index dfc697b..0000000 --- a/src/FRC.NetworkTables/Interfaces/IServerOverridable.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading.Tasks; - -namespace NetworkTables.Interfaces -{ - internal interface IServerOverridable - { - void SetServerOverride(IPAddress address, int port); - void ClearServerOverride(); - } -} diff --git a/src/FRC.NetworkTables/Logging/Logger.cs b/src/FRC.NetworkTables/Logging/Logger.cs deleted file mode 100644 index 755d23d..0000000 --- a/src/FRC.NetworkTables/Logging/Logger.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.IO; -using System.Runtime.CompilerServices; -// ReSharper disable ExplicitCallerInfoArgument - -namespace NetworkTables.Logging -{ - internal class Logger - { - private static Logger s_instance; - - public static Logger Instance => s_instance ?? (s_instance = new Logger()); - - internal Logger() - { - m_func = DefLogFunc; - } - - private LogFunc m_func; - - public LogLevel MinLevel { get; set; } = 0; - - public void SetLogger(LogFunc func) - { - m_func = func; - } - - public void SetDefaultLogger() - { - m_func = DefLogFunc; - } - - public void Log(LogLevel level, string file, int line, string msg) - { - if (m_func == null || level < MinLevel) return; - m_func(level, file, line, msg); - } - - public bool HasLogger() - { - return m_func != null; - } - - private static void DefLogFunc(LogLevel level, string file, int line, string msg) - { - if (level == LogLevel.LogInfo) - { - Console.Error.WriteLine($"NT: {msg}"); - } - - string levelmsg; - if (level >= LogLevel.LogCritical) - levelmsg = "CRITICAL"; - else if (level >= LogLevel.LogError) - levelmsg = "ERROR"; - else if (level >= LogLevel.LogWarning) - levelmsg = "WARNING"; - else - return; - string fname = Path.GetFileName(file); - Console.Error.WriteLine($"NT: {levelmsg}: {msg} ({fname}:{line.ToString()})"); - } - - - // ReSharper disable once UnusedParameter.Global - public static void Log(Logger logger, LogLevel level, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - if (logger == null) return; - do - { - if (logger.MinLevel <= level && logger.HasLogger()) - { - logger.Log(level, filePath, lineNumber, msg); - } - } - while (false); - } - - public static void Error(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogError, msg, memberName, filePath, lineNumber); - } - - public static void Warning(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogWarning, msg, memberName, filePath, lineNumber); - } - - public static void Info(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogInfo, msg, memberName, filePath, lineNumber); - } - - public static void Debug(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogDebug, msg, memberName, filePath, lineNumber); - } - - public static void Debug1(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogDebug1, msg, memberName, filePath, lineNumber); - } - - public static void Debug2(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogDebug2, msg, memberName, filePath, lineNumber); - } - - public static void Debug3(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogDebug3, msg, memberName, filePath, lineNumber); - } - - public static void Debug4(Logger logger, string msg, [CallerMemberName] string memberName = "", - [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) - { - Log(logger, LogLevel.LogDebug4, msg, memberName, filePath, lineNumber); - } - } - -} diff --git a/src/FRC.NetworkTables/Message.cs b/src/FRC.NetworkTables/Message.cs deleted file mode 100644 index 3ab64b6..0000000 --- a/src/FRC.NetworkTables/Message.cs +++ /dev/null @@ -1,388 +0,0 @@ -using System.Collections.Generic; -using NetworkTables.Wire; -using static NetworkTables.Message.MsgType; -using static NetworkTables.Logging.Logger; -using NetworkTables.Logging; - -namespace NetworkTables -{ - internal class Message - { - public enum MsgType : uint - { - Unknown = 0xffff, - KeepAlive = 0x00, - ClientHello = 0x01, - ProtoUnsup = 0x02, - ServerHelloDone = 0x03, - ServerHello = 0x04, - ClientHelloDone = 0x05, - EntryAssign = 0x10, - EntryUpdate = 0x11, - FlagsUpdate = 0x12, - EntryDelete = 0x13, - ClearEntries = 0x14, - ExecuteRpc = 0x20, - RpcResponse = 0x21 - }; - - public delegate NtType GetEntryTypeFunc(uint id); - - private string m_str = ""; - - public Message() - { - Type = Unknown; - Id = 0; - Flags = 0; - SeqNumUid = 0; - } - - private Message(MsgType type) - { - Type = type; - Id = 0; - Flags = 0; - SeqNumUid = 0; - } - - public MsgType Type { get; } - - public bool Is(MsgType type) - { - return Type == type; - } - - public string Str => m_str; - - public Value Val { get; private set; } = new Value(); - - public uint Id { get; private set; } - - public uint Flags { get; private set; } - - public uint SeqNumUid { get; private set; } - - private const uint ClearAllMagic = 0xD06CB27Au; - - public void Write(WireEncoder encoder) - { - switch (Type) - { - case MsgType.KeepAlive: - encoder.Write8((byte)MsgType.KeepAlive); - break; - case MsgType.ClientHello: - encoder.Write8((byte)MsgType.ClientHello); - encoder.Write16((ushort)encoder.ProtoRev); - if (encoder.ProtoRev < 0x0300u) return; - encoder.WriteString(m_str); - break; - case MsgType.ProtoUnsup: - encoder.Write8((byte)MsgType.ProtoUnsup); - encoder.Write16((ushort)encoder.ProtoRev); - break; - case MsgType.ServerHelloDone: - encoder.Write8((byte)MsgType.ServerHelloDone); - break; - case MsgType.ServerHello: - if (encoder.ProtoRev < 0x0300u) return; // new message in version 3.0 - encoder.Write8((byte)MsgType.ServerHello); - encoder.Write8((byte)Flags); - encoder.WriteString(m_str); - break; - case MsgType.ClientHelloDone: - if (encoder.ProtoRev < 0x0300u) return; // new message in version 3.0 - encoder.Write8((byte)MsgType.ClientHelloDone); - break; - case MsgType.EntryAssign: - encoder.Write8((byte)MsgType.EntryAssign); - encoder.WriteString(m_str); - encoder.WriteType(Val.Type); - encoder.Write16((ushort)Id); - encoder.Write16((ushort)SeqNumUid); - if (encoder.ProtoRev >= 0x0300u) encoder.Write8((byte)Flags); - encoder.WriteValue(Val); - break; - case MsgType.EntryUpdate: - encoder.Write8((byte)MsgType.EntryUpdate); - encoder.Write16((ushort)Id); - encoder.Write16((ushort)SeqNumUid); - if (encoder.ProtoRev >= 0x0300u) encoder.WriteType(Val.Type); - encoder.WriteValue(Val); - break; - case MsgType.FlagsUpdate: - if (encoder.ProtoRev < 0x0300u) return; // new message in version 3.0 - encoder.Write8((byte)MsgType.FlagsUpdate); - encoder.Write16((ushort)Id); - encoder.Write8((byte)Flags); - break; - case MsgType.EntryDelete: - if (encoder.ProtoRev < 0x0300u) return; // new message in version 3.0 - encoder.Write8((byte)MsgType.EntryDelete); - encoder.Write16((ushort)Id); - break; - case MsgType.ClearEntries: - if (encoder.ProtoRev < 0x0300u) return; // new message in version 3.0 - encoder.Write8((byte)MsgType.ClearEntries); - encoder.Write32(ClearAllMagic); - break; - case MsgType.ExecuteRpc: - if (encoder.ProtoRev < 0x0300u) return; // new message in version 3.0 - encoder.Write8((byte)MsgType.ExecuteRpc); - encoder.Write16((ushort)Id); - encoder.Write16((ushort)SeqNumUid); - encoder.WriteValue(Val); - break; - case MsgType.RpcResponse: - if (encoder.ProtoRev < 0x0300u) return; // new message in version 3.0 - encoder.Write8((byte)MsgType.RpcResponse); - encoder.Write16((ushort)Id); - encoder.Write16((ushort)SeqNumUid); - encoder.WriteValue(Val); - break; - } - } - - public static Message Read(WireDecoder decoder, GetEntryTypeFunc getEntryType) - { - byte msgType = 0; - if (!decoder.Read8(ref msgType)) return null; - MsgType mtype = (MsgType)msgType; - var msg = new Message(mtype); - NtType type = 0; - byte tmpB = 0; - ushort tmpUs = 0; - switch (mtype) - { - case MsgType.KeepAlive: - break; - case MsgType.ClientHello: - ushort protoRev = 0; - if (!decoder.Read16(ref protoRev)) return null; - msg.Id = protoRev; - if (protoRev >= 0x0300u) - { - if (!decoder.ReadString(ref msg.m_str)) return null; - } - break; - case MsgType.ProtoUnsup: - ushort rdproto = 0; - if (!decoder.Read16(ref rdproto)) return null; - msg.Id = rdproto; - break; - case MsgType.ServerHelloDone: - break; - case MsgType.ServerHello: - if (decoder.ProtoRev < 0x0300u) - { - decoder.Error = "received SERVER_HELLO_DONE in protocol < 3.0"; - return null; - } - byte rdflgs = 0; - if (!decoder.Read8(ref rdflgs)) return null; - msg.Flags = rdflgs; - if (!decoder.ReadString(ref msg.m_str)) return null; - break; - case MsgType.ClientHelloDone: - if (decoder.ProtoRev < 0x0300) - { - decoder.Error = "recieved SERVER_HELLO_DONE in protocol < 3.0"; - return null; - } - break; - case MsgType.EntryAssign: - if (!decoder.ReadString(ref msg.m_str)) return null; - if (!decoder.ReadType(ref type)) return null; - if (!decoder.Read16(ref tmpUs)) return null; - msg.Id = tmpUs; - if (!decoder.Read16(ref tmpUs)) return null; - msg.SeqNumUid = tmpUs; - if (decoder.ProtoRev >= 0x0300) - { - if (!decoder.Read8(ref tmpB)) return null; - msg.Flags = tmpB; - } - msg.Val = decoder.ReadValue(type); - if (msg.Val == null) return null; - break; - case MsgType.EntryUpdate: - if (!decoder.Read16(ref tmpUs)) return null; - msg.Id = tmpUs; - if (!decoder.Read16(ref tmpUs)) return null; - msg.SeqNumUid = tmpUs; - if (decoder.ProtoRev >= 0x0300) - { - if (!decoder.ReadType(ref type)) return null; - } - else - { - type = getEntryType(msg.Id); - } - Debug4(Logger.Instance, $"update message data type: {type.GetString()}"); - msg.Val = decoder.ReadValue(type); - if (msg.Val == null) return null; - break; - case MsgType.FlagsUpdate: - if (decoder.ProtoRev < 0x0300) - { - decoder.Error = "received FLAGS_UPDATE in protocol < 3.0"; - return null; - } - if (!decoder.Read16(ref tmpUs)) return null; - msg.Id = tmpUs; - if (!decoder.Read8(ref tmpB)) return null; - msg.Flags = tmpB; - break; - case MsgType.EntryDelete: - if (decoder.ProtoRev < 0x0300) - { - decoder.Error = "received ENTRY_DELETE in protocol < 3.0"; - return null; - } - if (!decoder.Read16(ref tmpUs)) return null; - msg.Id = tmpUs; - break; - case MsgType.ClearEntries: - if (decoder.ProtoRev < 0x0300) - { - decoder.Error = "received CLEAR_ENTRIES in protocol < 3.0"; - return null; - } - uint magic = 0; - if (!decoder.Read32(ref magic)) return null; - if (magic != ClearAllMagic) - { - decoder.Error = "received incorrect CLEAR_ENTRIES magic value, ignoring"; - return null; - } - break; - case MsgType.ExecuteRpc: - if (decoder.ProtoRev < 0x0300) - { - decoder.Error = "received EXECUTE_RPC in protocol < 3.0"; - return null; - } - if (!decoder.Read16(ref tmpUs)) return null; - msg.Id = tmpUs; - if (!decoder.Read16(ref tmpUs)) return null; - msg.SeqNumUid = tmpUs; - ulong size; - if (!decoder.ReadUleb128(out size)) return null; - byte[] results; - if (!decoder.Read(out results, (int)size)) return null; - msg.Val = Value.MakeRpc(results, (int)size); - break; - case MsgType.RpcResponse: - if (decoder.ProtoRev < 0x0300) - { - decoder.Error = "received RPC_RESPONSE in protocol < 3.0"; - return null; - } - if (!decoder.Read16(ref tmpUs)) return null; - msg.Id = tmpUs; - if (!decoder.Read16(ref tmpUs)) return null; - msg.SeqNumUid = tmpUs; - ulong size2; - if (!decoder.ReadUleb128(out size2)) return null; - byte[] results2; - if (!decoder.Read(out results2, (int)size2)) return null; - msg.Val = Value.MakeRpc(results2, (int)size2); - break; - default: - decoder.Error = "unrecognized message type"; - Info(Logger.Instance, $"unrecognized message type: {msgType.ToString()}"); - return null; - } - return msg; - } - - public static Message KeepAlive() => new Message(MsgType.KeepAlive); - - public static Message ProtoUnsup() => new Message(MsgType.ProtoUnsup); - - public static Message ServerHelloDone() => new Message(MsgType.ServerHelloDone); - - public static Message ClientHelloDone() => new Message(MsgType.ClientHelloDone); - - public static Message ClearEntries() => new Message(MsgType.ClearEntries); - - public static Message ClientHello(string selfId) - { - var msg = new Message(MsgType.ClientHello) {m_str = selfId}; - return msg; - } - - public static Message ServerHello(uint flags, string selfId) - { - var msg = new Message(MsgType.ServerHello) - { - m_str = selfId, - Flags = flags - }; - return msg; - } - - public static Message EntryAssign(string name, uint id, uint seqNum, Value value, EntryFlags flags) - { - var msg = new Message(MsgType.EntryAssign) - { - m_str = name, - Val = value, - Id = id, - Flags = (uint) flags, - SeqNumUid = seqNum - }; - return msg; - } - - public static Message EntryUpdate(uint id, uint seqNum, Value value) - { - var msg = new Message(MsgType.EntryUpdate) - { - Val = value, - Id = id, - SeqNumUid = seqNum - }; - return msg; - } - - public static Message FlagsUpdate(uint id, EntryFlags flags) - { - var msg = new Message(MsgType.FlagsUpdate) - { - Id = id, - Flags = (uint) flags - }; - return msg; - } - - public static Message EntryDelete(uint id) - { - var msg = new Message(MsgType.EntryDelete) {Id = id}; - return msg; - } - - public static Message ExecuteRpc(uint id, uint uid, IList param) - { - var msg = new Message(MsgType.ExecuteRpc) - { - Val = Value.MakeRpc(param, param.Count), - Id = id, - SeqNumUid = uid - }; - return msg; - } - - public static Message RpcResponse(uint id, uint uid, IList results) - { - var msg = new Message(MsgType.RpcResponse) - { - Val = Value.MakeRpc(results, results.Count), - Id = id, - SeqNumUid = uid - }; - return msg; - } - } -} diff --git a/src/FRC.NetworkTables/MessageTypeExtensions.cs b/src/FRC.NetworkTables/MessageTypeExtensions.cs deleted file mode 100644 index 15d481f..0000000 --- a/src/FRC.NetworkTables/MessageTypeExtensions.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace NetworkTables -{ - internal static class MessageTypeExtensions - { - internal static string GetString(this Message.MsgType msgType) - { - switch (msgType) - { - case Message.MsgType.KeepAlive: - return "KeepAlive"; - case Message.MsgType.ClientHello: - return "ClientHello"; - case Message.MsgType.ProtoUnsup: - return "ProtoUnsup"; - case Message.MsgType.ServerHelloDone: - return "ServerHelloDone"; - case Message.MsgType.ServerHello: - return "ServerHello"; - case Message.MsgType.ClientHelloDone: - return "ClientHelloDone"; - case Message.MsgType.EntryAssign: - return "EntryAssign"; - case Message.MsgType.EntryUpdate: - return "EntryUpdate"; - case Message.MsgType.FlagsUpdate: - return "FlagsUpdate"; - case Message.MsgType.EntryDelete: - return "EntryDelete"; - case Message.MsgType.ClearEntries: - return "ClearEntries"; - case Message.MsgType.ExecuteRpc: - return "ExecuteRpc"; - case Message.MsgType.RpcResponse: - return "RpcResponse"; - default: - return "Unknown"; - } - } - - internal static string GetString(this NtType ntType) - { - switch (ntType) - { - case NtType.Boolean: - return "Boolean"; - case NtType.Double: - return "Double"; - case NtType.String: - return "String"; - case NtType.Raw: - return "Raw"; - case NtType.BooleanArray: - return "BooleanArray"; - case NtType.DoubleArray: - return "DoubleArray"; - case NtType.StringArray: - return "StringArray"; - case NtType.Rpc: - return "Rpc"; - default: - return "Unknown"; - } - } - } -} diff --git a/src/FRC.NetworkTables/NetworkConnection.cs b/src/FRC.NetworkTables/NetworkConnection.cs deleted file mode 100644 index 27b8279..0000000 --- a/src/FRC.NetworkTables/NetworkConnection.cs +++ /dev/null @@ -1,456 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using NetworkTables.Streams; -using NetworkTables.Support; -using NetworkTables.TcpSockets; -using NetworkTables.Wire; -using static NetworkTables.Logging.Logger; -using System.IO; -using System.Net; -using System.Threading.Tasks; -using Nito.AsyncEx.Synchronous; -using NetworkTables.Logging; - -namespace NetworkTables -{ - internal class NetworkConnection : IDisposable - { - public int ProtoRev { get; set; } - - - public enum State { Created, Init, Handshake, Synchronized, Active, Dead }; - - public delegate bool HandshakeFunc(NetworkConnection conn, Func getMsg, Action> sendMsgs); - - public delegate void ProcessIncomingFunc(Message msg, NetworkConnection conn); - - private static long s_uid; - - private readonly Stream m_stream; - - // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable - private readonly IClient m_client; - - public int PeerPort { get; } - public string PeerIP { get; } - - private readonly Notifier m_notifier; - - private readonly BlockingCollection> m_outgoing = new BlockingCollection>(); - - private readonly HandshakeFunc m_handshake; - - private readonly Message.GetEntryTypeFunc m_getEntryType; - - private ProcessIncomingFunc m_processIncoming; - - private Task m_readThread; - private Task m_writeThread; - - private State m_state; - - private string m_remoteId; - - private DateTime m_lastPost = DateTime.UtcNow; - - private readonly object m_pendingMutex = new object(); - - private readonly object m_remoteIdMutex = new object(); - - private readonly List m_pendingOutgoing = new List(); - - private readonly List<(int First, int Second)> m_pendingUpdate = new List<(int First, int Second)>(); - - public NetworkConnection(IClient client, Notifier notifier, HandshakeFunc handshake, - Message.GetEntryTypeFunc getEntryType) - { - Uid = (uint)Interlocked.Increment(ref s_uid) - 1; - m_client = client; - m_stream = client.GetStream(); - m_notifier = notifier; - m_handshake = handshake; - m_getEntryType = getEntryType; - - Active = false; - ProtoRev = 0x0300; - m_state = State.Created; - LastUpdate = 0; - - if (m_client.RemoteEndPoint is IPEndPoint ipEp) - { - PeerIP = ipEp.Address.ToString(); - PeerPort = ipEp.Port; - } - else - { - PeerIP = ""; - PeerPort = 0; - } - - // turns of Nagle, as we bundle packets ourselves - m_client.NoDelay = true; - } - - public bool Disposed { get; private set; } - - public void Dispose() - { - Stop(); - // Set process incoming to null to make sure any closures don't hold references. - m_processIncoming = null; - Disposed = true; - } - - public void SetProcessIncoming(ProcessIncomingFunc func) - { - m_processIncoming = func; - } - - public void Start() - { - if (Active) return; - Active = true; - m_state = State.Init; - // clear queue - while (m_outgoing.Count != 0) m_outgoing.Take(); - - //Start our tasks - m_writeThread = Task.Factory.StartNew(WriteThreadMain, TaskCreationOptions.LongRunning); - m_readThread = Task.Factory.StartNew(ReadThreadMain, TaskCreationOptions.LongRunning); - } - - public void Stop() - { - Debug2(Logger.Instance, $"NetworkConnection stopping ({this})"); - m_state = State.Dead; - - Active = false; - //Closing stream to terminate read thread - m_stream?.Dispose(); - m_client?.Dispose(); - //Send an empty message to terminate the write thread - m_outgoing.Add(new List()); - - //Wait for our threads to detach from each. - m_writeThread?.WaitAndUnwrapException(); - m_readThread?.WaitAndUnwrapException(); - - // clear the queue - while (m_outgoing.Count != 0) m_outgoing.Take(); - } - - public ConnectionInfo GetConnectionInfo() - { - return new ConnectionInfo(RemoteId, PeerIP, PeerPort, LastUpdate, ProtoRev); - } - - private readonly object m_stateMutex = new object(); - - public void NotifyIfActive(ConnectionListenerCallback callback) - { - lock (m_stateMutex) - { - if (m_state == State.Active) m_notifier.NotifyConnection(true, GetConnectionInfo(), callback); - } - } - - public State GetState() - { - lock (m_stateMutex) - { - return m_state; - } - } - - public void SetState(State state) - { - lock (m_stateMutex) - { - // Don't update state any more once we've died - if (m_state == State.Dead) return; - // One-shot notify state changes - if (m_state != State.Active && state == State.Active) - m_notifier.NotifyConnection(true, GetConnectionInfo()); - if (m_state != State.Dead && state == State.Dead) - m_notifier.NotifyConnection(false, GetConnectionInfo()); - m_state = state; - - } - } - - public bool Active { get; private set; } - - public Stream GetStream() - { - return m_stream; - } - - private void ResizePendingUpdate(int newSize) - { - int currentSize = m_pendingUpdate.Count; - - if (newSize > currentSize) - { - if (newSize > m_pendingUpdate.Capacity) - m_pendingUpdate.Capacity = newSize; - m_pendingUpdate.AddRange(Enumerable.Repeat(default((int First, int Second)), newSize - currentSize)); - } - } - - public void QueueOutgoing(Message msg) - { - lock (m_pendingMutex) - { - //Merge with previouse - Message.MsgType type = msg.Type; - switch (type) - { - case Message.MsgType.EntryAssign: - case Message.MsgType.EntryUpdate: - { - // don't do this for unassigned id's - int id = (int)msg.Id; - if (id == 0xffff) - { - m_pendingOutgoing.Add(msg); - break; - } - if (id < m_pendingUpdate.Count && m_pendingUpdate[id].First != 0) - { - var oldmsg = m_pendingOutgoing[m_pendingUpdate[id].First - 1]; - if (oldmsg != null && oldmsg.Is(Message.MsgType.EntryAssign) && - msg.Is(Message.MsgType.EntryUpdate)) - { - // need to update assignement - m_pendingOutgoing[m_pendingUpdate[id].First] = Message.EntryAssign(oldmsg.Str, (uint)id, msg.SeqNumUid, msg.Val, - (EntryFlags)oldmsg.Flags); - - } - else - { - // new but remember it - m_pendingOutgoing[m_pendingUpdate[id].First] = msg; - } - } - else - { - // new but don't remember it - int pos = m_pendingOutgoing.Count; - m_pendingOutgoing.Add(msg); - if (id >= m_pendingUpdate.Count) ResizePendingUpdate(id + 1); - m_pendingUpdate[id] = (pos + 1, m_pendingUpdate[id].Second); - } - break; - } - case Message.MsgType.EntryDelete: - { - //Don't do this for unnasigned uid's - int id = (int)msg.Id; - if (id == 0xffff) - { - m_pendingOutgoing.Add(msg); - break; - } - - if (id < m_pendingUpdate.Count) - { - if (m_pendingUpdate[id].First != 0) - { - m_pendingOutgoing[m_pendingUpdate[id].First - 1] = new Message(); - m_pendingUpdate[id] = (0, m_pendingUpdate[id].Second); - } - if (m_pendingUpdate[id].Second != 0) - { - m_pendingOutgoing[m_pendingUpdate[id].Second - 1] = new Message(); - m_pendingUpdate[id] = (m_pendingUpdate[id].First, 0); - } - } - //Add deletion - m_pendingOutgoing.Add(msg); - break; - } - case Message.MsgType.FlagsUpdate: - { - //Don't do this for unassigned uids - int id = (int)msg.Id; - if (id == 0xffff) - { - m_pendingOutgoing.Add(msg); - break; - } - - if (id < m_pendingUpdate.Count && m_pendingUpdate[id].Second != 0) - { - //Overwrite the previous one for this uid - m_pendingOutgoing[m_pendingUpdate[id].Second - 1] = msg; - } - else - { - int pos = m_pendingOutgoing.Count; - m_pendingOutgoing.Add(msg); - if (id > m_pendingUpdate.Count) ResizePendingUpdate(id + 1); - m_pendingUpdate[id] = (m_pendingUpdate[id].First, pos + 1); - - } - break; - } - case Message.MsgType.ClearEntries: - { - //Knock out all previous assignes/updates - for (int i = 0; i < m_pendingOutgoing.Count; i++) - { - var message = m_pendingOutgoing[i]; - if (message == null) continue; - var t = message.Type; - if (t == Message.MsgType.EntryAssign || t == Message.MsgType.EntryUpdate - || t == Message.MsgType.FlagsUpdate || t == Message.MsgType.EntryDelete - || t == Message.MsgType.ClearEntries) - { - m_pendingOutgoing[i] = new Message(); - } - } - m_pendingUpdate.Clear(); - m_pendingOutgoing.Add(msg); - break; - } - default: - m_pendingOutgoing.Add(msg); - break; - } - } - } - - public void PostOutgoing(bool keepAlive) - { - lock (m_pendingMutex) - { - var now = DateTime.UtcNow; - if (m_pendingOutgoing.Count == 0) - { - if (!keepAlive) return; - // send keep-alives once a second (if no other messages have been sent) - if ((now - m_lastPost) < TimeSpan.FromSeconds(1)) return; - m_outgoing.Add(new List { Message.KeepAlive() }); - } - else - { - m_outgoing.Add(new List(m_pendingOutgoing)); - m_pendingOutgoing.Clear(); - m_pendingUpdate.Clear(); - - } - m_lastPost = now; - } - } - - public uint Uid { get; } - - public string RemoteId - { - get - { - lock (m_remoteIdMutex) - { - return m_remoteId; - } - } - set - { - lock (m_remoteIdMutex) - { - m_remoteId = value; - } - } - } - - public long LastUpdate { get; private set; } - - - private void ReadThreadMain() - { - WireDecoder decoder = new WireDecoder(m_stream, ProtoRev); - - SetState(State.Handshake); - - if (!m_handshake(this,() => - { - decoder.ProtoRev = ProtoRev; - var msg = Message.Read(decoder, m_getEntryType); - if (msg == null && decoder.Error != null) - { - Debug(Logger.Instance, $"error reading in handshake: {decoder.Error}"); - } - return msg; - }, messages => - { - m_outgoing.Add(messages); - })) - { - SetState(State.Dead); - Active = false; - return; - } - - SetState(State.Active); - m_notifier.NotifyConnection(true, GetConnectionInfo()); - while (Active) - { - if (m_stream == null) break; - decoder.ProtoRev = ProtoRev; - decoder.Reset(); - var msg = Message.Read(decoder, m_getEntryType); - if (msg == null) - { - if (decoder.Error != null) Info(Logger.Instance, $"read error: {decoder.Error}"); - //terminate connection on bad message - m_stream?.Dispose(); - break; - } - // ToString on the enum type does not stop the boxing - Debug3(Logger.Instance, $"received type={msg.Type.GetString()} with str={msg.Str} id={msg.Id.ToString()} seqNum={msg.SeqNumUid.ToString()}"); - LastUpdate = Timestamp.Now(); - m_processIncoming(msg, this); - } - - Debug2(Logger.Instance, $"read thread died ({this})"); - if (m_state != State.Dead) m_notifier.NotifyConnection(false, GetConnectionInfo()); - SetState(State.Dead); - Active = false; - m_outgoing.Add(new List()); // Also kill write thread - } - - private void WriteThreadMain() - { - WireEncoder encoder = new WireEncoder(ProtoRev); - - while (Active) - { - var msgs = m_outgoing.Take(); - Debug4(Logger.Instance, "write thread woke up"); - if (msgs.Count == 0) continue; - encoder.ProtoRev = ProtoRev; - encoder.Reset(); - Debug3(Logger.Instance, $"sending {msgs.Count.ToString()} messages"); - foreach (var message in msgs) - { - if (message != null) - { - Debug3(Logger.Instance, $"sending type={message.Type.GetString()} with str={message.Str} id={message.Id.ToString()} seqNum={message.SeqNumUid.ToString()}"); - message.Write(encoder); - } - } - if (m_stream == null) break; - if (encoder.Count == 0) continue; - if (m_stream.Send(encoder.Buffer, 0, encoder.Count) == 0) break; - Debug4(Logger.Instance, $"sent {encoder.Count.ToString()} bytes"); - } - Debug2(Logger.Instance, $"write thread died ({this})"); - SetState(State.Dead); - Active = false; - m_stream?.Dispose(); // Also kill read thread - } - } -} diff --git a/src/FRC.NetworkTables/Notifier.cs b/src/FRC.NetworkTables/Notifier.cs deleted file mode 100644 index 1d13b2c..0000000 --- a/src/FRC.NetworkTables/Notifier.cs +++ /dev/null @@ -1,369 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using NetworkTables.Extensions; -using Nito.AsyncEx.Synchronous; - -namespace NetworkTables -{ - internal class Notifier : IDisposable - { - private static Notifier s_instance; - private bool m_destroyed; - private bool m_localNotifiers; - - private Task m_thread; - - // Special class for Entry Listeners - private class UidListEntryListener - { - private readonly List m_list = new List(); - private readonly Queue m_free = new Queue(); - - public int Count => m_list.Count; - - public EntryListener this[int i] => m_list[i]; - - public int Add(string prefix, EntryListenerCallback callback, NotifyFlags flags) - { - int uid; - var listener = new EntryListener(prefix, callback, flags); - if (m_free.Count == 0) - { - uid = m_list.Count; - m_list.Add(listener); - } - else - { - uid = m_free.Dequeue(); - m_list[uid] = listener; - } - return uid + 1; - } - - public void Erase(int uid) - { - --uid; - if (uid >= m_list.Count || m_list[uid].IsNull()) return; - m_free.Enqueue(uid); - m_list[uid].SetNull(); - } - } - - // Special class for Connection Listeners - private class UidListConnectionListenerCallback - { - private readonly List m_list = new List(); - private readonly Queue m_free = new Queue(); - - public int Count => m_list.Count; - - public ConnectionListenerCallback this[int i] => m_list[i]; - - public int Add(ConnectionListenerCallback args) - { - int uid; - if (m_free.Count == 0) - { - uid = m_list.Count; - m_list.Add(args); - } - else - { - uid = m_free.Dequeue(); - m_list[uid] = args; - } - return uid + 1; - } - - public void Erase(int uid) - { - --uid; - if (uid >= m_list.Count || m_list[uid] == null) return; - m_free.Enqueue(uid); - m_list[uid] = null; - } - } - - private struct EntryListener - { - public EntryListener(string prefix, EntryListenerCallback callback, NotifyFlags flags) - { - Prefix = prefix; - Callback = callback; - Flags = flags; - } - - public string Prefix { get; } - public EntryListenerCallback Callback { get; private set; } - public NotifyFlags Flags { get; } - - public void SetNull() - { - Callback = null; - } - - public bool IsNull() - { - return Callback == null; - } - } - - private readonly UidListEntryListener m_entryListeners = new UidListEntryListener(); - private readonly UidListConnectionListenerCallback m_connListeners = new UidListConnectionListenerCallback(); - - private struct EntryNotification - { - public EntryNotification(string name, Value value, NotifyFlags flags, - EntryListenerCallback only) - { - Name = name; - Value = value; - Flags = flags; - Only = only; - } - - public string Name { get; } - public Value Value { get; } - public NotifyFlags Flags { get; } - public EntryListenerCallback Only { get; } - } - - private readonly Queue m_entryNotifications = new Queue(); - - private struct ConnectionNotification - { - public ConnectionNotification(bool connected, ConnectionInfo connInfo, ConnectionListenerCallback only) - { - Connected = connected; - ConnInfo = connInfo; - Only = only; - } - public bool Connected { get; } - public ConnectionInfo ConnInfo { get; } - public ConnectionListenerCallback Only { get; } - } - - private readonly Queue m_connNotifications = new Queue(); - - public static Notifier Instance - { - get - { - if (s_instance == null) - { - Notifier d = new Notifier(); - Interlocked.CompareExchange(ref s_instance, d, null); - } - return s_instance; - } - } - - internal Notifier() - { - m_active = false; - m_localNotifiers = false; - m_destroyed = false; - } - - public void Dispose() - { - m_destroyed = true; - Stop(); - } - - private void ThreadMain() - { - bool lockEntered = false; - try - { - Monitor.Enter(m_mutex, ref lockEntered); - while (m_active) - { - while (m_entryNotifications.Count == 0 && m_connNotifications.Count == 0) - { - m_cond.Wait(m_mutex, ref lockEntered); - if (!m_active) return; - } - - //Entry notifications - while (m_entryNotifications.Count != 0) - { - if (!m_active) return; - var item = m_entryNotifications.Dequeue(); - if (item.Value == null) continue; - string name = item.Name; - - if (item.Only != null) - { - // Don't hold mutex during callback execution - Monitor.Exit(m_mutex); - lockEntered = false; - item.Only(0, name, item.Value, item.Flags); - Monitor.Enter(m_mutex, ref lockEntered); - continue; - } - - // Use index because iterator might get invalidated - for (int i = 0; i < m_entryListeners.Count; ++i) - { - if (m_entryListeners[i].IsNull()) continue; //removed - - // Flags must be within requested set flag for this listener - // Because assign messages can result in both a value and flags update, - // we handle that case specifically - NotifyFlags listenFlags = m_entryListeners[i].Flags; - NotifyFlags flags = item.Flags; - const NotifyFlags assignBoth = (NotifyFlags.NotifyUpdate | NotifyFlags.NotifyFlagsChanged); - - if ((flags & assignBoth) == assignBoth) - { - if ((listenFlags & assignBoth) == 0) continue; - listenFlags &= ~assignBoth; - flags &= ~assignBoth; - } - if ((flags & ~listenFlags) != 0) continue; - - //Must match prefix - if (!name.StartsWith(m_entryListeners[i].Prefix)) continue; - - // make a copy of the callback so wwe can release the mutex - var callback = m_entryListeners[i].Callback; - - Monitor.Exit(m_mutex); - lockEntered = false; - callback(i + 1, name, item.Value, item.Flags); - Monitor.Enter(m_mutex, ref lockEntered); - } - - } - - //Connection notifications - while (m_connNotifications.Count != 0) - { - if (!m_active) return; - var item = m_connNotifications.Dequeue(); - - if (item.Only != null) - { - Monitor.Exit(m_mutex); - lockEntered = false; - item.Only(0, item.Connected, item.ConnInfo); - Monitor.Enter(m_mutex, ref lockEntered); - continue; - } - - - // Use index because iterator might get invalidated - for (int i = 0; i < m_connListeners.Count; ++i) - { - if (m_connListeners[i] == null) continue; - var callback = m_connListeners[i]; - - Monitor.Exit(m_mutex); - lockEntered = false; - callback(i + 1, item.Connected, item.ConnInfo); - Monitor.Enter(m_mutex, ref lockEntered); - } - } - } - } - finally - { - if (lockEntered) Monitor.Exit(m_mutex); - } - } - - private bool m_active; - private readonly object m_mutex = new object(); - private readonly AutoResetEvent m_cond = new AutoResetEvent(false); - - public void Start() - { - lock (m_mutex) - { - if (m_active) return; - m_active = true; - } - - //Start our tasks - m_thread = Task.Factory.StartNew(ThreadMain, TaskCreationOptions.LongRunning); - } - - public void Stop() - { - m_active = false; - //Notify condition so thread terminates. - m_cond.Set(); - // Use GetAwaiter to unwrap the exception - m_thread?.WaitAndUnwrapException(); - } - - public bool LocalNotifiers() - { - return m_localNotifiers; - } - - public bool Destroyed() - { - return m_destroyed; - } - - public int AddEntryListener(string prefix, EntryListenerCallback callback, NotifyFlags flags) - { - lock (m_mutex) - { - if ((flags & NotifyFlags.NotifyLocal) != 0) m_localNotifiers = true; - return m_entryListeners.Add(prefix, callback, flags); - } - } - - public void RemoveEntryListener(int entryListenerUid) - { - lock (m_mutex) - { - m_entryListeners.Erase(entryListenerUid); - } - } - - public void NotifyEntry(string name, Value value, NotifyFlags flags, EntryListenerCallback only = null) - { - if (!m_active) return; - // optimization: don't generate needless local queue entries if we have - // no local listeners (as this is a common case on the server side) - if ((flags & NotifyFlags.NotifyLocal) != 0 && !m_localNotifiers) return; - lock (m_mutex) - { - m_entryNotifications.Enqueue(new EntryNotification(name, value, flags, only)); - } - m_cond.Set(); - } - - public int AddConnectionListener(ConnectionListenerCallback callback) - { - lock (m_mutex) - { - return m_connListeners.Add(callback); - } - } - - public void RemoveConnectionListener(int connListenerUid) - { - lock (m_mutex) - { - m_connListeners.Erase(connListenerUid); - } - } - - public void NotifyConnection(bool connected, ConnectionInfo connInfo, ConnectionListenerCallback only = null) - { - if (!m_active) return; - lock (m_mutex) - { - m_connNotifications.Enqueue(new ConnectionNotification(connected, connInfo, only)); - } - m_cond.Set(); - } - } -} diff --git a/src/FRC.NetworkTables/Properties/AssemblyInfo.cs b/src/FRC.NetworkTables/Properties/AssemblyInfo.cs deleted file mode 100644 index b5a4016..0000000 --- a/src/FRC.NetworkTables/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("FRC.NetworkTables")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyVersion("3.0.0.0")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9624771e-3ea6-4a6c-b813-a66ed43a9433")] - -[assembly: InternalsVisibleTo("NetworkTables.Test")] diff --git a/src/FRC.NetworkTables/RpcServer.cs b/src/FRC.NetworkTables/RpcServer.cs deleted file mode 100644 index 0529c74..0000000 --- a/src/FRC.NetworkTables/RpcServer.cs +++ /dev/null @@ -1,296 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using NetworkTables.Logging; -using Nito.AsyncEx; -using Nito.AsyncEx.Synchronous; -using static NetworkTables.Logging.Logger; - -namespace NetworkTables -{ - internal class RpcServer : IDisposable - { - private readonly Dictionary<(uint First, uint Second), SendMsgFunc> m_responseMap = new Dictionary<(uint First, uint Second), SendMsgFunc>(); - - private static RpcServer s_instance; - - /// - /// Gets the local instance of Dispatcher - /// - public static RpcServer Instance - { - get - { - if (s_instance == null) - { - RpcServer d = new RpcServer(); - Interlocked.CompareExchange(ref s_instance, d, null); - } - return s_instance; - } - } - - public bool Active { get; private set; } - - public void Dispose() - { - Logger.Instance.SetDefaultLogger(); - m_terminating = true; - //m_cancellationTokenSource.Cancel(); - using (m_lockObject.Lock()) - { - m_callCond.NotifyAll(); - m_pollCond.NotifyAll(); - } - - //Join our dispatch thread. - m_thread?.WaitAndUnwrapException(); - } - - public delegate void SendMsgFunc(Message msg); - - public void Start() - { - using (m_lockObject.Lock()) - { - if (Active) return; - Active = true; - } - - //Start our task - m_thread = Task.Factory.StartNew(ThreadMain, TaskCreationOptions.LongRunning); - } - - public void Stop() - { - Active = false; - if (m_thread != null) - { - using (m_lockObject.Lock()) - { - m_callCond.NotifyAll(); - m_pollCond.NotifyAll(); - } - //Join our dispatch thread. - m_thread?.GetAwaiter().GetResult(); - } - } - - public void ProcessRpc(string name, Message msg, RpcCallback func, uint connId, SendMsgFunc sendResponse, ref ConnectionInfo connInfo) - { - - using (m_lockObject.Lock()) - { - if (func != null) - m_callQueue.Enqueue(new RpcCall(name, msg, func, connId, sendResponse, connInfo)); - else - // ReSharper disable once ExpressionIsAlwaysNull - m_pollQueue.Enqueue(new RpcCall(name, msg, func, connId, sendResponse, connInfo)); - if (func != null) - { - m_callCond.NotifyAll(); - } - else - { - m_pollCond.NotifyAll(); - } - } - - } - - public async Task PollRpcAsync(CancellationToken token) - { - IDisposable monitor = null; - try - { - monitor = await m_lockObject.LockAsync(token).ConfigureAwait(false); - while (m_pollQueue.Count == 0) - { - if (m_terminating) return null; - await m_pollCond.WaitAsync(token).ConfigureAwait(false); - if (token.IsCancellationRequested) return null; - if (m_terminating) return null; - } - var item = m_pollQueue.Dequeue(); - uint callUid; - if (item.ConnId != 0xffff) - callUid = (item.ConnId << 16) | item.Msg.SeqNumUid; - else - callUid = item.Msg.SeqNumUid; - if (!item.Msg.Val.IsRpc()) return null; - RpcCallInfo callInfo = new RpcCallInfo(item.Msg.Id, callUid, item.Name, item.Msg.Val.GetRpc()); - m_responseMap.Add((item.Msg.Id, callUid), item.SendResponse); - return callInfo; - } - catch (OperationCanceledException) - { - // Operation canceled. Return null. - return null; - } - finally - { - monitor?.Dispose(); - } - } - - public bool PollRpc(bool blocking, out RpcCallInfo callInfo) - { - return PollRpc(blocking, Timeout.InfiniteTimeSpan, out callInfo); - } - - public bool PollRpc(bool blocking, TimeSpan timeout, out RpcCallInfo callInfo) - { - IDisposable monitor = null; - try - { - monitor = m_lockObject.Lock(); - DateTime startTime = DateTime.UtcNow; - while (m_pollQueue.Count == 0) - { - if (!blocking || m_terminating) - { - callInfo = default(RpcCallInfo); - return false; - } - CancellationTokenSource source = new CancellationTokenSource(); - var task = m_pollCond.WaitAsync(source.Token); - TimeSpan waitTimeout = timeout; - if (timeout != Timeout.InfiniteTimeSpan) - { - DateTime now = DateTime.UtcNow; - if (now < startTime + timeout) - { - // We still have time to wait. - waitTimeout = (startTime + timeout) - now; - } - else - { - // We're past the wait time. No need to wait anymore - waitTimeout = TimeSpan.Zero; - } - } - bool success = task.Wait(waitTimeout); - if (!success || m_terminating) - { - source.Cancel(); - // Call wait again without timeout to wait for lock to be reaquired - // ReSharper disable once MethodSupportsCancellation - task.WaitWithoutException(); - callInfo = default(RpcCallInfo); - return false; - } - } - var item = m_pollQueue.Dequeue(); - uint callUid; - if (item.ConnId != 0xffff) - callUid = (item.ConnId << 16) | item.Msg.SeqNumUid; - else - callUid = item.Msg.SeqNumUid; - if (!item.Msg.Val.IsRpc()) - { - callInfo = default(RpcCallInfo); - return false; - } - callInfo = new RpcCallInfo(item.Msg.Id, callUid, item.Name, item.Msg.Val.GetRpc()); - m_responseMap.Add((item.Msg.Id, callUid), item.SendResponse); - return true; - } - finally - { - monitor?.Dispose(); - } - } - - public void PostRpcResponse(long rpcId, long callId, IList result) - { - var pair = ((uint)rpcId, (uint)callId); - if (!m_responseMap.TryGetValue(pair, out SendMsgFunc func)) - { - Warning(Logger.Instance, "posting PRC response to nonexistent call (or duplicate response)"); - return; - } - func(Message.RpcResponse((uint)rpcId, (uint)callId, result)); - m_responseMap.Remove(pair); - } - - internal RpcServer() - { - Active = false; - m_terminating = false; - m_lockObject = new AsyncLock(); - m_callCond = new AsyncConditionVariable(m_lockObject); - m_pollCond = new AsyncConditionVariable(m_lockObject); - } - - private void ThreadMain() - { - IDisposable monitor = null; - try - { - monitor = m_lockObject.Lock(); - while (Active) - { - while (m_callQueue.Count == 0) - { - m_callCond.Wait(); - if (!Active) return; - } - while (m_callQueue.Count != 0) - { - if (!Active) return; - var item = m_callQueue.Dequeue(); - Debug4(Logger.Instance, $"rpc calling {item.Name}"); - - if (string.IsNullOrEmpty(item.Name) || item.Msg == null | item.Func == null || - item.SendResponse == null) - continue; - IDisposable monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - var result = item.Func(item.Name, item.Msg.Val.GetRpc(), item.ConnInfo); - var response = Message.RpcResponse(item.Msg.Id, item.Msg.SeqNumUid, result); - item.SendResponse(response); - Interlocked.Exchange(ref monitor, m_lockObject.Lock()); - } - } - } - finally - { - monitor?.Dispose(); - } - } - - private bool m_terminating; - //private readonly CancellationTokenSource m_cancellationTokenSource = new CancellationTokenSource(); - - private struct RpcCall - { - public RpcCall(string name, Message msg, RpcCallback func, uint connId, SendMsgFunc sendResponse, ConnectionInfo connInfo) - { - Name = name; - Msg = msg; - Func = func; - ConnId = connId; - SendResponse = sendResponse; - ConnInfo = connInfo; - } - - public string Name { get; } - public Message Msg { get; } - public RpcCallback Func { get; } - public uint ConnId { get; } - public SendMsgFunc SendResponse { get; } - public ConnectionInfo ConnInfo { get; } - - } - - private readonly Queue m_callQueue = new Queue(); - private readonly Queue m_pollQueue = new Queue(); - - private Task m_thread; - - private readonly AsyncLock m_lockObject; - private readonly AsyncConditionVariable m_callCond; - private readonly AsyncConditionVariable m_pollCond; - } -} diff --git a/src/FRC.NetworkTables/SequenceNumber.cs b/src/FRC.NetworkTables/SequenceNumber.cs deleted file mode 100644 index e653b71..0000000 --- a/src/FRC.NetworkTables/SequenceNumber.cs +++ /dev/null @@ -1,86 +0,0 @@ -namespace NetworkTables -{ - internal struct SequenceNumber - { - private bool Equals(SequenceNumber other) - { - return Value == other.Value; - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (obj.GetType() != typeof(SequenceNumber)) return false; - return Equals((SequenceNumber)obj); - } - - public override int GetHashCode() - { - //No good hash code here, so just have to be careful - return 0; - } - - public SequenceNumber(uint value) - { - Value = value; - } - - public SequenceNumber(SequenceNumber old) - { - Value = old.Value; - } - - public uint Value - { - get; private set; - } - - public static SequenceNumber operator ++(SequenceNumber input) - { - ++input.Value; - if (input.Value > 0xffff) input.Value = 0; - return input; - } - - public static bool operator <(SequenceNumber lhs, SequenceNumber rhs) - { - if (lhs.Value < rhs.Value) - return (rhs.Value - lhs.Value) < (1u << 15); - else if (lhs.Value > rhs.Value) - return (lhs.Value - rhs.Value) > (1u << 15); - else - return false; - } - - public static bool operator >(SequenceNumber lhs, SequenceNumber rhs) - { - if (lhs.Value < rhs.Value) - return (rhs.Value - lhs.Value) > (1u << 15); - else if (lhs.Value > rhs.Value) - return (lhs.Value - rhs.Value) < (1u << 15); - else - return false; - } - - public static bool operator <=(SequenceNumber lhs, SequenceNumber rhs) - { - return lhs == rhs || lhs < rhs; - } - - public static bool operator >=(SequenceNumber lhs, SequenceNumber rhs) - { - return lhs == rhs || lhs > rhs; - } - - public static bool operator ==(SequenceNumber lhs, SequenceNumber rhs) - { - return lhs.Value == rhs.Value; - } - - public static bool operator !=(SequenceNumber lhs, SequenceNumber rhs) - { - return lhs.Value != rhs.Value; - } - - } -} diff --git a/src/FRC.NetworkTables/Storage.cs b/src/FRC.NetworkTables/Storage.cs deleted file mode 100644 index 4eb9ef6..0000000 --- a/src/FRC.NetworkTables/Storage.cs +++ /dev/null @@ -1,1234 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using NetworkTables.Logging; -using Nito.AsyncEx; -using static NetworkTables.Logging.Logger; -using static NetworkTables.Message.MsgType; -using Nito.AsyncEx.Synchronous; - -namespace NetworkTables -{ - internal partial class Storage : IDisposable - { - private static Storage s_instance; - - public static Storage Instance - { - get - { - if (s_instance == null) - { - Storage d = new Storage(); - Interlocked.CompareExchange(ref s_instance, d, null); - } - return s_instance; - } - } - - internal Dictionary Entries => m_entries; - internal List IdMap => m_idMap; - - - internal Storage() : this(Notifier.Instance, RpcServer.Instance) - { - - } - - - public void Dispose() - { - Logger.Instance.SetDefaultLogger(); - m_terminating = true; - using (m_monitor.Enter()) - { - m_monitor.PulseAll(); - } - } - - internal Storage(Notifier notifier, RpcServer rpcServer) - { - m_notifier = notifier; - m_rpcServer = rpcServer; - } - - internal class Entry - { - public Entry(string name) - { - Name = name; - Flags = 0; - Id = 0xffff; - Value = null; - SeqNum = new SequenceNumber(); - RpcCallback = null; - RpcCallUid = 0; - } - - public bool IsPersistent() => (Flags & EntryFlags.Persistent) != 0; - - public readonly string Name; - public Value Value; - public EntryFlags Flags; - public uint Id; - - public SequenceNumber SeqNum; - - public RpcCallback RpcCallback; - public uint RpcCallUid; - - } - - private Dictionary m_entries = new Dictionary(); - private readonly List m_idMap = new List(); - internal readonly Dictionary<(uint, uint), byte[]> m_rpcResults = new Dictionary<(uint, uint), byte[]>(); - private readonly HashSet m_blockingRpcCalls = new HashSet(); - - private bool m_terminating; - private readonly AsyncMonitor m_monitor = new AsyncMonitor(); - - QueueOutgoingFunc m_queueOutgoing; - bool m_server = true; - - bool m_persistentDirty; - - private readonly Notifier m_notifier; - private readonly RpcServer m_rpcServer; - - - - - public delegate void QueueOutgoingFunc(Message msg, NetworkConnection only, NetworkConnection except); - - public void SetOutgoing(QueueOutgoingFunc queueOutgoing, bool server) - { - using (m_monitor.Enter()) - { - m_queueOutgoing = queueOutgoing; - m_server = server; - } - } - - public void ClearOutgoing() - { - m_queueOutgoing = null; - } - - public NtType GetEntryType(uint id) - { - using (m_monitor.Enter()) - { - if (id >= m_idMap.Count) return NtType.Unassigned; - Entry entry = m_idMap[(int)id]; - if (entry?.Value == null) return NtType.Unassigned; - return entry.Value.Type; - } - } - - public void ProcessIncoming(Message msg, NetworkConnection conn, WeakReference connWeak) - { - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - IDisposable monitorToUnlock; - Message.MsgType type = msg.Type; - SequenceNumber seqNum; - Entry entry; - uint id; - - switch (type) - { - case KeepAlive: - break; // ignore - case ClientHello: - case ProtoUnsup: - case ServerHelloDone: - case ServerHello: - case ClientHelloDone: - // shouldn't get these, but ignore if we do - break; - case EntryAssign: - { - id = msg.Id; - string name = msg.Str; - bool mayNeedUpdate = false; - if (m_server) - { - if (id == 0xffff) - { - if (m_entries.ContainsKey(name)) return; - - - id = (uint)m_idMap.Count; - entry = new Entry(name) - { - Value = msg.Val, - Flags = (EntryFlags) msg.Flags, - Id = id - }; - m_entries[name] = entry; - m_idMap.Add(entry); - - if (entry.IsPersistent()) m_persistentDirty = true; - - m_notifier.NotifyEntry(name, entry.Value, NotifyFlags.NotifyNew); - - if (m_queueOutgoing != null) - { - var queueOutgoing = m_queueOutgoing; - var outMsg = Message.EntryAssign(name, id, entry.SeqNum.Value, msg.Val, (EntryFlags)msg.Flags); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(outMsg, null, null); - } - - return; - } - if (id >= m_idMap.Count || m_idMap[(int)id] == null) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "server: received assignment to unknown entry"); - return; - } - entry = m_idMap[(int)id]; - } - else - { - if (id == 0xffff) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "client: received entry assignment request?"); - return; - } - if (id >= m_idMap.Count) ResizeIdMap(id + 1); - entry = m_idMap[(int)id]; - if (entry == null) - { - Entry newEntry; - if (!m_entries.ContainsKey(name)) - { - //Entry didn't exist at all. - newEntry = new Entry(name) - { - Value = msg.Val, - Flags = (EntryFlags) msg.Flags, - Id = id - }; - m_idMap[(int)id] = newEntry; - m_entries[name] = newEntry; - - m_notifier.NotifyEntry(name, newEntry.Value, NotifyFlags.NotifyNew); - return; - } - else - { - newEntry = m_entries[name]; - } - mayNeedUpdate = true; - entry = newEntry; - entry.Id = id; - m_idMap[(int)id] = entry; - - if ((EntryFlags)msg.Flags != entry.Flags) - { - var queueOutgoing = m_queueOutgoing; - var outmsg = Message.FlagsUpdate(id, entry.Flags); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(outmsg, null, null); - Interlocked.Exchange(ref monitor, m_monitor.Enter()); - } - } - } - - seqNum = new SequenceNumber(msg.SeqNumUid); - if (seqNum < entry.SeqNum) - { - if (mayNeedUpdate) - { - var queueOutgoing = m_queueOutgoing; - var outmsg = Message.EntryUpdate(entry.Id, entry.SeqNum.Value, entry.Value); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(outmsg, null, null); - } - return; - } - //Sanity check. Name should match id - if (msg.Str != entry.Name) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "entry assignment for same id with different name?"); - return; - } - - NotifyFlags notifyFlags = NotifyFlags.NotifyUpdate; - - if (!mayNeedUpdate && conn.ProtoRev >= 0x0300) - { - if ((entry.Flags & EntryFlags.Persistent) != ((EntryFlags)msg.Flags & EntryFlags.Persistent)) - { - m_persistentDirty = true; - } - if (entry.Flags != (EntryFlags)msg.Flags) - { - notifyFlags |= NotifyFlags.NotifyFlagsChanged; - } - entry.Flags = (EntryFlags)msg.Flags; - } - - if (entry.IsPersistent() && entry.Value != msg.Val) - { - m_persistentDirty = true; - } - - entry.Value = msg.Val; - entry.SeqNum = seqNum; - - m_notifier.NotifyEntry(name, entry.Value, notifyFlags); - - if (m_server && m_queueOutgoing != null) - { - var queueOutgoing = m_queueOutgoing; - var outmsg = Message.EntryAssign(entry.Name, id, msg.SeqNumUid, msg.Val, entry.Flags); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(outmsg, null, conn); - } - break; - } - case EntryUpdate: - id = msg.Id; - if (id >= m_idMap.Count || m_idMap[(int)id] == null) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "received update to unknown entyr"); - return; - } - - entry = m_idMap[(int)id]; - - seqNum = new SequenceNumber(msg.SeqNumUid); - - if (seqNum <= entry.SeqNum) return; - - entry.Value = msg.Val; - entry.SeqNum = seqNum; - - if (entry.IsPersistent()) m_persistentDirty = true; - m_notifier.NotifyEntry(entry.Name, entry.Value, NotifyFlags.NotifyUpdate); - - if (m_server && m_queueOutgoing != null) - { - var queueOutgoing = m_queueOutgoing; - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, conn); - } - break; - case FlagsUpdate: - { - id = msg.Id; - if (id >= m_idMap.Count || m_idMap[(int)id] == null) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "reeived flags update to unknown entry"); - return; - } - - entry = m_idMap[(int)id]; - - if (entry.Flags == (EntryFlags)msg.Flags) return; - - if ((entry.Flags & EntryFlags.Persistent) != ((EntryFlags)msg.Flags & EntryFlags.Persistent)) - m_persistentDirty = true; - - entry.Flags = (EntryFlags)msg.Flags; - - m_notifier.NotifyEntry(entry.Name, entry.Value, NotifyFlags.NotifyFlagsChanged); - - if (m_server && m_queueOutgoing != null) - { - var queueOutgoing = m_queueOutgoing; - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, conn); - } - break; - } - case EntryDelete: - { - id = msg.Id; - if (id >= m_idMap.Count || m_idMap[(int)id] == null) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "received delete to unknown entry"); - return; - } - - - entry = m_idMap[(int)id]; - - if (entry.IsPersistent()) m_persistentDirty = true; - - m_idMap[(int)id] = null; - - if (m_entries.TryGetValue(entry.Name, out entry)) - { - m_entries.Remove(entry.Name); - - m_notifier.NotifyEntry(entry.Name, entry.Value, NotifyFlags.NotifyDelete); - } - - if (m_server && m_queueOutgoing != null) - { - var queueOutgoing = m_queueOutgoing; - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, conn); - } - break; - } - case ClearEntries: - { - DeleteAllEntriesImpl(); - - if (m_server && m_queueOutgoing != null) - { - var queueOutgoing = m_queueOutgoing; - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, conn); - } - break; - } - case ExecuteRpc: - if (!m_server) return; - id = msg.Id; - if (id >= m_idMap.Count || m_idMap[(int)id] == null) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "received RPC call to unknown entry"); - return; - } - entry = m_idMap[(int)id]; - if (!entry.Value.IsRpc()) - { - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - Debug(Logger.Instance, "received RPC call to non-RPC entry"); - return; - } - ConnectionInfo connInfo = conn.GetConnectionInfo(); - m_rpcServer.ProcessRpc(entry.Name, msg, entry.RpcCallback, conn.Uid, message => - { - connWeak.TryGetTarget(out NetworkConnection c); - if (c != null && !c.Disposed) - c.QueueOutgoing(message); - }, ref connInfo); - break; - case RpcResponse: - if (m_server) return; - if (!msg.Val.IsRpc()) return; //Not an RPC message - m_rpcResults.Add((msg.Id, msg.SeqNumUid), msg.Val.GetRpc()); - m_monitor.PulseAll(); - break; - } - } - finally - { - monitor?.Dispose(); - } - } - - public void GetInitialAssignments(NetworkConnection conn, List msgs) - { - using(m_monitor.Enter()) - { - conn.SetState(NetworkConnection.State.Synchronized); - foreach (var i in m_entries) - { - Entry entry = i.Value; - msgs.Add(Message.EntryAssign(i.Key, entry.Id, entry.SeqNum.Value, entry.Value, entry.Flags)); - } - } - } - - private void ResizeIdMap(uint newSize) - { - int currentSize = m_idMap.Count; - - if (newSize > currentSize) - { - if (newSize > m_idMap.Capacity) - m_idMap.Capacity = (int)newSize; - m_idMap.AddRange(Enumerable.Repeat(null, (int)newSize - currentSize)); - } - } - - public void ApplyInitialAssignments(NetworkConnection conn, Message[] msgs, bool newServer, List outMsgs) - { - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - if (m_server) return; - - conn.SetState(NetworkConnection.State.Synchronized); - - List updateMsgs = new List(); - - foreach (var i in m_entries) i.Value.Id = 0xffff; - - m_idMap.Clear(); - - foreach (var msg in msgs) - { - if (!msg.Is(EntryAssign)) - { - Debug(Logger.Instance, "client: received non-entry assignment request?"); - continue; - } - - uint id = msg.Id; - - if (id == 0xffff) - { - Debug(Logger.Instance, "client: received entry assignment request?"); - continue; - } - - SequenceNumber seqNum = new SequenceNumber(msg.SeqNumUid); - string name = msg.Str; - - - if (!m_entries.TryGetValue(name, out Entry entry)) - { - entry = new Entry(name) - { - Value = msg.Val, - Flags = (EntryFlags)msg.Flags, - SeqNum = seqNum - }; - m_notifier.NotifyEntry(name, entry.Value, NotifyFlags.NotifyNew); - m_entries.Add(name, entry); - } - else - { - if (!newServer && seqNum <= entry.SeqNum) - { - updateMsgs.Add(Message.EntryUpdate(entry.Id, entry.SeqNum.Value, entry.Value)); - } - else - { - entry.Value = msg.Val; - entry.SeqNum = seqNum; - NotifyFlags notifyFlags = NotifyFlags.NotifyUpdate; - - if (conn.ProtoRev >= 0x0300) - { - if (entry.Flags != (EntryFlags)msg.Flags) notifyFlags |= NotifyFlags.NotifyFlagsChanged; - entry.Flags = (EntryFlags)msg.Flags; - } - - m_notifier.NotifyEntry(name, entry.Value, notifyFlags); - } - } - - entry.Id = id; - if (id >= m_idMap.Count) ResizeIdMap(id + 1); - m_idMap[(int)id] = entry; - } - - foreach (var i in m_entries) - { - Entry entry = i.Value; - if (entry.Id != 0xffff) continue; - outMsgs.Add(Message.EntryAssign(entry.Name, entry.Id, entry.SeqNum.Value, entry.Value, entry.Flags)); - } - - var queueOutgoing = m_queueOutgoing; - IDisposable monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - foreach (var msg in updateMsgs) queueOutgoing(msg, null, null); - } - finally - { - monitor?.Dispose(); - } - } - - public Value GetEntryValue(string name) - { - using(m_monitor.Enter()) - { - if (m_entries.TryGetValue(name, out Entry entry)) - { - //Grabbed - return entry.Value; - } - else - { - return null; - } - } - } - - public bool SetDefaultEntryValue(string name, Value value) - { - if (value == null) return false; // can't compare to a null value - if (string.IsNullOrEmpty(name)) return false; // can't compare enpty name - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - if (m_entries.TryGetValue(name, out Entry newEntry)) // entry already exists - { - var oldValue = newEntry.Value; - if (oldValue != null && oldValue.Type == value.Type) return true; - else return false; - } - - // if we've gotten here, entry does not exist, and we can write it. - newEntry = new Entry(name); - m_entries.Add(name, newEntry); - - var entry = newEntry; - - entry.Value = value; - - // if we're the server, assign an id if it doesn't have one - if (m_server && entry.Id == 0xffff) - { - int id = m_idMap.Count; - entry.Id = (uint)id; - m_idMap.Add(entry); - } - - // notify (for local listeners) - if (m_notifier.LocalNotifiers()) - { - // always a new entry if we got this far - m_notifier.NotifyEntry(name, value, NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal); - } - - // generate message - if (m_queueOutgoing == null) return true; - var queueOutgoing = m_queueOutgoing; - var msg = Message.EntryAssign(name, entry.Id, entry.SeqNum.Value, value, entry.Flags); - - IDisposable monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - return true; - } - finally - { - monitor?.Dispose(); - } - } - - public bool SetEntryValue(string name, Value value) - { - if (string.IsNullOrEmpty(name)) return true; - if (value == null) return true; - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - IDisposable monitorToUnlock; - if (!m_entries.TryGetValue(name, out Entry entry)) - { - entry = new Entry(name); - m_entries.Add(name, entry); - } - var oldValue = entry.Value; - if (oldValue != null && oldValue.Type != value.Type) - { - return false; //Type mismatch error; - } - entry.Value = value; - - if (m_server && entry.Id == 0xffff) - { - uint id = (uint)m_idMap.Count; - entry.Id = id; - m_idMap.Add(entry); - } - - if (entry.IsPersistent() && oldValue != value) m_persistentDirty = true; - - if (m_notifier.LocalNotifiers()) - { - if (oldValue == null) - { - m_notifier.NotifyEntry(name, value, (NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); - } - else if (oldValue != value) - { - m_notifier.NotifyEntry(name, value, (NotifyFlags.NotifyUpdate | NotifyFlags.NotifyLocal)); - } - } - - if (m_queueOutgoing == null) return true; - var queueOutgoing = m_queueOutgoing; - if (oldValue == null) - { - var msg = Message.EntryAssign(name, entry.Id, entry.SeqNum.Value, value, entry.Flags); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - else if (oldValue != value) - { - ++entry.SeqNum; - if (entry.Id != 0xffff) - { - var msg = Message.EntryUpdate(entry.Id, entry.SeqNum.Value, value); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - } - return true; - } - finally - { - monitor?.Dispose(); - } - } - - public void SetEntryTypeValue(string name, Value value) - { - if (string.IsNullOrEmpty(name)) return; - if (value == null) return; - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - IDisposable monitorToUnlock; - if (!m_entries.TryGetValue(name, out Entry entry)) - { - entry = new Entry(name); - m_entries.Add(name, entry); - } - var oldValue = entry.Value; - entry.Value = value; - if (oldValue != null && oldValue == value) return; - - if (m_server && entry.Id == 0xffff) - { - int id = m_idMap.Count; - entry.Id = (uint)id; - m_idMap.Add(entry); - } - - if (entry.IsPersistent()) m_persistentDirty = true; - - if (m_notifier.LocalNotifiers()) - { - if (oldValue == null) - { - m_notifier.NotifyEntry(name, value, NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal); - } - else - { - m_notifier.NotifyEntry(name, value, NotifyFlags.NotifyUpdate | NotifyFlags.NotifyLocal); - } - } - - if (m_queueOutgoing == null) return; - var queueOutgoing = m_queueOutgoing; - if (oldValue == null || oldValue.Type != value.Type) - { - ++entry.SeqNum; - var msg = Message.EntryAssign(name, entry.Id, entry.SeqNum.Value, value, entry.Flags); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - else - { - ++entry.SeqNum; - if (entry.Id != 0xffff) - { - var msg = Message.EntryUpdate(entry.Id, entry.SeqNum.Value, value); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - } - } - finally - { - monitor?.Dispose(); - } - } - - public void SetEntryFlags(string name, EntryFlags flags) - { - if (string.IsNullOrEmpty(name)) return; - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - if (!m_entries.TryGetValue(name, out Entry entry)) - { - //Key does not exist. Return - return; - } - if (entry.Flags == flags) return; - - if ((entry.Flags & EntryFlags.Persistent) != (flags & EntryFlags.Persistent)) - m_persistentDirty = true; - - entry.Flags = flags; - - m_notifier.NotifyEntry(name, entry.Value, NotifyFlags.NotifyFlagsChanged | NotifyFlags.NotifyLocal); - - if (m_queueOutgoing == null) return; - var queueOutgoing = m_queueOutgoing; - uint id = entry.Id; - if (id != 0xffff) - { - IDisposable monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(Message.FlagsUpdate(id, flags), null, null); - } - } - finally - { - monitor?.Dispose(); - } - } - - public EntryFlags GetEntryFlags(string name) - { - using(m_monitor.Enter()) - { - if (m_entries.TryGetValue(name, out Entry entry)) - { - //Grabbed - return entry.Flags; - } - else - { - return 0; - } - } - } - - public void DeleteEntry(string name) - { - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - if (!m_entries.TryGetValue(name, out Entry entry)) return; - uint id = entry.Id; - if (entry.IsPersistent()) m_persistentDirty = true; - - - m_entries.Remove(name); - - if (id < m_idMap.Count) m_idMap[(int)id] = null; - if (entry.Value == null) return; - - m_notifier.NotifyEntry(name, entry.Value, (NotifyFlags.NotifyDelete | NotifyFlags.NotifyLocal)); - - if (id != 0xffff) - { - if (m_queueOutgoing == null) return; - var queueOutgoing = m_queueOutgoing; - IDisposable monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(Message.EntryDelete(id), null, null); - } - } - finally - { - monitor?.Dispose(); - } - } - - private void DeleteAllEntriesImpl() - { - if (m_entries.Count == 0) return; - - // only delete non-persistent values - // can't erase without invalidating iterators, so build - // a new dictionary - - Dictionary entries = new Dictionary(); - foreach (var i in m_entries) - { - var entry = i.Value; - if (!entry.IsPersistent()) - { - // notify it's getting deleted - if (m_notifier.LocalNotifiers()) - { - m_notifier.NotifyEntry(i.Key, i.Value.Value, NotifyFlags.NotifyDelete | NotifyFlags.NotifyLocal); - } - // remove it from idmap - if (entry.Id != 0xffff) m_idMap[(int)entry.Id] = null; - } - else - { - // Add it to new entries - entries.Add(i.Key, i.Value); - } - } - m_entries = entries; - } - - public void DeleteAllEntries() - { - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - if (m_entries.Count == 0) return; - - DeleteAllEntriesImpl(); - - if (m_queueOutgoing == null) return; - var queueOutgoing = m_queueOutgoing; - IDisposable monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(Message.ClearEntries(), null, null); - } - finally - { - monitor?.Dispose(); - } - } - - public List GetEntryInfo(string prefix, NtType types) - { - if (prefix == null) prefix = string.Empty; - using(m_monitor.Enter()) - { - List infos = new List(); - foreach (var i in m_entries) - { - if (!i.Key.StartsWith(prefix)) continue; - Entry entry = i.Value; - var value = entry.Value; - if (value == null) continue; - if (types != 0 && (types & value.Type) == 0) continue; - EntryInfo info = new EntryInfo(i.Key, value.Type, entry.Flags, (uint)value.LastChange); - infos.Add(info); - } - return infos; - } - } - - public void NotifyEntries(string prefix, EntryListenerCallback only = null) - { - using(m_monitor.Enter()) - { - foreach (var i in m_entries) - { - if (!i.Key.StartsWith(prefix)) continue; - m_notifier.NotifyEntry(i.Key, i.Value.Value, NotifyFlags.NotifyImmediate, only); - } - } - } - - - - public void CreateRpc(string name, IList def, RpcCallback callback) - { - if (string.IsNullOrEmpty(name) || def == null || def.Count == 0 || callback == null) return; - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - IDisposable monitorToUnlock; - if (!m_server) return; - - if (!m_entries.TryGetValue(name, out Entry entry)) - { - entry = new Entry(name); - m_entries.Add(name, entry); - } - - var oldValue = entry.Value; - var value = Value.MakeRpc(def); - entry.Value = value; - entry.RpcCallback = callback; - m_rpcServer.Start(); - - if (oldValue != null && oldValue == value) return; - - if (entry.Id == 0xffff) - { - int id = m_idMap.Count; - entry.Id = (uint)id; - m_idMap.Add(entry); - } - - if (m_queueOutgoing == null) return; - var queueOutgoing = m_queueOutgoing; - if (oldValue == null || oldValue.Type != value.Type) - { - ++entry.SeqNum; - var msg = Message.EntryAssign(name, entry.Id, entry.SeqNum.Value, value, entry.Flags); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - else - { - ++entry.SeqNum; - var msg = Message.EntryUpdate(entry.Id, entry.SeqNum.Value, value); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - - } - finally - { - monitor?.Dispose(); - } - } - - public void CreatePolledRpc(string name, IList def) - { - if (string.IsNullOrEmpty(name) || def == null || def.Count == 0) return; - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - IDisposable monitorToUnlock; - if (!m_server) return; - - if (!m_entries.TryGetValue(name, out Entry entry)) - { - entry = new Entry(name); - m_entries.Add(name, entry); - } - - var oldValue = entry.Value; - var value = Value.MakeRpc(def); - entry.Value = value; - entry.RpcCallback = null; - - if (oldValue != null && oldValue == value) return; - - if (entry.Id == 0xffff) - { - int id = m_idMap.Count; - entry.Id = (uint)id; - m_idMap.Add(entry); - } - - if (m_queueOutgoing == null) return; - var queueOutgoing = m_queueOutgoing; - if (oldValue == null || oldValue.Type != value.Type) - { - ++entry.SeqNum; - var msg = Message.EntryAssign(name, entry.Id, entry.SeqNum.Value, value, entry.Flags); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - else - { - ++entry.SeqNum; - var msg = Message.EntryUpdate(entry.Id, entry.SeqNum.Value, value); - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - } - finally - { - monitor?.Dispose(); - } - } - - public long CallRpc(string name, IList param) - { - if (string.IsNullOrEmpty(name)) return 0; - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - IDisposable monitorToUnlock; - if (!m_entries.TryGetValue(name, out Entry entry)) - { - return 0; - } - if (!entry.Value.IsRpc()) return 0; - - ++entry.RpcCallUid; - - if (entry.RpcCallUid > 0xffff) entry.RpcCallUid = 0; - uint combinedUid = (entry.Id << 16) | entry.RpcCallUid; - var msg = Message.ExecuteRpc(entry.Id, entry.RpcCallUid, param); - if (m_server) - { - var rpcCallback = entry.RpcCallback; - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - ConnectionInfo connInfo = new ConnectionInfo("Server", "localhost", 0, Support.Timestamp.Now(), 0x0300); - m_rpcServer.ProcessRpc(name, msg, rpcCallback, 0xffff, message => - { - using(m_monitor.Enter()) - { - m_rpcResults.Add((message.Id, message.SeqNumUid), message.Val.GetRpc()); - m_monitor.PulseAll(); - } - }, ref connInfo); - } - else - { - var queueOutgoing = m_queueOutgoing; - monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - queueOutgoing(msg, null, null); - } - return combinedUid; - - } - finally - { - monitor?.Dispose(); - } - } - - public async Task> GetRpcResultAsync(long callUid, CancellationToken token) - { - IDisposable monitor = null; - try - { - monitor = await m_monitor.EnterAsync(token).ConfigureAwait(false); - if (!m_blockingRpcCalls.Add(callUid)) return null; - for (;;) - { - var pair = ((uint)callUid >> 16, (uint)callUid & 0xffff); - if (!m_rpcResults.TryGetValue(pair, out byte[] str)) - { - if (m_terminating) - { - m_blockingRpcCalls.Remove(callUid); - return null; - } - - await m_monitor.WaitAsync(token).ConfigureAwait(false); - if (token.IsCancellationRequested) - { - m_blockingRpcCalls.Remove(callUid); - return null; - } - if (m_terminating) - { - m_blockingRpcCalls.Remove(callUid); - return null; - } - continue; - } - byte[] result = new byte[str.Length]; - Array.Copy(str, result, result.Length); - m_blockingRpcCalls.Remove(callUid); - return result; - } - } - catch (OperationCanceledException) - { - // Operation canceled. Return null. - return null; - } - finally - { - - monitor?.Dispose(); - } - } - - public bool GetRpcResult(bool blocking, long callUid, out byte[] result) - { - return GetRpcResult(blocking, callUid, Timeout.InfiniteTimeSpan, out result); - } - - public bool GetRpcResult(bool blocking, long callUid, TimeSpan timeout, out byte[] result) - { - IDisposable monitor = null; - try - { - monitor = m_monitor.Enter(); - if (!m_blockingRpcCalls.Add(callUid)) - { - result = null; - return false; - } - DateTime startTime = DateTime.UtcNow; - - for (;;) - { - var pair = ((uint)callUid >> 16, (uint)callUid & 0xffff); - if (!m_rpcResults.TryGetValue(pair, out byte[] str)) - { - if (!blocking || m_terminating) - { - result = null; - m_blockingRpcCalls.Remove(callUid); - return false; - } - CancellationTokenSource source = new CancellationTokenSource(); - var task = m_monitor.WaitAsync(source.Token); - TimeSpan waitTimeout = timeout; - if (timeout != Timeout.InfiniteTimeSpan) - { - DateTime now = DateTime.UtcNow; - if (now < startTime + timeout) - { - // We still have time to wait. - waitTimeout = (startTime + timeout) - now; - } - else - { - // We're past the wait time. No need to wait anymore - waitTimeout = TimeSpan.Zero; - } - } - bool success = task.Wait(waitTimeout); - if (!success || m_terminating) - { - source.Cancel(); - // Call wait again without timeout to wait for lock to be reaquired - // ReSharper disable once MethodSupportsCancellation - task.WaitWithoutException(); - m_blockingRpcCalls.Remove(callUid); - result = null; - return false; - } - continue; - } - byte[] vresult = new byte[str.Length]; - Array.Copy(str, vresult, vresult.Length); - result = vresult; - m_blockingRpcCalls.Remove(callUid); - return true; - } - } - finally - { - monitor?.Dispose(); - } - } - } -} diff --git a/src/FRC.NetworkTables/StorageSaving.cs b/src/FRC.NetworkTables/StorageSaving.cs deleted file mode 100644 index a23b628..0000000 --- a/src/FRC.NetworkTables/StorageSaving.cs +++ /dev/null @@ -1,748 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Nito.AsyncEx.Synchronous; -using static NetworkTables.Logging.Logger; -using NetworkTables.Logging; - -namespace NetworkTables -{ - internal partial class Storage - { - private class StoragePairComparer : IComparer<(string key, Value value)> - { - public int Compare((string key, Value value) x, (string key, Value value) y) - { - return string.Compare(x.key, y.key, StringComparison.Ordinal); - } - } - - private readonly static StoragePairComparer s_storageComparer = new StoragePairComparer(); - - private bool GetPersistentEntries(bool periodic, List<(string key, Value value)> entries) - { - using (m_monitor.Enter()) - { - if (periodic && !m_persistentDirty) return false; - m_persistentDirty = false; - foreach (var i in m_entries) - { - Entry entry = i.Value; - if (!entry.IsPersistent()) continue; - entries.Add((i.Key, entry.Value)); - } - } - entries.Sort(s_storageComparer); - return true; - } - - private static async Task SavePersistentImpl(StreamWriter stream, IEnumerable<(string key, Value value)> entries) - { - await stream.WriteAsync("[NetworkTables Storage 3.0]\n").ConfigureAwait(false); - foreach (var i in entries) - { - var v = i.value; - if (v == null) continue; - switch (v.Type) - { - case NtType.Boolean: - await stream.WriteAsync("boolean ").ConfigureAwait(false); - break; - case NtType.Double: - await stream.WriteAsync("double ").ConfigureAwait(false); - break; - case NtType.String: - await stream.WriteAsync("string ").ConfigureAwait(false); - break; - case NtType.Raw: - await stream.WriteAsync("raw ").ConfigureAwait(false); - break; - case NtType.BooleanArray: - await stream.WriteAsync("array boolean ").ConfigureAwait(false); - break; - case NtType.DoubleArray: - await stream.WriteAsync("array double ").ConfigureAwait(false); - break; - case NtType.StringArray: - await stream.WriteAsync("array string ").ConfigureAwait(false); - break; - default: - continue; - } - - await WriteStringAsync(stream, i.key).ConfigureAwait(false); - - await stream.WriteAsync('=').ConfigureAwait(false); - - switch (v.Type) - { - case NtType.Boolean: - await stream.WriteAsync(v.GetBoolean() ? "true" : "false").ConfigureAwait(false); - break; - case NtType.Double: - // ReSharper disable once SpecifyACultureInStringConversionExplicitly - await stream.WriteAsync(v.GetDouble().ToString()).ConfigureAwait(false); - break; - case NtType.String: - await WriteStringAsync(stream, v.GetString()).ConfigureAwait(false); - break; - case NtType.Raw: - await stream.WriteAsync(Convert.ToBase64String(v.GetRaw())).ConfigureAwait(false); - break; - case NtType.BooleanArray: - bool first = true; - foreach (var b in v.GetBooleanArray()) - { - if (!first) stream.Write(","); - first = false; - await stream.WriteAsync(b ? "true" : "false").ConfigureAwait(false); - } - break; - case NtType.DoubleArray: - first = true; - foreach (var b in v.GetDoubleArray()) - { - if (!first) stream.Write(","); - first = false; - // ReSharper disable once SpecifyACultureInStringConversionExplicitly - await stream.WriteAsync(b.ToString()).ConfigureAwait(false); - } - break; - case NtType.StringArray: - first = true; - foreach (var b in v.GetStringArray()) - { - if (!first) stream.Write(","); - first = false; - await WriteStringAsync(stream, b).ConfigureAwait(false); - } - break; - } - //eol - await stream.WriteAsync('\n').ConfigureAwait(false); - } - } - - private static char HexDigit(int x) - { - const byte hexChar = (byte)'A'; - return (char)(x < 10 ? (byte)'0' + x : hexChar + x - 10); - } - - private static async Task WriteStringAsync(StreamWriter stream, string str) - { - await stream.WriteAsync('"').ConfigureAwait(false); - foreach (var c in str) - { - switch (c) - { - case '\\': - await stream.WriteAsync("\\\\").ConfigureAwait(false); - break; - case '\t': - await stream.WriteAsync("\\t").ConfigureAwait(false); - break; - case '\n': - await stream.WriteAsync("\\n").ConfigureAwait(false); - break; - case '"': - await stream.WriteAsync("\\\"").ConfigureAwait(false); - break; - case '\0': - await stream.WriteAsync("\\x00").ConfigureAwait(false); - break; - default: - if (IsPrintable(c) && c != '=') - { - await stream.WriteAsync(c).ConfigureAwait(false); - break; - } - - await stream.WriteAsync("\\x").ConfigureAwait(false); - await stream.WriteAsync(HexDigit((c >> 4) & 0xF)).ConfigureAwait(false); - await stream.WriteAsync(HexDigit((c >> 0) & 0xF)).ConfigureAwait(false); - break; - } - } - await stream.WriteAsync('"').ConfigureAwait(false); - } - - private static bool IsPrintable(char c) - { - return c > 0x1f && c < 127; - } - - private static void ReadStringToken(out string first, out string second, string source) - { - if (string.IsNullOrEmpty(source) || source[0] != '"') - { - first = ""; - second = source; - return; - } - int size = source.Length; - int pos; - for (pos = 1; pos < size; ++pos) - { - if (source[pos] == '"' && source[pos - 1] != '\\') - { - ++pos; - break; - } - } - - first = source.Substring(0, pos); - second = source.Substring(pos); - } - - private static bool IsXDigit(char c) - { - if ('0' <= c && c <= '9') return true; - if ('a' <= c && c <= 'f') return true; - if ('A' <= c && c <= 'F') return true; - return false; - } - - private static int FromXDigit(char ch) - { - if (ch >= 'a' && ch <= 'f') - return (ch - 'a' + 10); - else if (ch >= 'A' && ch <= 'F') - return (ch - 'A' + 10); - else - return ch - '0'; - } - - private static void UnescapeString(string source, out string dest) - { - if (!(source.Length >= 2 && source[0] == '"' && source[source.Length - 1] == '"')) - { - throw new ArgumentOutOfRangeException(nameof(source), "Source not correct"); - } - - StringBuilder builder = new StringBuilder(source.Length - 2); - int s = 1; - int end = source.Length - 1; - - for (; s != end; ++s) - { - if (source[s] != '\\') - { - builder.Append(source[s]); - continue; - } - switch (source[++s]) - { - case '\\': - case '"': - builder.Append(source[s]); - break; - case 't': - builder.Append('\t'); - break; - case 'n': - builder.Append('\n'); - break; - case 'x': - if (!IsXDigit(source[s + 1])) - { - builder.Append('x'); - break; - } - int ch = FromXDigit(source[++s]); - if (IsXDigit(source[s + 1])) - { - ch <<= 4; - ch |= FromXDigit(source[++s]); - } - builder.Append((char)ch); - break; - default: - builder.Append(source[s - 1]); - break; - } - } - dest = builder.ToString(); - } - - public void SavePersistent(Stream stream, bool periodic) - { - List<(string key, Value value)> entries = new List<(string key, Value value)>(); - if (!GetPersistentEntries(periodic, entries)) return; - StreamWriter w = new StreamWriter(stream); - Task task = SavePersistentImpl(w, entries); - task.WaitAndUnwrapException(); - w.Flush(); - } - - public string SavePersistent(string filename, bool periodic) - { - string err = null; - try - { - string fn = filename; - string tmp = filename; - - tmp += ".tmp"; - string bak = filename; - bak += ".bak"; - - //Get entries before creating files - List<(string key, Value value)> entries = new List<(string key, Value value)>(); - if (!GetPersistentEntries(periodic, entries)) return null; - - - - //Start writing to a temp file - try - { - using (FileStream fStream = File.Open(tmp, FileMode.Create, FileAccess.Write, FileShare.Read)) - using (StreamWriter writer = new StreamWriter(fStream)) - { - Debug(Logger.Instance, $"saving persistent file '{filename}'"); - Task task = SavePersistentImpl(writer, entries); - task.WaitAndUnwrapException(); - writer.Flush(); - } - } - catch (IOException) - { - err = "could not open or save file"; - return err; - } - - try - { - File.Delete(bak); - File.Move(fn, bak); - } - catch (IOException) - { - //Unable to delete or copy. Ignoring - } - - try - { - File.Move(tmp, fn); - } - catch (IOException) - { - //Attempt to restore backup - try - { - File.Move(bak, fn); - } - catch (IOException) - { - //Do nothing if it fails - } - err = "could not rename temp file to real file"; - } - return err; - } - finally - { - if (err != null && periodic) m_persistentDirty = true; - } - } - - public async Task SavePersistentAsync(string filename, bool periodic) - { - string fn = filename; - string tmp = filename; - - tmp += ".tmp"; - string bak = filename; - bak += ".bak"; - - //Get entries before creating files - List<(string key, Value value)> entries = new List<(string key, Value value)>(); - if (!GetPersistentEntries(periodic, entries)) return null; - - string err = null; - - //Start writing to a temp file - try - { - using (FileStream fStream = File.Open(tmp, FileMode.Create, FileAccess.Write, FileShare.Read)) - using (StreamWriter writer = new StreamWriter(fStream)) - { - Debug(Logger.Instance, $"saving persistent file '{filename}'"); - await SavePersistentImpl(writer, entries).ConfigureAwait(false); - await writer.FlushAsync().ConfigureAwait(false); - } - } - catch (IOException) - { - err = "could not open or save file"; - m_persistentDirty = true; - return err; - } - - try - { - File.Delete(bak); - File.Move(fn, bak); - } - catch (IOException) - { - //Unable to delete or copy. Ignoring - } - - try - { - File.Move(tmp, fn); - } - catch (IOException) - { - //Attempt to restore backup - try - { - File.Move(bak, fn); - } - catch (IOException) - { - //Do nothing if it fails - } - err = "could not rename temp file to real file"; - } - - if (err != null && periodic) m_persistentDirty = true; - return err; - } - - private static Value ReadStringArray(string line, int lineNum, List stringArray, Action warn) - { - stringArray.Clear(); - while (!string.IsNullOrEmpty(line)) - { - ReadStringToken(out string elemTok, out line, line); - if (string.IsNullOrEmpty(elemTok)) - { - warn?.Invoke(lineNum, "missing string value"); - return null; - } - if (elemTok[elemTok.Length - 1] != '"') - { - warn?.Invoke(lineNum, "unterminated string value"); - return null; - } - UnescapeString(elemTok, out string str); - stringArray.Add(str); - - line = line.TrimStart(' ', '\t'); - if (string.IsNullOrEmpty(line)) break; - if (line[0] != ',') - { - warn?.Invoke(lineNum, "expected comma between strings"); - return null; - } - line = line.Substring(1).TrimStart(' ', '\t'); - } - - return Value.MakeStringArray(stringArray.ToArray()); - } - - private static Value ReadDoubleArray(string line, int lineNum, List doubleArray, - Action warn) - { - doubleArray.Clear(); - while (!string.IsNullOrEmpty(line)) - { - string[] spl = line.Split(new[] { ',' }, 2); - line = spl.Length == 1 ? string.Empty : spl[1]; - string strTok = spl[0].Trim(' ', '\t'); - bool tmpBoolean = double.TryParse(strTok, out double tmpDouble); - if (!tmpBoolean) - { - warn?.Invoke(lineNum, "invalid double value"); - return null; - } - doubleArray.Add(tmpDouble); - } - return Value.MakeDoubleArray(doubleArray.ToArray()); - } - - private static Value ReadBooleanArray(string line, int lineNum, List boolArray, - Action warn) - { - boolArray.Clear(); - while (!string.IsNullOrEmpty(line)) - { - string[] spl = line.Split(new[] { ',' }, 2); - line = spl.Length < 2 ? string.Empty : spl[1]; - string strTok = spl[0].Trim(' ', '\t'); - if (strTok == "true") - boolArray.Add(true); - else if (strTok == "false") - boolArray.Add(false); - else - { - warn?.Invoke(lineNum, "unrecognized boolean value, not 'true' or 'false'"); - return null; - } - } - return Value.MakeBooleanArray(boolArray.ToArray()); - } - - public string LoadPersistent(string filename, Action warn) - { - try - { - using (Stream stream = new FileStream(filename, FileMode.Open)) - { - Task task = LoadPersistentAsync(stream, warn); - task.WaitAndUnwrapException(); - if (!task.Result) return "error reading file"; - return null; - } - } - catch (FileNotFoundException) - { - return "could not open file"; - } - } - - public async Task LoadPersistentAsync(string filename, Action warn) - { - try - { - using (Stream stream = new FileStream(filename, FileMode.Open)) - { - if (!await LoadPersistentAsync(stream, warn).ConfigureAwait(false)) return "error reading file"; - return null; - } - } - catch (FileNotFoundException) - { - return "could not open file"; - } - } - - public bool LoadPersistent(Stream stream, Action warn) - { - Task task = LoadPersistentAsync(stream, warn); - task.WaitAndUnwrapException(); - return task.Result; - } - - public async Task LoadPersistentAsync(Stream stream, Action warn) - { - int lineNum = 1; - - List<(string key, Value value)> entries = new List<(string key, Value value)>(); - - List boolArray = new List(); - List doubleArray = new List(); - List stringArray = new List(); - - using (StreamReader reader = new StreamReader(stream)) - { - string lineStr; - while ((lineStr = await reader.ReadLineAsync().ConfigureAwait(false)) != null) - { - string line = lineStr.Trim(); - if (line != string.Empty && line[0] != ';' && line[0] != '#') - { - break; - } - } - - if (lineStr != "[NetworkTables Storage 3.0]") - { - warn?.Invoke(lineNum, "header line mismatch, ignoring rest of file"); - return false; - } - - while ((lineStr = await reader.ReadLineAsync().ConfigureAwait(false)) != null) - { - string line = lineStr.Trim(); - ++lineNum; - - if (line == string.Empty || line[0] == ';' || line[0] == '#') - { - continue; - } - - string[] split = line.Split(new[] { ' ' }, 2); - var typeTok = split[0]; - line = split[1]; - NtType type = NtType.Unassigned; - if (typeTok == "boolean") type = NtType.Boolean; - else if (typeTok == "double") type = NtType.Double; - else if (typeTok == "string") type = NtType.String; - else if (typeTok == "raw") type = NtType.Raw; - else if (typeTok == "array") - { - split = line.Split(new[] { ' ' }, 2); - var arrayTok = split[0]; - line = split[1]; - if (arrayTok == "boolean") type = NtType.BooleanArray; - else if (arrayTok == "double") type = NtType.DoubleArray; - else if (arrayTok == "string") type = NtType.StringArray; - } - - if (type == NtType.Unassigned) - { - warn?.Invoke(lineNum, "unrecognized type"); - continue; - } - - ReadStringToken(out string nameTok, out line, line); - if (string.IsNullOrEmpty(nameTok)) - { - warn?.Invoke(lineNum, "unterminated name string"); - continue; - } - UnescapeString(nameTok, out string name); - - line = line.TrimStart('\t'); - if (string.IsNullOrEmpty(line) || line[0] != '=') - { - warn?.Invoke(lineNum, "expected = after name"); - continue; - } - line = line.Substring(1).TrimStart(' ', '\t'); - - Value value = null; - string str; - switch (type) - { - case NtType.Boolean: - if (line == "true") - value = Value.MakeBoolean(true); - else if (line == "false") - value = Value.MakeBoolean(false); - else - { - warn?.Invoke(lineNum, "unrecognized boolean value, not 'true' or 'false'"); - continue; - } - break; - case NtType.Double: - str = line; - double tmpDouble; - var tmpBoolean = double.TryParse(str, out tmpDouble); - if (!tmpBoolean) - { - warn?.Invoke(lineNum, "invalid double value"); - continue; - } - value = Value.MakeDouble(tmpDouble); - break; - case NtType.String: - string strTok; - ReadStringToken(out strTok, out line, line); - if (string.IsNullOrEmpty(strTok)) - { - warn?.Invoke(lineNum, "missing string value"); - continue; - } - if (strTok[strTok.Length - 1] != '"') - { - warn?.Invoke(lineNum, "unterminated string value"); - continue; - } - UnescapeString(strTok, out str); - value = Value.MakeString(str); - break; - case NtType.Raw: - value = Value.MakeRaw(Convert.FromBase64String(line)); - break; - case NtType.BooleanArray: - value = ReadBooleanArray(line, lineNum, boolArray, warn); - if (value == null) continue; - break; - case NtType.DoubleArray: - value = ReadDoubleArray(line, lineNum, doubleArray, warn); - if (value == null) continue; - break; - case NtType.StringArray: - value = ReadStringArray(line, lineNum, stringArray, warn); - if (value == null) continue; - break; - } - if (name.Length != 0 && value != null) - { - entries.Add((name, value)); - } - - } - - List msgs = new List(); - - IDisposable monitor = null; - try - { - monitor = await m_monitor.EnterAsync().ConfigureAwait(false); - foreach (var i in entries) - { - if (!m_entries.TryGetValue(i.key, out Entry entry)) - { - entry = new Entry(i.key); - m_entries.Add(i.key, entry); - } - var oldValue = entry.Value; - entry.Value = i.value; - bool wasPersist = entry.IsPersistent(); - if (!wasPersist) entry.Flags |= EntryFlags.Persistent; - - if (m_server && entry.Id == 0xffff) - { - uint id = (uint)m_idMap.Count; - entry.Id = id; - m_idMap.Add(entry); - } - - if (m_notifier.LocalNotifiers()) - { - if (oldValue != null) - { - m_notifier.NotifyEntry(i.key, i.value, (NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); - } - else if (oldValue != i.value) - { - NotifyFlags notifyFlags = NotifyFlags.NotifyUpdate | NotifyFlags.NotifyLocal; - if (!wasPersist) notifyFlags |= NotifyFlags.NotifyFlagsChanged; - m_notifier.NotifyEntry(i.key, i.value, notifyFlags); - } - } - - if (m_queueOutgoing == null) continue; - ++entry.SeqNum; - - if (oldValue == null || oldValue.Type != i.value.Type) - { - msgs.Add(Message.EntryAssign(i.key, entry.Id, entry.SeqNum.Value, i.value, entry.Flags)); - } - else if (entry.Id != 0xffff) - { - if (oldValue != i.value) - { - msgs.Add(Message.EntryUpdate(entry.Id, entry.SeqNum.Value, i.value)); - } - if (!wasPersist) - msgs.Add(Message.FlagsUpdate(entry.Id, entry.Flags)); - } - } - - if (m_queueOutgoing != null) - { - var queuOutgoing = m_queueOutgoing; - IDisposable monitorToUnlock = Interlocked.Exchange(ref monitor, null); - monitorToUnlock.Dispose(); - foreach (var msg in msgs) queuOutgoing(msg, null, null); - } - } - finally - { - monitor?.Dispose(); - } - } - return true; - } - } -} diff --git a/src/FRC.NetworkTables/Streams/StreamExtensions.cs b/src/FRC.NetworkTables/Streams/StreamExtensions.cs deleted file mode 100644 index 971e6bd..0000000 --- a/src/FRC.NetworkTables/Streams/StreamExtensions.cs +++ /dev/null @@ -1,105 +0,0 @@ -using NetworkTables.Logging; -using System.IO; -using System.Net.Sockets; -using static NetworkTables.Logging.Logger; - -namespace NetworkTables.Streams -{ - internal static class StreamExtensions - { - public static int Send(this Stream stream, byte[] buffer, int pos, int len) - { - if (!stream.CanWrite) - { - return 0; - } - - int errorCode = 0; - while (true) - { - try - { - stream.Write(buffer, pos, len); - break; - } - catch (IOException ex) - { - SocketException sx = ex.InnerException as SocketException; - if (sx == null) - { - //Not socket exception is real error. Rethrow - throw; - } - if (sx.SocketErrorCode != SocketError.WouldBlock)//WSAEWOULDBLOCK - { - errorCode = (int)sx.SocketErrorCode; - break; - } - } - } - - if (errorCode != 0) - { - string error = $"Send() failed: WSA error={errorCode.ToString()}\n"; - Debug4(Logger.Instance, error); - return 0; - } - return len; - } - - public static bool ReceiveByte(this Stream stream, out byte data) - { - data = 0; - if (!stream.CanRead) return false; - - try - { - int ret = stream.ReadByte(); - if (ret < 0) return false; - data = (byte)ret; - return true; - } - catch (IOException ex) - { - SocketException sx = ex.InnerException as SocketException; - if (sx == null) - { - //Not socket exception is real error. Rethrow - throw; - } - //Return false on socket exception - return false; - } - } - - public static int Receive(this Stream stream, byte[] buffer, int offset, int size) - { - if (!stream.CanRead) return 0; - try - { - int pos = offset; - - while (pos < size + offset) - { - int count = stream.Read(buffer, pos, size - pos); - if (count == 0) return 0; - pos += count; - } - - return size; - } - catch (IOException ex) - { - SocketException sx = ex.InnerException as SocketException; - if (sx == null) - { - //Not socket exception is real error. Rethrow - throw; - } - //Return 0 on socket exception - return 0; - } - - } - } -} diff --git a/src/FRC.NetworkTables/Support/Timestamp.cs b/src/FRC.NetworkTables/Support/Timestamp.cs deleted file mode 100644 index 8690c2a..0000000 --- a/src/FRC.NetworkTables/Support/Timestamp.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace NetworkTables.Support -{ - internal static class Timestamp - { - public static long Now() - { - // Gets a consistent timestamp that we can use for checking if data is new. - return DateTime.UtcNow.ToFileTimeUtc(); - } - } -} diff --git a/src/FRC.NetworkTables/TcpSockets/IClient.cs b/src/FRC.NetworkTables/TcpSockets/IClient.cs deleted file mode 100644 index 110982f..0000000 --- a/src/FRC.NetworkTables/TcpSockets/IClient.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.IO; -using System.Net; - -namespace NetworkTables.TcpSockets -{ - interface IClient : IDisposable - { - Stream GetStream(); - EndPoint RemoteEndPoint { get; } - bool NoDelay { set; } - } -} diff --git a/src/FRC.NetworkTables/TcpSockets/INetworkAcceptor.cs b/src/FRC.NetworkTables/TcpSockets/INetworkAcceptor.cs deleted file mode 100644 index 4444f2c..0000000 --- a/src/FRC.NetworkTables/TcpSockets/INetworkAcceptor.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace NetworkTables.TcpSockets -{ - internal interface INetworkAcceptor: IDisposable - { - int Start(); - void Shutdown(); - IClient Accept(); - } -} diff --git a/src/FRC.NetworkTables/TcpSockets/NtTcpClient.cs b/src/FRC.NetworkTables/TcpSockets/NtTcpClient.cs deleted file mode 100644 index 8d3f38c..0000000 --- a/src/FRC.NetworkTables/TcpSockets/NtTcpClient.cs +++ /dev/null @@ -1,208 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net; -using System.Net.Sockets; -using System.IO; -using static NetworkTables.Logging.Logger; -using NetworkTables.Logging; - -namespace NetworkTables.TcpSockets -{ - internal class NtTcpClient : IClient - { - private Socket m_clientSocket; - private NetworkStream m_dataStream; - private bool m_cleanedUp; - private bool m_active; - - public NtTcpClient() : this(AddressFamily.InterNetwork) { } - - public bool NoDelay - { - get { return m_clientSocket.NoDelay; } - set { m_clientSocket.NoDelay = value; } - } - - public EndPoint RemoteEndPoint => m_clientSocket.RemoteEndPoint; - - public NtTcpClient(AddressFamily family) - { - if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) - { - throw new ArgumentException("Invalid TCP Family", nameof(family)); - } - - m_clientSocket = new Socket(family, SocketType.Stream, ProtocolType.Tcp); - } - - internal NtTcpClient(Socket acceptedSocket) - { - m_clientSocket = acceptedSocket; - m_active = true; - } - - public bool Active - { - get { return m_active; } - set { m_active = value; } - } - - public Stream GetStream() - { - if (m_cleanedUp) - { - throw new ObjectDisposedException(GetType().FullName); - } - if (!m_clientSocket.Connected) - { - throw new InvalidOperationException("Not Connected"); - } - return m_dataStream ?? (m_dataStream = new NetworkStream(m_clientSocket, true)); - } - - public void Connect(IPAddress[] ipAddresses, int port) - { - m_clientSocket.Connect(ipAddresses, port); - m_active = true; - } - - public bool ConnectWithTimeout(IPAddress[] ipAddresses, int port, Logger logger, int timeout) - { - if (ipAddresses == null) - throw new ArgumentNullException(nameof(ipAddresses), "IP Addresses cannot be null"); - if (ipAddresses.Length == 0) - throw new ArgumentOutOfRangeException(nameof(ipAddresses), "IP Adresses must have values internally"); - - IPEndPoint ipEp = new IPEndPoint(ipAddresses[0], port); - bool isProperlySupported = RuntimeDetector.GetRuntimeHasProperSockets(); - try - { - m_clientSocket.Blocking = false; - if (isProperlySupported) - { - m_clientSocket.Connect(ipAddresses, port); - } - else - { - m_clientSocket.Connect(ipEp); - } - //We have connected - m_active = true; - return true; - - } - catch (SocketException ex) - { - - if (ex.SocketErrorCode == SocketError.WouldBlock || ex.SocketErrorCode == SocketError.InProgress) - { - DateTime waitUntil = DateTime.UtcNow + TimeSpan.FromSeconds(timeout); - try - { - while (true) - { - if (m_clientSocket.Poll(1000, SelectMode.SelectWrite)) - { - if (!isProperlySupported) - m_clientSocket.Connect(ipEp); - // We have connected - m_active = true; - return true; - } - else - { - if (DateTime.UtcNow >= waitUntil) - { - // We have timed out - Info(logger, $"Connect() to {ipAddresses[0]} port {port.ToString()} timed out"); - break; - } - } - } - } - catch (SocketException ex2) - { - if (!isProperlySupported) - { - if (ex2.SocketErrorCode == SocketError.IsConnected) - { - m_active = true; - return true; - } - } - Error(logger, $"Select() to {ipAddresses[0]} port {port.ToString()} error {ex2.SocketErrorCode}"); - } - } - else - { - if (ex.SocketErrorCode == SocketError.ConnectionRefused) - { - // A connection refused is an unexceptional case - Info(logger, $"Connect() to {ipAddresses[0]} port {port.ToString()} timed out"); - } - Error(logger, $"Connect() to {ipAddresses[0]} port {port.ToString()} error {ex.SocketErrorCode}"); - } - - } - finally - { - m_clientSocket.Blocking = true; - } - return false; - } - - protected virtual void Dispose(bool disposing) - { - if (m_cleanedUp) - { - return; - } - - if (disposing) - { - IDisposable dataStream = m_dataStream; - if (dataStream != null) - { - dataStream.Dispose(); - } - else - { - Socket chkClientSocket = m_clientSocket; - if (chkClientSocket != null) - { - try - { - chkClientSocket.Shutdown(SocketShutdown.Both); - } - catch (SocketException) { } // Ignore any socket exception - finally - { - chkClientSocket.Dispose(); - m_clientSocket = null; - } - } - } - - GC.SuppressFinalize(this); - } - - m_cleanedUp = true; - } - - ~NtTcpClient() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - } - - public bool Connected => m_clientSocket.Connected; - } - -} diff --git a/src/FRC.NetworkTables/TcpSockets/NtTcpListener.cs b/src/FRC.NetworkTables/TcpSockets/NtTcpListener.cs deleted file mode 100644 index 9c45a0d..0000000 --- a/src/FRC.NetworkTables/TcpSockets/NtTcpListener.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net; -using System.Net.Sockets; - -namespace NetworkTables.TcpSockets -{ - internal class NtTcpListener - { - private readonly IPEndPoint m_serverSocketEp; - private Socket m_serverSocket; - private bool m_active; - - - public NtTcpListener(IPAddress localaddr, int port) - { - if (localaddr == null) - { - throw new ArgumentNullException(nameof(localaddr)); - } - m_serverSocketEp = new IPEndPoint(localaddr, port); - m_serverSocket = new Socket(m_serverSocketEp.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - } - - public void Start(int backlog = (int)SocketOptionName.MaxConnections) - { - if (backlog < 0) - { - throw new ArgumentOutOfRangeException(nameof(backlog)); - } - - if (m_serverSocket == null) - { - throw new InvalidOperationException("Invalid Socket Handle"); - } - - if (m_active) - { - return; - } - try - { - m_serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); - } - catch (SocketException) - { - // Raspberry Pi does not support setting the socket option, so must catch. - } - m_serverSocket.Bind(m_serverSocketEp); - try - { - m_serverSocket.Listen(backlog); - } - catch (SocketException) - { - Stop(); - throw; - } - - m_active = true; - } - - public void Stop() - { - if (m_serverSocket != null) - { - m_serverSocket.Dispose(); - m_serverSocket = null; - } - m_active = false; - m_serverSocket = new Socket(m_serverSocketEp.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - } - - public Socket Accept(out SocketError errorCode) - { - Socket socket; - try - { - socket = m_serverSocket.Accept(); - } - catch (SocketException ex) - { - errorCode = ex.SocketErrorCode; - return null; - } - errorCode = 0; - return socket; - } - } -} diff --git a/src/FRC.NetworkTables/TcpSockets/RuntimeDetector.cs b/src/FRC.NetworkTables/TcpSockets/RuntimeDetector.cs deleted file mode 100644 index 0373b66..0000000 --- a/src/FRC.NetworkTables/TcpSockets/RuntimeDetector.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -#if NETSTANDARD1_3 -using System.Runtime.InteropServices; -#endif - -namespace NetworkTables.TcpSockets -{ - internal static class RuntimeDetector - { - enum ProperSocketsCacheState - { - NotCached, - Supported, - NotSupported - } - - private static ProperSocketsCacheState s_socketState = ProperSocketsCacheState.NotCached; - - /// - /// Gets if the runtime has sockets that support proper connections - /// - /// - public static bool GetRuntimeHasProperSockets() - { - if (s_socketState == ProperSocketsCacheState.NotCached) - { - Type type = Type.GetType("Mono.Runtime"); - if (type == null) - { -#if NETSTANDARD1_3 - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - // Windows - s_socketState = ProperSocketsCacheState.Supported; - return true; - } - else - { - // Unix - s_socketState = ProperSocketsCacheState.NotSupported; - return false; - } -#else - // Full .net framework works perfectly. - s_socketState = ProperSocketsCacheState.Supported; - return true; -#endif - } - // For now mono does not support, so return false - s_socketState = ProperSocketsCacheState.NotSupported; - return false; - } - return s_socketState == ProperSocketsCacheState.Supported; - } - } -} diff --git a/src/FRC.NetworkTables/TcpSockets/TcpAcceptor.cs b/src/FRC.NetworkTables/TcpSockets/TcpAcceptor.cs deleted file mode 100644 index 3a55700..0000000 --- a/src/FRC.NetworkTables/TcpSockets/TcpAcceptor.cs +++ /dev/null @@ -1,115 +0,0 @@ -using NetworkTables.Logging; -using System; -using System.Net; -using System.Net.Sockets; -using static NetworkTables.Logging.Logger; - -namespace NetworkTables.TcpSockets -{ - internal class TcpAcceptor : INetworkAcceptor - { - private NtTcpListener m_server; - - private readonly int m_port; - private readonly string m_address; - - private bool m_shutdown; - private bool m_listening; - - public TcpAcceptor(int port, string address) - { - m_port = port; - m_address = address; - } - - public void Dispose() - { - if (m_server != null) - { - Shutdown(); - } - } - - public int Start() - { - if (m_listening) return 0; - var address = !string.IsNullOrEmpty(m_address) ? IPAddress.Parse(m_address) : IPAddress.Any; - - m_server = new NtTcpListener(address, m_port); - - try - { - m_server.Start(5); - } - catch (ObjectDisposedException) - { - return 1; - } - catch (SocketException ex) - { - Error(Logger.Instance, $"TcpListener Start(): failed {ex.SocketErrorCode}"); - return (int)ex.SocketErrorCode; - } - - m_listening = true; - return 0; - } - - public void Shutdown() - { - m_shutdown = true; - - //Force wakeup with non-blocking connect to ourselves - var address = !string.IsNullOrEmpty(m_address) ? IPAddress.Parse(m_address) : IPAddress.Loopback; - - Socket connectSocket; - try - { - connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - } - catch (SocketException) - { - return; - } - - connectSocket.Blocking = false; - - try - { - connectSocket.Connect(address, m_port); - connectSocket.Dispose(); - } - catch (SocketException) - { - } - - m_listening = false; - m_server?.Stop(); - m_server = null; - - - - m_listening = false; - m_server?.Stop(); - m_server = null; - } - - public IClient Accept() - { - if (!m_listening || m_shutdown) return null; - - Socket socket = m_server.Accept(out SocketError error); - if (socket == null) - { - if (!m_shutdown) Error(Logger.Instance, $"Accept() failed: {error}"); - return null; - } - if (m_shutdown) - { - socket.Dispose(); - return null; - } - return new NtTcpClient(socket); - } - } -} diff --git a/src/FRC.NetworkTables/TcpSockets/TcpConnector.cs b/src/FRC.NetworkTables/TcpSockets/TcpConnector.cs deleted file mode 100644 index 4d6f8e6..0000000 --- a/src/FRC.NetworkTables/TcpSockets/TcpConnector.cs +++ /dev/null @@ -1,106 +0,0 @@ -using NetworkTables.Logging; -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Threading.Tasks; -using System.Runtime.ExceptionServices; -using static NetworkTables.Logging.Logger; - -namespace NetworkTables.TcpSockets -{ - internal class TcpConnector - { - private static bool WaitAndUnwrapException(Task task, int timeout) - { - try - { - return task.Wait(timeout); - } - catch (AggregateException ex) - { - ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); - throw ex.InnerException; - } - } - - private static int ResolveHostName(string hostName, out IPAddress[] addr) - { - try - { - var entries = Dns.GetHostAddressesAsync(hostName); - var success = WaitAndUnwrapException(entries, 1000); - if (!success) - { - addr = null; - return 1; - } - List addresses = new List(); - foreach (var ipAddress in entries.Result) - { - // Only allow IPV4 addresses for now - // Sockets don't all support IPV6 - if (ipAddress.AddressFamily == AddressFamily.InterNetwork) - { - if (!addresses.Contains(ipAddress)) - { - addresses.Add(ipAddress); - } - } - } - addr = addresses.ToArray(); - - } - catch (SocketException e) - { - addr = null; - return (int)e.SocketErrorCode; - } - return 0; - } - - public static NtTcpClient Connect(string server, int port, Logger logger, int timeout = 0) - { - if (ResolveHostName(server, out IPAddress[] addr) != 0) - { - try - { - addr = new IPAddress[1]; - addr[0] = IPAddress.Parse(server); - } - catch (FormatException) - { - Error(logger, $"could not resolve {server} address"); - return null; - } - } - - //Create out client - NtTcpClient client = new NtTcpClient(AddressFamily.InterNetwork); - // No time limit, connect forever - if (timeout == 0) - { - try - { - client.Connect(addr, port); - } - catch (SocketException ex) - { - Error(logger, $"Connect() to {server} port {port.ToString()} failed: {ex.SocketErrorCode}"); - ((IDisposable)client).Dispose(); - return null; - } - return client; - } - - //Connect with time limit - bool connectedWithTimeout = client.ConnectWithTimeout(addr, port, logger, timeout); - if (!connectedWithTimeout) - { - ((IDisposable)client).Dispose(); - return null; - } - return client; - } - } -} diff --git a/src/NetworkTablesAPI/Controllers/NTController.cs b/src/NetworkTablesAPI/Controllers/NTController.cs new file mode 100644 index 0000000..996cb4b --- /dev/null +++ b/src/NetworkTablesAPI/Controllers/NTController.cs @@ -0,0 +1,18 @@ +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace NetworkTablesAPI.Controllers +{ + [ApiController] + public class NTController : ControllerBase + { + [HttpGet("{key}")] + public ActionResult> GetValue(string key) + { + return new string[]{ "Hello" }; + } + } +} diff --git a/src/NetworkTablesAPI/Controllers/ValuesController.cs b/src/NetworkTablesAPI/Controllers/ValuesController.cs new file mode 100644 index 0000000..668c18e --- /dev/null +++ b/src/NetworkTablesAPI/Controllers/ValuesController.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; + +namespace NetworkTablesAPI.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class ValuesController : ControllerBase + { + // GET api/values + [HttpGet] + public ActionResult> Get() + { + return new string[] { "value1", "value2" }; + } + + // GET api/values/5 + [HttpGet("{id}")] + public ActionResult Get(string id) + { + return "value"; + } + + // POST api/values + [HttpPost] + public void Post([FromBody] string value) + { + } + + // PUT api/values/5 + [HttpPut("{id}")] + public void Put(int id, [FromBody] string value) + { + } + + // DELETE api/values/5 + [HttpDelete("{id}")] + public void Delete(int id) + { + } + } +} diff --git a/src/NetworkTablesAPI/NetworkTablesAPI.csproj b/src/NetworkTablesAPI/NetworkTablesAPI.csproj new file mode 100644 index 0000000..a2256c8 --- /dev/null +++ b/src/NetworkTablesAPI/NetworkTablesAPI.csproj @@ -0,0 +1,22 @@ + + + + netcoreapp3.0 + + + + 8.0 + enable + + + + + + + + + + + + + diff --git a/src/NetworkTablesAPI/Program.cs b/src/NetworkTablesAPI/Program.cs new file mode 100644 index 0000000..b245ced --- /dev/null +++ b/src/NetworkTablesAPI/Program.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace NetworkTablesAPI +{ + public class Program + { + public static void Main(string[] args) + { + CreateWebHostBuilder(args).Build().Run(); + } + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); + } +} diff --git a/src/NetworkTablesAPI/Properties/launchSettings.json b/src/NetworkTablesAPI/Properties/launchSettings.json new file mode 100644 index 0000000..f351c42 --- /dev/null +++ b/src/NetworkTablesAPI/Properties/launchSettings.json @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:51712", + "sslPort": 44311 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/values", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "NetworkTablesAPI": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "api/values", + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/src/NetworkTablesAPI/Startup.cs b/src/NetworkTablesAPI/Startup.cs new file mode 100644 index 0000000..b3fe90e --- /dev/null +++ b/src/NetworkTablesAPI/Startup.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using FRC.NetworkTables; +using FRC.NetworkTables.Core.Web; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpsPolicy; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Newtonsoft.Json; + +namespace NetworkTablesAPI +{ + + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + var instance = NetworkTableInstance.Default; + instance.StartServer(); + services.AddNetworkTables(instance); + services.AddCors(options => options.AddPolicy("CorsPolicy", + builder => + { + builder.AllowAnyMethod().AllowAnyHeader() + .WithOrigins("http://localhost:44311") + .AllowCredentials(); + })); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseHsts(); + } + + app.UseHttpsRedirection(); + + app.UseCors("CorsPolicy"); + + app.UseNetworkTables(); + + app.UseMvc(); + } + } +} diff --git a/src/NetworkTablesAPI/appsettings.Development.json b/src/NetworkTablesAPI/appsettings.Development.json new file mode 100644 index 0000000..a2880cb --- /dev/null +++ b/src/NetworkTablesAPI/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/src/NetworkTablesAPI/appsettings.json b/src/NetworkTablesAPI/appsettings.json new file mode 100644 index 0000000..7376aad --- /dev/null +++ b/src/NetworkTablesAPI/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/src/Shared/ConnectionInfo.cs b/src/Shared/ConnectionInfo.cs deleted file mode 100644 index c84a684..0000000 --- a/src/Shared/ConnectionInfo.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace NetworkTables -{ - /// - /// This class contains all info needed for a given connection. - /// - public struct ConnectionInfo - { - /// Gets the Remote Id of the Connection. - public string RemoteId { get; } - /// Gets the Remote IP Address of the Connection. - public string RemoteIp { get; } - /// Gets the Remote Port of the Connection. - public int RemotePort { get; } - /// Gets the last update time of the Connection. - public long LastUpdate { get; } - /// Gets the Protocol Version of the Connection. - public int ProtocolVersion { get; } - - internal ConnectionInfo(string rId, string rIp, int rPort, long lastUpdate, int protocolVersion) - { - RemoteId = rId; - RemoteIp = rIp; - RemotePort = rPort; - LastUpdate = lastUpdate; - ProtocolVersion = protocolVersion; - } - } -} diff --git a/src/Shared/Delegates.cs b/src/Shared/Delegates.cs deleted file mode 100644 index 248ce83..0000000 --- a/src/Shared/Delegates.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections.Generic; - -namespace NetworkTables -{ - /// - /// This delegate is used when creating callbacks to be used for EntryListeners - /// - /// The uid of the callback - /// The name of the entry being called back - /// The value of the entry being called back - /// The flags of the entry bing called back - public delegate void EntryListenerCallback(int uid, string name, Value value, NotifyFlags flags); - - /// - /// This delegate is used when creating callbacks to be used for Connection Listeners - /// - /// The uid of the callback - /// True if this is an initial connection, false if the connection disconnected - /// The information for the connection - public delegate void ConnectionListenerCallback(int uid, bool connected, ConnectionInfo conn); - - /// - /// This delegate is use to specify the log function called back from the library - /// - /// The level of the current log - /// The file the log was called from - /// The line the log was called from - /// The message of the log - public delegate void LogFunc(LogLevel level, string file, int line, string msg); - - /// - /// This delegate is used for Remote Procedure Call callbacks - /// - /// The name of the callback - /// The binary data of the callback - /// The connection info for the requested caller - /// The raw rpc data to send in response - public delegate IList RpcCallback(string name, byte[] param, ConnectionInfo connInfo); -} diff --git a/src/Shared/EntryInfo.cs b/src/Shared/EntryInfo.cs deleted file mode 100644 index b972697..0000000 --- a/src/Shared/EntryInfo.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace NetworkTables -{ - /// - /// This class contains all info for a given entry. - /// - public struct EntryInfo - { - /// Gets the Name of the entry. - public string Name { get; } - /// Gets the Type of the entry. - public NtType Type { get; } - /// Gets the Flags attached to the entry. - public EntryFlags Flags { get; } - /// Gets the last change time of the entry. - public long LastChange { get; } - - internal EntryInfo(string name, NtType type, EntryFlags flags, long lastChange) - { - Name = name; - Type = type; - Flags = flags; - LastChange = lastChange; - } - } -} diff --git a/src/Shared/Enumerations.cs b/src/Shared/Enumerations.cs deleted file mode 100644 index 9aca47e..0000000 --- a/src/Shared/Enumerations.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; - -namespace NetworkTables -{ - /// - /// The flags avalible for TableListeners - /// - [Flags] - public enum NotifyFlags - { - /// - /// Notify nobody - /// - NotifyNone = 0x00, - /// - /// Initial listener addition - /// - NotifyImmediate = 0x01, - /// - /// Changed locally - /// - NotifyLocal = 0x02, - /// - /// Newly created entry - /// - NotifyNew = 0x04, - /// - /// Deleted entry - /// - NotifyDelete = 0x08, - /// - /// Value changed for entry - /// - NotifyUpdate = 0x10, - /// - /// Flags changed for entry - /// - NotifyFlagsChanged = 0x20 - }; - - /// - /// The flags avalible for Entries - /// - [Flags] - public enum EntryFlags - { - /// - /// No flags - /// - None = 0x00, - /// - /// Set entry to be persistent - /// - Persistent = 0x01 - } - - /// - /// The log level to use for the NT logger - /// - public enum LogLevel - { - /// - LogCritical = 50, - /// - LogError = 40, - /// - LogWarning = 30, - /// - LogInfo = 20, - /// - LogDebug = 10, - /// - LogDebug1 = 9, - /// - LogDebug2 = 8, - /// - LogDebug3 = 7, - /// - LogDebug4 = 6 - } - -} diff --git a/src/Shared/Exceptions/PersistentException.cs b/src/Shared/Exceptions/PersistentException.cs deleted file mode 100644 index 9ffa74b..0000000 --- a/src/Shared/Exceptions/PersistentException.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.IO; - -namespace NetworkTables.Exceptions -{ - /// - /// An exception thrown when the persistent load/save fails in a . - /// - public class PersistentException : IOException - { - /// - /// Creates a new . - /// - /// The error message. - public PersistentException(string message) : base(message) - { - - } - } -} \ No newline at end of file diff --git a/src/Shared/Exceptions/TableKeyDifferentTypeException.cs b/src/Shared/Exceptions/TableKeyDifferentTypeException.cs deleted file mode 100644 index e776216..0000000 --- a/src/Shared/Exceptions/TableKeyDifferentTypeException.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using NetworkTables.Tables; - -namespace NetworkTables.Exceptions -{ - /// - /// An exception thrown when the key has a different type then requested in the - /// - public class TableKeyDifferentTypeException : InvalidOperationException - { - /// - /// Gets the key that was requested - /// - public string RequestedKey { get; } - /// - /// Gets the type that was requested - /// - public NtType RequestedType { get; } - /// - /// Gets the type that actually exists in the table or value - /// - public NtType TypeInTable { get; } - - /// - /// Gets if the exception was thrown during a Get() method. - /// - public bool ThrownByValueGet { get; } - - /// - /// Creates a new . - /// - /// The table key that was different. - /// The type requested. - /// The type actually in the table. - public TableKeyDifferentTypeException(string key, NtType requested, NtType typeInTable) - : base($"Key: {key}, Requested Type: {requested}, Type in Table: {typeInTable}") - { - RequestedKey = key; - RequestedType = requested; - TypeInTable = typeInTable; - ThrownByValueGet = false; - } - - /// - /// Creates a new during a error - /// - /// The type requested. - /// The type actually in the value. - public TableKeyDifferentTypeException(NtType requested, NtType typeInTable) - : base($"Requested Type {requested} does not match actual Type {typeInTable}.") - { - RequestedKey = ""; - RequestedType = requested; - TypeInTable = typeInTable; - ThrownByValueGet = true; - } - } -} diff --git a/src/Shared/Exceptions/TableKeyNotDefinedException.cs b/src/Shared/Exceptions/TableKeyNotDefinedException.cs deleted file mode 100644 index c05c46f..0000000 --- a/src/Shared/Exceptions/TableKeyNotDefinedException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using NetworkTables.Tables; - -namespace NetworkTables.Exceptions -{ - /// - /// An exception thrown when the lookup of a key-value fails in an . - /// - public class TableKeyNotDefinedException : InvalidOperationException - { - /// - /// Gets the key that is not defined - /// - public string Key { get; } - - /// - /// Creates a new . - /// - /// The key that was not defined in the table. - public TableKeyNotDefinedException(string key) : base($"Unknown Table Key: {key}") - { - Key = key; - } - } -} \ No newline at end of file diff --git a/src/Shared/ListStream.cs b/src/Shared/ListStream.cs deleted file mode 100644 index 0e5869e..0000000 --- a/src/Shared/ListStream.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace NetworkTables -{ - internal class ListStream : Stream - { - private readonly IList m_buffer; - - private int m_position; - - public ListStream(IList list) - { - m_buffer = list ?? throw new ArgumentNullException(nameof(list), "List cannot be null"); - m_position = 0; - } - - public override void Flush() - { - // Do nothing - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new InvalidOperationException(); - } - - public override void SetLength(long value) - { - throw new InvalidOperationException(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - if (buffer == null) throw new ArgumentNullException(nameof(buffer), "The buffer cannot be null"); - if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), "The offset cannot be less then 0"); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), "The count cannot be less then 0"); - if (buffer.Length - offset < count) throw new ArgumentException("Cannot read past the end of the buffer"); - // Implementation from .NET Core - int num = m_buffer.Count - m_position; - if (num > count) num = count; - if (num <= 0) return 0; - - int byteCount = num; - while (--byteCount >= 0) - buffer[offset + byteCount] = m_buffer[m_position + byteCount]; - - m_position += num; - - return num; - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new InvalidOperationException(); - } - - public override bool CanRead => true; - public override bool CanSeek => false; - public override bool CanWrite => false; - public override long Length => m_buffer.Count; - - public override long Position - { - get { return m_position; } - set - { - if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), "Value cannot be less then 0"); - if (value > m_buffer.Count) - throw new ArgumentOutOfRangeException(nameof(value), - $"Value cannot be greater then {m_buffer.Count.ToString()}"); - m_position = (int)value; - } - } - } -} diff --git a/src/Shared/NetworkTable.cs b/src/Shared/NetworkTable.cs deleted file mode 100644 index 935f19c..0000000 --- a/src/Shared/NetworkTable.cs +++ /dev/null @@ -1,1233 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using NetworkTables.Exceptions; -using NetworkTables.Tables; - -namespace NetworkTables -{ - /// - /// This class is the Main Class for interfacing with NetworkTables. - /// - /// For most users, this will be the only class that will be needed. - /// Any interfaces needed to work with this can be found in the - /// namespace. - /// - /// The following example demonstrates creating a server: - /// - /// - /// //Set Server Mode - /// NetworkTable.SetServerMode(); - /// - /// //Initialize the Server - /// NetworkTable.Initialize(); - /// - /// //Get a reference to the smartdashboard. - /// var smartDashboard = NetworkTable.GetTable("SmartDashboard"); - /// - /// smartDashboard can now be used to get and set values in the smart dashboard. - /// Examples on this can be found below the client section. - /// - /// The following example demonstrates creating a client and connecting it to a server: - /// - /// - /// //Set IP Address. Replace xxxx with your team number if connecting to a RoboRIO, - /// //or the server's IP if the server is not a RoboRIO. - /// NetworkTable.SetIPAddress("roborio-xxxx.local"); - /// - /// //Set Client Mode - /// NetworkTable.SetClientMode(); - /// - /// //Initialize the client - /// NetworkTable.Initialize(); - /// - /// //Get a reference to the smartdashboard. - /// var smartDashboard = NetworkTable.GetTable("SmartDashboard"); - /// - /// smartDashboard can now be used to get and set values in the smart dashboard. - /// - /// The following example shows how to get and put values into the smart dashboard: - /// - /// - /// //Strings - /// smartDashboard.PutString("MyString", "MyValue"); - /// string s = smartDashboard.GetString("MyString"); - /// //Note that if the key has not been put in the smart dashboard, - /// //the GetString function will throw a TableKeyNotDefinedException. - /// //To get around this, set a default value to be returned if there is no key, like this: - /// string s = smartDashboard.GetString("MyString", "Default"); - /// - /// //Numbers - /// smartDashboard.PutNumber("MyNumber", 3.562); - /// double s = smartDashboard.GetNumber("MyNumber"); - /// //Note that if the key has not been put in the smart dashboard, - /// //the GetString function will throw a TableKeyNotDefinedException. - /// //To get around this, set a default value to be returned if there is no key, like this: - /// double s = smartDashboard.GetDouble("MyNumber", 0.0); - /// - /// //Bools - /// smartDashboard.PutBoolean("MyBool", true); - /// bool s = smartDashboard.GetBoolean("MyBool"); - /// //Note that if the key has not been put in the smart dashboard, - /// //the GetString function will throw a TableKeyNotDefinedException. - /// //To get around this, set a default value to be returned if there is no key, like this: - /// bool s = smartDashboard.GetBoolean("MyBool", false); - /// - /// - public class NetworkTable : ITable, IRemote - { - /// The character used to seperate tables and keys. - public const char PathSeperatorChar = '/'; - /// The default port NetworkTables listens on. - public const int DefaultPort = 1735; - // String version of seperater char to avoid allocations - internal const string PathSeperatorCharString = "/"; - - internal static bool s_enableDs = true; - - private static readonly object s_lockObject = new object(); - - /// - /// The default file name used for Persistent Storage. - /// - public const string DefaultPersistentFileName = "networktables.ini"; - internal static int Port { get; private set; } = DefaultPort; - internal static bool Client { get; private set; } - internal static bool Running { get; private set; } - - internal static string PersistentFilename { get; private set; } = DefaultPersistentFileName; - - private static void CheckInit() - { - lock (s_lockObject) - { - if (Running) - throw new InvalidOperationException("Network Tables has already been initialized"); - } - } - - /// - /// Initializes NetworkTables. Please call or - /// first. - /// - /// - /// If NetworkTables is already running, the old instance will be shutdown and a new instance will - /// be created. - /// - public static void Initialize() - { - lock (s_lockObject) - { - if (Running) - Shutdown(); - if (Client) - { - NtCore.StartClient(); - if (s_enableDs) - { - NtCore.StartDSClient(Port); - } - } - else - { - NtCore.StartServer(PersistentFilename, "", Port); - } - Running = true; - } - } - - /// - /// Shuts down NetworkTables. - /// - public static void Shutdown() - { - lock (s_lockObject) - { - if (!Running) - return; - if (Client) - { - NtCore.StopDSClient(); - NtCore.StopClient(); - } - else - { - NtCore.StopServer(); - } - Running = false; - } - } - - /// - /// Sets NetworkTables to be a client. - /// - /// This is thrown if Network Tables - /// has already been initialized. - /// This or must be called - /// before or . - public static void SetClientMode() - { - lock (s_lockObject) - { - if (Client) - return; - CheckInit(); - Client = true; - } - } - - /// - /// Sets NetworkTables to be a server - /// - /// This is thrown if Network Tables - /// has already been initialized. - /// This or must be called - /// before or - public static void SetServerMode() - { - lock (s_lockObject) - { - if (!Client) - return; - CheckInit(); - Client = false; - } - } - - /// - /// Sets the team the robot is configured for. This will set the Mdns - /// address that NetworkTables will connect to in client mode. - /// - /// The team number - /// /// This must be called before or - /// if the system is a client. - public static void SetTeam(int team) - { - lock (s_lockObject) - { - string[] addresses = new string[5]; - addresses[0] = "10." + (int)(team / 100) + "." + (int)(team % 100) + ".2"; - addresses[1] = "172.22.11.2"; - addresses[2] = "roboRIO-" + team + "-FRC.local"; - addresses[3] = "roboRIO-" + team + "-FRC.lan"; - addresses[4] = "roboRIO-" + team + "-FRC.frc-field.local"; - SetIPAddress(addresses); - } - } - - /// - /// Sets the IP address that will be connected to in client mode. - /// - /// The IP address to connect to in client mode - public static void SetIPAddress(string address) - { - lock (s_lockObject) - { - string[] addresses = new string[1]; - addresses[0] = address; - SetIPAddress(addresses); - } - } - - /// - /// Sets the IP address that will be connected to in client mode using round robin order. - /// - /// The IP address to connect to in client mode using round robin order. - public static void SetIPAddress(IList addresses) - { - int port = 0; - lock (s_lockObject) - { - port = Port; - } - List laddresses = new List(addresses.Count); - foreach (string s in addresses) - { - laddresses.Add(new NtIPAddress(s, port)); - } - - NtCore.SetServer(laddresses); - - if (addresses.Count > 0 && (addresses[0] == "localhost" || addresses[0] == "127.0.0.1")) - { - NtCore.StopDSClient(); - } - else if (s_enableDs) - { - NtCore.StartDSClient(port); - } - } - - /// - /// Gets the table with the specified key. - /// - /// If the table does not exist, a new table will be created. - /// This will automatically initialize network tables if it has not been already. - /// The network table key to request. - /// The requested. - public static NetworkTable GetTable(string key) - { - lock (s_lockObject) - { - if (!Running) Initialize(); - if (key == "" || key[0] == PathSeperatorChar) - return new NetworkTable(key); - return new NetworkTable(PathSeperatorChar + key); - } - } - - /// - /// Sets the Port for NetworkTables to connect to in client mode or listen to - /// in server mode. - /// - /// The port number to listen on or connect to. - public static void SetPort(int port) - { - if (port == Port) - return; - CheckInit(); - Port = port; - } - - /// - /// Set true to enable connection to the local robot IP address - /// (defaults to enabled) - /// - /// True to enabled using the DS connection - public static void SetDSClientEnabled(bool enabled) - { - lock (s_lockObject) - { - s_enableDs = enabled; - if (s_enableDs) - { - NtCore.StartDSClient(Port); - } - else - { - NtCore.StopDSClient(); - } - } - } - - /// - /// Sets the Persistent file name. - /// - /// The filename that the NetworkTables server uses - /// for automatic loading and saving of persistent values. - public static void SetPersistentFilename(string filename) - { - if (PersistentFilename == filename) - return; - CheckInit(); - PersistentFilename = filename; - } - - /// - /// Sets the Network Identity - /// - /// The name to identify this program as on the network. - public static void SetNetworkIdentity(string name) - { - NtCore.SetNetworkIdentity(name); - } - - private readonly string m_path; - private readonly string m_pathWithSeperator; - - private NetworkTable(string path) - { - m_path = path; - m_pathWithSeperator = path + PathSeperatorCharString; - } - - /// - public override string ToString() - { - return $"NetworkTable: {m_path}"; - } - - /// - /// Checkts the table and tells if it contains the specified key. - /// - /// The key to be checked. - /// True if the table contains the key, otherwise false. - public bool ContainsKey(string key) - { - return NtCore.ContainsEntry(m_pathWithSeperator + key); - } - - /// - /// Checks the table and tells if if contains the specified sub-table. - /// - /// The sub-table to check for - /// True if the table contains the sub-table, otherwise false - public bool ContainsSubTable(string key) - { - return NtCore.GetEntryInfo(m_pathWithSeperator + key + PathSeperatorChar, 0).Count != 0; - } - - /// - /// Gets a set of all the keys contained in the table with the specified type. - /// - /// Bitmask of types to check for; 0 is treated as a "don't care". - /// A set of all keys currently in the table. - public HashSet GetKeys(NtType types) - { - HashSet keys = new HashSet(); - int prefixLen = m_path.Length + 1; - foreach (EntryInfo entry in NtCore.GetEntryInfo(m_pathWithSeperator, types)) - { - string relativeKey = entry.Name.Substring(prefixLen); - if (relativeKey.IndexOf(PathSeperatorChar) != -1) - continue; - keys.Add(relativeKey); - } - return keys; - } - - /// - /// Gets a set of all the keys contained in the table. - /// - /// A set of all keys currently in the table. - public HashSet GetKeys() - { - return GetKeys(0); - } - - /// - /// Gets a set of all the sub-tables contained in the table. - /// - /// A set of all subtables currently contained in the table. - public HashSet GetSubTables() - { - HashSet keys = new HashSet(); - int prefixLen = m_path.Length + 1; - foreach (EntryInfo entry in NtCore.GetEntryInfo(m_pathWithSeperator, 0)) - { - string relativeKey = entry.Name.Substring(prefixLen); - int endSubTable = relativeKey.IndexOf(PathSeperatorChar); - if (endSubTable == -1) - continue; - keys.Add(relativeKey.Substring(0, endSubTable)); - } - return keys; - } - - /// - /// Returns the at the specified key. If there is no - /// table at the specified key, it will create a new table. - /// - /// The key name. - /// The to be returned. - public ITable GetSubTable(string key) - { - return new NetworkTable(m_pathWithSeperator + key); - } - - /// - /// Makes a key's value persistent through program restarts. - /// - /// The key name (cannot be null). - public void SetPersistent(string key) - { - SetFlags(key, EntryFlags.Persistent); - } - - /// - /// Stop making a key's value persistent through program restarts. - /// - /// The key name (cannot be null). - public void ClearPersistent(string key) - { - ClearFlags(key, EntryFlags.Persistent); - } - - /// - /// Returns whether a value is persistent through program restarts. - /// - /// The key name (cannot be null). - /// True if the value is persistent. - public bool IsPersistent(string key) - { - return GetFlags(key).HasFlag(EntryFlags.Persistent); - } - - /// - /// Sets flags on the specified key in this table. - /// - /// The key name. - /// The flags to set. (Bitmask) - public void SetFlags(string key, EntryFlags flags) - { - NtCore.SetEntryFlags(m_pathWithSeperator + key, GetFlags(key) | flags); - } - - /// - /// Clears flags on the specified key in this table. - /// - /// The key name. - /// The flags to clear. (Bitmask) - public void ClearFlags(string key, EntryFlags flags) - { - NtCore.SetEntryFlags(m_pathWithSeperator + key, GetFlags(key) & ~flags); - } - - /// - /// Returns the flags for the specified key. - /// - /// The key name. - /// The flags attached to the key. - public EntryFlags GetFlags(string key) - { - return NtCore.GetEntryFlags(m_pathWithSeperator + key); - } - - /// - /// Deletes the specifed key in this table. - /// - /// The key name. - public void Delete(string key) - { - NtCore.DeleteEntry(m_pathWithSeperator + key); - } - - /// - /// Deletes ALL keys in ALL subtables. Use with caution! - /// - public static void GlobalDeleteAll() - { - NtCore.DeleteAllEntries(); - } - - /// - /// Flushes all updated values immediately to the network. - /// - /// - /// Note that this is rate-limited to protect the network from flooding. - /// This is primarily useful for synchronizing network updates with user code. - /// - public static void Flush() - { - NtCore.Flush(); - } - - /// - /// Sets the periodic update rate of the NetworkTables in seconds. - /// - /// The update interval in seconds (0.01 to 1.0). - public static void SetUpdateRate(double interval) - { - NtCore.SetUpdateRate(interval); - } - - /// - /// Saves persistent keys to a file. The server does this automatically. - /// - /// The file name. - /// Error string, or null on success - /// Thrown if there is an error - /// saving the file. - public static string SavePersistent(string filename) - { - return NtCore.SavePersistent(filename); - } - -#if !NET40 - /// - /// Saves persistent keys to a file asynchronously. The server does this automatically. - /// - /// The file name. - /// Error string, or null on success - /// Thrown if there is an error - /// saving the file. - public static async Task SavePersistentAsync(string filename) - { - return await NtCore.SavePersistentAsync(filename).ConfigureAwait(false); - } -#endif //NET40 - - /// - /// Loads persistent keys from a file. The server does this automatically. - /// - /// The file name. - /// A List of warnings (errors result in an exception instead.) - /// Thrown if there is an error - /// loading the file. - public static IList LoadPersistent(string filename) - { - return NtCore.LoadPersistent(filename); - } - -#if !NET40 - /// - /// Loads persistent keys from a file asynchronously. The server does this automatically. - /// - /// The file name. - /// A List of warnings (errors result in an exception instead.) - /// Thrown if there is an error - /// loading the file. - public static async Task> LoadPersistentAsync(string filename) - { - return await NtCore.LoadPersistentAsync(filename).ConfigureAwait(false); - } -#endif // NET40 - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public Value GetValue(string key) - { - string localPath = m_pathWithSeperator + key; - var v = NtCore.GetEntryValue(localPath); - if (v == null) throw new TableKeyNotDefinedException(localPath); - return v; - } - - /// - public Value GetValue(string key, Value defaultValue) - { - string localPath = m_pathWithSeperator + key; - var v = NtCore.GetEntryValue(localPath); - if (v == null) return defaultValue; - return v; - } - - /// - public bool PutValue(string key, Value value) - { - key = m_pathWithSeperator + key; - return NtCore.SetEntryValue(key, value); - } - - /// - public bool PutNumber(string key, double value) - { - - return NtCore.SetEntryDouble(m_pathWithSeperator + key, value); - } - - /// - public double GetNumber(string key, double defaultValue) - { - - return NtCore.GetEntryDouble(m_pathWithSeperator + key, defaultValue); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public double GetNumber(string key) - { - - return NtCore.GetEntryDouble(m_pathWithSeperator + key); - } - - /// - public bool PutString(string key, string value) - { - - return NtCore.SetEntryString(m_pathWithSeperator + key, value); - } - - /// - public string GetString(string key, string defaultValue) - { - - return NtCore.GetEntryString(m_pathWithSeperator + key, defaultValue); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public string GetString(string key) - { - - return NtCore.GetEntryString(m_pathWithSeperator + key); - } - - /// - public bool PutBoolean(string key, bool value) - { - - return NtCore.SetEntryBoolean(m_pathWithSeperator + key, value); - } - - /// - public bool GetBoolean(string key, bool defaultValue) - { - - return NtCore.GetEntryBoolean(m_pathWithSeperator + key, defaultValue); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public bool GetBoolean(string key) - { - - return NtCore.GetEntryBoolean(m_pathWithSeperator + key); - } - - /// - public bool PutStringArray(string key, IList value) - { - - return NtCore.SetEntryStringArray(m_pathWithSeperator + key, value); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public string[] GetStringArray(string key) - { - - return NtCore.GetEntryStringArray(m_pathWithSeperator + key); - } - - /// - public string[] GetStringArray(string key, string[] defaultValue) - { - - return NtCore.GetEntryStringArray(m_pathWithSeperator + key, defaultValue); - - } - - /// - public bool PutNumberArray(string key, IList value) - { - - return NtCore.SetEntryDoubleArray(m_pathWithSeperator + key, value); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public double[] GetNumberArray(string key) - { - - return NtCore.GetEntryDoubleArray(m_pathWithSeperator + key); - } - - /// - public double[] GetNumberArray(string key, double[] defaultValue) - { - - return NtCore.GetEntryDoubleArray(m_pathWithSeperator + key, defaultValue); - } - - /// - public bool PutBooleanArray(string key, IList value) - { - - return NtCore.SetEntryBooleanArray(m_pathWithSeperator + key, value); - } - - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public bool[] GetBooleanArray(string key) - { - - return NtCore.GetEntryBooleanArray(m_pathWithSeperator + key); - } - - /// - public bool PutRaw(string key, IList value) - { - - return NtCore.SetEntryRaw(m_pathWithSeperator + key, value); - } - /// - [Obsolete("Please use the Default Value Get... Methods instead.")] - public byte[] GetRaw(string key) - { - - return NtCore.GetEntryRaw(m_pathWithSeperator + key); - } - /// - public byte[] GetRaw(string key, byte[] defaultValue) - { - - return NtCore.GetEntryRaw(m_pathWithSeperator + key, defaultValue); - } - - /// - public bool[] GetBooleanArray(string key, bool[] defaultValue) - { - - return NtCore.GetEntryBooleanArray(m_pathWithSeperator + key, defaultValue); - } - - private readonly Dictionary> m_listenerMap = new Dictionary>(); - - private readonly Dictionary, List> m_actionListenerMap = new Dictionary, List>(); - - /// - public void AddTableListenerEx(ITableListener listener, NotifyFlags flags) - { - lock (m_listenerMap) - { - if (!m_listenerMap.TryGetValue(listener, out List adapters)) - { - adapters = new List(); - m_listenerMap.Add(listener, adapters); - } - - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - if (relativeKey.IndexOf(PathSeperatorChar) != -1) - { - return; - } - listener.ValueChanged(this, relativeKey, value, flags_); - }; - - int id = NtCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - } - - /// - public void AddTableListenerEx(string key, ITableListener listener, NotifyFlags flags) - { - lock (m_listenerMap) - { - if (!m_listenerMap.TryGetValue(listener, out List adapters)) - { - adapters = new List(); - m_listenerMap.Add(listener, adapters); - } - string fullKey = m_pathWithSeperator + key; - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, funcKey, value, flags_) => - { - if (!funcKey.Equals(fullKey)) - return; - listener.ValueChanged(this, key, value, flags_); - }; - - int id = NtCore.AddEntryListener(fullKey, func, flags); - - adapters.Add(id); - } - } - - /// - public void AddSubTableListener(ITableListener listener, bool localNotify) - { - lock (m_listenerMap) - { - if (!m_listenerMap.TryGetValue(listener, out List adapters)) - { - adapters = new List(); - m_listenerMap.Add(listener, adapters); - } - HashSet notifiedTables = new HashSet(); - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - int endSubTable = relativeKey.IndexOf(PathSeperatorChar); - if (endSubTable == -1) - return; - string subTableKey = relativeKey.Substring(0, endSubTable); - if (notifiedTables.Contains(subTableKey)) - return; - notifiedTables.Add(subTableKey); - listener.ValueChanged(this, subTableKey, null, flags_); - }; - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (localNotify) - flags |= NotifyFlags.NotifyLocal; - int id = NtCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - } - - /// - public void AddTableListener(ITableListener listener, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(listener, flags); - } - - /// - public void AddTableListener(string key, ITableListener listener, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(key, listener, flags); - } - - /// - public void AddSubTableListener(ITableListener listener) - { - AddSubTableListener(listener, false); - } - - /// - public void RemoveTableListener(ITableListener listener) - { - lock (m_listenerMap) - { - if (m_listenerMap.TryGetValue(listener, out List adapters)) - { - foreach (int t in adapters) - { - NtCore.RemoveEntryListener(t); - } - adapters.Clear(); - } - } - } - - - /// - public void AddTableListenerEx(Action listenerDelegate, NotifyFlags flags) - { - lock (m_actionListenerMap) - { - if (!m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - adapters = new List(); - m_actionListenerMap.Add(listenerDelegate, adapters); - } - - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - if (relativeKey.IndexOf(PathSeperatorChar) != -1) - { - return; - } - listenerDelegate(this, relativeKey, value, flags_); - }; - - int id = NtCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - } - - /// - public void AddTableListenerEx(string key, Action listenerDelegate, NotifyFlags flags) - { - lock (m_actionListenerMap) - { - if (!m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - adapters = new List(); - m_actionListenerMap.Add(listenerDelegate, adapters); - } - string fullKey = m_pathWithSeperator + key; - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, funcKey, value, flags_) => - { - if (!funcKey.Equals(fullKey)) - return; - listenerDelegate(this, key, value, flags_); - }; - - int id = NtCore.AddEntryListener(fullKey, func, flags); - - adapters.Add(id); - } - } - - /// - public void AddSubTableListener(Action listenerDelegate, bool localNotify) - { - lock (m_actionListenerMap) - { - if (!m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - adapters = new List(); - m_actionListenerMap.Add(listenerDelegate, adapters); - } - HashSet notifiedTables = new HashSet(); - // ReSharper disable once InconsistentNaming - EntryListenerCallback func = (uid, key, value, flags_) => - { - string relativeKey = key.Substring(m_path.Length + 1); - int endSubTable = relativeKey.IndexOf(PathSeperatorChar); - if (endSubTable == -1) - return; - string subTableKey = relativeKey.Substring(0, endSubTable); - if (notifiedTables.Contains(subTableKey)) - return; - notifiedTables.Add(subTableKey); - listenerDelegate(this, subTableKey, null, flags_); - }; - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (localNotify) - flags |= NotifyFlags.NotifyLocal; - int id = NtCore.AddEntryListener(m_pathWithSeperator, func, flags); - - adapters.Add(id); - } - } - - /// - public void AddTableListener(Action listenerDelegate, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(listenerDelegate, flags); - } - - /// - public void AddTableListener(string key, Action listenerDelegate, bool immediateNotify = false) - { - NotifyFlags flags = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (immediateNotify) - flags |= NotifyFlags.NotifyImmediate; - AddTableListenerEx(key, listenerDelegate, flags); - } - - /// - public void AddSubTableListener(Action listenerDelegate) - { - AddSubTableListener(listenerDelegate, false); - } - - /// - public void RemoveTableListener(Action listenerDelegate) - { - lock (m_actionListenerMap) - { - if (m_actionListenerMap.TryGetValue(listenerDelegate, out List adapters)) - { - foreach (int t in adapters) - { - NtCore.RemoveEntryListener(t); - } - adapters.Clear(); - } - } - } - - private readonly Dictionary m_connectionListenerMap = - new Dictionary(); - - private readonly Dictionary, int> m_actionConnectionListenerMap - = new Dictionary, int>(); - - /// - public void AddConnectionListener(IRemoteConnectionListener listener, bool immediateNotify) - { - lock (m_connectionListenerMap) - { - if (m_connectionListenerMap.ContainsKey(listener)) - { - throw new ArgumentException("Cannot add the same listener twice", nameof(listener)); - } - - ConnectionListenerCallback func = (uid, connected, conn) => - { - if (connected) listener.Connected(this, conn); - else listener.Disconnected(this, conn); - }; - int id = NtCore.AddConnectionListener(func, immediateNotify); - m_connectionListenerMap.Add(listener, id); - } - - } - - /// - public void RemoveConnectionListener(IRemoteConnectionListener listener) - { - lock (m_connectionListenerMap) - { - if (m_connectionListenerMap.TryGetValue(listener, out int val)) - { - NtCore.RemoveConnectionListener(val); - m_connectionListenerMap.Remove(listener); - - } - } - } - - /// - public void AddConnectionListener(Action listener, bool immediateNotify) - { - lock (m_actionConnectionListenerMap) - { - if (m_actionConnectionListenerMap.ContainsKey(listener)) - { - throw new ArgumentException("Cannot add the same listener twice", nameof(listener)); - } - - ConnectionListenerCallback func = (uid, connected, conn) => - { - listener(this, conn, connected); - }; - int id = NtCore.AddConnectionListener(func, immediateNotify); - m_actionConnectionListenerMap.Add(listener, id); - } - } - - /// - public void RemoveConnectionListener(Action listener) - { - lock (m_actionConnectionListenerMap) - { - if (m_actionConnectionListenerMap.TryGetValue(listener, out int val)) - { - NtCore.RemoveConnectionListener(val); - m_actionConnectionListenerMap.Remove(listener); - } - } - } - - private static readonly Dictionary s_connectionListenerMap = - new Dictionary(); - - private static readonly Dictionary, int> s_actionConnectionListenerMap - = new Dictionary, int>(); - - private static readonly Lazy s_staticRemote = new Lazy(true); - - /// - public static void AddGlobalConnectionListener(IRemoteConnectionListener listener, bool immediateNotify) - { - lock (s_connectionListenerMap) - { - if (s_connectionListenerMap.ContainsKey(listener)) - { - throw new ArgumentException("Cannot add the same listener twice", nameof(listener)); - } - - ConnectionListenerCallback func = (uid, connected, conn) => - { - if (connected) listener.Connected(s_staticRemote.Value, conn); - else listener.Disconnected(s_staticRemote.Value, conn); - }; - - int id = NtCore.AddConnectionListener(func, immediateNotify); - s_connectionListenerMap.Add(listener, id); - } - - } - - /// - public static void RemoveGlobalConnectionListener(IRemoteConnectionListener listener) - { - lock (s_connectionListenerMap) - { - if (s_connectionListenerMap.TryGetValue(listener, out int val)) - { - NtCore.RemoveConnectionListener(val); - s_connectionListenerMap.Remove(listener); - } - } - } - - /// - public static void AddGlobalConnectionListener(Action listener, bool immediateNotify) - { - lock (s_actionConnectionListenerMap) - { - if (s_actionConnectionListenerMap.ContainsKey(listener)) - { - throw new ArgumentException("Cannot add the same listener twice", nameof(listener)); - } - - ConnectionListenerCallback func = (uid, connected, conn) => - { - listener(s_staticRemote.Value, conn, connected); - }; - int id = NtCore.AddConnectionListener(func, immediateNotify); - s_actionConnectionListenerMap.Add(listener, id); - } - } - - /// - public static void RemoveGlobalConnectionListener(Action listener) - { - lock (s_actionConnectionListenerMap) - { - if (s_actionConnectionListenerMap.TryGetValue(listener, out int val)) - { - NtCore.RemoveConnectionListener(val); - s_actionConnectionListenerMap.Remove(listener); - } - } - } - - /// - /// Gets if the NetworkTables is connected to a client or server. - /// - public bool IsConnected - { - get - { - var conns = NtCore.GetConnections(); - return conns.Count > 0; - } - } - - /// - /// Gets a list of all the connections attached to this instance. - /// - /// - /// Note that connections do not propogate through the server to clients. - /// This means that a client will see at most 1 connection, and the server will see - /// all connections to itself. - /// - /// An array of all connections attached to this instance. - public static List Connections() - { - return NtCore.GetConnections(); - } - - /// - public bool SetDefaultValue(string key, Value defaultValue) - { - return NtCore.SetDefaultEntryValue(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultNumber(string key, double defaultValue) - { - return NtCore.SetDefaultEntryDouble(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultBoolean(string key, bool defaultValue) - { - return NtCore.SetDefaultEntryBoolean(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultString(string key, string defaultValue) - { - return NtCore.SetDefaultEntryString(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultRaw(string key, IList defaultValue) - { - return NtCore.SetDefaultEntryRaw(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultBooleanArray(string key, IList defaultValue) - { - return NtCore.SetDefaultEntryBooleanArray(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultNumberArray(string key, IList defaultValue) - { - return NtCore.SetDefaultEntryDoubleArray(m_pathWithSeperator + key, defaultValue); - } - /// - public bool SetDefaultStringArray(string key, IList defaultValue) - { - return NtCore.SetDefaultEntryStringArray(m_pathWithSeperator + key, defaultValue); - } - - /// - /// Gets if the NetworkTables instance is a Server. - /// - public bool IsServer => !Client; - } -} \ No newline at end of file diff --git a/src/Shared/NtCore.cs b/src/Shared/NtCore.cs deleted file mode 100644 index a24680f..0000000 --- a/src/Shared/NtCore.cs +++ /dev/null @@ -1,1177 +0,0 @@ -using System; -using System.Collections.Generic; -using NetworkTables.Exceptions; -using System.Threading.Tasks; -using System.Linq; -#if !CORE -using NetworkTables.Logging; -#endif -#if CORE -using NetworkTables.Core.Native; -#endif - -namespace NetworkTables -{ - /// - /// This class contains all NtCore methods exposed by the underlying library. - /// - /// All keys in this method start from the root of the table - /// - public static class NtCore - { - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryBoolean(string name, bool value) - { -#if CORE - return CoreMethods.SetDefaultEntryBoolean(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, Value.MakeBoolean(value)); -#endif - } - - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryDouble(string name, double value) - { -#if CORE - return CoreMethods.SetDefaultEntryDouble(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, Value.MakeDouble(value)); -#endif - } - - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryString(string name, string value) - { -#if CORE - return CoreMethods.SetDefaultEntryString(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, Value.MakeString(value)); -#endif - } - - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryBooleanArray(string name, IList value) - { -#if CORE - return CoreMethods.SetDefaultEntryBooleanArray(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, Value.MakeBooleanArray(value)); -#endif - } - - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryDoubleArray(string name, IList value) - { -#if CORE - return CoreMethods.SetDefaultEntryDoubleArray(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, Value.MakeDoubleArray(value)); -#endif - } - - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryStringArray(string name, IList value) - { -#if CORE - return CoreMethods.SetDefaultEntryStringArray(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, Value.MakeStringArray(value)); -#endif - } - - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryRaw(string name, IList value) - { -#if CORE - return CoreMethods.SetDefaultEntryRaw(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, Value.MakeRaw(value)); -#endif - } - - /// - /// Sets an entry value - /// - /// If the type of the new value differs from the type currently - /// stored and the force parameter is false (default), returns error and - /// does not update value. If force is true, the value type in the - /// table is changed - /// The entry name - /// The value to set - /// True to force an update even if types are different - /// True on success, otherwise false - public static bool SetEntryBoolean(string name, bool value, bool force = false) - { -#if CORE - return CoreMethods.SetEntryBoolean(name, value, force); -#else - if (force) - { - Storage.Instance.SetEntryTypeValue(name, Value.MakeBoolean(value)); - return true; - } - return Storage.Instance.SetEntryValue(name, Value.MakeBoolean(value)); -#endif - } - - /// - /// Sets an entry value - /// - /// If the type of the new value differs from the type currently - /// stored and the force parameter is false (default), returns error and - /// does not update value. If force is true, the value type in the - /// table is changed - /// The entry name - /// The value to set - /// True to force an update even if types are different - /// True on success, otherwise false - public static bool SetEntryDouble(string name, double value, bool force = false) - { -#if CORE - return CoreMethods.SetEntryDouble(name, value, force); -#else - if (force) - { - Storage.Instance.SetEntryTypeValue(name, Value.MakeDouble(value)); - return true; - } - return Storage.Instance.SetEntryValue(name, Value.MakeDouble(value)); -#endif - } - - /// - /// Sets an entry value - /// - /// If the type of the new value differs from the type currently - /// stored and the force parameter is false (default), returns error and - /// does not update value. If force is true, the value type in the - /// table is changed - /// The entry name - /// The value to set - /// True to force an update even if types are different - /// True on success, otherwise false - public static bool SetEntryString(string name, string value, bool force = false) - { -#if CORE - return CoreMethods.SetEntryString(name, value, force); -#else - if (force) - { - Storage.Instance.SetEntryTypeValue(name, Value.MakeString(value)); - return true; - } - return Storage.Instance.SetEntryValue(name, Value.MakeString(value)); -#endif - } - - /// - /// Sets an entry value - /// - /// If the type of the new value differs from the type currently - /// stored and the force parameter is false (default), returns error and - /// does not update value. If force is true, the value type in the - /// table is changed - /// The entry name - /// The value to set - /// True to force an update even if types are different - /// True on success, otherwise false - public static bool SetEntryBooleanArray(string name, IList value, bool force = false) - { -#if CORE - return CoreMethods.SetEntryBooleanArray(name, value, force); -#else - if (force) - { - Storage.Instance.SetEntryTypeValue(name, Value.MakeBooleanArray(value)); - return true; - } - return Storage.Instance.SetEntryValue(name, Value.MakeBooleanArray(value)); -#endif - } - - /// - /// Sets an entry value - /// - /// If the type of the new value differs from the type currently - /// stored and the force parameter is false (default), returns error and - /// does not update value. If force is true, the value type in the - /// table is changed - /// The entry name - /// The value to set - /// True to force an update even if types are different - /// True on success, otherwise false - public static bool SetEntryDoubleArray(string name, IList value, bool force = false) - { -#if CORE - return CoreMethods.SetEntryDoubleArray(name, value, force); -#else - if (force) - { - Storage.Instance.SetEntryTypeValue(name, Value.MakeDoubleArray(value)); - return true; - } - return Storage.Instance.SetEntryValue(name, Value.MakeDoubleArray(value)); -#endif - } - - /// - /// Sets an entry value - /// - /// If the type of the new value differs from the type currently - /// stored and the force parameter is false (default), returns error and - /// does not update value. If force is true, the value type in the - /// table is changed - /// The entry name - /// The value to set - /// True to force an update even if types are different - /// True on success, otherwise false - public static bool SetEntryStringArray(string name, IList value, bool force = false) - { -#if CORE - return CoreMethods.SetEntryStringArray(name, value, force); -#else - if (force) - { - Storage.Instance.SetEntryTypeValue(name, Value.MakeStringArray(value)); - return true; - } - return Storage.Instance.SetEntryValue(name, Value.MakeStringArray(value)); -#endif - } - - /// - /// Sets an entry value - /// - /// If the type of the new value differs from the type currently - /// stored and the force parameter is false (default), returns error and - /// does not update value. If force is true, the value type in the - /// table is changed - /// The entry name - /// The value to set - /// True to force an update even if types are different - /// True on success, otherwise false - public static bool SetEntryRaw(string name, IList value, bool force = false) - { -#if CORE - return CoreMethods.SetEntryRaw(name, value, force); -#else - if (force) - { - Storage.Instance.SetEntryTypeValue(name, Value.MakeRaw(value)); - return true; - } - return Storage.Instance.SetEntryValue(name, Value.MakeRaw(value)); -#endif - } - - - - #region ThrowingGetters - -#if !CORE - internal static Exception GetValueException(string name, Value v, NtType requestedType) - { - if (v == null || v.Type == NtType.Unassigned) - { - return new TableKeyNotDefinedException(name); - } - else - { - return new TableKeyDifferentTypeException(name, requestedType, v.Type); - } - } -#endif - - /// - /// Gets an entry value - /// - /// The entry name - /// The value in the table - /// Thrown if the key does - /// not exist in the table - /// Thrown if the type - /// requested does not match the type in the table - public static bool GetEntryBoolean(string name) - { -#if CORE - return CoreMethods.GetEntryBoolean(name); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsBoolean()) throw GetValueException(name, v, NtType.Boolean); - return v.GetBoolean(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The value in the table - /// Thrown if the key does - /// not exist in the table - /// Thrown if the type - /// requested does not match the type in the table - public static double GetEntryDouble(string name) - { -#if CORE - return CoreMethods.GetEntryDouble(name); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsDouble()) throw GetValueException(name, v, NtType.Double); - return v.GetDouble(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The value in the table - /// Thrown if the key does - /// not exist in the table - /// Thrown if the type - /// requested does not match the type in the table - public static string GetEntryString(string name) - { -#if CORE - return CoreMethods.GetEntryString(name); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsString()) throw GetValueException(name, v, NtType.String); - return v.GetString(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The value in the table - /// Thrown if the key does - /// not exist in the table - /// Thrown if the type - /// requested does not match the type in the table - public static bool[] GetEntryBooleanArray(string name) - { -#if CORE - return CoreMethods.GetEntryBooleanArray(name); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsBooleanArray()) throw GetValueException(name, v, NtType.BooleanArray); - return v.GetBooleanArray(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The value in the table - /// Thrown if the key does - /// not exist in the table - /// Thrown if the type - /// requested does not match the type in the table - public static double[] GetEntryDoubleArray(string name) - { -#if CORE - return CoreMethods.GetEntryDoubleArray(name); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsDoubleArray()) throw GetValueException(name, v, NtType.DoubleArray); - return v.GetDoubleArray(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The value in the table - /// Thrown if the key does - /// not exist in the table - /// Thrown if the type - /// requested does not match the type in the table - public static string[] GetEntryStringArray(string name) - { -#if CORE - return CoreMethods.GetEntryStringArray(name); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsStringArray()) throw GetValueException(name, v, NtType.StringArray); - return v.GetStringArray(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The value in the table - /// Thrown if the key does - /// not exist in the table - /// Thrown if the type - /// requested does not match the type in the table - public static byte[] GetEntryRaw(string name) - { -#if CORE - return CoreMethods.GetEntryRaw(name); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsRaw()) throw GetValueException(name, v, NtType.Raw); - return v.GetRaw(); -#endif - } - - #endregion - - #region DefaultGetters - - /// - /// Gets an entry value - /// - /// The entry name - /// The default value if the key does not exist or is the wrong typel - /// The value requested, or defaultValue if the key does not exist or is the wrong type - public static bool GetEntryBoolean(string name, bool defaultValue) - { -#if CORE - return CoreMethods.GetEntryBoolean(name, defaultValue); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsBoolean()) return defaultValue; - return v.GetBoolean(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The default value if the key does not exist or is the wrong typel - /// The value requested, or defaultValue if the key does not exist or is the wrong type - public static double GetEntryDouble(string name, double defaultValue) - { -#if CORE - return CoreMethods.GetEntryDouble(name, defaultValue); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsDouble()) return defaultValue; - return v.GetDouble(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The default value if the key does not exist or is the wrong typel - /// The value requested, or defaultValue if the key does not exist or is the wrong type - public static string GetEntryString(string name, string defaultValue) - { -#if CORE - return CoreMethods.GetEntryString(name, defaultValue); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsString()) return defaultValue; - return v.GetString(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The default value if the key does not exist or is the wrong typel - /// The value requested, or defaultValue if the key does not exist or is the wrong type - public static bool[] GetEntryBooleanArray(string name, bool[] defaultValue) - { -#if CORE - return CoreMethods.GetEntryBooleanArray(name, defaultValue); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsBooleanArray()) - { - return defaultValue; - } - return v.GetBooleanArray(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The default value if the key does not exist or is the wrong typel - /// The value requested, or defaultValue if the key does not exist or is the wrong type - public static double[] GetEntryDoubleArray(string name, double[] defaultValue) - { -#if CORE - return CoreMethods.GetEntryDoubleArray(name, defaultValue); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsDoubleArray()) - { - return defaultValue; - } - return v.GetDoubleArray(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The default value if the key does not exist or is the wrong typel - /// The value requested, or defaultValue if the key does not exist or is the wrong type - public static string[] GetEntryStringArray(string name, string[] defaultValue) - { -#if CORE - return CoreMethods.GetEntryStringArray(name, defaultValue); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsStringArray()) - { - return defaultValue; - } - return v.GetStringArray(); -#endif - } - - /// - /// Gets an entry value - /// - /// The entry name - /// The default value if the key does not exist or is the wrong typel - /// The value requested, or defaultValue if the key does not exist or is the wrong type - public static byte[] GetEntryRaw(string name, byte[] defaultValue) - { -#if CORE - return CoreMethods.GetEntryRaw(name, defaultValue); -#else - var v = Storage.Instance.GetEntryValue(name); - if (v == null || !v.IsRaw()) - { - return defaultValue; - } - return v.GetRaw(); -#endif - } -#endregion - - /// - /// Returns a copy of the current entry value - /// - /// The entry name - /// The value in the table - /// Note if the value does not exist in the table, returns null. - /// In addition, is a possible type - public static Value GetEntryValue(string name) - { -#if CORE - return CoreMethods.GetEntryValue(name); -#else - return Storage.Instance.GetEntryValue(name); -#endif - } - - /// - /// Sets a new entry value - /// - /// The entry name - /// The value to set - /// True on successful set, false on error - /// If type of new value differs from the type of the - /// currently stored entry, returns false and does not update value - public static bool SetEntryValue(string name, Value value) - { -#if CORE - return CoreMethods.SetEntryValue(name, value); -#else - return Storage.Instance.SetEntryValue(name, value); -#endif - } - - /// - /// Sets an entry value in the table if it does not exist. - /// - /// The entry name - /// The value to set - /// False if the type does not match existing value - public static bool SetDefaultEntryValue(string name, Value value) - { -#if CORE - return CoreMethods.SetDefaultEntryValue(name, value); -#else - return Storage.Instance.SetDefaultEntryValue(name, value); -#endif - } - - /// - /// Sets a new entry value, forcing an update on a type mismatch - /// - /// The entry name - /// The value to set - /// If type of new value differs from the type of the - /// currently stored entry, the value will be force updated - public static void SetEntryTypeValue(string name, Value value) - { -#if CORE - CoreMethods.SetEntryValue(name, value, true); -#else - Storage.Instance.SetEntryTypeValue(name, value); -#endif - } - - /// - /// Sets flags associated with an entry - /// - /// The entry name - /// The bitmask of the flags to set - public static void SetEntryFlags(string name, EntryFlags flags) - { -#if CORE - CoreMethods.SetEntryFlags(name, flags); -#else - Storage.Instance.SetEntryFlags(name, flags); -#endif - } - - /// - /// Gets flags associated with an entry - /// - /// The entry names - /// Bitmask of the flags contained in the entry - public static EntryFlags GetEntryFlags(string name) - { -#if CORE - return CoreMethods.GetEntryFlags(name); -#else - return Storage.Instance.GetEntryFlags(name); -#endif - } - - /// - /// Deletes an entry from the table - /// - /// The entry name - public static void DeleteEntry(string name) - { -#if CORE - CoreMethods.DeleteEntry(name); -#else - Storage.Instance.DeleteEntry(name); -#endif - } - - /// - ///Deletes all non-persistent entries from the table - /// - public static void DeleteAllEntries() - { -#if CORE - CoreMethods.DeleteAllEntries(); -#else - Storage.Instance.DeleteAllEntries(); -#endif - } - - /// - /// Gets an array of entry information - /// - /// - /// The results are optionally filtered by a string prefix and entry type to only - /// return a subset of all entries - /// - /// A required entry prefix. Only entries with this prefix will be returned - /// Bitmask of values, 0 is "don't care" - /// Array of entry information - public static List GetEntryInfo(string prefix, NtType types) - { -#if CORE - return CoreMethods.GetEntryInfo(prefix, types); -#else - return Storage.Instance.GetEntryInfo(prefix, types); -#endif - } - - /// - /// Gets the type of a specified entry - /// - /// The entry name - /// The type of the entry. if the entry does not exist - public static NtType GetType(string name) - { -#if CORE - return CoreMethods.GetType(name); -#else - var v = GetEntryValue(name); - if (v == null) return NtType.Unassigned; - return v.Type; -#endif - } - - /// - /// Gets if the table contains a specific entry - /// - /// The entry name - /// True if the entry exists, otherwise false - public static bool ContainsEntry(string name) - { -#if CORE - return CoreMethods.ContainsEntry(name); -#else - return GetType(name) != NtType.Unassigned; -#endif - } - - /// - /// Forces an immediate update of all entry changes to the network - /// - /// This is done on a regularly scheduled interval set by - /// . Fluses are rate limited to avoid - /// excessive network trafic - public static void Flush() - { -#if CORE - CoreMethods.Flush(); -#else - Dispatcher.Instance.Flush(); -#endif - } - - /// - /// Adds a listener for a specified prefix in the table - /// - /// The prefix to listen for in the table - /// The callback to call when any entry with the specified prefix is updated - /// The flags to use for notifying - /// The id of the entry listener - public static int AddEntryListener(string prefix, EntryListenerCallback callback, NotifyFlags flags) - { -#if CORE - return CoreMethods.AddEntryListener(prefix, callback, flags); -#else - Notifier notifier = Notifier.Instance; - int uid = notifier.AddEntryListener(prefix, callback, flags); - notifier.Start(); - if ((flags & NotifyFlags.NotifyImmediate) != 0) - Storage.Instance.NotifyEntries(prefix, callback); - return uid; -#endif - } - - /// - /// Removed an entry listener from the table - /// - /// The entry listener id - public static void RemoveEntryListener(int uid) - { -#if CORE - CoreMethods.RemoveEntryListener(uid); -#else - Notifier.Instance.RemoveEntryListener(uid); -#endif - } - - /// - /// Adds a connection listener to the table - /// - /// The callback to call when a new remote connects or disconnects - /// True to notify immediately with all connected remotes - /// The id of the connection listener - public static int AddConnectionListener(ConnectionListenerCallback callback, bool immediateNotify) - { -#if CORE - return CoreMethods.AddConnectionListener(callback, immediateNotify); -#else - Notifier notifier = Notifier.Instance; - int uid = notifier.AddConnectionListener(callback); - notifier.Start(); - if (immediateNotify) Dispatcher.Instance.NotifyConnections(callback); - return uid; -#endif - } - - /// - /// Removes a connection listener from the table - /// - /// The connection listener id - public static void RemoveConnectionListener(int uid) - { -#if CORE - CoreMethods.RemoveConnectionListener(uid); -#else - Notifier.Instance.RemoveConnectionListener(uid); -#endif - } - - /// - /// Gets if the notifier thread for callbacks has been destroyed - /// - /// True if the notifier has been destroyed - public static bool NotifierDestroyed() - { -#if CORE - return CoreMethods.NotifierDestroyed(); -#else - return Notifier.Instance.Destroyed(); -#endif - } - - /// - /// Sets the remote identity for this table - /// - /// This is the id that will be seen by - /// the remotes - /// The id - public static void SetNetworkIdentity(string name) - { -#if CORE - CoreMethods.SetNetworkIdentity(name); -#else - Dispatcher.Instance.Identity = name; -#endif - } - - /// - /// Starts this table in server mode - /// - /// The filename to use for the persistent file - /// The specific ip address to listen on - /// The port to listen on - public static void StartServer(string persistFilename, string listenAddress, int port) - { -#if CORE - CoreMethods.StartServer(persistFilename, listenAddress, port); -#else - Dispatcher.Instance.StartServer(persistFilename, listenAddress, port); -#endif - } - - /// - /// Stops the server if it is running - /// - public static void StopServer() - { -#if CORE - CoreMethods.StopServer(); -#else - Dispatcher.Instance.Stop(); -#endif - } - - /// - /// Starts this table in client mode, potentially using the DS to get IP - /// - public static void StartClient() - { -#if CORE - CoreMethods.StartClient(); -#else - Dispatcher.Instance.StartClient(); -#endif - } - - /// - /// Starts this table in client mode - /// - /// The server name - /// The server port - public static void StartClient(string serverName, int port) - { -#if CORE - CoreMethods.StartClient(serverName, (uint)port); -#else - var d = Dispatcher.Instance; - d.SetServer(serverName, port); - d.StartClient(); -#endif - } - - /// - /// Starts this table in client mode attempting to connect to multiple servers - /// in round robin fashion - /// - /// The servers to try and connect to - public static void StartClient(IList servers) - { -#if CORE - CoreMethods.StartClient(servers); -#else - var d = Dispatcher.Instance; - d.SetServer(servers); - d.StartClient(); -#endif - } - - /// - /// Stops the client if it is running - /// - public static void StopClient() - { -#if CORE - CoreMethods.StopClient(); -#else - Dispatcher.Instance.Stop(); -#endif - } - - /// - /// Sets the server to connect to as a client - /// - /// The server name - /// The port - public static void SetServer(string serverName, int port) - { -#if CORE - CoreMethods.SetServer(serverName, port); -#else - Dispatcher.Instance.SetServer(serverName, port); -#endif - } - - /// - /// Sets the list of servers to connect to as a client - /// - /// List of servers to try to connect to - public static void SetServer(IList servers) - { -#if CORE - CoreMethods.SetServer(servers); -#else - Dispatcher.Instance.SetServer(servers); -#endif - } - - /// - /// Starts the DS client to look for the robot IP - /// - /// The NetworkTables port to connect to - public static void StartDSClient(int port) - { -#if CORE - CoreMethods.StartDSClient(port); -#else - DsClient.Instance.Start(port); -#endif - } - - /// - /// Stops the DS client - /// - public static void StopDSClient() - { -#if CORE - CoreMethods.StopDSClient(); -#else - DsClient.Instance.Stop(); -#endif - } - - /// - /// Stops the Rpc server if it is running - /// - public static void StopRpcServer() - { -#if CORE - CoreMethods.StopRpcServer(); -#else - RpcServer.Instance.Stop(); -#endif - } - - /// - /// Stops the notifier listener thread if it is running - /// - public static void StopNotifier() - { -#if CORE - CoreMethods.StopNotifier(); -#else - Notifier.Instance.Stop(); -#endif - } - - /// - /// Sets the update rate for the table (seconds) - /// - /// The interval to update the table in (seconds) - public static void SetUpdateRate(double interval) - { -#if CORE - CoreMethods.SetUpdateRate(interval); -#else - Dispatcher.Instance.UpdateRate = interval; -#endif - } - - /// - /// Gets an array of all the connections in the table. - /// - /// The table's remote connections - public static List GetConnections() - { -#if CORE - return CoreMethods.GetConnections(); -#else - return Dispatcher.Instance.GetConnections(); -#endif - } - - /// - /// Saves all persistent variables to the files specified - /// - /// The file to save to - /// Error string, or null on success - public static string SavePersistent(string filename) - { -#if CORE - return CoreMethods.SavePersistent(filename); -#else - return Storage.Instance.SavePersistent(filename, false); -#endif - } - -#if !NET40 - /// - /// Saves all persistent variables to the files specified asynchronously - /// - /// The file to save to - /// Error string, or null on success - public static async Task SavePersistentAsync(string filename) - { -#if CORE - return await Task.Run(() => CoreMethods.SavePersistent(filename)).ConfigureAwait(false); -#else - return await Storage.Instance.SavePersistentAsync(filename, false).ConfigureAwait(false); -#endif - } -#endif // NET40 - - /// - /// Loads persistent variables from a specified file - /// - /// The file to load from - /// Function called whenever an error is seen during loading. Int is line number, string is message. - /// Error string, or null on success - public static string LoadPersistent(string filename, Action warn) - { -#if CORE - return CoreMethods.LoadPersistent(filename, warn); -#else - return Storage.Instance.LoadPersistent(filename, warn); -#endif - } - -#if !NET40 - /// - /// Loads persistent variables from a specified file asynchronously - /// - /// The file to load from - /// Function called whenever an error is seen during loading. Int is line number, string is message. - /// Error string, or null on success - public static async Task LoadPersistentAsync(string filename, Action warn) - { -#if CORE - return await Task.Run(() => CoreMethods.LoadPersistent(filename, warn)).ConfigureAwait(false); -#else - return await Storage.Instance.LoadPersistentAsync(filename, warn).ConfigureAwait(false); -#endif - } -#endif // NET40 - - /// - /// Gets the current timestamp of the library to be used for value time comparisons - /// - /// The current time in milliseconds - public static long Now() - { - return Support.Timestamp.Now(); - } - - /// - /// Sets the logger to be used when an error is encountered by NetworkTables - /// - /// The function to use to log - /// The minimum level required to log - public static void SetLogger(LogFunc func, LogLevel minLevel) - { -#if CORE - CoreMethods.SetLogger(func, minLevel); -#else - Logger logger = Logger.Instance; - logger.SetLogger(func); - logger.MinLevel = minLevel; -#endif - } - - /// - /// Loads persistent variables from a specified file - /// - /// The file to load from - /// An array of all errors reported during loading - public static IList LoadPersistent(string filename) - { - List warns = new List(); - var err = LoadPersistent(filename, (i, s) => - { - warns.Add($"{i}: {s}"); - }); - if (err != null) throw new PersistentException($"Load Persistent Failed: {err}"); - return warns.ToArray(); - } - -#if !NET40 - /// - /// Loads persistent variables from a specified file asynchronously - /// - /// The file to load from - /// An array of all errors reported during loading - public static async Task> LoadPersistentAsync(string filename) - { - List warns = new List(); - var err = await LoadPersistentAsync(filename, (i, s) => - { - warns.Add($"{i}: {s}"); - }).ConfigureAwait(false); - if (err != null) throw new PersistentException($"Load Persistent Failed: {err}"); - return warns.ToArray(); - } -#endif - } -} diff --git a/src/Shared/NtIPAddress.cs b/src/Shared/NtIPAddress.cs deleted file mode 100644 index 8cbd0da..0000000 --- a/src/Shared/NtIPAddress.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace NetworkTables { - /// - /// A NetworkTables IP Address - /// - /// Used for Round Robin connections - public class NtIPAddress - { - /// - /// The IP Address - /// - public string IpAddress { get; } - /// - /// The Port - /// - public int Port { get; } - - /// - /// Creates a new NetworkTable IP Address - /// - /// The IP Address - /// The Port - public NtIPAddress(string ip, int port) - { - IpAddress = ip; - Port = port; - } - } -} \ No newline at end of file diff --git a/src/Shared/NtType.cs b/src/Shared/NtType.cs deleted file mode 100644 index d3ce9a0..0000000 --- a/src/Shared/NtType.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; - -namespace NetworkTables -{ - /// - /// An enumeration of all types allowed in the NetworkTables. - /// - [Flags] - public enum NtType : uint - { - /// - /// No type assigned - /// - Unassigned = 0, - /// - /// Boolean type - /// - Boolean = 0x01, - /// - /// Double type - /// - Double = 0x02, - /// - /// String type - /// - String = 0x04, - /// - /// Raw type - /// - Raw = 0x08, - /// - /// Boolean Array type - /// - BooleanArray = 0x10, - /// - /// Double Array type - /// - DoubleArray = 0x20, - /// - /// String Array type - /// - StringArray = 0x40, - /// - /// Rpc type - /// - Rpc = 0x80 - } -} diff --git a/src/Shared/RemoteProcedureCall.cs b/src/Shared/RemoteProcedureCall.cs deleted file mode 100644 index ab0f943..0000000 --- a/src/Shared/RemoteProcedureCall.cs +++ /dev/null @@ -1,371 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using NetworkTables.Wire; -#if CORE -using NetworkTables.Core.Native; -using System.Runtime.InteropServices; -#endif - -namespace NetworkTables -{ - /// - /// NetworkTables client to server remote procedure calls - /// - public static class RemoteProcedureCall - { - - /// - /// Creates an procedure that can be called by a remote client - /// - /// - /// Note that this can only be called by a server. - /// - /// The name for this Rpc - /// The definition for this Rpc - /// The callback to use the the procedure is called from a remote - public static void CreateRpc(string name, IList def, RpcCallback callback) - { -#if CORE - CoreMethods.CreateRpc(name, def, callback); -#else - Storage.Instance.CreateRpc(name, def, callback); -#endif - } - - /// - /// Creates an procedure that can be called by a remote client - /// - /// - /// Note that this can only be called by a server. - /// - /// The name for this Rpc - /// The definition for this Rpc - /// The callback to use the the procedure is called from a remote - public static void CreateRpc(string name, RpcDefinition def, RpcCallback callback) - { -#if CORE - CreateRpc(name, PackRpcDefinition(def), callback); -#else - Storage.Instance.CreateRpc(name, PackRpcDefinition(def), callback); -#endif - } - - /// - /// Creates an procedure called by a remote client that can be polled by the server - /// - /// - /// Note that this can only be called by a server. - /// - /// The name for this Rpc - /// The definition for this Rpc - public static void CreatePolledRpc(string name, IList def) - { -#if CORE - CoreMethods.CreatePolledRpc(name, def); -#else - Storage.Instance.CreatePolledRpc(name, def); -#endif - } - - /// - /// Creates an procedure called by a remote client that can be polled by the server - /// - /// - /// Note that this can only be called by a server. - /// - /// The name for this Rpc - /// The definition for this Rpc - public static void CreatePolledRpc(string name, RpcDefinition def) - { -#if CORE - CreatePolledRpc(name, PackRpcDefinition(def)); -#else - Storage.Instance.CreatePolledRpc(name, PackRpcDefinition(def)); -#endif - } - - /// - /// Polls for an Rpc request from a client - /// - /// True to block waiting for a request - /// Timeout to wait for if blocking - /// The info for the call request - /// True if an Rpc call has been requested, otherwise false - public static bool PollRpc(bool blocking, TimeSpan timeout, out RpcCallInfo callInfo) - { -#if CORE - return CoreMethods.PollRpc(blocking, timeout, out callInfo); -#else - return RpcServer.Instance.PollRpc(blocking, timeout, out callInfo); -#endif - } - -#if !CORE - /// - /// Polls for an Rpc request from a client asynchronously - /// - /// Token to cancel the polling on - /// The info for the call request, or null if canceled. - public static async Task PollRpcAsync(CancellationToken token) - { -#if CORE - throw new NotSupportedException("NetworkTables.Core does not support Async Polled Rpcs, as there is no way to cancel the call"); -#else - return await RpcServer.Instance.PollRpcAsync(token).ConfigureAwait(false); -#endif - } -#endif - - /// - /// Polls for an Rpc request from a client - /// - /// True to block waiting for a request - /// The info for the call request - /// True if an Rpc call has been requested, otherwise false - public static bool PollRpc(bool blocking, out RpcCallInfo callInfo) - { -#if CORE - return CoreMethods.PollRpc(blocking, out callInfo); -#else - return RpcServer.Instance.PollRpc(blocking, out callInfo); -#endif - } - - /// - /// Posts an Rpc response to a polled Rpc request - /// - /// The id of the rpc to respond to - /// The id of the request to respond to - /// The result to send as a response - public static void PostRpcResponse(long rpcId, long callUid, IList result) - { -#if CORE - CoreMethods.PostRpcResponse(rpcId, callUid, result); -#else - RpcServer.Instance.PostRpcResponse(rpcId, callUid, result); -#endif - } - - /// - /// Calls a procedure on a remote server - /// - /// The name of the Rpc - /// The data to send for the request - /// The Rpc call id - public static long CallRpc(string name, IList param) - { -#if CORE - return CoreMethods.CallRpc(name, param); -#else - return Storage.Instance.CallRpc(name, param); -#endif - } - - /// - /// Calls a procedure on a remote server - /// - /// The name of the Rpc - /// The data to send for the request - /// The Rpc call id - public static long CallRpc(string name, IList param) - { -#if CORE - return CallRpc(name, PackRpcValues(param)); -#else - return Storage.Instance.CallRpc(name, PackRpcValues(param)); -#endif - } - -#if !NET40 - /// - /// Calls a procedure on a remote server, and awaits a response asynchronously - /// - /// The name of the Rpc - /// The token to cancel the response request - /// The data to send for the request - /// The results received from the server for the request - public static async Task> CallRpcWithResultAsync(string name, CancellationToken token, IList param) - { - long id = CallRpc(name, param); - return await GetRpcResultAsync(id, token).ConfigureAwait(false); - } - - /// - /// Calls a procedure on a remote server, and awaits a response asynchronously - /// - /// The name of the Rpc - /// The token to cancel the response request - /// The data to send for the request - /// The results received from the server for the request - public static async Task> CallRpcWithResultAsync(string name, CancellationToken token, IList param) - { - long id = CallRpc(name, param); - return await GetRpcResultAsync(id, token).ConfigureAwait(false); - } - - /// - /// Gets the result of an Rpc request asynchronously - /// - /// The Rpc call id - /// Token to cancel the request on - /// Array of results sent back from the server from the request - public static async Task> GetRpcResultAsync(long callUid, CancellationToken token) - { -#if CORE - return await CoreMethods.GetRpcResultAsync(callUid, token).ConfigureAwait(false); -#else - return await Storage.Instance.GetRpcResultAsync(callUid, token).ConfigureAwait(false); -#endif - } -#endif // NET40 - - /// - /// Gets the result of an Rpc request - /// - /// True if the call should block until the request is received - /// The Rpc call id - /// Timeout to wait for if blocking - /// Array of results sent back from the server from the request - /// True if a result was received, otherwise false - public static bool GetRpcResult(bool blocking, long callUid, TimeSpan timeout, out byte[] result) - { -#if CORE - return CoreMethods.GetRpcResult(blocking, callUid, timeout, out result); -#else - return Storage.Instance.GetRpcResult(blocking, callUid, timeout, out result); -#endif - } - - /// - /// Gets the result of an Rpc request - /// - /// True if the call should block until the request is received - /// The Rpc call id - /// Array of results sent back from the server from the request - /// True if a result was received, otherwise false - public static bool GetRpcResult(bool blocking, long callUid, out byte[] result) - { -#if CORE - return CoreMethods.GetRpcResult(blocking, callUid, out result); -#else - return Storage.Instance.GetRpcResult(blocking, callUid, out result); -#endif - } - - /// - /// Pack an Rpc defintion in to a byte array - /// - /// The definition to pack - /// The packed data - public static byte[] PackRpcDefinition(RpcDefinition def) - { - WireEncoder enc = new WireEncoder(0x0300); - enc.Write8((byte)def.Version); - enc.WriteString(def.Name); - - int paramsSize = def.Params.Count; - if (paramsSize > 0xff) paramsSize = 0xff; - enc.Write8((byte)paramsSize); - for (int i = 0; i < paramsSize; i++) - { - enc.WriteType(def.Params[i].DefValue.Type); - enc.WriteString(def.Params[i].Name); - enc.WriteValue(def.Params[i].DefValue); - } - - int resultsSize = def.Results.Count; - if (resultsSize > 0xff) resultsSize = 0xff; - enc.Write8((byte)resultsSize); - for (int i = 0; i < resultsSize; i++) - { - enc.WriteType(def.Results[i].Type); - enc.WriteString(def.Results[i].Name); - } - return enc.Buffer; - } - - /// - /// Unpack an Rpc definition from a byte array - /// - /// The data array - /// The definition to unpack to - /// True if the data was unpacked successfully - public static bool UnpackRpcDefinition(IList packed, ref RpcDefinition def) - { - ListStream iStream = new ListStream(packed); - WireDecoder dec = new WireDecoder(iStream, 0x0300); - byte ref8 = 0; - string str = ""; - - if (!dec.Read8(ref ref8)) return false; - def.SetVersion(ref8); - if (!dec.ReadString(ref str)) return false; - def.SetName(str); - - if (!dec.Read8(ref ref8)) return false; - int paramsSize = ref8; - def.Params.Clear(); - NtType type = 0; - for (int i = 0; i < paramsSize; i++) - { - - if (!dec.ReadType(ref type)) return false; - if (!dec.ReadString(ref str)) return false; - var val = dec.ReadValue(type); - if (val == null) return false; - def.Params.Add(new RpcParamDef(str, val)); - } - - if (!dec.Read8(ref ref8)) return false; - int resultsSize = ref8; - def.Results.Clear(); - for (int i = 0; i < resultsSize; i++) - { - type = 0; - if (!dec.ReadType(ref type)) return false; - if (!dec.ReadString(ref str)) return false; - def.Results.Add(new RpcResultsDef(str, type)); - } - - return true; - } - - /// - /// Pack a list of values - /// - /// The values to pack - /// The packed values - public static byte[] PackRpcValues(IList values) - { - WireEncoder enc = new WireEncoder(0x0300); - foreach (var value in values) - { - enc.WriteValue(value); - } - return enc.Buffer; - } - - /// - /// Unpack a list of values - /// - /// The packed data - /// The types the packed data should be - /// A list of the unpacked values - public static List UnpackRpcValues(IList packed, IList types) - { - ListStream iStream = new ListStream(packed); - WireDecoder dec = new WireDecoder(iStream, 0x0300); - List vec = new List(); - foreach (var ntType in types) - { - var item = dec.ReadValue(ntType); - if (item == null) return new List(); - vec.Add(item); - } - return vec; - } - } -} diff --git a/src/Shared/RpcStructs.cs b/src/Shared/RpcStructs.cs deleted file mode 100644 index 91d333d..0000000 --- a/src/Shared/RpcStructs.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace NetworkTables -{ - /// - /// Definitions for an Rpc parameter - /// - public struct RpcParamDef - { - /// - /// Gets the name for this parameter - /// - public string Name { get; } - /// - /// Gets the value for this parameter - /// - public Value DefValue { get; } - - /// - /// Creates a new Rpc parameter definition - /// - /// The name of the parameter - /// The value of the parameter - public RpcParamDef(string name, Value def) - { - Name = name; - DefValue = def; - } - } - - /// - /// Defitions for an Rpc result - /// - public struct RpcResultsDef - { - /// - /// Gets the name for this result - /// - public string Name { get; } - /// - /// Gets the type this result should be - /// - public NtType Type { get; } - - /// - /// Create a new Rpc result definition - /// - /// The name of the result - /// The type of the result - public RpcResultsDef(string name, NtType type) - { - Name = name; - Type = type; - } - } - - /// - /// Definitions for an Rpc call - /// - public struct RpcDefinition - { - /// - /// The version of this Rpc definition - /// - public int Version { get; private set; } - /// - /// The name of this Rpc definition - /// - public string Name { get; private set; } - - /// - /// The parameters to send over this Rpc definition - /// - public List Params { get; } - - /// - /// The results to receive from this Rpc definition - /// - public List Results { get; } - - /// - /// Creates a new Rpc defintion without parameters or results - /// - /// The version of this definition - /// The name of this definition - public RpcDefinition(int version, string name) - { - Version = version; - Name = name; - Params = new List(); - Results = new List(); - } - - internal void SetName(string name) - { - Name = name; - } - - internal void SetVersion(int version) - { - Version = version; - } - - /// - /// Creates a new Rpc definition with parameters and results - /// - /// The version of this definition - /// The name of this defition - /// The parameter definitions for this Rpc definition - /// The result definitions for this Rpc definition - public RpcDefinition(int version, string name, List param, List res) - { - Version = version; - Name = name; - Params = param; - Results = res; - } - } - - /// - /// Call info related to a polled Rpc call - /// - public struct RpcCallInfo - { - /// - /// The Id of the Rpc being polled - /// - public long RpcId { get; } - /// - /// The Id of the Rpc call that set this polled value - /// - public long CallUid { get; } - /// - /// The name of this call info - /// - public string Name { get; } - /// - /// The data from this rpc call - /// - public byte[] Params { get; } - - /// - /// Creates a new polled RpcCallInfo def - /// - /// The Rpc that is getting polled - /// The call Id that set this polled value - /// The name of this polled call info - /// The data associated with this polled info - public RpcCallInfo(long rpcId, long callUid, string name, byte[] param) - { - RpcId = rpcId; - CallUid = callUid; - Name = name; - Params = new byte[param.Length]; - Array.Copy(param, Params, param.Length); - } - } -} diff --git a/src/Shared/StaticRemote.cs b/src/Shared/StaticRemote.cs deleted file mode 100644 index 9c662f6..0000000 --- a/src/Shared/StaticRemote.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using NetworkTables.Tables; - -namespace NetworkTables -{ - /// - /// This class is used to pass back an IRemote parameter to the global connection listener methods - /// - internal class StaticRemote : IRemote - { - public bool IsConnected - { - get - { - var conns = NtCore.GetConnections(); - return conns.Count > 0; - } - } - - public bool IsServer => !NetworkTable.Client; - - public void AddConnectionListener(Action listener, bool immediateNotify) - { - NetworkTable.AddGlobalConnectionListener(listener, immediateNotify); - } - - public void AddConnectionListener(IRemoteConnectionListener listener, bool immediateNotify) - { - NetworkTable.AddGlobalConnectionListener(listener, immediateNotify); - } - - public void RemoveConnectionListener(Action listener) - { - NetworkTable.RemoveGlobalConnectionListener(listener); - } - - public void RemoveConnectionListener(IRemoteConnectionListener listener) - { - NetworkTable.RemoveGlobalConnectionListener(listener); - } - } -} \ No newline at end of file diff --git a/src/Shared/Tables/IRemote.cs b/src/Shared/Tables/IRemote.cs deleted file mode 100644 index 5cc1309..0000000 --- a/src/Shared/Tables/IRemote.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; - -namespace NetworkTables.Tables -{ - /// - /// Represents an object that has a remote connection. - /// - public interface IRemote - { - /// - /// Register an object to listen for connection and disconnection events. - /// - /// The listener to be registered - /// True if the listener object should be notified of the current - /// connection state immediately. - void AddConnectionListener(IRemoteConnectionListener listener, bool immediateNotify); - - /// - /// Unregister a listener from connection events. - /// - /// The listener to be unregistered. - void RemoveConnectionListener(IRemoteConnectionListener listener); - - /// - /// Register a delegate to listen for connection and disconnection events. - /// - /// The listener to be registered. - /// True if the listener object should be notified of the current - /// connection state immediately. - /// - /// The of the action is the current table, the - /// is the info of the connected or disconnected target, and the bool is true if the event is - /// a connect, otherwise false. - /// - void AddConnectionListener(Action listener, bool immediateNotify); - - /// - /// Unregister a listener delegate from connection events. - /// - /// The listener to be unregistered. - void RemoveConnectionListener(Action listener); - - /// - /// Gets if the current object is connected. - /// - bool IsConnected { get; } - - /// - /// Gets if the object is a server. - /// - bool IsServer { get; } - } -} \ No newline at end of file diff --git a/src/Shared/Tables/IRemoteConnectionListener.cs b/src/Shared/Tables/IRemoteConnectionListener.cs deleted file mode 100644 index a468390..0000000 --- a/src/Shared/Tables/IRemoteConnectionListener.cs +++ /dev/null @@ -1,25 +0,0 @@ -// ReSharper disable UnusedParameter.Global -namespace NetworkTables.Tables -{ - /// - /// A listener that listens for connection changes in an object. - /// - public interface IRemoteConnectionListener - { - /// - /// Called when an is connected - /// - /// The object that connected. - /// An object containing information about the - /// connected remote. - void Connected(IRemote remote, ConnectionInfo info); - - /// - /// Called when an is disconnected. - /// - /// The object that disconnected. - /// An object containing information about the - /// disconnected remote. - void Disconnected(IRemote remote, ConnectionInfo info); - } -} \ No newline at end of file diff --git a/src/Shared/Tables/ITable.cs b/src/Shared/Tables/ITable.cs deleted file mode 100644 index ba9366d..0000000 --- a/src/Shared/Tables/ITable.cs +++ /dev/null @@ -1,508 +0,0 @@ -using System; -using System.Collections.Generic; -using NetworkTables.Exceptions; - -namespace NetworkTables.Tables -{ - /// - /// A table whose values can be read from and written to. - /// - public interface ITable - { - /// - /// Determines whether the given key is in this table. - /// - /// The key to search for - /// If the table has a value assignend to the given key - bool ContainsKey(string key); - - /// - /// Determines whether there exists a non-empty subtable for this key in this table. - /// - /// The key to search for - /// If there is a subtable with the key which contains at least one key/subtable of its own - bool ContainsSubTable(string key); - - /// - /// Gets the subtable in this table for the given name. - /// - /// The name of the table relative to this one. - /// A sub table relative to this one - ITable GetSubTable(string key); - - /// - /// Gets the keys currently in the table with the specified flags - /// - /// The bitmask of flags to check for. - /// A set of the keys currently in the table with the specified flags. - HashSet GetKeys(NtType types); - - /// - /// Gets all keys currently in the table. - /// - /// A set of all keys in the table. - HashSet GetKeys(); - - /// - /// Gets all sub-tables currently in the table. - /// - /// A set of all sub-tables in the table. - HashSet GetSubTables(); - - /// - /// Makes a key's value persistent through program restarts. - /// - /// The key name (cannot be null). - void SetPersistent(string key); - - /// - /// Stop making a key's value persistent through program restarts. - /// - /// The key name (cannot be null). - void ClearPersistent(string key); - - /// - /// Returns whether a value is persistent through program restarts. - /// - /// The key name (cannot be null). - /// True if the value is persistent. - bool IsPersistent(string key); - - /// - /// Sets flags on the specified key in this table. - /// - /// The key name. - /// The flags to set. (Bitmask) - void SetFlags(string key, EntryFlags flags); - - /// - /// Clears flags on the specified key in this table. - /// - /// The key name. - /// The flags to clear. (Bitmask) - void ClearFlags(string key, EntryFlags flags); - - /// - /// Returns the flags for the specified key. - /// - /// The key name. - /// The flags attached to the key. - EntryFlags GetFlags(string key); - - /// - /// Deletes the specifed key in this table. - /// - /// The key name. - void Delete(string key); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value requested, or defaultValue if the key does not exist or is null. - Value GetValue(string key, Value defaultValue); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The requested value. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - Value GetValue(string key); - - /// - /// Maps the specified key to the specified value in the table. - /// - /// - /// The key cannot be null. The value can be retreived by calling the Get method with - /// the key used to Put the number in. - /// - /// The key to map the value to. - /// The value to set. - /// True if the key was set properly, otherwise false - /// Thrown if the value is not a type supported - /// by the table. - bool PutValue(string key, Value value); - - /// - /// Maps the specified key to the specified value in the table. - /// - /// - /// The key cannot be null. The value can be retreived by calling the Get method with - /// the key used to Put the number in. - /// - /// The key to map the value to. - /// The value to set. - /// True if the key was set properly, otherwise false - bool PutNumber(string key, double value); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value requested, or defaultValue if the key does not exist or is null. - double GetNumber(string key, double defaultValue); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The requested value. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - double GetNumber(string key); - - /// - /// Maps the specified key to the specified value in the table. - /// - /// - /// The key cannot be null. The value can be retreived by calling the Get method with - /// the key used to Put the number in. - /// - /// The key to map the value to. - /// The value to set. - /// True if the key was set properly, otherwise false - bool PutString(string key, string value); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value requested, or defaultValue if the key does not exist or is null. - string GetString(string key, string defaultValue); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The requested value. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - string GetString(string key); - - /// - /// Maps the specified key to the specified value in the table. - /// - /// - /// The key cannot be null. The value can be retreived by calling the Get method with - /// the key used to Put the number in. - /// - /// The key to map the value to. - /// The value to set. - /// True if the key was set properly, otherwise false - bool PutBoolean(string key, bool value); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value requested, or defaultValue if the key does not exist or is null. - bool GetBoolean(string key, bool defaultValue); - - /// - /// Returns the value that the key maps to. - /// - /// The key name. - /// The requested value. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - bool GetBoolean(string key); - - /// - /// Maps the specified key to the specified array of values in the table. - /// - /// - /// The key cannot be null. The value can be retreived by calling the Get method with - /// the key used to Put the number in. - /// - /// The key to map the value to. - /// The value to set. - /// True if the key was set properly, otherwise false - bool PutBooleanArray(string key, IList value); - - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The requested value array. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - bool[] GetBooleanArray(string key); - - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value array requested, or defaultValue if the key does not exist or is null. - bool[] GetBooleanArray(string key, bool[] defaultValue); - - /// - /// Maps the specified key to the specified array of values in the table. - /// - /// - /// The key cannot be null. The value can be retreived by calling the Get method with - /// the key used to Put the number in. - /// - /// The key to map the value to. - /// The value to set. - /// True if the key was set properly, otherwise false - bool PutNumberArray(string key, IList value); - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The requested value array. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - double[] GetNumberArray(string key); - - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value array requested, or defaultValue if the key does not exist or is null. - double[] GetNumberArray(string key, double[] defaultValue); - - /// - /// Maps the specified key to the specified array of values in the table. - /// - /// - /// The key cannot be null. The value can be retreived by calling the Get method with - /// the key used to Put the number in. - /// - /// The key to map the value to. - /// The value to set. - /// True if the key was set properly, otherwise false - bool PutStringArray(string key, IList value); - - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The requested value array. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - string[] GetStringArray(string key); - - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value array requested, or defaultValue if the key does not exist or is null. - string[] GetStringArray(string key, string[] defaultValue); - - /// - /// Put a raw value (byte array) in the table. - /// - /// The key to be assigned to. - /// The value that will be assigned. - /// False if the table key already exists with a different type. - bool PutRaw(string key, IList value); - - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The requested value array. - /// Thrown if the key does not - /// exist in the table, or if the key is null. - /// Thrown if the key exists - /// as a different type in the table. - byte[] GetRaw(string key); - - /// - /// Returns the value array that the key maps to. - /// - /// The key name. - /// The default value if the key does not exist or is null - /// The value array requested, or defaultValue if the key does not exist or is null. - byte[] GetRaw(string key, byte[] defaultValue); - - - /// - /// Add a listener to changes to the table. - /// - /// The listener to add - /// The flags to use for the listener - void AddTableListenerEx(ITableListener listener, NotifyFlags flags); - - /// - /// Add a listener for changes to a specific key in the table. - /// - /// The key to listen for - /// The listener to add - /// The flags to use for the listener - void AddTableListenerEx(string key, ITableListener listener, NotifyFlags flags); - - /// - /// Adds a SubTable Listener. - /// - /// The to add. - /// True if we want to notify local and remote listeners, - /// otherwise just notify remote listeners. - void AddSubTableListener(ITableListener listener, bool localNotify); - - /// - /// Add a listener to changes to the table. - /// - /// The listener to add - /// If true then this listener will be notified of all current entries (marked as new) - void AddTableListener(ITableListener listener, bool immediateNotify = false); - - /// - /// Add a listener for changes to a specific key in the table. - /// - /// The key to listen for - /// The listener to add - /// If true then this listener will be notified of all current entries (marked as new) - void AddTableListener(string key, ITableListener listener, bool immediateNotify = false); - - /// - /// Adds a SubTable Listener with the default flags, and without local notify. - /// - /// The to add. - void AddSubTableListener(ITableListener listener); - - /// - /// Remove a listener from receiving table events. - /// - /// The listener to be removed. - void RemoveTableListener(ITableListener listener); - - /// - /// Add a listener to changes to the table. - /// - /// The Table Listener Delegate to add. - /// The flags to use for the listener - void AddTableListenerEx(Action listenerDelegate, NotifyFlags flags); - - /// - /// Add a listener for changes to a specific key in the table. - /// - /// The key to listen for - /// The Table Listener Delegate to add. - /// The flags to use for the listener - void AddTableListenerEx(string key, Action listenerDelegate, NotifyFlags flags); - - /// - /// Adds a SubTable Listener. - /// - /// The Table Listener Delegate to add. - /// True if we want to notify local and remote listeners, - /// otherwise just notify remote listeners. - void AddSubTableListener(Action listenerDelegate, bool localNotify); - - /// - /// Add a listener to changes to the table. - /// - /// The Table Listener Delegate to add. - /// If true then this listener will be notified of all current entries (marked as new) - void AddTableListener(Action listenerDelegate, bool immediateNotify = false); - - /// - /// Add a listener for changes to a specific key in the table. - /// - /// The key to listen for - /// The Table Listener Delegate to add. - /// If true then this listener will be notified of all current entries (marked as new) - void AddTableListener(string key, Action listenerDelegate, bool immediateNotify = false); - - /// - /// Adds a SubTable Listener with the default flags, and without local notify. - /// - /// The Table Listener Delegate to add. - void AddSubTableListener(Action listenerDelegate); - - /// - /// Remove a listener from receiving table events. - /// - /// The Table Listener Delegate to remove. - void RemoveTableListener(Action listenerDelegate); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultValue(string key, Value defaultValue); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultNumber(string key, double defaultValue); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultBoolean(string key, bool defaultValue); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultString(string key, string defaultValue); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultRaw(string key, IList defaultValue); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultBooleanArray(string key, IList defaultValue); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultNumberArray(string key, IList defaultValue); - - /// - /// Sets the value in the table at the specified key if it does not exist. - /// - /// The key to set - /// The value to set if the key does not exits - /// False if the key exists with a different type, otherwise true - bool SetDefaultStringArray(string key, IList defaultValue); - } -} \ No newline at end of file diff --git a/src/Shared/Tables/ITableListener.cs b/src/Shared/Tables/ITableListener.cs deleted file mode 100644 index 0c20185..0000000 --- a/src/Shared/Tables/ITableListener.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace NetworkTables.Tables -{ - /// - /// A listener that listens to changes in values in an - /// - public interface ITableListener - { - /// - /// Called when a key-value pair is changed in an . - /// - /// The table the key-value pair exist in. - /// The key associated with the value that changed. - /// The new value. - /// The update flags. - void ValueChanged(ITable source, string key, Value value, NotifyFlags flags); - } -} \ No newline at end of file diff --git a/src/Shared/Value.cs b/src/Shared/Value.cs deleted file mode 100644 index 0ff6d67..0000000 --- a/src/Shared/Value.cs +++ /dev/null @@ -1,680 +0,0 @@ -using System; -using System.Collections.Generic; -using NetworkTables.Exceptions; -using NetworkTables.Support; -using System.Linq; - -namespace NetworkTables -{ - /// - /// This class represents all types allowed by NetworkTables - /// - public class Value - { - /// - /// Creates a value with an Unassigned default type - /// - public Value() - { - Type = NtType.Unassigned; - } - - /// - public override int GetHashCode() - { - return Val.GetHashCode(); - } - - /// - /// Gets the type of this Value - /// - public NtType Type { get; } - - internal object Val { get; } - - /// - /// Gets the Timestamp when this value was last changed. - /// - public long LastChange { get; } = Timestamp.Now(); - - /// - /// Gets if the type is boolean - /// - /// True if the type is boolean - public bool IsBoolean() => Type == NtType.Boolean; - /// - /// Gets if the type is double - /// - /// True if the type is double - public bool IsDouble() => Type == NtType.Double; - /// - /// Gets if the type is string - /// - /// True if the type is string - public bool IsString() => Type == NtType.String; - - /// - /// Gets if the type is raw - /// - /// True if the type is raw - public bool IsRaw() => Type == NtType.Raw; - - /// - /// Gets if the type is Rpc - /// - /// True if the type is Rpc - public bool IsRpc() => Type == NtType.Rpc; - - /// - /// Gets if the type is boolean array - /// - /// True if the type is a boolean array - public bool IsBooleanArray() => Type == NtType.BooleanArray; - - /// - /// Gets if the type is double array - /// - /// True if the type is a double array - public bool IsDoubleArray() => Type == NtType.DoubleArray; - - /// - /// Gets if the type is string array - /// - /// True if the type is a string array - public bool IsStringArray() => Type == NtType.StringArray; - - /// - /// Gets the raw object contained in this value. - /// - /// Object representation of the value - public object GetObjectValue() - { - if (IsRaw()) return GetRaw(); - else if (IsRpc()) return GetRpc(); - else if (IsBooleanArray()) return GetBooleanArray(); - else if (IsDoubleArray()) return GetDoubleArray(); - else if (IsStringArray()) return GetStringArray(); - else return Val; - } - - /// - /// Gets a enumerable of all the types supported by the class. - /// - /// An enumerable of all supported types - public static IEnumerable GetSupportedValueTypes() - { - yield return typeof(double); - yield return typeof(bool); - yield return typeof(string); - yield return typeof(IList); - yield return typeof(IList); - yield return typeof(IList); - yield return typeof(IList); - } - - /// - /// Makes a value from a specific object - /// - /// The object ot make the value from - /// The value if valid, otherwise an Empty value - public static Value MakeValue(object val) - { - Value v = new Value(); - if (val is double) - { - return MakeDouble((double) val); - } - else if (val is bool) - { - return MakeBoolean((bool) val); - } - else if (val is string) - { - return MakeString((string)val); - } - else if (val is IList) - { - return MakeRaw((IList)val); - } - else if (val is IList) - { - return MakeDoubleArray((IList)val); - } - else if (val is IList) - { - return MakeBooleanArray((IList)val); - } - else if (val is IList) - { - return MakeStringArray((IList)val); - } - else - { - return MakeEmpty(); - } - } - - /// - /// Gets a copy of the value using a generic parameter. - /// - /// The type of value to return - /// True if the type is the value type, otherwise false - /// The value contained in this value. - public T GetValue(out bool success) - { - success = false; - if (Type == NtType.Unassigned) - { - return default(T); - } - else if (typeof(T) == typeof(double)) - { - if (IsDouble()) success = true; - } - else if (typeof(T) == typeof(bool)) - { - if (IsBoolean()) success = true; - } - else if (typeof(T) == typeof(string)) - { - if (IsString()) success = true; - } - else if (typeof(T) == typeof(byte[])) - { - if (IsRaw()) - { - success = true; - // Create copy of array - return (T)(object)GetRaw(); - } - } - else if (typeof(T) == typeof(bool[])) - { - if ((IsBooleanArray())) - { - success = true; - // Create copy of array - return (T)(object)GetBooleanArray(); - } - } - else if (typeof(T) == typeof(double[])) - { - if (IsDoubleArray()) - { - success = true; - // Create copy of array - return (T)(object)GetDoubleArray(); - } - } - else if (typeof(T) == typeof(string[])) - { - if (IsStringArray()) - { - success = true; - // Create copy of array - return (T)(object)GetStringArray(); - } - } - if (success) return (T)Val; - else return default(T); - } - - /// - /// Gets the boolean value from the type - /// - /// boolean contained in type - /// Thrown if - /// type is not boolean. - public bool GetBoolean() - { - if (Type != NtType.Boolean) - { - throw new TableKeyDifferentTypeException(NtType.Boolean, Type); - } - return (bool)Val; - } - /// - /// Gets the double value from the type - /// - /// double contained in type - /// Thrown if - /// type is not double. - public double GetDouble() - { - if (Type != NtType.Double) - { - throw new TableKeyDifferentTypeException(NtType.Double, Type); - } - return (double)Val; - } - - /// - /// Gets the string value from the type - /// - /// string contained in type - /// Thrown if - /// type is not string. - public string GetString() - { - if (Type != NtType.String) - { - throw new TableKeyDifferentTypeException(NtType.String, Type); - } - return (string)Val; - } - - //For reference types (other then strings) return copies; - - /// - /// Gets the raw value from the type - /// - /// raw byte array contained in type - /// Thrown if - /// type is not raw. - public byte[] GetRaw() - { - if (Type != NtType.Raw) - { - throw new TableKeyDifferentTypeException(NtType.Raw, Type); - } - byte[] v = (byte[])Val; - - byte[] tmp = new byte[v.Length]; - Array.Copy(v, tmp, v.Length); - return tmp; - } - - /// - /// Gets the rpc value from the type - /// - /// rpc byte array contained in type - /// Thrown if - /// type is not rpc. - public byte[] GetRpc() - { - if (Type != NtType.Rpc) - { - throw new TableKeyDifferentTypeException(NtType.Rpc, Type); - } - byte[] v = (byte[])Val; - - byte[] tmp = new byte[v.Length]; - Array.Copy(v, tmp, v.Length); - return tmp; - } - - /// - /// Gets the boolean array value from the type - /// - /// boolean array contained in type - /// Thrown if - /// type is not boolean array. - public bool[] GetBooleanArray() - { - if (Type != NtType.BooleanArray) - { - throw new TableKeyDifferentTypeException(NtType.BooleanArray, Type); - } - bool[] v = (bool[])Val; - - bool[] tmp = new bool[v.Length]; - Array.Copy(v, tmp, v.Length); - return tmp; - } - - /// - /// Gets the double array value from the type - /// - /// double array contained in type - /// Thrown if - /// type is not double array. - public double[] GetDoubleArray() - { - if (Type != NtType.DoubleArray) - { - throw new TableKeyDifferentTypeException(NtType.DoubleArray, Type); - } - double[] v = (double[])Val; - - double[] tmp = new double[v.Length]; - Array.Copy(v, tmp, v.Length); - return tmp; - } - - /// - /// Gets the string array value from the type - /// - /// string array contained in type - /// Thrown if - /// type is not string arrya. - public string[] GetStringArray() - { - if (Type != NtType.StringArray) - { - throw new TableKeyDifferentTypeException(NtType.StringArray, Type); - } - string[] v = (string[])Val; - - string[] tmp = new string[v.Length]; - Array.Copy(v, tmp, v.Length); - return tmp; - } - - /// - /// Gets a string representation of the backing value - /// - /// String representation of the backing value - public override string ToString() - { - if (Val == null) return "Unassigned"; - return Val.ToString(); - } - - /// - public override bool Equals(object obj) - { - var v = obj as Value; - if (v == null) return false; - return this == v; - } - - /// - /// Checks to see if two Values are equal - /// - /// The left hand - /// The right hand - /// True if the Values are equal - public static bool operator ==(Value lhs, Value rhs) - { - if (ReferenceEquals(lhs, rhs)) return true; - if (((object)lhs == null) || ((object)rhs == null)) return false; - if (lhs.Type != rhs.Type) return false; - switch (lhs.Type) - { - case NtType.Unassigned: - return true; - case NtType.Boolean: - return (bool)lhs.Val == (bool)rhs.Val; - case NtType.Double: - // ReSharper disable once CompareOfFloatsByEqualityOperator - return (double)lhs.Val == (double)rhs.Val; - case NtType.String: - return (string)lhs.Val == (string)rhs.Val; - case NtType.Raw: - case NtType.Rpc: - byte[] rawLhs = (byte[])lhs.Val; - byte[] rawRhs = (byte[])rhs.Val; - if (rawLhs.Length != rawRhs.Length) return false; - for (int i = 0; i < rawLhs.Length; i++) - { - if (rawLhs[i] != rawRhs[i]) return false; - } - return true; - case NtType.BooleanArray: - bool[] boolLhs = (bool[])lhs.Val; - bool[] boolRhs = (bool[])rhs.Val; - if (boolLhs.Length != boolRhs.Length) return false; - for (int i = 0; i < boolLhs.Length; i++) - { - if (boolLhs[i] != boolRhs[i]) return false; - } - return true; - case NtType.DoubleArray: - double[] doubleLhs = (double[])lhs.Val; - double[] doubleRhs = (double[])rhs.Val; - if (doubleLhs.Length != doubleRhs.Length) return false; - for (int i = 0; i < doubleLhs.Length; i++) - { - // ReSharper disable once CompareOfFloatsByEqualityOperator - if (doubleLhs[i] != doubleRhs[i]) return false; - } - return true; - case NtType.StringArray: - string[] stringLhs = (string[])lhs.Val; - string[] stringRhs = (string[])rhs.Val; - if (stringLhs.Length != stringRhs.Length) return false; - for (int i = 0; i < stringLhs.Length; i++) - { - if (stringLhs[i] != stringRhs[i]) return false; - } - return true; - default: - return false; - - } - } - - /// - /// Checks to see if two Values are not equal - /// - /// The left hand - /// The right hand - /// True if the Values are not equal - public static bool operator !=(Value lhs, Value rhs) - { - return !(lhs == rhs); - } - - /// - /// Makes a double - /// - /// The value to set the to - /// The created - public static Value MakeDouble(double val) - { - return new Value(val); - } - - /// - /// Makes a boolean - /// - /// The value to set the to - /// The created - public static Value MakeBoolean(bool val) - { - return new Value(val); - } - - /// - /// Makes a string - /// - /// The value to set the to - /// The created - public static Value MakeString(string val) - { - if (val == null) throw new ArgumentNullException(nameof(val)); - return new Value(val); - } - - /// - /// Makes a raw - /// - /// The value to set the to - /// The created - public static Value MakeRaw(params byte[] val) - { - byte[] tmp = new byte[val.Length]; - Array.Copy(val, tmp, val.Length); - return new Value(tmp); - } - - /// - /// Makes a raw - /// - /// The value to set the to - /// The created - public static Value MakeRaw(IList val) - { - return new Value(val.ToArray()); - } - - /// - /// Makes an Rpc - /// - /// The value to set the to - /// The size of the array to use for the Rpc - /// The created - public static Value MakeRpc(byte[] val, int size) - { - if (size > val.Length) return null; - byte[] tmp = new byte[size]; - Array.Copy(val, tmp, size); - return new Value(tmp, true); - } - - /// - /// Makes an Rpc - /// - /// The value to set the to - /// The created - public static Value MakeRpc(params byte[] val) - { - byte[] tmp = new byte[val.Length]; - Array.Copy(val, tmp, val.Length); - return new Value(tmp, true); - } - - /// - /// Makes an Rpc - /// - /// The value to set the to - /// The size of the array to use for the Rpc - /// The created - public static Value MakeRpc(IList val, int size) - { - if (size > val.Count) return null; - return new Value(val.ToArray(), true); - } - - /// - /// Makes an Rpc - /// - /// The value to set the to - /// The created - public static Value MakeRpc(IList val) - { - return new Value(val.ToArray(), true); - } - - /// - /// Makes a boolean array - /// - /// The value to set the to - /// The created - public static Value MakeBooleanArray(params bool[] val) - { - bool[] tmp = new bool[val.Length]; - Array.Copy(val, tmp, val.Length); - return new Value(tmp); - } - - /// - /// Makes a double array - /// - /// The value to set the to - /// The created - public static Value MakeDoubleArray(params double[] val) - { - double[] tmp = new double[val.Length]; - Array.Copy(val, tmp, val.Length); - return new Value(tmp); - } - - /// - /// Makes a string array - /// - /// The value to set the to - /// The created - public static Value MakeStringArray(params string[] val) - { - string[] tmp = new string[val.Length]; - Array.Copy(val, tmp, val.Length); - return new Value(tmp); - } - - /// - /// Makes a boolean array - /// - /// The value to set the to - /// The created - public static Value MakeBooleanArray(IList val) - { - return new Value(val.ToArray()); - } - - /// - /// Makes a double array - /// - /// The value to set the to - /// The created - public static Value MakeDoubleArray(IList val) - { - return new Value(val.ToArray()); - } - - /// - /// Makes a string array - /// - /// The value to set the to - /// The created - public static Value MakeStringArray(IList val) - { - return new Value(val.ToArray()); - } - - internal static Value MakeEmpty() - { - return new Value(); - } - - private Value(string val) - { - Type = NtType.String; - Val = val; - } - - private Value(byte[] val) - { - Type = NtType.Raw; - Val = val; - } - - // Extra parameter - // ReSharper disable once UnusedParameter.Local - private Value(byte[] val, bool rpc) - { - Type = NtType.Rpc; - Val = val; - } - - private Value(bool val) - { - Type = NtType.Boolean; - Val = val; - } - - private Value(double val) - { - Type = NtType.Double; - Val = val; - } - - private Value(string[] val) - { - Type = NtType.StringArray; - Val = val; - } - - private Value(double[] val) - { - Type = NtType.DoubleArray; - Val = val; - } - - private Value(bool[] val) - { - Type = NtType.BooleanArray; - Val = val; - } - } -} diff --git a/src/Shared/Wire/FastBitConverterBE.cs b/src/Shared/Wire/FastBitConverterBE.cs deleted file mode 100644 index 22da070..0000000 --- a/src/Shared/Wire/FastBitConverterBE.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace NetworkTables.Wire -{ - internal class FastBitConverterBE : IFastBitConverter - { -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddUShort(List list, ushort val) - { - list.Add((byte)(val & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - } - -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddShort(List list, short val) - { - list.Add((byte)(val & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - } - -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddUInt(List list, uint val) - { - list.Add((byte)(val & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 24) & 0xff)); - } - -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddInt(List list, int val) - { - list.Add((byte)(val & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 24) & 0xff)); - } - -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddULong(List list, ulong val) - { - list.Add((byte)(val & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 24) & 0xff)); - list.Add((byte)((val >> 32) & 0xff)); - list.Add((byte)((val >> 40) & 0xff)); - list.Add((byte)((val >> 48) & 0xff)); - list.Add((byte)((val >> 56) & 0xff)); - } - -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddLong(List list, long val) - { - list.Add((byte)(val & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 24) & 0xff)); - list.Add((byte)((val >> 32) & 0xff)); - list.Add((byte)((val >> 40) & 0xff)); - list.Add((byte)((val >> 48) & 0xff)); - list.Add((byte)((val >> 56) & 0xff)); - } - -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddDouble(List list, double val) - { - AddLong(list, BitConverter.DoubleToInt64Bits(val)); - } - } -} diff --git a/src/Shared/Wire/FastBitConverterCache.cs b/src/Shared/Wire/FastBitConverterCache.cs deleted file mode 100644 index f63f328..0000000 --- a/src/Shared/Wire/FastBitConverterCache.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace NetworkTables.Wire -{ - internal static class FastBitConverterCache - { - private static readonly Lazy s_fastBE = new Lazy(true); - private static readonly Lazy s_fastLE = new Lazy(true); - - internal static IFastBitConverter GetFastBitConverter() - { - if (BitConverter.IsLittleEndian) - { - return s_fastLE.Value; - } - else - { - return s_fastBE.Value; - } - } - } - -} \ No newline at end of file diff --git a/src/Shared/Wire/FastBitConverterLE.cs b/src/Shared/Wire/FastBitConverterLE.cs deleted file mode 100644 index e32a177..0000000 --- a/src/Shared/Wire/FastBitConverterLE.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace NetworkTables.Wire -{ - internal class FastBitConverterLE : IFastBitConverter - { -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddUShort(List list, ushort val) - { - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)(val & 0xff)); - } -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddShort(List list, short val) - { - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)(val & 0xff)); - } -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddUInt(List list, uint val) - { - list.Add((byte)((val >> 24) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)(val & 0xff)); - } -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddInt(List list, int val) - { - list.Add((byte)((val >> 24) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)(val & 0xff)); - } -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddULong(List list, ulong val) - { - list.Add((byte)((val >> 56) & 0xff)); - list.Add((byte)((val >> 48) & 0xff)); - list.Add((byte)((val >> 40) & 0xff)); - list.Add((byte)((val >> 32) & 0xff)); - list.Add((byte)((val >> 24) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)(val & 0xff)); - } -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddLong(List list, long val) - { - list.Add((byte)((val >> 56) & 0xff)); - list.Add((byte)((val >> 48) & 0xff)); - list.Add((byte)((val >> 40) & 0xff)); - list.Add((byte)((val >> 32) & 0xff)); - list.Add((byte)((val >> 24) & 0xff)); - list.Add((byte)((val >> 16) & 0xff)); - list.Add((byte)((val >> 8) & 0xff)); - list.Add((byte)(val & 0xff)); - } -#if !NET40 - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif - public void AddDouble(List list, double val) - { - AddLong(list, BitConverter.DoubleToInt64Bits(val)); - } - } -} diff --git a/src/Shared/Wire/IFastBitConverter.cs b/src/Shared/Wire/IFastBitConverter.cs deleted file mode 100644 index f08ef55..0000000 --- a/src/Shared/Wire/IFastBitConverter.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace NetworkTables.Wire -{ - internal interface IFastBitConverter - { - void AddUShort(List list, ushort val); - void AddShort(List list, short val); - void AddUInt(List list, uint val); - void AddInt(List list, int val); - void AddULong(List list, ulong val); - void AddLong(List list, long val); - void AddDouble(List list, double val); - } -} diff --git a/src/Shared/Wire/Leb128.cs b/src/Shared/Wire/Leb128.cs deleted file mode 100644 index 52afc5b..0000000 --- a/src/Shared/Wire/Leb128.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Collections.Generic; -using System.IO; - -namespace NetworkTables.Wire -{ - internal static class Leb128 - { - public static int SizeUleb128(ulong val) - { - int count = 0; - do - { - val >>= 7; - ++count; - } while (val != 0); - return count; - } - - public static int WriteUleb128(List addr, ulong val) - { - int count = 0; - do - { - byte b = (byte)(val & 0x7f); - val >>= 7; - - if (val != 0) - b |= 0x80; - addr.Add(b); - count++; - } while (val != 0); - return count; - } - - public static int ReadUleb128(byte[] addr, ref int start, out ulong ret) - { - ulong result = 0; - int shift = 0; - int count = 0; - - while (true) - { - if (start >= addr.Length) - { - ret = 0; - return 0; - } - byte b = addr[start]; - start++; - count++; - result |= (uint)((byte)(b & 0x7f) << shift); - shift += 7; - if ((b & 0x80) == 0) break; - } - ret = result; - return count; - } - - public static bool ReadUleb128(Stream istream, out ulong ret) - { - ulong result = 0; - int shift = 0; - ret = 0; - - while (true) - { - byte[] b = new byte[1]; - b[0] = 0; - if (istream.Read(b, 0, 1) != 1) return false; - result |= (uint)((byte)(b[0] & 0x7f) << shift); - shift += 7; - - if ((b[0] & 0x80) == 0) break; - } - - ret = result; - - return true; - } - } -} diff --git a/src/Shared/Wire/WireDecoder.cs b/src/Shared/Wire/WireDecoder.cs deleted file mode 100644 index 46c99b0..0000000 --- a/src/Shared/Wire/WireDecoder.cs +++ /dev/null @@ -1,342 +0,0 @@ -using System; -using System.IO; -using System.Net; -using System.Text; -using System.Collections.Generic; - -#if (!CORE) -using NetworkTables.Streams; -#endif - - -namespace NetworkTables.Wire -{ - /// - /// Utility class that can be used to read values from a byte array - /// - public class WireDecoder - { - internal static double ReadDouble(byte[] buf, int count) - { - return BitConverter.Int64BitsToDouble(IPAddress.NetworkToHostOrder(BitConverter.ToInt64(buf, count * 8))); - } - - private readonly Stream m_stream; - private byte[] m_buffer; - private int m_allocated; - - /// - /// Gets the error currently set by the decoder - /// - public string Error { get; internal set; } - - /// - /// Gets or sets the protocol revision of NetworkTables - /// - public int ProtoRev { get; set; } - - /// - /// Creates a new - /// - /// The Input Stream to read from - /// The protocol revision for the decoder - public WireDecoder(Stream istream, int protoRev) - { - m_allocated = 1024; - m_buffer = new byte[m_allocated]; - Error = null; - m_stream = istream; - ProtoRev = protoRev; - } - - /// - /// Creates a new using a list of bytes - /// - /// The data to decode - /// The protocol revision for the decoder - public WireDecoder(IList data, int protoRev) - { - m_allocated = 1024; - m_buffer = new byte[m_allocated]; - Error = null; - m_stream = new ListStream(data); - ProtoRev = protoRev; - } - - /// - /// Resets the wire decoder - /// - public void Reset() - { - Error = null; - } - - private void Realloc(int len) - { - if (m_allocated >= len) return; - int newLen = m_allocated * 2; - while (newLen < len) newLen *= 2; - byte[] newBuf = new byte[newLen]; - Array.Copy(m_buffer, newBuf, m_buffer.Length); - m_buffer = newBuf; - m_allocated = newLen; - } - - /// - /// Reads a specific number of bytes from the buffer - /// - /// The buffer to output to. - /// The length of data to read - /// True if the bytes were read, otherwise false - public bool Read(out byte[] buf, int len) - { - if (len == 0) - { - //Special case - buf = m_buffer; - return true; - } - if (len > m_allocated) Realloc(len); - buf = m_buffer; -#if CORE - int rv = m_stream.Read(m_buffer, 0, len); -#else - int rv = m_stream.Receive(m_buffer, 0, len); -#endif - return rv != 0; - } - - /// - /// Read the next that is waiting in the buffer - /// - /// The that is next in the buffer - /// True if the type was read, else false - public bool ReadType(ref NtType type) - { - byte itype = 0; - if (!Read8(ref itype)) return false; - switch (itype) - { - case 0x00: - type = NtType.Boolean; - break; - case 0x01: - type = NtType.Double; - break; - case 0x02: - type = NtType.String; - break; - case 0x03: - type = NtType.Raw; - break; - case 0x10: - type = NtType.BooleanArray; - break; - case 0x11: - type = NtType.DoubleArray; - break; - case 0x12: - type = NtType.StringArray; - break; - case 0x20: - type = NtType.Rpc; - break; - default: - type = NtType.Unassigned; - Error = "unrecognized value type"; - return false; - } - return true; - } - - /// - /// Read the next that is waiting in the buffer - /// - /// The the should be - /// True if the value was read, otherwise false - public Value ReadValue(NtType type) - { - byte size = 0; - byte[] buf; - Error = null; - switch (type) - { - case NtType.Boolean: - byte vB = 0; - return !Read8(ref vB) ? null : Value.MakeBoolean(vB != 0); - case NtType.Double: - double vD = 0; - return !ReadDouble(ref vD) ? null : Value.MakeDouble(vD); - case NtType.Raw: - if (ProtoRev < 0x0300u) - { - Error = "Received raw value in protocol < 3.0"; - return null; - } - byte[] vRa = null; - return !ReadRaw(ref vRa) ? null : Value.MakeRaw(vRa); - case NtType.Rpc: - if (ProtoRev < 0x0300u) - { - Error = "Received raw value in protocol < 3.0"; - return null; - } - byte[] vR = null; - return !ReadRaw(ref vR) ? null : Value.MakeRpc(vR, vR.Length); - case NtType.String: - string vS = ""; - return !ReadString(ref vS) ? null : Value.MakeString(vS); - case NtType.BooleanArray: - if (!Read8(ref size)) return null; - - if (!Read(out buf, size)) return null; - bool[] bBuf = new bool[size]; - for (int i = 0; i < size; i++) - { - bBuf[i] = buf[i] != 0; - } - return Value.MakeBooleanArray(bBuf); - case NtType.DoubleArray: - if (!Read8(ref size)) return null; - if (!Read(out buf, size * 8)) return null; - double[] dBuf = new double[size]; - for (int i = 0; i < size; i++) - { - dBuf[i] = ReadDouble(buf, i); - } - return Value.MakeDoubleArray(dBuf); - case NtType.StringArray: - if (!Read8(ref size)) return null; - string[] sBuf = new string[size]; - for (int i = 0; i < size; i++) - { - if (!ReadString(ref sBuf[i])) return null; - } - return Value.MakeStringArray(sBuf); - default: - Error = "invalid type when trying to read value"; - Console.WriteLine("invalid type when trying to read value"); - return null; - } - } - - /// - /// Checks to see if a specific number of bytes exists in the buffer - /// - /// The number of bytes to check - /// True if the number of requested bytes exists in the array - /// Note that using a will always result in false. - public bool HasMoreBytes(int numBytesToCheck) - { - try - { - long length = m_stream.Length; - long position = m_stream.Position; - return length - position >= numBytesToCheck; - } - catch (NotImplementedException) - { - return false; - } - } - - /// - /// Read a Uleb128 length from the buffer. - /// - /// The length read - /// True if the length was read - public bool ReadUleb128(out ulong val) - { - return Leb128.ReadUleb128(m_stream, out val); - } - - /// - /// Reads a byte from the buffer - /// - /// The byte read - /// True if the byte was read - public bool Read8(ref byte val) - { - if (!Read(out byte[] buf, 1)) return false; - val = (byte)(buf[0] & 0xff); - return true; - } - - /// - /// Reads a ushort from the buffer - /// - /// The ushort read - /// True if the ushort was read - public bool Read16(ref ushort val) - { - if (!Read(out byte[] buf, 2)) return false; - val = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(buf, 0)); - return true; - } - - /// - /// Reads a uint from the buffer - /// - /// The uint read - /// True if the uint was read - public bool Read32(ref uint val) - { - if (!Read(out byte[] buf, 4)) return false; - val = (uint)IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(buf, 0)); - return true; - } - - /// - /// Reads a double from the buffer - /// - /// The double read - /// True if the double was read - public bool ReadDouble(ref double val) - { - if (!Read(out byte[] buf, 8)) return false; - val = ReadDouble(buf, 0); - return true; - } - - /// - /// Reads a string from the buffer - /// - /// The string read - /// True if the string was read - public bool ReadString(ref string val) - { - int len; - if (ProtoRev < 0x0300u) - { - ushort v = 0; - if (!Read16(ref v)) return false; - len = v; - } - else - { - if (!ReadUleb128(out ulong v)) return false; - len = (int)v; - } - if (!Read(out byte[] buf, len)) return false; - val = Encoding.UTF8.GetString(buf, 0, len); - return true; - } - - /// - /// Reads a raw byte array from the buffer - /// - /// The raw array read - /// True if the raw array was read - public bool ReadRaw(ref byte[] val) - { - if (!ReadUleb128(out ulong v)) return false; - var len = (int)v; - - if (!Read(out byte[] buf, len)) return false; - - val = new byte[len]; - Array.Copy(m_buffer, 0, val, 0, len); - return true; - } - } -} diff --git a/src/Shared/Wire/WireEncoder.cs b/src/Shared/Wire/WireEncoder.cs deleted file mode 100644 index c5645f9..0000000 --- a/src/Shared/Wire/WireEncoder.cs +++ /dev/null @@ -1,342 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Text; - -namespace NetworkTables.Wire -{ - /// - /// Utility class that can write values to be sent over a byte array - /// - public class WireEncoder - { - private IFastBitConverter m_fastBitConverter; - - private readonly List m_buffer = new List(1024); - - /// - /// Gets the current buffer of data - /// - public byte[] Buffer => m_buffer.ToArray(); - - /// - /// Gets the error currently set by the encoder - /// - public string Error { get; private set; } - - /// - /// Writes a double to the buffer - /// - /// The value to write - public void WriteDouble(double val) - { - m_fastBitConverter.AddDouble(m_buffer, val); - } - - /// - /// Gets the size - /// - /// - public int Count => m_buffer.Count; - - /// - /// Gets or sets the protocol revision of NetworkTables - /// - public int ProtoRev { get; set; } - - /// - /// Creates a new - /// - /// The protocol vision for the encoder - public WireEncoder(int protoRev) - { - m_fastBitConverter = FastBitConverterCache.GetFastBitConverter(); - ProtoRev = protoRev; - } - - /// - /// Resets the encoder - /// - public void Reset() - { - m_buffer.Clear(); - Error = null; - } - - /// - /// Writes a byte to the encoder - /// - /// The byte to write - public void Write8(byte val) - { - m_buffer.Add(val); - } - - /// - /// Writes a ushort to the encoder - /// - /// The ushort to write to the encoder - public void Write16(ushort val) - { - m_fastBitConverter.AddUShort(m_buffer, val); - } - - /// - /// Writes a uint to the encoder - /// - /// The uint to write to the encoder - public void Write32(uint val) - { - m_fastBitConverter.AddUInt(m_buffer, val); - } - - /// - /// Write a Uleb128 length to the encoder - /// - /// The Uleb128 length to write - public void WriteUleb128(ulong val) - { - Leb128.WriteUleb128(m_buffer, val); - } - - /// - /// Writes a to the encoder - /// - /// The to write - public void WriteType(NtType type) - { - switch (type) - { - case NtType.Boolean: - m_buffer.Add(0x00); - break; - case NtType.Double: - m_buffer.Add(0x01); - break; - case NtType.String: - m_buffer.Add(0x02); - break; - case NtType.Raw: - if (ProtoRev < 0x0300u) - { - Error = "raw type not supported in protocol < 3.0"; - return; - } - m_buffer.Add(0x03); - break; - case NtType.BooleanArray: - m_buffer.Add(0x10); - break; - case NtType.DoubleArray: - m_buffer.Add(0x11); - break; - case NtType.StringArray: - m_buffer.Add(0x12); - break; - case NtType.Rpc: - if (ProtoRev < 0x0300u) - { - Error = "RPC type not supported in protocol < 3.0"; - return; - } - m_buffer.Add(0x20); - break; - default: - Error = "unrecognized Type"; - return; - } - Error = null; - } - - /// - /// Gets the size of a value if it was to be written to the encoder - /// - /// The to check the size of - /// The size the would take on the encoder - public int GetValueSize(Value value) - { - if (value == null) return 0; - int size; - switch (value.Type) - { - case NtType.Boolean: - return 1; - case NtType.Double: - return 8; - case NtType.Raw: - if (ProtoRev < 0x0300u) return 0; - return GetRawSize((byte[])value.Val); - case NtType.Rpc: - if (ProtoRev < 0x0300u) return 0; - return GetRawSize((byte[])value.Val); - case NtType.String: - return GetStringSize((string)value.Val); - case NtType.BooleanArray: - size = ((bool[])value.Val).Length; - if (size > 0xff) size = 0xff; - return 1 + size; - case NtType.DoubleArray: - size = ((double[])value.Val).Length; - if (size > 0xff) size = 0xff; - return 1 + size * 8; - case NtType.StringArray: - string[] v = (string[])value.Val; - size = v.Length; - if (size > 0xff) size = 0xff; - int len = 1; - for (int i = 0; i < size; i++) - { - len += GetStringSize(v[i]); - } - return len; - default: - return 0; - } - } - - /// - /// Writes a to the encoder - /// - /// The to write - public void WriteValue(Value value) - { - if (value == null) - { - Error = "Value cannot be null"; - return; - } - switch (value.Type) - { - case NtType.Boolean: - Write8((bool)value.Val ? (byte)1 : (byte)0); - break; - case NtType.Double: - WriteDouble((double)value.Val); - break; - case NtType.Raw: - if (ProtoRev < 0x0300u) - { - Error = "Raw values not supported in protocol < 3.0"; - return; - } - WriteRaw((byte[])value.Val); - break; - case NtType.String: - WriteString((string)value.Val); - break; - case NtType.Rpc: - if (ProtoRev < 0x0300u) - { - Error = "RPC values not supported in protocol < 3.0"; - return; - } - WriteRaw((byte[])value.Val); - break; - case NtType.BooleanArray: - var vB = (bool[])value.Val; - int sizeB = vB.Length; - if (sizeB > 0xff) sizeB = 0xff; - Write8((byte)sizeB); - for (int i = 0; i < sizeB; i++) - { - Write8(vB[i] ? (byte)1 : (byte)0); - } - break; - case NtType.DoubleArray: - var vD = (double[])value.Val; - int sizeD = vD.Length; - if (sizeD > 0xff) sizeD = 0xff; - Write8((byte)sizeD); - for (int i = 0; i < sizeD; i++) - { - WriteDouble(vD[i]); - } - break; - case NtType.StringArray: - var vS = (string[])value.Val; - int sizeS = vS.Length; - if (sizeS > 0xff) sizeS = 0xff; - Write8((byte)sizeS); - for (int i = 0; i < sizeS; i++) - { - WriteString(vS[i]); - } - break; - default: - Error = "unrecognized type when writing value"; - return; - } - Error = null; - } - - /// - /// Gets the size of a raw array if it was to be written to the encoder - /// - /// The raw array to check the size of - /// The size the raw array would take on the encoder - public int GetRawSize(byte[] raw) - { - return Leb128.SizeUleb128((ulong)raw.Length) + raw.Length; - } - - /// - /// Writes a raw array to the encoder - /// - /// The raw array to write - public void WriteRaw(byte[] raw) - { - WriteUleb128((ulong)raw.Length); - m_buffer.AddRange(raw); - } - - /// - /// Gets the size of a string if it was to be written to the encoder - /// - /// The string to check the size of - /// The size the string would take on the encoder - public int GetStringSize(string str) - { - if (ProtoRev < 0x0300u) - { - int len = str.Length; - if (len > 0xffff) len = 0xffff; - return 2 + len; - } - return Leb128.SizeUleb128((ulong)str.Length) + str.Length; - } - - /// - /// Write a string to the encoder - /// - /// The string to write - public void WriteString(string str) - { - int len = str.Length; - if (ProtoRev < 0x0300u) - { - if (len > 0xffff) len = 0xffff; - - Write16((ushort)len); - byte[] b = Encoding.UTF8.GetBytes(str); - byte[] bytes; - if (b.Length > len) - { - bytes = new byte[len]; - Array.Copy(b, bytes, len); - } - else - { - bytes = b; - } - m_buffer.AddRange(bytes); - } - else - { - WriteUleb128((ulong)len); - m_buffer.AddRange(Encoding.UTF8.GetBytes(str)); - } - - - } - } -} diff --git a/test/FRC.NetworkTables.Core.Test/EntryListenerTest.cs b/test/FRC.NetworkTables.Core.Test/EntryListenerTest.cs new file mode 100644 index 0000000..ee75c03 --- /dev/null +++ b/test/FRC.NetworkTables.Core.Test/EntryListenerTest.cs @@ -0,0 +1,57 @@ +using FRC.NetworkTables.Interop; +using System; +using System.Collections.Generic; +using System.Threading; +using Xunit; + + +namespace FRC.NetworkTables.Core.Test +{ + public class EntryListenerTest + { + private void Connect(NetworkTableInstance server, NetworkTableInstance client) + { + server.SetNetworkIdentity("server"); + client.SetNetworkIdentity("client"); + + server.StartServer("entrylistenertest.ini", "127.0.0.1", 10000); + client.StartClient("127.0.0.1", 10000); + + var poller = NtCore.CreateConnectionListenerPoller(client.Handle); + NtCore.AddPolledConnectionListener(poller, false); + var polled = NtCore.PollConnectionListenerTimeout(poller, 1.0, out var timedOut); + var len = polled.Length; + NtCore.DisposeConnectionListenerSpan(polled); + Assert.NotEqual(0, len); + } + + [Fact] + public void TestPrefixNewRemote() + { + using (var server = NetworkTableInstance.Create()) + using (var client = NetworkTableInstance.Create()) + { + Connect(server, client); + List events = new List(); + var handle = server.AddEntryListener("/foo", (in RefEntryNotification n) => + { + events.Add(n.CopyNotification); + }, NotifyFlags.New); + + client.GetEntry("/foo/bar").SetDouble(1.0); + client.GetEntry("/baz").SetDouble(1.0); + client.Flush(); + Thread.Sleep(100); + + Assert.True(server.WaitForEntryListenerQueue(1.0)); + + Assert.Single(events); + Assert.Equal(handle, events[0].Listener); + Assert.Equal(server.GetEntry("/foo/bar"), events[0].Entry); + Assert.Equal("/foo/bar", events[0].Name); + Assert.Equal(NetworkTableValue.MakeDouble(1.0), events[0].Value); + Assert.Equal(NotifyFlags.New, events[0].Flags); + } + } + } +} diff --git a/test/FRC.NetworkTables.Core.Test/FRC.NetworkTables.Core.Test.csproj b/test/FRC.NetworkTables.Core.Test/FRC.NetworkTables.Core.Test.csproj new file mode 100644 index 0000000..13fbba8 --- /dev/null +++ b/test/FRC.NetworkTables.Core.Test/FRC.NetworkTables.Core.Test.csproj @@ -0,0 +1,28 @@ + + + + netcoreapp3.0 + + false + + + + true + 8.0 + enable + + + + + + + + + + + + + + + + diff --git a/test/FRC.NetworkTables.Core.Test/LinkTest.cs b/test/FRC.NetworkTables.Core.Test/LinkTest.cs new file mode 100644 index 0000000..2a0dfd9 --- /dev/null +++ b/test/FRC.NetworkTables.Core.Test/LinkTest.cs @@ -0,0 +1,15 @@ +using System; +using Xunit; + +namespace FRC.NetworkTables.Core.Test +{ + public class LinkTest + { + [Fact] + public void EnsureNativeLinkTest() + { + var inst = NetworkTableInstance.Default; + inst.Flush(); + } + } +} diff --git a/test/FRC.NetworkTables.Core.Test/NetworkTableTest.cs b/test/FRC.NetworkTables.Core.Test/NetworkTableTest.cs new file mode 100644 index 0000000..12ba15e --- /dev/null +++ b/test/FRC.NetworkTables.Core.Test/NetworkTableTest.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace FRC.NetworkTables.Core.Test +{ + public class NetworkTableTest + { + } +} diff --git a/test/NetworkTables.Core.Test/NetworkTables.Core.Test.csproj b/test/NetworkTables.Core.Test/NetworkTables.Core.Test.csproj deleted file mode 100644 index ea3fd7f..0000000 --- a/test/NetworkTables.Core.Test/NetworkTables.Core.Test.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - net451;netcoreapp1.0 - $(NoWarn);CS0618 - true - NetworkTables.Core.Test - NetworkTables.Core.Test - true - false - false - false - - - - - - - - - - - - - - - - - - - - - diff --git a/test/NetworkTables.Core.Test/Properties/AssemblyInfo.cs b/test/NetworkTables.Core.Test/Properties/AssemblyInfo.cs deleted file mode 100644 index 641a41c..0000000 --- a/test/NetworkTables.Core.Test/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("NetworkTables.NtCore.Test")] -[assembly: AssemblyTrademark("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("cd229281-355d-49b5-a2f8-eed454c78837")] diff --git a/test/NetworkTables.Core.Test/SpecScanners/InteropForTesting.cs b/test/NetworkTables.Core.Test/SpecScanners/InteropForTesting.cs deleted file mode 100644 index ca89c1e..0000000 --- a/test/NetworkTables.Core.Test/SpecScanners/InteropForTesting.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using NetworkTables.Core.Native; -using FRC.NativeLibraryUtilities; - -// ReSharper disable InconsistentNaming -// ReSharper disable NotAccessedField.Global - -namespace NetworkTables.Core.Test.SpecScanners -{ - public class InteropForTesting - { - private InteropForTesting() { } - - static InteropForTesting() - { - var nativeLoader = Interop.NativeLoader; - - NativeDelegateInitializer.SetupNativeDelegates(nativeLoader); - } - -#pragma warning disable 649 - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetStringForTestingDelegate(byte[] name, ref int size); - - [NativeDelegate] - internal static NT_GetStringForTestingDelegate NT_GetStringForTesting; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetEntryInfoForTestingDelegate( - byte[] name, NtType type, uint flags, ulong lastChange, ref int size); - [NativeDelegate] - internal static NT_GetEntryInfoForTestingDelegate NT_GetEntryInfoForTesting; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_FreeEntryInfoForTestingDelegate(IntPtr info); - [NativeDelegate] - internal static NT_FreeEntryInfoForTestingDelegate NT_FreeEntryInfoForTesting; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetConnectionInfoForTestingDelegate( - byte[] id, byte[] ip, uint port, ulong lastUpdate, uint protoVersion, ref int size); - [NativeDelegate] - internal static NT_GetConnectionInfoForTestingDelegate NT_GetConnectionInfoForTesting; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_FreeConnectionInfoForTestingDelegate(IntPtr info); - [NativeDelegate] - internal static NT_FreeConnectionInfoForTestingDelegate NT_FreeConnectionInfoForTesting; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr NT_GetRpcCallInfoForTestingDelegate( - uint rpcId, uint callUid, byte[] name, byte[] param, UIntPtr paramLen, ref int size); - [NativeDelegate] - internal static NT_GetRpcCallInfoForTestingDelegate NT_GetRpcCallInfoForTesting; - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DisposeRpcCallInfoDelegate(ref NtRpcCallInfo callInfo); - [NativeDelegate] - internal static NT_DisposeRpcCallInfoDelegate NT_DisposeRpcCallInfo; - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void NT_DisposeRpcCallInfoIntPtrDelegate(IntPtr callInfo); - [NativeDelegate("NT_DisposeRpcCallInfo")] - internal static NT_DisposeRpcCallInfoIntPtrDelegate NT_DisposeRpcCallInfoIntPtr; - -#pragma warning restore 649 - } -} diff --git a/test/NetworkTables.Core.Test/SpecScanners/TestNativeLibraryInterface.cs b/test/NetworkTables.Core.Test/SpecScanners/TestNativeLibraryInterface.cs deleted file mode 100644 index 818f230..0000000 --- a/test/NetworkTables.Core.Test/SpecScanners/TestNativeLibraryInterface.cs +++ /dev/null @@ -1,498 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Text; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using NetworkTables.Core.Native; -using FRC.NativeLibraryUtilities; -using NUnit.Framework; -using FRC; -using static FRC.UTF8String; -using static NetworkTables.Core.Test.SpecScanners.InteropForTesting; -using static NetworkTables.Core.Native.CoreMethods; -using static NetworkTables.Core.Native.Interop; - -namespace NetworkTables.Core.Test.SpecScanners -{ - [TestFixture] - public class TestNativeLibraryInterface - { -#if !NETCOREAPP1_0 - public struct HALDelegateClass - { - public string ClassName; - public List Methods; - } - - // Code for this found here - // http://stackoverflow.com/questions/19001423/getting-path-of-a-to-the-parent-folder-of-the-solution-file-c-sharp - private static string FindRootSolutionDirectory() - { -#if NETCOREAPP1_0 - return null -#else - var assembly = Assembly.GetExecutingAssembly(); - var p = Path.DirectorySeparatorChar; - var path = assembly.CodeBase.Replace("file:///", "").Replace("/", p.ToString()); - path = Path.GetDirectoryName(path); - - - var directory = new DirectoryInfo( - path ?? Directory.GetCurrentDirectory()); - while (directory != null && !directory.GetFiles("*.sln").Any()) - { - directory = directory.Parent; - } - return directory?.FullName; -#endif - } - - // Gets a list of all of our delegates used by the HAL - public static List GetDelegates() - { - List halBaseMethods = new List(); - - var pathToSolution = FindRootSolutionDirectory(); - var p = Path.DirectorySeparatorChar; - Assert.That(pathToSolution, Is.Not.Null); - var file = $"{pathToSolution}{p}src{p}FRC.NetworkTables.Core{p}Native{p}Interop.cs"; - HALDelegateClass cs = new HALDelegateClass - { - ClassName = "", - Methods = new List() - }; - using (var stream = File.OpenRead(file)) - { - var tree = CSharpSyntaxTree.ParseText(SourceText.From(stream), path: file); - cs.ClassName = Path.GetFileName(file); - var methods = - tree.GetRoot() - .DescendantNodes() - .OfType() - .Select(a => a).ToList(); - cs.Methods.AddRange(methods); - } - halBaseMethods.Add(cs); - - return halBaseMethods; - } - - - /// - /// Gets a list of all the native symbols needed by HAL-RoboRIO - /// - /// - public static List GetRequestedNativeSymbols() - { - List nativeFunctions = new List(); - var pathToSolution = FindRootSolutionDirectory(); - var p = Path.DirectorySeparatorChar; - Assert.That(pathToSolution, Is.Not.Null); - var dir = $"{pathToSolution}{p}src{p}FRC.NetworkTables.Core{p}Native"; - foreach (var file in Directory.GetFiles(dir, "*.cs")) - { - if (!file.ToLower().Contains("Interop")) continue; - using (StreamReader reader = new StreamReader(file)) - { - bool foundInitialize = false; - string line; - while (!foundInitialize) - { - line = reader.ReadLine(); - if (line == null) break; - if (line.ToLower().Contains("static void initializedelegates")) foundInitialize = true; - } - if (!foundInitialize) continue; - - while ((line = reader.ReadLine()) != null) - { - if (line.TrimStart(' ').StartsWith("//")) continue; - if (line.ToLower().Contains("marshal.getdelegateforfunctionpointer")) - { - int startParam = line.IndexOf('"'); - int endParam = line.IndexOf('"', startParam + 1); - nativeFunctions.Add(line.Substring(startParam + 1, endParam - startParam - 1)); - } - } - } - } - return nativeFunctions; - } - - - [Test] - public void TestRoboRioMapsToNativeAssemblySymbols() - { - OsType type = NativeLibraryLoader.GetOsType(); - - //Only run the roboRIO symbol test on windows. - if (type != OsType.Windows32 && type != OsType.Windows64) Assert.Pass(); - - var roboRIOSymbols = GetRequestedNativeSymbols(); - - var pathToSolution = FindRootSolutionDirectory(); - var ps = Path.DirectorySeparatorChar; - Assert.That(pathToSolution, Is.Not.Null); - var dirToNetworkTablesLib = $"{pathToSolution}{ps}src{ps}FRC.NetworkTables.Core.DesktopLibraries"; - - // Start the child process. - Process p = new Process(); - p.StartInfo.UseShellExecute = false; - p.StartInfo.RedirectStandardOutput = true; - p.StartInfo.CreateNoWindow = true; - p.StartInfo.FileName = $"{dirToNetworkTablesLib}\\Libraries\\frcnm.exe"; - Console.WriteLine(p.StartInfo.FileName); - p.StartInfo.Arguments = $"{dirToNetworkTablesLib}\\Libraries\\Linux\\arm\\libntcore.so"; - p.Start(); - string output = p.StandardOutput.ReadToEnd(); - p.WaitForExit(); - - bool found = true; - - - string[] nativeSymbols = output.Split('\r'); - - foreach (var halSymbol in roboRIOSymbols) - { - bool foundSymbol = nativeSymbols.Any(nativeSymbol => nativeSymbol.EndsWith(halSymbol)); - if (!foundSymbol) - { - found = false; - Console.WriteLine(halSymbol); - } - } - - Assert.That(found); - } -#endif - - //Checks all our types for blittable - private void CheckForBlittable(List types, List allowedTypes, List nonBlittableFuncs, string nonBlittableLine) - { - bool allBlittable = true; - foreach (TypeSyntax t in types) - { - bool found = false; - foreach (string a in allowedTypes) - { - if (t.ToString().Contains(a)) //Contains is OK, since arrays of blittable types are blittable. - { - found = true; - } - } - if (!found) - { - allBlittable = false; - } - } - - if (!allBlittable) - { - nonBlittableFuncs.Add(nonBlittableLine); - } - } - - private static bool IsBlittable(Type type) - { - // If is array - if (type.IsArray) - { - //Check that the elements are value type, and that the element itself is blittable. - var elements = type.GetElementType(); - return elements.GetTypeInfo().IsValueType && IsBlittable(elements); - } - try - { - //Otherwise try and pin the type. If it pins, it is blittable. - //If exception is thrown, it is not blittable, and do not allow. -#if NETCOREAPP1_0 - object obj = Activator.CreateInstance(type); -#else - object obj = FormatterServices.GetUninitializedObject(type); -#endif - GCHandle.Alloc(obj, GCHandleType.Pinned).Free(); - return true; - } - catch - { - return false; - } - } - - [Test] - public void TestNtConnectionInfo() - { - string name = "Testing"; - string ip = "localhost"; - uint port = 1756; - ulong lastUpdate = 26; - uint protoRev = 0x0300; - int nativeSize = 0; - - byte[] nameArr = CreateUTF8String(name); - byte[] ipArr = CreateUTF8String(ip); - IntPtr connectionInfoPtr = NT_GetConnectionInfoForTesting(nameArr, ipArr, port, lastUpdate, protoRev, - ref nativeSize); - Assert.That(Marshal.SizeOf(typeof(NtConnectionInfo)), Is.EqualTo(nativeSize)); - Assert.That(IsBlittable(typeof(NtConnectionInfo))); - - using (DisposableNativeString nameToWrite = new DisposableNativeString(name)) - using (DisposableNativeString ipToWrite = new DisposableNativeString(ip)) - { - - - NtConnectionInfo managedInfo = new NtConnectionInfo(new NtStringRead(nameToWrite.Buffer, nameToWrite.Length), - new NtStringRead(ipToWrite.Buffer, ipToWrite.Length), port, lastUpdate, protoRev); - - Assert.That(managedInfo.RemoteId.ToString(), Is.EqualTo(name)); - Assert.That(managedInfo.RemoteIp.ToString(), Is.EqualTo(ip)); - Assert.That(managedInfo.RemotePort, Is.EqualTo(port)); - Assert.That(managedInfo.LastUpdate, Is.EqualTo(lastUpdate)); - Assert.That(managedInfo.ProtocolVersion, Is.EqualTo(protoRev)); - - - List nativeArray = new List(); - List managedArray = new List(); - - int bytesToSkip = (Marshal.SizeOf(typeof(IntPtr)) == 8) ? 32 : 16; - unsafe - { - NtConnectionInfo* connInfo = (NtConnectionInfo*)connectionInfoPtr.ToPointer(); - Assert.That(connInfo->RemoteId.ToString(), Is.EqualTo(name)); - Assert.That(connInfo->RemoteIp.ToString(), Is.EqualTo(ip)); - Assert.That(connInfo->RemotePort, Is.EqualTo(port)); - Assert.That(connInfo->LastUpdate, Is.EqualTo(lastUpdate)); - Assert.That(connInfo->ProtocolVersion, Is.EqualTo(protoRev)); - - - - byte* bp = (byte*)connInfo; - for (int i = bytesToSkip; i < nativeSize; i++) - { - nativeArray.Add(bp[i]); - } - - NtConnectionInfo* managedConn = &managedInfo; - byte* mbp = (byte*)managedConn; - - for (int i = bytesToSkip; i < Marshal.SizeOf(typeof(NtConnectionInfo)); i++) - { - managedArray.Add(mbp[i]); - } - } - - // Assert that everything past our pointer values are equivelent - Assert.That(nativeArray, Is.EquivalentTo(managedArray)); - - } - - NT_FreeConnectionInfoForTesting(connectionInfoPtr); - } - - [Test] - public void TestNtStringRead() - { - int numberNonChangingBytes = 0; - int numberPointers = 2; - int pointerSize = Marshal.SizeOf(typeof(IntPtr)); - - int pointerTotal = numberPointers * pointerSize; - Assert.That(Marshal.SizeOf(typeof(NtStringRead)), Is.EqualTo(pointerTotal + numberNonChangingBytes)); - Assert.That(IsBlittable(typeof(NtStringRead))); - } - - [Test] - public void TestNtStringWrite() - { - int numberNonChangingBytes = 0; - int numberPointers = 2; - int pointerSize = Marshal.SizeOf(typeof(IntPtr)); - - int pointerTotal = numberPointers * pointerSize; - Assert.That(Marshal.SizeOf(typeof(DisposableNativeString)), Is.EqualTo(pointerTotal + numberNonChangingBytes)); - Assert.That(IsBlittable(typeof(DisposableNativeString))); - } - - [Test] - public void TestNtRpcCallInfo() - { - uint rpcId = 10549; - uint callUid = 8085; - string name = "TestName"; - string param = "Params\0Others"; - - byte[] nameArr = CreateUTF8String(name); - byte[] paramArr = CreateUTF8String(param); - int nativeSize = 0; - - IntPtr rpcCallInfoPtr = NT_GetRpcCallInfoForTesting(rpcId, callUid, nameArr, paramArr, (UIntPtr)(paramArr.Length - 1), ref nativeSize); - - - - Assert.That(Marshal.SizeOf(typeof(NtRpcCallInfo)), Is.EqualTo(nativeSize)); - Assert.That(IsBlittable(typeof(NtRpcCallInfo))); - - using (DisposableNativeString nameToWrite = new DisposableNativeString(name)) - using (DisposableNativeString paramToWrite = new DisposableNativeString(param)) - { - - - NtRpcCallInfo managedInfo = new NtRpcCallInfo(new NtStringRead(nameToWrite.Buffer, nameToWrite.Length), - new NtStringRead(paramToWrite.Buffer, paramToWrite.Length), rpcId, callUid); - - Assert.That(managedInfo.Name.ToString(), Is.EqualTo(name)); - Assert.That(managedInfo.Param.ToString(), Is.EqualTo(param)); - Assert.That(managedInfo.CallUid, Is.EqualTo(callUid)); - Assert.That(managedInfo.RpcId, Is.EqualTo(rpcId)); - - - List nativeArray = new List(); - List managedArray = new List(); - - int bytesToSkip = (Marshal.SizeOf(typeof(IntPtr)) == 8) ? 32 : 16; - unsafe - { - NtRpcCallInfo* callInfo = (NtRpcCallInfo*)rpcCallInfoPtr.ToPointer(); - Assert.That(callInfo->Name.ToString(), Is.EqualTo(name)); - Assert.That(callInfo->Param.ToString(), Is.EqualTo(param)); - Assert.That(callInfo->CallUid, Is.EqualTo(callUid)); - Assert.That(callInfo->RpcId, Is.EqualTo(rpcId)); - - - - byte* bp = (byte*)callInfo; - for (int i = 0; i < nativeSize - bytesToSkip; i++) - { - nativeArray.Add(bp[i]); - } - - NtRpcCallInfo* managedRpc = &managedInfo; - byte* mbp = (byte*)managedRpc; - - for (int i = 0; i < Marshal.SizeOf(typeof(NtRpcCallInfo)) - bytesToSkip; i++) - { - managedArray.Add(mbp[i]); - } - } - - // Assert that everything past our pointer values are equivelent - Assert.That(nativeArray, Is.EquivalentTo(managedArray)); - - } - - NT_DisposeRpcCallInfoIntPtr(rpcCallInfoPtr); - } - - [Test] - public void TestNtStringWriteArray() - { - object obj = new DisposableNativeString[6]; - Assert.DoesNotThrow(() => GCHandle.Alloc(obj, GCHandleType.Pinned).Free()); - } -#if !NETCOREAPP1_0 - [Test] - public void TestNativeIntefaceBlittable() - { - OsType type = NativeLibraryLoader.GetOsType(); - //Only run the blittable test on windows. Pathing on linux is being an issue - if (type != OsType.Windows32 && type != OsType.Windows64) Assert.Pass(); - - List allowedTypes = new List() - { - // Allowed types with arrays are also allowed - "byte", "sbyte", "short", "ushort", "int", "uint", "long", "ulong", "IntPtr", "UIntPtr", "float", "void", "double", - - // For now force our enum types to be OK - "NtType", - //"CTR_Code", "HALAccelerometerRange", "HALAllianceStationID", "AnalogTriggerType", "Mode", - - //Allow delegates to be blittable - "WarmFunction", "NT_LogFunc", "NT_ConnectionListenerCallback", "NT_EntryListenerCallback", "NT_RPCCallback", - - //Also allow any structs known to be blittable - "NtStringRead", "DisposableNativeString", "NtConnectionInfo", "NtRpcCallInfo", - - //For now allow bool, since it marshalls easily - //This will change if the native windows HAL is not 1 byte bools - "bool", - }; - - List notBlittableMethods = new List(); - - - var halBaseDelegates = GetDelegates(); - foreach (var halDelegate in halBaseDelegates) - { - foreach (var methodSyntax in halDelegate.Methods) - { - List types = new List(); - - if (methodSyntax.AttributeLists.Count != 0) - { - types.Add(methodSyntax.ReturnType); - } - else - { - types.Add(methodSyntax.ReturnType); - } - - List param = new List(); - - StringBuilder builder = new StringBuilder(); - builder.Append($"\t {methodSyntax.ReturnType} {methodSyntax.Identifier} ("); - bool first = true; - foreach (var parameter in methodSyntax.ParameterList.Parameters) - { - if (parameter.AttributeLists.Count != 0) - { - types.Add(parameter.Type); - } - else - { - types.Add(parameter.Type); - } - - - param.Add(parameter.Type.ToString()); - if (first) - { - first = false; - builder.Append($"{parameter.Type} {parameter.Identifier}"); - } - else - { - builder.Append($", {parameter.Type} {parameter.Identifier}"); - } - } - builder.Append(")"); - - CheckForBlittable(types, allowedTypes, notBlittableMethods, builder.ToString()); - } - } - - foreach (string s in notBlittableMethods) - { - Console.WriteLine(s); - } - - if (notBlittableMethods.Count != 0) - { - Assert.Fail(); - } - else - { - Assert.Pass(); - } - } -#endif - } - -} diff --git a/test/NetworkTables.Core.Test/TestBase.cs b/test/NetworkTables.Core.Test/TestBase.cs deleted file mode 100644 index f54a0af..0000000 --- a/test/NetworkTables.Core.Test/TestBase.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - public class TestBase - { - public static void DeleteAllWithPersistent() - { - foreach (var entryInfo in NtCore.GetEntryInfo("", 0)) - { - NtCore.DeleteEntry(entryInfo.Name); - } - } - - public static bool s_started = false; - - [TestFixtureSetUp] - public void ClassSetUp() - { - if (!s_started) - { - Console.WriteLine(IntPtr.Size != sizeof(int) ? "Tests running in 64 Bit mode" : "Tests running in 32 Bit mode."); - NetworkTable.SetIPAddress("127.0.0.1"); - NetworkTable.SetPort(8912); - NetworkTable.SetServerMode(); - NetworkTable.Initialize(); - s_started = true; - } - } - } -} diff --git a/test/NetworkTables.Core.Test/TestInfoStructures.cs b/test/NetworkTables.Core.Test/TestInfoStructures.cs deleted file mode 100644 index 25dc97e..0000000 --- a/test/NetworkTables.Core.Test/TestInfoStructures.cs +++ /dev/null @@ -1,41 +0,0 @@ -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestInfoStructures - { - [Test] - public void TestConnectionInfo() - { - string remoteId = "remote"; - string remoteIp = "remoteIp"; - int remotePort = 1234; - long lastUpdate = 50; - int protocolVersion = 3; - ConnectionInfo info = new ConnectionInfo(remoteId, remoteIp, remotePort, lastUpdate, protocolVersion); - - Assert.That(info.RemoteId, Is.EqualTo(remoteId)); - Assert.That(info.RemoteIp, Is.EqualTo(remoteIp)); - Assert.That(info.RemotePort, Is.EqualTo(remotePort)); - Assert.That(info.LastUpdate, Is.EqualTo(lastUpdate)); - Assert.That(info.ProtocolVersion, Is.EqualTo(protocolVersion)); - } - - [Test] - public void TestEntryInfo() - { - string name = "TestEntryInfo"; - NtType type = NtType.Boolean; - EntryFlags flags = EntryFlags.Persistent; - long lastChange = 55; - - EntryInfo info = new EntryInfo(name, type, flags, lastChange); - - Assert.That(info.Name, Is.EqualTo(name)); - Assert.That(info.Type, Is.EqualTo(type)); - Assert.That(info.Flags, Is.EqualTo(flags)); - Assert.That(info.LastChange, Is.EqualTo(lastChange)); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestLeb128.cs b/test/NetworkTables.Core.Test/TestLeb128.cs deleted file mode 100644 index 56976fc..0000000 --- a/test/NetworkTables.Core.Test/TestLeb128.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System.Collections.Generic; -using NetworkTables.Wire; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestLeb128 - { - [Test] - public void TestLeb128Write() - { - ExpectLeb128Eq(0, 0, 0x00); - ExpectLeb128Eq(1, 0, 0x01); - ExpectLeb128Eq(63, 0, 0x3f); - ExpectLeb128Eq(64, 0, 0x40); - ExpectLeb128Eq(0x7f, 0, 0x7f); - ExpectLeb128Eq(0x80, 0, 0x80, 0x01); - ExpectLeb128Eq(0x81, 0, 0x81, 0x01); - ExpectLeb128Eq(0x90, 0, 0x90, 0x01); - ExpectLeb128Eq(0xff, 0, 0xff, 0x01); - ExpectLeb128Eq(0x100, 0, 0x80, 0x02); - ExpectLeb128Eq(0x101, 0, 0x81, 0x02); - } - - public void ExpectLeb128Eq(ulong value, ulong pad, params byte[] expected) - { - List buf = new List(32); - int size = Leb128.WriteUleb128(buf, value); - Assert.That(size, Is.EqualTo(buf.Count)); - Assert.That(expected, Is.EquivalentTo(buf)); - } - - [Test] - public void TestLeb128Read() - { - ExpectReadLeb128Eq(0, 0x00); - ExpectReadLeb128Eq(1, 0x01); - ExpectReadLeb128Eq(63, 0x3f); - ExpectReadLeb128Eq(64, 0x40); - ExpectReadLeb128Eq(0x7f, 0x7f); - ExpectReadLeb128Eq(0x80, 0x80, 0x01); - ExpectReadLeb128Eq(0x81, 0x81, 0x01); - ExpectReadLeb128Eq(0x90, 0x90, 0x01); - ExpectReadLeb128Eq(0xff, 0xff, 0x01); - ExpectReadLeb128Eq(0x100, 0x80, 0x02); - ExpectReadLeb128Eq(0x101, 0x81, 0x02); - ExpectReadLeb128Eq(8320, 0x80, 0xc1, 0x80, 0x80, 0x10); - } - - public void ExpectReadLeb128Eq(ulong expected, params byte[] value) - { - do - { - int count = 0; - ulong val = 0; - int size = Leb128.ReadUleb128(value, ref count, out val); - Assert.That(size, Is.EqualTo(value.Length)); - Assert.That(val, Is.EqualTo(expected)); - } while (false); - } - - [Test] - public void TestLeb128Size() - { - Assert.That(Leb128.SizeUleb128(0), Is.EqualTo(1)); - - Assert.That(Leb128.SizeUleb128(0x1UL), Is.EqualTo(1)); - Assert.That(Leb128.SizeUleb128(0x40UL), Is.EqualTo(1)); - Assert.That(Leb128.SizeUleb128(0x7fUL), Is.EqualTo(1)); - - Assert.That(Leb128.SizeUleb128(0x80UL), Is.EqualTo(2)); - Assert.That(Leb128.SizeUleb128(0x2000UL), Is.EqualTo(2)); - Assert.That(Leb128.SizeUleb128(0x3fffUL), Is.EqualTo(2)); - - Assert.That(Leb128.SizeUleb128(0x4000UL), Is.EqualTo(3)); - Assert.That(Leb128.SizeUleb128(0x100000UL), Is.EqualTo(3)); - Assert.That(Leb128.SizeUleb128(0x1fffffUL), Is.EqualTo(3)); - - Assert.That(Leb128.SizeUleb128(0x200000UL), Is.EqualTo(4)); - Assert.That(Leb128.SizeUleb128(0x8000000UL), Is.EqualTo(4)); - Assert.That(Leb128.SizeUleb128(0xfffffffUL), Is.EqualTo(4)); - - Assert.That(Leb128.SizeUleb128(0x10000000UL), Is.EqualTo(5)); - Assert.That(Leb128.SizeUleb128(0x40000000UL), Is.EqualTo(5)); - Assert.That(Leb128.SizeUleb128(0x7fffffffUL), Is.EqualTo(5)); - - Assert.That(Leb128.SizeUleb128(uint.MaxValue), Is.EqualTo(5)); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeForceSet.cs b/test/NetworkTables.Core.Test/TestNativeForceSet.cs deleted file mode 100644 index 6093c91..0000000 --- a/test/NetworkTables.Core.Test/TestNativeForceSet.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System.Collections.Generic; -using NetworkTables.Core.Native; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeForceSet : TestBase - { - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - } - - [Test] - public void TestForceSetString() - { - string key = "MyKey"; - - double setVal1 = 5.58; - - CoreMethods.SetEntryDouble(key, setVal1); - - double retVal1 = CoreMethods.GetEntryDouble(key); - Assert.That(retVal1, Is.EqualTo(setVal1)); - - string setVal = "SecondSet"; - - CoreMethods.SetEntryString(key, setVal, true); - - string retVal = CoreMethods.GetEntryString(key); - Assert.That(retVal, Is.EqualTo(setVal)); - } - - [Test] - public void TestForceSetDouble() - { - string key = "MyKey"; - - string setVal1 = "FirstSet"; - - CoreMethods.SetEntryString(key, setVal1); - - string retVal1 = CoreMethods.GetEntryString(key); - Assert.That(retVal1, Is.EqualTo(setVal1)); - - double setVal = 6.32121; - - CoreMethods.SetEntryDouble(key, setVal, true); - - double retVal = CoreMethods.GetEntryDouble(key); - Assert.That(retVal, Is.EqualTo(setVal)); - } - - [Test] - public void TestForceSetBoolean() - { - string key = "MyKey"; - - double setVal1 = 5.58; - - CoreMethods.SetEntryDouble(key, setVal1); - - double retVal1 = CoreMethods.GetEntryDouble(key); - Assert.That(retVal1, Is.EqualTo(setVal1)); - - bool setVal = false; - - CoreMethods.SetEntryBoolean(key, setVal, true); - - bool retVal = CoreMethods.GetEntryBoolean(key); - Assert.That(retVal, Is.EqualTo(setVal)); - } - - [Test] - public void TestForceRawSet() - { - string key = "MyKey"; - - double setVal1 = 5.58; - - CoreMethods.SetEntryDouble(key, setVal1); - - double retVal1 = CoreMethods.GetEntryDouble(key); - Assert.That(retVal1, Is.EqualTo(setVal1)); - - - byte[] secondWrite = { - 85, 234, 211, 36, 0, 0, 45 - }; - CoreMethods.SetEntryRaw(key, secondWrite, true); - - IList retVal = CoreMethods.GetEntryRaw(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - - [Test] - public void TestForceBooleanArraySet() - { - string key = "MyKey"; - - double setVal1 = 5.58; - - CoreMethods.SetEntryDouble(key, setVal1); - - double retVal1 = CoreMethods.GetEntryDouble(key); - Assert.That(retVal1, Is.EqualTo(setVal1)); - - - bool[] secondWrite = { - false, true, false, false, true, true, false - }; - CoreMethods.SetEntryBooleanArray(key, secondWrite, true); - - IList retVal = CoreMethods.GetEntryBooleanArray(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - - [Test] - public void TestForceDoubleArraySet() - { - string key = "MyKey"; - - double setVal1 = 5.58; - - CoreMethods.SetEntryDouble(key, setVal1); - - double retVal1 = CoreMethods.GetEntryDouble(key); - Assert.That(retVal1, Is.EqualTo(setVal1)); - - - double[] secondWrite = { - 85, 234, 211, 36, 0, 0, 45 - }; - CoreMethods.SetEntryDoubleArray(key, secondWrite, true); - - IList retVal = CoreMethods.GetEntryDoubleArray(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - - [Test] - public void TestForceStringArraySet() - { - string key = "MyKey"; - - double setVal1 = 5.58; - - CoreMethods.SetEntryDouble(key, setVal1); - - double retVal1 = CoreMethods.GetEntryDouble(key); - Assert.That(retVal1, Is.EqualTo(setVal1)); - - - string[] secondWrite = { - "85", "234", "211", "36", "0", "0", "45" - }; - CoreMethods.SetEntryStringArray(key, secondWrite, true); - - IList retVal = CoreMethods.GetEntryStringArray(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeGettersDefaultParameter.cs b/test/NetworkTables.Core.Test/TestNativeGettersDefaultParameter.cs deleted file mode 100644 index bdf6556..0000000 --- a/test/NetworkTables.Core.Test/TestNativeGettersDefaultParameter.cs +++ /dev/null @@ -1,257 +0,0 @@ -using System.Collections.Generic; -using NetworkTables.Core.Native; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeGettersDefaultParameter : TestBase - { - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - } - - [Test] - public void TestGetStringNonExistant() - { - string key = "mykey"; - string testVal = "Hello Test"; - Assert.That(CoreMethods.GetEntryString(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetBooleanNonExistant() - { - string key = "mykey"; - bool testVal = true; - Assert.That(CoreMethods.GetEntryBoolean(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetDoubleNonExistant() - { - string key = "mykey"; - double testVal = 5.86; - Assert.That(CoreMethods.GetEntryDouble(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetRawNonExistant() - { - string key = "mykey"; - byte[] testVal = { 56, 88, 92, 0, 0, 1 }; - Assert.That(CoreMethods.GetEntryRaw(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetDoubleArrayNonExistant() - { - string key = "mykey"; - double[] testVal = { 3.58, 6.825, 454.54 }; - Assert.That(CoreMethods.GetEntryDoubleArray(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetStringArrayNonExistant() - { - string key = "mykey"; - string[] testVal = { "write1", "write2", "write3" }; - Assert.That(CoreMethods.GetEntryStringArray(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetBooleanArrayNonExistant() - { - string key = "mykey"; - bool[] testVal = { true, false, true }; - Assert.That(CoreMethods.GetEntryBooleanArray(key, testVal), Is.EqualTo(testVal)); - } - - - - [Test] - public void TestGetStringWrongType() - { - string key = "mykey"; - string testVal = "Hello Test"; - CoreMethods.SetEntryBoolean(key, true); - - Assert.That(CoreMethods.GetEntryString(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetBooleanWrongType() - { - string key = "mykey"; - bool testVal = true; - CoreMethods.SetEntryDouble(key, 5.86); - - Assert.That(CoreMethods.GetEntryBoolean(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetDoubleWrongType() - { - string key = "mykey"; - double testVal = 5.86; - CoreMethods.SetEntryBoolean(key, true); - - Assert.That(CoreMethods.GetEntryDouble(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetRawWrongType() - { - string key = "mykey"; - byte[] testVal = { 56, 88, 92, 0, 0, 1 }; - CoreMethods.SetEntryBoolean(key, true); - - Assert.That(CoreMethods.GetEntryRaw(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetDoubleArrayWrongType() - { - string key = "mykey"; - double[] testVal = { 3.58, 6.825, 454.54 }; - CoreMethods.SetEntryBoolean(key, true); - - Assert.That(CoreMethods.GetEntryDoubleArray(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetStringArrayWrongType() - { - string key = "mykey"; - string[] testVal = { "write1", "write2", "write3" }; - CoreMethods.SetEntryBoolean(key, true); - - Assert.That(CoreMethods.GetEntryStringArray(key, testVal), Is.EqualTo(testVal)); - } - - [Test] - public void TestGetBooleanArrayWrongType() - { - string key = "mykey"; - bool[] testVal = { true, false, true }; - CoreMethods.SetEntryBoolean(key, true); - - Assert.That(CoreMethods.GetEntryBooleanArray(key, testVal), Is.EqualTo(testVal)); - } - - - - - [Test] - public void TestGetStringValid() - { - string key = "mykey"; - string testVal = "Hello Test"; - string actualVal = "Im Valid"; - CoreMethods.SetEntryString(key, actualVal); - - Assert.That(CoreMethods.GetEntryString(key, testVal), Is.EqualTo(actualVal)); - } - - [Test] - public void TestGetBooleanValid() - { - string key = "mykey"; - bool testVal = true; - bool actualVal = false; - CoreMethods.SetEntryBoolean(key, actualVal); - - Assert.That(CoreMethods.GetEntryBoolean(key, testVal), Is.EqualTo(actualVal)); - } - - [Test] - public void TestGetDoubleValid() - { - string key = "mykey"; - double testVal = 5.86; - double actualVal = 1213.323; - CoreMethods.SetEntryDouble(key, actualVal); - - Assert.That(CoreMethods.GetEntryDouble(key, testVal), Is.EqualTo(actualVal)); - } - - [Test] - public void TestGetRawValid() - { - string key = "mykey"; - byte[] testVal = { 56, 88, 92, 0, 0, 1 }; - - byte[] actualVal = { 42, 28, 142, 0, 22, 0, 132 }; - CoreMethods.SetEntryRaw(key, actualVal); - - IList retVal = CoreMethods.GetEntryRaw(key, testVal); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for(int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - - [Test] - public void TestGetDoubleArrayValid() - { - string key = "mykey"; - double[] testVal = { 3.58, 6.825, 454.54 }; - - double[] actualVal = { 3.54538, 43536.825, 34534454.34554, 3423413.23432 }; - CoreMethods.SetEntryDoubleArray(key, actualVal); - - IList retVal = CoreMethods.GetEntryDoubleArray(key, testVal); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for (int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - - [Test] - public void TestGetStringArrayValid() - { - string key = "mykey"; - string[] testVal = { "write1", "write2", "write3" }; - - string[] actualVal = { "writeas1", "wriasdte2", "writasde3", "adsadsd4" }; - CoreMethods.SetEntryStringArray(key, actualVal); - - IList retVal = CoreMethods.GetEntryStringArray(key, testVal); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for (int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - - [Test] - public void TestGetBooleanArrayValid() - { - string key = "mykey"; - bool[] testVal = { true, false, true }; - - bool[] actualVal = { false, false, true, true, false }; - CoreMethods.SetEntryBooleanArray(key, actualVal); - - IList retVal = CoreMethods.GetEntryBooleanArray(key, testVal); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for (int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeGettersNoDefaultParameter.cs b/test/NetworkTables.Core.Test/TestNativeGettersNoDefaultParameter.cs deleted file mode 100644 index 1cc5755..0000000 --- a/test/NetworkTables.Core.Test/TestNativeGettersNoDefaultParameter.cs +++ /dev/null @@ -1,236 +0,0 @@ -using System.Collections.Generic; -using NetworkTables.Core.Native; -using NetworkTables.Exceptions; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeGettersNoDefaultParameter : TestBase - { - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - } - - [Test] - public void TestGetStringNonExistant() - { - string key = "mykey"; - Assert.Throws(() => CoreMethods.GetEntryString(key)); - } - - [Test] - public void TestGetBooleanNonExistant() - { - string key = "mykey"; - Assert.Throws(() =>CoreMethods.GetEntryBoolean(key)); - } - - [Test] - public void TestGetDoubleNonExistant() - { - string key = "mykey"; - Assert.Throws(() =>CoreMethods.GetEntryDouble(key)); - } - - [Test] - public void TestGetRawNonExistant() - { - string key = "mykey"; - Assert.Throws(() =>CoreMethods.GetEntryRaw(key)); - } - - [Test] - public void TestGetDoubleArrayNonExistant() - { - string key = "mykey"; - Assert.Throws(() =>CoreMethods.GetEntryDoubleArray(key)); - } - - [Test] - public void TestGetStringArrayNonExistant() - { - string key = "mykey"; - Assert.Throws(() =>CoreMethods.GetEntryStringArray(key)); - } - - [Test] - public void TestGetBooleanArrayNonExistant() - { - string key = "mykey"; - Assert.Throws(() =>CoreMethods.GetEntryBooleanArray(key)); - } - - - - [Test] - public void TestGetStringWrongType() - { - string key = "mykey"; - CoreMethods.SetEntryBoolean(key, true); - - Assert.Throws(() =>CoreMethods.GetEntryString(key)); - } - - [Test] - public void TestGetBooleanWrongType() - { - string key = "mykey"; - CoreMethods.SetEntryDouble(key, 5.86); - - Assert.Throws(() =>CoreMethods.GetEntryBoolean(key)); - } - - [Test] - public void TestGetDoubleWrongType() - { - string key = "mykey"; - CoreMethods.SetEntryBoolean(key, true); - - Assert.Throws(() =>CoreMethods.GetEntryDouble(key)); - } - - [Test] - public void TestGetRawWrongType() - { - string key = "mykey"; - CoreMethods.SetEntryBoolean(key, true); - - Assert.Throws(() =>CoreMethods.GetEntryRaw(key)); - } - - [Test] - public void TestGetDoubleArrayWrongType() - { - string key = "mykey"; - CoreMethods.SetEntryBoolean(key, true); - - Assert.Throws(() =>CoreMethods.GetEntryDoubleArray(key)); - } - - [Test] - public void TestGetStringArrayWrongType() - { - string key = "mykey"; - CoreMethods.SetEntryBoolean(key, true); - - Assert.Throws(() =>CoreMethods.GetEntryStringArray(key)); - } - - [Test] - public void TestGetBooleanArrayWrongType() - { - string key = "mykey"; - CoreMethods.SetEntryBoolean(key, true); - - Assert.Throws(() => CoreMethods.GetEntryBooleanArray(key)); - } - - - - - [Test] - public void TestGetStringValid() - { - string key = "mykey"; - string actualVal = "Im Valid"; - CoreMethods.SetEntryString(key, actualVal); - - Assert.That(CoreMethods.GetEntryString(key), Is.EqualTo(actualVal)); - } - - [Test] - public void TestGetBooleanValid() - { - string key = "mykey"; - bool actualVal = false; - CoreMethods.SetEntryBoolean(key, actualVal); - - Assert.That(CoreMethods.GetEntryBoolean(key), Is.EqualTo(actualVal)); - } - - [Test] - public void TestGetDoubleValid() - { - string key = "mykey"; - double actualVal = 1213.323; - CoreMethods.SetEntryDouble(key, actualVal); - - Assert.That(CoreMethods.GetEntryDouble(key), Is.EqualTo(actualVal)); - } - - [Test] - public void TestGetRawValid() - { - string key = "mykey"; - - byte[] actualVal = { 42, 28, 142, 0, 22, 0, 132 }; - CoreMethods.SetEntryRaw(key, actualVal); - - IList retVal = CoreMethods.GetEntryRaw(key); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for (int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - - [Test] - public void TestGetDoubleArrayValid() - { - string key = "mykey"; - - double[] actualVal = { 3.54538, 43536.825, 34534454.34554, 3423413.23432 }; - CoreMethods.SetEntryDoubleArray(key, actualVal); - - IList retVal = CoreMethods.GetEntryDoubleArray(key); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for (int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - - [Test] - public void TestGetStringArrayValid() - { - string key = "mykey"; - - string[] actualVal = { "writeas1", "wriasdte2", "writasde3", "adsadsd4" }; - CoreMethods.SetEntryStringArray(key, actualVal); - - IList retVal = CoreMethods.GetEntryStringArray(key); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for (int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - - [Test] - public void TestGetBooleanArrayValid() - { - string key = "mykey"; - - bool[] actualVal = { false, false, true, true, false }; - CoreMethods.SetEntryBooleanArray(key, actualVal); - - IList retVal = CoreMethods.GetEntryBooleanArray(key); - - Assert.That(retVal.Count, Is.EqualTo(actualVal.Length)); - - for (int i = 0; i < actualVal.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(actualVal[i])); - } - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeInterface.cs b/test/NetworkTables.Core.Test/TestNativeInterface.cs deleted file mode 100644 index 731c6f4..0000000 --- a/test/NetworkTables.Core.Test/TestNativeInterface.cs +++ /dev/null @@ -1,303 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Threading; -using NetworkTables.Core.Native; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeInterface : TestBase - { - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - } - - [Test] - public void TestGetEntries() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - CoreMethods.SetEntryDouble(key2, toWrite2); - CoreMethods.SetEntryFlags(key2, EntryFlags.Persistent); - - string key3 = "testKey3"; - bool toWrite3 = true; - CoreMethods.SetEntryBoolean(key3, toWrite3); - - var entries = CoreMethods.GetEntryInfo("", 0); - - Assert.That(3, Is.EqualTo(entries.Count)); - - Assert.That(entries[0].Name, Is.EqualTo(key1)); - Assert.That(entries[0].Type, Is.EqualTo(NtType.String)); - Assert.That(entries[0].Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(entries[0].LastChange, Is.GreaterThan(0)); - Assert.That(entries[1].Name, Is.EqualTo(key2)); - Assert.That(entries[1].Type, Is.EqualTo(NtType.Double)); - Assert.That(entries[1].Flags, Is.EqualTo(EntryFlags.Persistent)); - Assert.That(entries[1].LastChange, Is.GreaterThan(0)); - Assert.That(entries[2].Name, Is.EqualTo(key3)); - Assert.That(entries[2].Type, Is.EqualTo(NtType.Boolean)); - Assert.That(entries[2].Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(entries[2].LastChange, Is.GreaterThan(0)); - } - - [Test] - public void TestGetEntriesOnlyString() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - CoreMethods.SetEntryDouble(key2, toWrite2); - - string key3 = "testKey3"; - bool toWrite3 = true; - CoreMethods.SetEntryBoolean(key3, toWrite3); - - Thread.Sleep(20); - - var entries = CoreMethods.GetEntryInfo("", NtType.String); - - Assert.That(1, Is.EqualTo(entries.Count)); - - Assert.That(entries[0].Name, Is.EqualTo(key1)); - Assert.That(entries[0].Type, Is.EqualTo(NtType.String)); - Assert.That(entries[0].Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(entries[0].LastChange, Is.GreaterThan(0)); - } - - [Test] - public void TestGetConnections() - { - var connection = CoreMethods.GetConnections(); - Assert.That(connection.Count, Is.EqualTo(0)); - } - - [Test] - public void TestSavePersistent() - { - string key1 = "key1"; - string toWrite1 = "val1"; - CoreMethods.SetEntryString(key1, toWrite1); - CoreMethods.SetEntryFlags(key1, EntryFlags.Persistent); - - string key2 = "key2"; - CoreMethods.SetEntryBoolean(key2, true); - CoreMethods.SetEntryFlags(key2, EntryFlags.Persistent); - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - CoreMethods.SavePersistent(fileName); - - string[] lines = File.ReadAllLines(fileName); - - Assert.That(lines.Length, Is.GreaterThanOrEqualTo(3)); - Assert.That(lines[0], Contains.Substring("[NetworkTables Storage 3.0]")); - Assert.That(lines[1], Contains.Substring($"string \"{key1}\"=\"{toWrite1}\"")); - Assert.That(lines[2], Contains.Substring($"boolean \"{key2}\"=true")); - } - - [Test] - public void TestLoadPersistent() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"{key1}\"=\"{val1}\"", - $"boolean \"{key2}\"=true", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NtCore.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(0)); - - var entries = CoreMethods.GetEntryInfo("", 0); - - Assert.That(entries.Count, Is.EqualTo(2)); - - Assert.That(CoreMethods.GetEntryString(key1, ""), Is.EqualTo(val1)); - Assert.That(CoreMethods.GetEntryBoolean(key2, false), Is.EqualTo(true)); - } - - [Test] - public void TestPersistentLoadError() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"{key1}\"=\"{val1}\"", - $"boolean \"{key2}\"=invalid", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NtCore.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(1)); - Assert.That(errors[0], Contains.Substring("3: unrecognized boolean value, not 'true' or 'false'")); - } - - [Test] - public void TestDeleteEntry() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - CoreMethods.SetEntryDouble(key2, toWrite2); - - Assert.That(CoreMethods.GetEntryInfo("", 0).Count, Is.EqualTo(2)); - - CoreMethods.DeleteEntry(key1); - - Assert.That(CoreMethods.GetEntryInfo("", 0).Count, Is.EqualTo(1)); - - const string err = "error"; - Assert.That(CoreMethods.GetEntryString(key1, err), Is.EqualTo(err)); - } - - [Test] - public void TestDeleteAllEntries() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - CoreMethods.SetEntryDouble(key2, toWrite2); - - Assert.That(CoreMethods.GetEntryInfo("", 0).Count, Is.EqualTo(2)); - - DeleteAllWithPersistent(); - - Assert.That(CoreMethods.GetEntryInfo("", 0).Count, Is.EqualTo(0)); - - const string err = "error"; - Assert.That(CoreMethods.GetEntryString(key1, err), Is.EqualTo(err)); - Assert.That(CoreMethods.GetEntryString(key2, err), Is.EqualTo(err)); - } - - [Test] - public void TestGetTypeSuccess() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - Assert.That(CoreMethods.GetType(key1), Is.EqualTo(NtType.String)); - } - - [Test] - public void TestGetTypeNonExistentKey() - { - Assert.That(CoreMethods.GetType("testKey"), Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void TestContainsKeySuccess() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - Assert.That(CoreMethods.ContainsEntry(key1)); - } - - [Test] - public void TestContainsKeyNonExistentKey() - { - Assert.That(!CoreMethods.ContainsEntry("testKey")); - } - - [Test] - public void TestGetEntryFlags() - { - string key = "testKey"; - CoreMethods.SetEntryString(key, "value"); - - EntryFlags flags = CoreMethods.GetEntryFlags(key); - - Assert.That(flags, Is.EqualTo(EntryFlags.None)); - - CoreMethods.SetEntryFlags(key, EntryFlags.Persistent); - - flags = CoreMethods.GetEntryFlags(key); - - Assert.That(flags, Is.EqualTo(EntryFlags.Persistent)); - } - - [Test] - public void TestSetNetworkIdentity() - { - CoreMethods.SetNetworkIdentity("UnitTests"); - - Assert.Pass(); - } - - [Test] - public void TestFlush() - { - CoreMethods.Flush(); - - Assert.Pass(); - } - - [Test] - public void TestNow() - { - Assert.That(CoreMethods.Now(), Is.GreaterThan(0)); - } - - [Test] - public void TestSetUpdateRate() - { - CoreMethods.SetUpdateRate(100); - - Assert.Pass(); - } - - - - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeListeners.cs b/test/NetworkTables.Core.Test/TestNativeListeners.cs deleted file mode 100644 index f47af53..0000000 --- a/test/NetworkTables.Core.Test/TestNativeListeners.cs +++ /dev/null @@ -1,366 +0,0 @@ -using System.Threading; -using NetworkTables.Core.Native; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeListeners : TestBase - { - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - } - - [TestFixtureTearDown] - public void FixtureTearDown() - { - CoreMethods.StopNotifier(); - } - - [Test] - public void TestAddEntryListener() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyLocal; - - int listener = CoreMethods.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - string toWrite2 = "NewNumber"; - CoreMethods.SetEntryString(key1, toWrite2); - - Thread.Sleep(20); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - Assert.That(recievedValue.IsString()); - string retValue = recievedValue.GetString(); - Assert.That(retValue, Is.EqualTo(toWrite2)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyLocal)); - - CoreMethods.RemoveEntryListener(listener); - } - - [Test] - public void TestAddEntryListenerImmediateNotify() - { - string key1 = "testKey"; - string toWrite1 = "written"; - CoreMethods.SetEntryString(key1, toWrite1); - - int count = 0; - string recievedKey = ""; - Value receivedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = CoreMethods.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - receivedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(20); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(receivedValue, Is.Not.Null); - - Assert.That(receivedValue.IsString()); - string retValue = receivedValue.GetString(); - Assert.That(retValue, Is.Not.Null); - Assert.That(retValue, Is.EqualTo(toWrite1)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - CoreMethods.RemoveEntryListener(listener); - } - - [TestCase(true)] - [TestCase(3.5)] - [TestCase("MyString")] - public void TestAddEntryListenerDefaultTypes(object val) - { - string key1 = "testKey"; - - if (val is double) CoreMethods.SetEntryDouble(key1, (double)val); - else if (val is bool) - CoreMethods.SetEntryBoolean(key1, (bool)val); - else if (val is string) CoreMethods.SetEntryString(key1, (string)val); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = CoreMethods.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(20); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - if (val is double) - { - Assert.That(recievedValue.IsDouble()); - double retValue = recievedValue.GetDouble(); - Assert.That(retValue, Is.EqualTo((double)val)); - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - } - else if (val is bool) - { - Assert.That(recievedValue.IsBoolean()); - bool retValue = recievedValue.GetBoolean(); - Assert.That(retValue, Is.EqualTo((bool)val)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - } - else if (val is string) - { - Assert.That(recievedValue.IsString()); - string retValue = recievedValue.GetString(); - Assert.That(retValue, Is.EqualTo((string)val)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - } - else - { - CoreMethods.RemoveEntryListener(listener); - Assert.Fail("Unknown type"); - return; - } - - CoreMethods.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerStringArray() - { - string key1 = "testKey"; - string[] toWrite1 = { "write1", "write2", "write3"}; - CoreMethods.SetEntryStringArray(key1, toWrite1); - - int count = 0; - string recievedKey = ""; - Value receivedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = CoreMethods.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - receivedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(receivedValue, Is.Not.Null); - - Assert.That(receivedValue.IsStringArray()); - string[] retValue = receivedValue.GetStringArray(); - Assert.That(retValue, Is.Not.Null); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - //Assert.That(retValue, Is.EqualTo(toWrite1)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - CoreMethods.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerRaw() - { - string key1 = "testKey"; - byte[] toWrite1 = { 56, 88, 92, 0, 0, 1 }; - CoreMethods.SetEntryRaw(key1, toWrite1); - - int count = 0; - string recievedKey = ""; - Value receivedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = CoreMethods.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - receivedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(receivedValue, Is.Not.Null); - - Assert.That(receivedValue.IsRaw()); - byte[] retValue = receivedValue.GetRaw(); - Assert.That(retValue, Is.Not.Null); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - CoreMethods.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerDoubleArray() - { - string key1 = "testKey"; - double[] toWrite1 = { 3.58, 6.825, 454.54}; - CoreMethods.SetEntryDoubleArray(key1, toWrite1); - - int count = 0; - string recievedKey = ""; - Value receivedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = CoreMethods.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - receivedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(receivedValue, Is.Not.Null); - - Assert.That(receivedValue.IsDoubleArray()); - double[] retValue = receivedValue.GetDoubleArray(); - Assert.That(retValue, Is.Not.Null); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - //Assert.That(retValue, Is.EqualTo(toWrite1)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - CoreMethods.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerBooleanArray() - { - string key1 = "testKey"; - bool[] toWrite1 = { true, true, true }; - CoreMethods.SetEntryBooleanArray(key1, toWrite1); - - int count = 0; - string recievedKey = ""; - Value receivedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = CoreMethods.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - receivedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(receivedValue, Is.Not.Null); - - Assert.That(receivedValue.IsBooleanArray()); - bool[] retValue = receivedValue.GetBooleanArray(); - Assert.That(retValue, Is.Not.Null); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - //Assert.That(retValue, Is.EqualTo(toWrite1)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - CoreMethods.RemoveEntryListener(listener); - } - - [Test] - public void TestAddRemoveConnectionListener() - { - ConnectionListenerCallback callback = (uid, connected, conn) => - { - - }; - - int id = CoreMethods.AddConnectionListener(callback, true); - - Assert.That(id, Is.Not.EqualTo(0)); - - CoreMethods.RemoveConnectionListener(id); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeMultipleSets.cs b/test/NetworkTables.Core.Test/TestNativeMultipleSets.cs deleted file mode 100644 index 5488d1c..0000000 --- a/test/NetworkTables.Core.Test/TestNativeMultipleSets.cs +++ /dev/null @@ -1,204 +0,0 @@ -using System.Collections.Generic; -using NetworkTables.Core.Native; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeMultipleSets : TestBase - { - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - } - - [Test] - public void TestMultipleSetString() - { - string key = "MyKey"; - - string setVal = "FirstSet"; - - CoreMethods.SetEntryString(key, setVal); - - string retVal = CoreMethods.GetEntryString(key); - Assert.That(retVal, Is.EqualTo(setVal)); - - setVal = "SecondSet"; - - CoreMethods.SetEntryString(key, setVal); - - retVal = CoreMethods.GetEntryString(key); - Assert.That(retVal, Is.EqualTo(setVal)); - } - - [Test] - public void TestMultipleSetDouble() - { - string key = "MyKey"; - - double setVal = 3.58; - - CoreMethods.SetEntryDouble(key, setVal); - - double retVal = CoreMethods.GetEntryDouble(key); - Assert.That(retVal, Is.EqualTo(setVal)); - - setVal = 6.32121; - - CoreMethods.SetEntryDouble(key, setVal); - - retVal = CoreMethods.GetEntryDouble(key); - Assert.That(retVal, Is.EqualTo(setVal)); - } - - [Test] - public void TestMultipleSetBoolean() - { - string key = "MyKey"; - - bool setVal = true; - - CoreMethods.SetEntryBoolean(key, setVal); - - bool retVal = CoreMethods.GetEntryBoolean(key); - Assert.That(retVal, Is.EqualTo(setVal)); - - setVal = false; - - CoreMethods.SetEntryBoolean(key, setVal); - - retVal = CoreMethods.GetEntryBoolean(key); - Assert.That(retVal, Is.EqualTo(setVal)); - } - - [Test] - public void TestMultipleRawSet() - { - string key = "MyKey"; - - byte[] firstWrite = { - 32, 86, 45, 156 - }; - CoreMethods.SetEntryRaw(key, firstWrite); - - - IList retVal = CoreMethods.GetEntryRaw(key); - - for(int i = 0; i < firstWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(firstWrite[i])); - } - - - byte[] secondWrite = { - 85, 234, 211, 36, 0, 0, 45 - }; - CoreMethods.SetEntryRaw(key, secondWrite); - - retVal = CoreMethods.GetEntryRaw(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - - [Test] - public void TestMultipleBooleanArraySet() - { - string key = "MyKey"; - - bool[] firstWrite = { - true, false, true, true - }; - CoreMethods.SetEntryBooleanArray(key, firstWrite); - - - IList retVal = CoreMethods.GetEntryBooleanArray(key); - - for (int i = 0; i < firstWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(firstWrite[i])); - } - - - bool[] secondWrite = { - false, true, false, false, true, true, false - }; - CoreMethods.SetEntryBooleanArray(key, secondWrite); - - retVal = CoreMethods.GetEntryBooleanArray(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - - [Test] - public void TestMultipleDoubleArraySet() - { - string key = "MyKey"; - - double[] firstWrite = { - 32, 86, 45, 156 - }; - CoreMethods.SetEntryDoubleArray(key, firstWrite); - - - IList retVal = CoreMethods.GetEntryDoubleArray(key); - - for (int i = 0; i < firstWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(firstWrite[i])); - } - - - double[] secondWrite = { - 85, 234, 211, 36, 0, 0, 45 - }; - CoreMethods.SetEntryDoubleArray(key, secondWrite); - - retVal = CoreMethods.GetEntryDoubleArray(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - - [Test] - public void TestMultipleStringArraySet() - { - string key = "MyKey"; - - string[] firstWrite = { - "32", "86", "45", "156" - }; - CoreMethods.SetEntryStringArray(key, firstWrite); - - - IList retVal = CoreMethods.GetEntryStringArray(key); - - for (int i = 0; i < firstWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(firstWrite[i])); - } - - - string[] secondWrite = { - "85", "234", "211", "36", "0", "0", "45" - }; - CoreMethods.SetEntryStringArray(key, secondWrite); - - retVal = CoreMethods.GetEntryStringArray(key); - - for (int i = 0; i < secondWrite.Length; i++) - { - Assert.That(retVal[i], Is.EqualTo(secondWrite[i])); - } - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeSetters.cs b/test/NetworkTables.Core.Test/TestNativeSetters.cs deleted file mode 100644 index 3de94d0..0000000 --- a/test/NetworkTables.Core.Test/TestNativeSetters.cs +++ /dev/null @@ -1,186 +0,0 @@ -using NetworkTables.Core.Native; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeSetters : TestBase - { - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - } - - [Test] - public void TestSetStringValid() - { - string key = "MyKey"; - - string setVal = "FirstSet"; - - Assert.That(CoreMethods.SetEntryString(key, setVal)); - } - - [Test] - public void TestSetDoubleValid() - { - string key = "MyKey"; - - double setVal = 3.58; - - Assert.That(CoreMethods.SetEntryDouble(key, setVal)); - } - - [Test] - public void TestSetBooleanValid() - { - string key = "MyKey"; - - bool setVal = true; - - Assert.That(CoreMethods.SetEntryBoolean(key, setVal)); - } - - [Test] - public void TestSetRawValid() - { - string key = "MyKey"; - - byte[] firstWrite = { - 32, 86, 45, 156 - }; - Assert.That(CoreMethods.SetEntryRaw(key, firstWrite)); - } - - [Test] - public void TestSetBooleanArrayValid() - { - string key = "MyKey"; - - bool[] firstWrite = { - true, false, true, true - }; - Assert.That(CoreMethods.SetEntryBooleanArray(key, firstWrite)); - } - - [Test] - public void TestSetDoubleArrayValid() - { - string key = "MyKey"; - - double[] firstWrite = { - 32, 86, 45, 156 - }; - Assert.That(CoreMethods.SetEntryDoubleArray(key, firstWrite)); - - } - - [Test] - public void TestSetStringArrayValid() - { - string key = "MyKey"; - - string[] firstWrite = { - "32", "86", "45", "156" - }; - Assert.That(CoreMethods.SetEntryStringArray(key, firstWrite)); - } - - - - - [Test] - public void TestStringSetInvalid() - { - string key = "MyKey"; - - string setVal = "FirstSet"; - - CoreMethods.SetEntryDouble(key, 3.33); - - setVal = "SecondSet"; - - Assert.That(!CoreMethods.SetEntryString(key, setVal)); - } - - [Test] - public void TestDoubleSetInvalid() - { - string key = "MyKey"; - - - CoreMethods.SetEntryBoolean(key, true); - - double setVal = 6.32121; - - Assert.That(!CoreMethods.SetEntryDouble(key, setVal)); - } - - [Test] - public void TestBooleanSetInvalid() - { - string key = "MyKey"; - - CoreMethods.SetEntryDouble(key, 3.33); - - bool setVal = false; - - Assert.That(!CoreMethods.SetEntryBoolean(key, setVal)); - } - - [Test] - public void TestRawSetInvalid() - { - string key = "MyKey"; - - CoreMethods.SetEntryDouble(key, 3.33); - - - byte[] secondWrite = { - 85, 234, 211, 36, 0, 0, 45 - }; - Assert.That(!CoreMethods.SetEntryRaw(key, secondWrite)); - } - - [Test] - public void TestBooleanArraySetInvalid() - { - string key = "MyKey"; - - CoreMethods.SetEntryDouble(key, 3.33); - bool[] secondWrite = { - false, true, false, false, true, true, false - }; - Assert.That(!CoreMethods.SetEntryBooleanArray(key, secondWrite)); - } - - [Test] - public void TestDoubleArraySetInvalid() - { - string key = "MyKey"; - - CoreMethods.SetEntryDouble(key, 3.33); - - - double[] secondWrite = { - 85, 234, 211, 36, 0, 0, 45 - }; - Assert.That(!CoreMethods.SetEntryDoubleArray(key, secondWrite)); - } - - [Test] - public void TestStringArraySetInvalid() - { - string key = "MyKey"; - - CoreMethods.SetEntryDouble(key, 3.33); - - - string[] secondWrite = { - "85", "234", "211", "36", "0", "0", "45" - }; - Assert.That(!CoreMethods.SetEntryStringArray(key, secondWrite)); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNativeStructs.cs b/test/NetworkTables.Core.Test/TestNativeStructs.cs deleted file mode 100644 index 990eabd..0000000 --- a/test/NetworkTables.Core.Test/TestNativeStructs.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using NetworkTables.Core.Native; -using NUnit.Framework; -using FRC; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNativeStructs : TestBase - { - [Test] - public void TestNtStringWriteCreateAndDispose() - { - DisposableNativeString write = new DisposableNativeString("TestString"); - write.Dispose(); - } - - [Test] - public void TestNtStringReadToString() - { - const string testStr = "TestString"; - using (DisposableNativeString write = new DisposableNativeString(testStr)) - { - NtStringRead read = new NtStringRead(write.Buffer, write.Length); - Assert.AreEqual(testStr, read.ToString()); - GC.KeepAlive(write); - } - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNetworkTableAPIListeners.cs b/test/NetworkTables.Core.Test/TestNetworkTableAPIListeners.cs deleted file mode 100644 index 99d1c87..0000000 --- a/test/NetworkTables.Core.Test/TestNetworkTableAPIListeners.cs +++ /dev/null @@ -1,479 +0,0 @@ -using System; -using System.Threading; -using NetworkTables.Tables; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - internal class MockTableListener : ITableListener - { - public ITable Source = null; - public string Key = null; - public Value Value = null; - public NotifyFlags Flags = 0; - - public void ValueChanged(ITable source, string key, Value value, NotifyFlags flags) - { - Source = source; - Key = key; - Value = value; - Flags = flags; - } - } - - internal class MockConnectionListener : IRemoteConnectionListener - { - public IRemote ConnectedRemote = null; - public IRemote DisconnectedRemote = null; - - public void Connected(IRemote remote, ConnectionInfo info) - { - ConnectedRemote = remote; - } - - public void Disconnected(IRemote remote, ConnectionInfo info) - { - DisconnectedRemote = remote; - } - } - - - - [TestFixture] - public class TestNetworkTableApiListeners : TestBase - { - private NetworkTable m_table; - - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - m_table = NetworkTable.GetTable("Table"); - } - - [Test] - public void TestAddTableListenerExListenerFlags() - { - MockTableListener listener = new MockTableListener(); - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(listener, f); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(key)); - Assert.That(listener.Value.IsString()); - Assert.That(listener.Value.GetString(), Is.EqualTo(value)); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - string key2 = "key2"; - string val2 = "value2"; - - m_table.PutString(key2, val2); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(key2)); - Assert.That(listener.Value.IsString()); - Assert.That(listener.Value.GetString(), Is.EqualTo(val2)); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerExKeyListenerFlags() - { - MockTableListener listener = new MockTableListener(); - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(key, listener, f); - - m_table.PutString("Key2", "Value2"); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(key)); - Assert.That(listener.Value.IsString()); - Assert.That(listener.Value.GetString(), Is.EqualTo(value)); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddSubTableListenerListenerLocalNotify() - { - MockTableListener listener = new MockTableListener(); - - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable("SubTable"); - - m_table.AddSubTableListener(listener, true); - - string key = "key"; - string value = "Value"; - - subTable.PutString(key, value); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(subTableName)); - Assert.That(listener.Value, Is.Null); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyLocal | NotifyFlags.NotifyNew)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerEntireTableImmediateNotify() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener(listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerEntireTable() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListenerImmediateNotify() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener("key", listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListener() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener("key", listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddSubTableListenerNotLocal() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddSubTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerExListenerFlagsDelegate() - { - ITable Source = null; - string Key = null; - Value Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, _f) => - { - Source = s; - Key = k; - Value = v; - Flags = _f; - }; - - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(listener, f); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(key)); - Assert.That(Value.IsString()); - Assert.That(Value.GetString(), Is.EqualTo(value)); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - string key2 = "key2"; - string val2 = "value2"; - - m_table.PutString(key2, val2); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(key2)); - Assert.That(Value.IsString()); - Assert.That(Value.GetString(), Is.EqualTo(val2)); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerExKeyListenerFlagsDelegate() - { - ITable Source = null; - string Key = null; - Value Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, _f) => - { - Source = s; - Key = k; - Value = v; - Flags = _f; - }; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(key, listener, f); - - m_table.PutString("Key2", "Value2"); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(key)); - Assert.That(Value.IsString()); - Assert.That(Value.GetString(), Is.EqualTo(value)); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddSubTableListenerListenerLocalNotifyDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable("SubTable"); - - m_table.AddSubTableListener(listener, true); - - string key = "key"; - string value = "Value"; - - subTable.PutString(key, value); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(subTableName)); - Assert.That(Value, Is.Null); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyLocal | NotifyFlags.NotifyNew)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerEntireTableImmediateNotifyDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener(listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerEntireTableDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListenerImmediateNotifyDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener("key", listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListenerDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener("key", listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddSubTableListenerNotLocalDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddSubTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - - [Test] - public void TestConnectionListener() - { - MockConnectionListener listener = new MockConnectionListener(); - - m_table.AddConnectionListener(listener, true); - - Thread.Sleep(20); - m_table.RemoveConnectionListener(listener); - - Assert.Pass("If we have gotten here without an exception we pass. Cannot test more without a remote."); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNetworkTableErrors.cs b/test/NetworkTables.Core.Test/TestNetworkTableErrors.cs deleted file mode 100644 index bc55fe3..0000000 --- a/test/NetworkTables.Core.Test/TestNetworkTableErrors.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using NetworkTables.Exceptions; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNetworkTableErrors : TestBase - { - private NetworkTable m_nt; - - [SetUp] - public void SetUp() - { - DeleteAllWithPersistent(); - m_nt = NetworkTable.GetTable(""); - } - - [Test] - public void TestBadPersistentFileRead() - { - Assert.Throws(() => - { - NetworkTable.LoadPersistent("invalid.txt"); - }); - } - - [Test] - public void TestPutEmptyName() - { - bool retVal = m_nt.PutNumber("emptyName", 3.14); - Assert.IsTrue(retVal); - } - - [Test] - public void TestPutNullName() - { - bool retVal = m_nt.PutNumber(null, 3.14); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullString() - { - Assert.Throws(() => - { - m_nt.PutString("nullString", null); - }, "Null string should not be allowed"); - - } - [Test] - public void TestPutEmptyString() - { - bool retVal = m_nt.PutString("emptyString", ""); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullStringArray() - { - Assert.Throws(() => - { - m_nt.PutStringArray("nullStringArray", null); - }, "Null array should not be allowed"); - } - [Test] - public void TestPutEmptyStringArray() - { - bool retVal = m_nt.PutStringArray("emptyStringArray", new string[0]); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullBooleanArray() - { - Assert.Throws(() => - { - m_nt.PutBooleanArray("nullBoolArray", null); - }, "Null array should not be allowed"); - } - [Test] - public void TestPutEmptyBooleanArray() - { - bool retVal = m_nt.PutBooleanArray("emptyBoolArray", new bool[0]); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullDoubleArray() - { - Assert.Throws(() => - { - m_nt.PutNumberArray("nullNumberArray", null); - }, "Null array should not be allowed"); - } - [Test] - public void TestPutEmptyDoubleArray() - { - bool retVal = m_nt.PutNumberArray("emptyNumberArray", new double[0]); - Assert.IsTrue(retVal); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNetworkTablesAPI.cs b/test/NetworkTables.Core.Test/TestNetworkTablesAPI.cs deleted file mode 100644 index 29fa782..0000000 --- a/test/NetworkTables.Core.Test/TestNetworkTablesAPI.cs +++ /dev/null @@ -1,959 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using NetworkTables.Exceptions; -using NetworkTables.Tables; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class TestNetworkTablesApi : TestBase - { - [TestFixtureSetUp] - public void FixtureSetup() - { - - } - - private NetworkTable m_table; - - [SetUp] - public void TestSetup() - { - DeleteAllWithPersistent(); - m_table = NetworkTable.GetTable("Table"); - } - - [Test] - public void TestToString() - { - Assert.That(m_table.ToString(), Is.EqualTo("NetworkTable: /Table")); - } - - [Test] - public void TestIsServer() - { - Assert.That(m_table.IsServer); - } - - [Test] - public void TestContainsKeyNo() - { - Assert.That(!m_table.ContainsKey("Key")); - } - - [Test] - public void TestContainsKeyYes() - { - string key = "key"; - m_table.PutString(key, "value"); - Assert.That(m_table.ContainsKey(key)); - } - - [Test] - public void TestContainsSubTableFalse() - { - Assert.That(!m_table.ContainsSubTable("SubTable")); - } - - [Test] - public void TestContainsSubTableTrue() - { - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable(subTableName); - subTable.PutBoolean("MyKey", true); - - Assert.That(m_table.ContainsSubTable(subTableName)); - } - - [Test] - public void TestGetKeysAll() - { - string key1 = "FirstKey"; - string key2 = "SecondKey"; - - m_table.PutString(key1, "String1"); - m_table.PutString(key2, "String2"); - - HashSet keys = m_table.GetKeys(); - - Assert.That(keys.Contains(key1)); - Assert.That(keys.Contains(key2)); - } - - [Test] - public void TestGetKeysOnlyPersistent() - { - string key1 = "FirstKey"; - string key2 = "SecondKey"; - - m_table.PutString(key1, "String1"); - m_table.PutNumber(key2, 3.586); - m_table.SetPersistent(key2); - - HashSet keys = m_table.GetKeys(NtType.Double); - - Assert.That(!keys.Contains(key1)); - Assert.That(keys.Contains(key2)); - } - - [Test] - public void TestGetSubTables() - { - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable(subTableName); - subTable.PutBoolean("MyKey", true); - - string subTableName2 = "SubTable2"; - - ITable subTable2 = m_table.GetSubTable(subTableName2); - subTable2.PutBoolean("MyKey2", true); - - HashSet subTables = m_table.GetSubTables(); - - Assert.That(subTables.Contains(subTableName)); - Assert.That(subTables.Contains(subTableName2)); - } - - [Test] - public void TestSetPersistent() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetPersistent(key2); - - Assert.That(m_table.IsPersistent(key2)); - } - - [Test] - public void TestClearPersistent() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetPersistent(key2); - - Assert.That(m_table.IsPersistent(key2)); - - m_table.ClearPersistent(key2); - - Assert.That(!m_table.IsPersistent(key2)); - } - - [Test] - public void TestSetFlags() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetFlags(key2, EntryFlags.Persistent); - - Assert.That(m_table.GetFlags(key2), Is.EqualTo(EntryFlags.Persistent)); - } - - [Test] - public void TestClearFlags() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetFlags(key2, EntryFlags.Persistent); - - Assert.That(m_table.GetFlags(key2), Is.EqualTo(EntryFlags.Persistent)); - - m_table.ClearFlags(key2, EntryFlags.Persistent); - - Assert.That(m_table.GetFlags(key2), Is.Not.EqualTo(EntryFlags.Persistent)); - } - - [Test] - public void TestDeleteKey() - { - string key = "MyKey"; - - m_table.PutString(key, "Value"); - - Assert.That(m_table.GetString(key), Is.EqualTo("Value")); - - m_table.Delete(key); - - Assert.Throws(() => m_table.GetString(key)); - } - - [Test] - public void TestDeleteAllEntries() - { - m_table.PutString("Test1", "val1"); - m_table.PutString("Test2", "val2"); - m_table.PutString("Test3", "val3"); - - Assert.That(m_table.GetKeys().Count, Is.EqualTo(3)); - - NetworkTable.GlobalDeleteAll(); - - Assert.That(m_table.GetKeys().Count, Is.EqualTo(0)); - } - - [Test] - public void TestSavePersistent() - { - string key1 = "key1"; - string toWrite1 = "val1"; - m_table.PutString(key1, toWrite1); - m_table.SetFlags(key1, EntryFlags.Persistent); - - string key2 = "key2"; - m_table.PutBoolean(key2, true); - m_table.SetFlags(key2, EntryFlags.Persistent); - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - NetworkTable.SavePersistent(fileName); - - string[] lines = File.ReadAllLines(fileName); - - Assert.That(lines.Length, Is.GreaterThanOrEqualTo(3)); - Assert.That(lines[0], Contains.Substring("[NetworkTables Storage 3.0]")); - Assert.That(lines[1], Contains.Substring($"string \"/Table/{key1}\"=\"{toWrite1}\"")); - Assert.That(lines[2], Contains.Substring($"boolean \"/Table/{key2}\"=true")); - } - - [Test] - public void TestLoadPersistent() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"/Table/{key1}\"=\"{val1}\"", - $"boolean \"/Table/{key2}\"=true", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NetworkTable.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(0)); - - HashSet entries = m_table.GetKeys(); - - Assert.That(entries.Count, Is.EqualTo(2)); - - Assert.That(m_table.GetString(key1, ""), Is.EqualTo(val1)); - Assert.That(m_table.GetBoolean(key2, false), Is.EqualTo(true)); - } - - [Test] - public void TestPersistentLoadError() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"/Table/{key1}\"=\"{val1}\"", - $"boolean \"/Table/{key2}\"=invalid", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NetworkTable.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(1)); - Assert.That(errors[0], Contains.Substring("3: unrecognized boolean value, not 'true' or 'false'")); - } - -#region Getters and Setters - - [Test] - [TestCase(3.56, ExpectedResult = 3.56)] - [TestCase(true, ExpectedResult = true)] - [TestCase("Hello", ExpectedResult = "Hello")] - [TestCase(new byte[] { 0, 5, 12, 0 }, ExpectedResult = new byte[] { 0, 5, 12, 0 })] - [TestCase(new double[] { 3.56, 5547.545 }, ExpectedResult = new double[] { 3.56, 5547.545 })] - [TestCase(new bool[] { false, true, true }, ExpectedResult = new bool[] { false, true, true })] - public object TestGetValue(object value) - { - string key = "key"; - if (value is double) - { - m_table.PutNumber(key, (double)value); - } - else if (value is string) - { - m_table.PutString(key, (string)value); - } - else if (value is bool) - { - m_table.PutBoolean(key, (bool)value); - } - else if (value is byte[]) - { - m_table.PutRaw(key, (byte[])value); - } - else if (value is double[]) - { - m_table.PutNumberArray(key, (double[])value); - } - else if (value is bool[]) - { - m_table.PutBooleanArray(key, (bool[])value); - } - else if (value is string[]) - { - m_table.PutStringArray(key, (string[])value); - } - else - { - throw new ArgumentException("Value is either null or an invalid type."); - } - return m_table.GetValue(key).GetObjectValue(); - } - - [Test] - public void TestGetValueStringArray() - { - string key = "key"; - string[] array = new[] { "Hello1", "Hello2" }; - - m_table.PutStringArray(key, array); - - var v = m_table.GetValue(key); - Assert.That(v, Is.Not.Null); - - Assert.That(v.GetStringArray(), Is.EquivalentTo(array)); - } - - [Test] - public void TestGetValueInvalid() - { - Assert.Throws(() => m_table.GetValue("key")); - } - - [Test] - [TestCase(3.56, ExpectedResult = 3.56)] - [TestCase(true, ExpectedResult = true)] - [TestCase("Hello", ExpectedResult = "Hello")] - [TestCase(new byte[] { 0, 5, 12, 0 }, ExpectedResult = new byte[] { 0, 5, 12, 0 })] - [TestCase(new double[] { 3.56, 5547.545 }, ExpectedResult = new double[] { 3.56, 5547.545 })] - [TestCase(new bool[] { false, true, true }, ExpectedResult = new bool[] { false, true, true })] - public object TestGetValueDefault(object value) - { - string key = "key"; - if (value is double) - { - m_table.PutNumber(key, (double)value); - } - else if (value is string) - { - m_table.PutString(key, (string)value); - } - else if (value is bool) - { - m_table.PutBoolean(key, (bool)value); - } - else if (value is byte[]) - { - m_table.PutRaw(key, (byte[])value); - } - else if (value is double[]) - { - m_table.PutNumberArray(key, (double[])value); - } - else if (value is bool[]) - { - m_table.PutBooleanArray(key, (bool[])value); - } - else if (value is string[]) - { - m_table.PutStringArray(key, (string[])value); - } - else - { - throw new ArgumentException("Value is either null or an invalid type."); - } - return m_table.GetValue(key, null).GetObjectValue(); - } - - [Test] - public void TestGetValueStringArrayDefault() - { - string key = "key"; - string[] array = new[] { "Hello1", "Hello2" }; - - m_table.PutStringArray(key, array); - - var v = m_table.GetValue(key); - Assert.That(v, Is.Not.Null); - - Assert.That(v.GetStringArray(), Is.EquivalentTo(array)); - } - - // TODO: REWRITE - /* - [Test] - [TestCase(3.56, ExpectedResult = 3.56)] - [TestCase(true, ExpectedResult = true)] - [TestCase("Hello", ExpectedResult = "Hello")] - [TestCase(new byte[] {0, 5, 12, 0}, ExpectedResult = new byte[] {0, 5, 12, 0})] - [TestCase(new double[] {3.56, 5547.545}, ExpectedResult = new double[] {3.56, 5547.545})] - [TestCase(new bool[] {false, true, true}, ExpectedResult = new bool[] {false, true, true})] - public object TestPutValue(object value) - { - string key = "key"; - m_table.PutValue(key, value); - return m_table.GetValue(key); - } - */ - - [Test] - public void TestPutValueStringArray() - { - string key = "key"; - string[] array = new[] { "Hello1", "Hello2" }; - - m_table.PutValue(key, Value.MakeStringArray(array)); - - var v = m_table.GetValue(key); - Assert.That(v, Is.Not.Null); - - Assert.That(v.GetStringArray(), Is.EquivalentTo(array)); - } - - - [Test] - public void TestPutAndGetNumberValid() - { - string key = "key"; - double setVal = 5.88; - Assert.That(m_table.PutNumber(key, setVal)); - - Assert.That(m_table.GetNumber(key), Is.EqualTo(setVal).Within(0.01)); - } - - [Test] - public void TestPutAndGetNumberValidDefault() - { - string key = "key"; - double setVal = 5.88; - Assert.That(m_table.PutNumber(key, setVal)); - - Assert.That(m_table.GetNumber(key, 3343.232), Is.EqualTo(setVal).Within(0.01)); - } - - [Test] - public void TestPutNumberIntoWrongType() - { - string key = "key"; - double setVal = 5.88; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutNumber(key, setVal)); - } - - [Test] - public void TestGetNumberErrorDefault() - { - string key = "key"; - - double defaultVal = 123322.32123; - Assert.That(m_table.GetNumber(key, defaultVal), Is.EqualTo(defaultVal).Within(0.01)); - } - - [Test] - public void TestGetNumberErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetNumber(key)); - } - - [Test] - public void TestGetNumberErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetNumber(key)); - } - - - - - - - [Test] - public void TestPutAndGetBooleanValid() - { - string key = "key"; - bool setVal = true; - Assert.That(m_table.PutBoolean(key, setVal)); - - Assert.That(m_table.GetBoolean(key), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutAndGetBooleanValidDefault() - { - string key = "key"; - bool setVal = true; - Assert.That(m_table.PutBoolean(key, setVal)); - - Assert.That(m_table.GetBoolean(key, false), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutBooleanIntoWrongType() - { - string key = "key"; - bool setVal = true; - m_table.PutString(key, "string"); - Assert.That(!m_table.PutBoolean(key, setVal)); - } - - [Test] - public void TestGetBooleanErrorDefault() - { - string key = "key"; - - bool defaultVal = true; - Assert.That(m_table.GetBoolean(key, defaultVal), Is.EqualTo(defaultVal)); - } - - [Test] - public void TestGetBooleanErrorThrowsWrongType() - { - string key = "key"; - m_table.PutString(key, "string"); - - Assert.Throws(() => m_table.GetBoolean(key)); - } - - [Test] - public void TestGetBooleanErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetBoolean(key)); - } - - - - - - [Test] - public void TestPutAndGetStringValid() - { - string key = "key"; - string setVal = "string"; - Assert.That(m_table.PutString(key, setVal)); - - Assert.That(m_table.GetString(key), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutAndGetStringValidDefault() - { - string key = "key"; - string setVal = "string"; - Assert.That(m_table.PutString(key, setVal)); - - Assert.That(m_table.GetString(key, "Default"), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutStringIntoWrongType() - { - string key = "key"; - string setVal = "string"; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutString(key, setVal)); - } - - [Test] - public void TestGetStringErrorDefault() - { - string key = "key"; - - string defaultVal = "string"; - Assert.That(m_table.GetString(key, defaultVal), Is.EqualTo(defaultVal)); - } - - [Test] - public void TestGetStringErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetString(key)); - } - - [Test] - public void TestGetStringErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetString(key)); - } - - - - [Test] - public void TestPutAndGetStringArrayValid() - { - string key = "key"; - string[] setVal = { - "string", - "string2", - "string3", - }; - Assert.That(m_table.PutStringArray(key, setVal)); - - Assert.That(m_table.GetStringArray(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetStringArrayValidDefault() - { - string key = "key"; - string[] setVal = { - "string", - "string2", - "string3", - }; - Assert.That(m_table.PutStringArray(key, setVal)); - - Assert.That(m_table.GetStringArray(key, new[] { "Default" }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutStringArrayIntoWrongType() - { - string key = "key"; - string[] setVal = { - "string", - "string2", - "string3", - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutStringArray(key, setVal)); - } - - [Test] - public void TestGetStringArrayErrorDefault() - { - string key = "key"; - - string[] defaultVal = { - "string", - "string2", - "string3", - }; - Assert.That(m_table.GetStringArray(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetStringArrayErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetStringArray(key)); - } - - [Test] - public void TestGetStringArrayErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetStringArray(key)); - } - - - - - [Test] - public void TestPutAndGetNumberArrayValid() - { - string key = "key"; - double[] setVal = { - 123.4, - 5.8, - 6.2, - }; - Assert.That(m_table.PutNumberArray(key, setVal)); - - Assert.That(m_table.GetNumberArray(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetNumberArrayValidDefault() - { - string key = "key"; - double[] setVal = { - 123.4, - 5.8, - 6.2, - }; - Assert.That(m_table.PutNumberArray(key, setVal)); - - Assert.That(m_table.GetNumberArray(key, new[] { 0.0 }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutNumberArrayIntoWrongType() - { - string key = "key"; - double[] setVal = { - 123.4, - 5.8, - 6.2, - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutNumberArray(key, setVal)); - } - - [Test] - public void TestGetNumberArrayErrorDefault() - { - string key = "key"; - - double[] defaultVal = { - 123.4, - 5.8, - 6.2, - }; - Assert.That(m_table.GetNumberArray(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetNumberArrayErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetNumberArray(key)); - } - - [Test] - public void TestGetNumberArrayErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetNumberArray(key)); - } - - - - [Test] - public void TestPutAndGetRawValid() - { - string key = "key"; - byte[] setVal = { - 123, - 5, - 6, - }; - Assert.That(m_table.PutRaw(key, setVal)); - - Assert.That(m_table.GetRaw(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetRawValidDefault() - { - string key = "key"; - byte[] setVal = { - 123, - 5, - 6, - }; - Assert.That(m_table.PutRaw(key, setVal)); - - Assert.That(m_table.GetRaw(key, new byte[] { 0 }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutRawIntoWrongType() - { - string key = "key"; - byte[] setVal = { - 123, - 5, - 6, - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutRaw(key, setVal)); - } - - [Test] - public void TestGetRawErrorDefault() - { - string key = "key"; - - byte[] defaultVal = { - 123, - 5, - 6, - }; - Assert.That(m_table.GetRaw(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetRawErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetRaw(key)); - } - - [Test] - public void TestGetRawErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetRaw(key)); - } - - - - - [Test] - public void TestPutAndGetBooleanArrayValid() - { - string key = "key"; - bool[] setVal = { - true, - false, - true, - }; - Assert.That(m_table.PutBooleanArray(key, setVal)); - - Assert.That(m_table.GetBooleanArray(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetBooleanArrayValidDefault() - { - string key = "key"; - bool[] setVal = { - true, - false, - true, - }; - Assert.That(m_table.PutBooleanArray(key, setVal)); - - Assert.That(m_table.GetBooleanArray(key, new[] { false }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutBooleanArrayIntoWrongType() - { - string key = "key"; - bool[] setVal = { - true, - false, - true, - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutBooleanArray(key, setVal)); - } - - [Test] - public void TestGetBooleanArrayErrorDefault() - { - string key = "key"; - - bool[] defaultVal = { - true, - false, - true, - }; - Assert.That(m_table.GetBooleanArray(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetBooleanArrayErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetBooleanArray(key)); - } - - [Test] - public void TestGetBooleanArrayErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetBooleanArray(key)); - } -#endregion - - // The below tests have no way to be checked, so we are just making sure they don't throw exceptions. - - - [Test] - public void TestSetNetworkIdentity() - { - NetworkTable.SetNetworkIdentity("UnitTests"); - - Assert.Pass(); - } - - [Test] - public void TestGetConnections() - { - Assert.That(NetworkTable.Connections(), Has.Count.EqualTo(0)); - } - - [Test] - public void TestIsConnected() - { - Assert.That(!m_table.IsConnected); - } - - [Test] - public void TestFlush() - { - NetworkTable.Flush(); - - Assert.Pass(); - } - - [Test] - public void TestSetUpdateRate() - { - NetworkTable.SetUpdateRate(100); - - Assert.Pass(); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestNetworkTablesStaticAPI.cs b/test/NetworkTables.Core.Test/TestNetworkTablesStaticAPI.cs deleted file mode 100644 index 67c4f22..0000000 --- a/test/NetworkTables.Core.Test/TestNetworkTablesStaticAPI.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - //[TestFixture] - public class TestNetworkTablesStaticApi : TestBase - { - [TestFixtureSetUp] - public void FixtureSetup() - { - NetworkTable.Shutdown(); - } - - [TestFixtureTearDown] - public void FixtureTeardown() - { - NetworkTable.Shutdown(); - NetworkTable.SetIPAddress("127.0.0.1"); - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - NetworkTable.SetPort(10000); - NetworkTable.SetServerMode(); - NetworkTable.Initialize(); - } - - [SetUp] - public void Setup() - { - NetworkTable.Shutdown(); - NetworkTable.SetIPAddress("127.0.0.1"); - } - - [Test] - public void TestDoubleInitializeServer() - { - NetworkTable.SetServerMode(); - Assert.That(NetworkTable.Client, Is.False); - NetworkTable.Initialize(); - Assert.DoesNotThrow(NetworkTable.Initialize); - } - - [Test] - public void TestDoubleInitializeClient() - { - NetworkTable.SetClientMode(); - Assert.That(NetworkTable.Client, Is.True); - NetworkTable.Initialize(); - Assert.DoesNotThrow(NetworkTable.Initialize); - } - - [Test] - public void TestClientShutdown() - { - NetworkTable.SetClientMode(); - NetworkTable.Initialize(); - Assert.That(NetworkTable.Running, Is.True); - NetworkTable.Shutdown(); - Assert.That(NetworkTable.Running, Is.False); - } - - [Test] - public void TestServerShutdown() - { - NetworkTable.SetServerMode(); - NetworkTable.Initialize(); - Assert.That(NetworkTable.Running, Is.True); - NetworkTable.Shutdown(); - Assert.That(NetworkTable.Running, Is.False); - } - - [Test] - public void TestSetClientModeWhileStopped() - { - NetworkTable.SetServerMode(); - Assert.That(NetworkTable.Client, Is.False); - NetworkTable.SetClientMode(); - Assert.That(NetworkTable.Client, Is.True); - NetworkTable.SetClientMode(); - Assert.That(NetworkTable.Client, Is.True); - } - - [Test] - public void TestSetClientModeWhileRunningServer() - { - NetworkTable.SetServerMode(); - Assert.That(NetworkTable.Client, Is.False); - NetworkTable.Initialize(); - Assert.Throws(NetworkTable.SetClientMode); - } - - /* - [Test] - public void TestSetTeam() - { - NetworkTable.SetTeam(1234); - Assert.That(NetworkTable.GetIPAddresses()[0], Is.EqualTo("roboRIO-1234-FRC.local")); - } - - [Test] - public void TestSetIpAddress() - { - NetworkTable.SetIPAddress("127.0.0.1"); - NetworkTable.SetIPAddress("10.12.34.2"); - Assert.That(NetworkTable.GetIPAddresses()[0], Is.EqualTo("10.12.34.2")); - } - */ - - [Test] - public void TestGetTableCausesInitialization() - { - Assert.That(NetworkTable.Running, Is.False); - NetworkTable.GetTable("empty"); - Assert.That(NetworkTable.Running, Is.True); - } - - [Test] - public void TestSetPersistentFilename() - { - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - Assert.That(NetworkTable.PersistentFilename, Is.EqualTo(NetworkTable.DefaultPersistentFileName)); - NetworkTable.SetPersistentFilename("TestFile.txt"); - Assert.That(NetworkTable.PersistentFilename, Is.EqualTo("TestFile.txt")); - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - Assert.That(NetworkTable.PersistentFilename, Is.EqualTo(NetworkTable.DefaultPersistentFileName)); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestRPC.cs b/test/NetworkTables.Core.Test/TestRPC.cs deleted file mode 100644 index 32c1e2c..0000000 --- a/test/NetworkTables.Core.Test/TestRPC.cs +++ /dev/null @@ -1,411 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class RpcTest : TestBase - { - [OneTimeSetUp] - public void FixtureSetUp() - { - NtCore.SetLogger((level, file, line, msg) => - { - Console.WriteLine(msg); - }, LogLevel.LogInfo); - } - - [OneTimeTearDown] - public void FixtureTearDown() - { - NtCore.StopRpcServer(); - } - - [Test] - public void TestPolledRpc() - { - Console.WriteLine("TestPolledRpc"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(true, TimeSpan.FromSeconds(1), out info); - Assert.That(polled, Is.True); - - IList toSendBack = Callback1(info.Name, info.Params, new ConnectionInfo()); - Assert.That(toSendBack.Count, Is.Not.EqualTo(0)); - - RemoteProcedureCall.PostRpcResponse(info.RpcId, info.CallUid, toSendBack); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestPolledRpcTimeout() - { - Console.WriteLine("TestPolledRpcTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - TimeSpan timeoutTime = TimeSpan.FromSeconds(1); - Stopwatch sw = Stopwatch.StartNew(); - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(true, timeoutTime, out info); - sw.Stop(); - Assert.That(polled, Is.False); - TimeSpan tolerance = TimeSpan.FromSeconds(0.25); - Assert.That(sw.Elapsed < timeoutTime + tolerance); - Assert.That(sw.Elapsed > timeoutTime - tolerance); - } - - [Test] - public void TestPolledRpcNonBlocking() - { - Console.WriteLine("TestPolledRpcNonBlocking"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(false, out info); - Assert.That(polled, Is.False); - } - - [Test] - public void TestPolledRpcNonBlockingWithTimeout() - { - Console.WriteLine("TestPolledRpcNonBlockingWithTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(false, TimeSpan.FromSeconds(1), out info); - Assert.That(polled, Is.False); - } - - private static IList Callback1(string names, byte[] paramsStr, ConnectionInfo connInfo) - { - var param = RemoteProcedureCall.UnpackRpcValues(paramsStr, new[] { NtType.Double }); - - if (param.Count == 0) - { - Console.Error.WriteLine("Empty Params?"); - return new byte[] { 0 }; - } - double val = param[0].GetDouble(); - - return RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(val + 1.2) }); - } - - [Test] - public void TestRpcLocal() - { - Console.WriteLine("TestRpcLocal"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeed() - { - Console.WriteLine("TestRpcSpeed"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - byte[] call1Result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out call1Result); - var res = RemoteProcedureCall.UnpackRpcValues(call1Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - - } - - [Test] - public void TestRpcLocalTimeoutFailure() - { - Console.WriteLine("LocalTimeoutFailure"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - TimeSpan timeoutTime = TimeSpan.FromSeconds(1); - Stopwatch sw = Stopwatch.StartNew(); - byte[] result = null; - bool success = RemoteProcedureCall.GetRpcResult(true, call1Uid, timeoutTime, out result); - sw.Stop(); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - TimeSpan tolerance = TimeSpan.FromSeconds(0.25); - Assert.That(sw.Elapsed < timeoutTime + tolerance); - Assert.That(sw.Elapsed > timeoutTime - tolerance); - } - - [Test] - public void TestRpcLocalNonBlocking() - { - Console.WriteLine("LoclaNonBlocking"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - bool success = RemoteProcedureCall.GetRpcResult(false, call1Uid, out result); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - } - - [Test] - public void TestRpcLocalNonBlockingWithTimeout() - { - Console.WriteLine("LocalNonBlockingWithTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - bool success = RemoteProcedureCall.GetRpcResult(false, call1Uid, TimeSpan.FromSeconds(1), out result); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - } - - [Test] - public void TestRpcLocalTimeoutSuccess() - { - Console.WriteLine("LocalTimeoutSuccess"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, TimeSpan.FromSeconds(1), out result); - Assert.That(result, Is.Not.Null); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedTimeoutSuccess() - { - Console.WriteLine("SpeedTimeoutSuccess"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - byte[] call1Result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, TimeSpan.FromSeconds(1), out call1Result); - Assert.That(call1Result, Is.Not.Null); - var res = RemoteProcedureCall.UnpackRpcValues(call1Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - - } - - [Test] - public void TestRpcLocalAsync() - { - Console.WriteLine("LocalAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.GetRpcResultAsync(call1Uid, source.Token); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var call1Result = RemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedAsync() - { - Console.WriteLine("SpeedAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.GetRpcResultAsync(call1Uid, source.Token); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var res = RemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - } - - [Test] - public void TestRpcLocalAsyncSingleCall() - { - Console.WriteLine("LocalAsyncSingleCall"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - Console.WriteLine("Waiting for RPC Result"); - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.CallRpcWithResultAsync("func1", source.Token, RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var call1Result = RemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedAsyncSingleCall() - { - Console.WriteLine("SpeedAsyncSingleCall"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.CallRpcWithResultAsync("func1", source.Token, RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var res = RemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - } - - private static IList Callback2(string names, byte[] paramsStr, ConnectionInfo connInfo) - { - var param = RemoteProcedureCall.UnpackRpcValues(paramsStr, new[] { NtType.Boolean, NtType.BooleanArray, NtType.Double, NtType.DoubleArray, NtType.Raw, NtType.String, NtType.StringArray }); - - if (param.Count == 0) - { - Console.Error.WriteLine("Empty Params?"); - return new byte[] { 0 }; - } - - return RemoteProcedureCall.PackRpcValues(new[] {Value.MakeBoolean(true), Value.MakeBooleanArray(new[] { true, false }), Value.MakeDouble(2.2), Value.MakeDoubleArray(new[] { 2.8, 6.876 }), - Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 }), Value.MakeString("NewString"), Value.MakeStringArray(new[] { "String1", "String2" }) }); - } - - [Test] - public void TestRpcAllTypes() - { - Console.WriteLine("AllTypes"); - var def = new RpcDefinition(1, "myfunc1", new List - { - new RpcParamDef("param1", Value.MakeBoolean(true)), - new RpcParamDef("param2", Value.MakeBooleanArray(new[] { true, false })), - new RpcParamDef("param3", Value.MakeDouble(0.0)), - new RpcParamDef("param4", Value.MakeDoubleArray(new[] { 2.8, 6.87 })), - new RpcParamDef("param5", Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 })), - new RpcParamDef("param6", Value.MakeString("NewString")), - new RpcParamDef("param7", Value.MakeStringArray(new[] { "String1", "String2" })), - }, new List - { - new RpcResultsDef("result1", NtType.Boolean), - new RpcResultsDef("result2", NtType.BooleanArray), - new RpcResultsDef("result3", NtType.Double), - new RpcResultsDef("result4", NtType.DoubleArray), - new RpcResultsDef("result5", NtType.Raw), - new RpcResultsDef("result6", NtType.String), - new RpcResultsDef("result7", NtType.StringArray), - }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback2); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] {Value.MakeBoolean(true), Value.MakeBooleanArray(new[] { true, false }), Value.MakeDouble(2.2), Value.MakeDoubleArray(new[] { 2.8, 6.87 }), - Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 }), Value.MakeString("NewString"), Value.MakeStringArray(new[] { "String1", "String2" })})); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Boolean, NtType.BooleanArray, NtType.Double, NtType.DoubleArray, NtType.Raw, NtType.String, NtType.StringArray }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestTearDownFixture.cs b/test/NetworkTables.Core.Test/TestTearDownFixture.cs deleted file mode 100644 index f7ed54f..0000000 --- a/test/NetworkTables.Core.Test/TestTearDownFixture.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using NetworkTables.Core.Native; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [SetUpFixture] - public class TestTearDownFixture - { - [OneTimeTearDown] - public void TearDown() - { -#if false - Console.WriteLine("Stopping Clietn"); - CoreMethods.StopClient(); - Console.WriteLine("Stopping Server"); - CoreMethods.StopServer(); -#endif - Console.WriteLine("Stopping Notifier"); - CoreMethods.StopNotifier(); - Console.WriteLine("Stoping RpcServer"); - CoreMethods.StopRpcServer(); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestWireDecoder.cs b/test/NetworkTables.Core.Test/TestWireDecoder.cs deleted file mode 100644 index b661d35..0000000 --- a/test/NetworkTables.Core.Test/TestWireDecoder.cs +++ /dev/null @@ -1,889 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Text; -using NetworkTables.Wire; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - class WireDecoderTest - { - readonly Value v_boolean = Value.MakeBoolean(true); - readonly Value v_double = Value.MakeDouble(1.0); - readonly Value v_string = Value.MakeString("hello"); - readonly Value v_raw = Value.MakeRaw((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - readonly Value v_rpc = Value.MakeRpc((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - readonly Value v_boolArray = Value.MakeBooleanArray(false, true, false); - readonly Value v_boolArrayBig = Value.MakeBooleanArray(new bool[255]); - readonly Value v_doubleArray = Value.MakeDoubleArray(0.5, 0.25); - readonly Value v_doubleArrayBig = Value.MakeDoubleArray(new double[255]); - - readonly Value v_stringArray = Value.MakeStringArray("hello", "goodbye"); - readonly Value v_stringArrayBig; - - - readonly string s_normal = "hello"; - - private readonly string s_long; - private readonly string s_big; - - private readonly string s_big2; - - public WireDecoderTest() - { - List sa = new List(); - for (int i = 0; i < 255; i++) - { - sa.Add("h"); - } - v_stringArrayBig = Value.MakeStringArray(sa.ToArray()); - - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < 127; i++) - { - builder.Append('*'); - } - builder.Append('x'); - s_long = builder.ToString(); - - builder.Clear(); - for (int i = 0; i < 65534; i++) - { - builder.Append('*'); - } - builder.Append('x'); - builder.Append('x'); - builder.Append('x'); - s_big = builder.ToString(); - - builder.Clear(); - for (int i = 0; i < 65534; i++) - { - builder.Append('*'); - } - builder.Append('x'); - s_big2 = builder.ToString(); - - } - - [Test] - public void Construct() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0300); - Assert.That(d.Error, Is.Null); - Assert.That(d.ProtoRev, Is.EqualTo(0x0300)); - } - - [Test] - public void SetProtoRev() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0300); - d.ProtoRev = 0x0200; - Assert.That(d.ProtoRev, Is.EqualTo(0x0200)); - } - - [Test] - public void Read8() - { - byte[] rawData = { 0x05, 0x01, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - byte val = 0; - Assert.That(d.Read8(ref val)); - Assert.That(val, Is.EqualTo(5)); - - Assert.That(d.Read8(ref val)); - Assert.That(val, Is.EqualTo(1)); - - Assert.That(d.Read8(ref val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(!d.Read8(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void Read16() - { - byte[] rawData = { 0x00, 0x05, 0x00, 0x01, 0x45, 0x67, 0x00, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - ushort val = 0; - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(5)); - - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(1)); - - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(0x4567)); - - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(!d.Read16(ref val)); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void Read32() - { - byte[] rawData = { 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xab, 0xcd, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - uint val = 0; - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(5)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(1)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(0xabcd)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(0x12345678)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(!d.Read32(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadDouble() - { - byte[] rawData = - { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x41, 0x0c, 0x13, 0x80, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - double val = 0; - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(0.0)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(2.3e5)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(double.PositiveInfinity)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(2.2250738585072014e-308)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(double.MaxValue)); - - Assert.That(!d.ReadDouble(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadUleb128() - { - byte[] rawData = { 0x00, 0x7f, 0x80, 0x01, 0x80 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - ulong val = 0; - Assert.That(d.ReadUleb128(out val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(d.ReadUleb128(out val)); - Assert.That(val, Is.EqualTo(0x7f)); - - Assert.That(d.ReadUleb128(out val)); - Assert.That(val, Is.EqualTo(0x80)); - - Assert.That(!d.ReadUleb128(out val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadType() - { - byte[] rawData = { 0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x20 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - NtType val = 0; - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Boolean)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Double)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.String)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Raw)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.BooleanArray)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.DoubleArray)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.StringArray)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Rpc)); - - Assert.That(!d.ReadType(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadTypeError() - { - byte[] rawData = { 0x30 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - NtType val = 0; - - Assert.That(!d.ReadType(ref val)); - - Assert.That(d.Error, Is.Not.Null); - } - - [Test] - public void Reset() - { - byte[] rawData = { 0x30 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - NtType val = 0; - - Assert.That(!d.ReadType(ref val)); - - Assert.That(d.Error, Is.Not.Null); - d.Reset(); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void BooleanValue2() - { - byte[] rawData = new byte[] { 0x01, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - var val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(v_boolean.Val)); - - var vFalse = Value.MakeBoolean(false); - val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - Assert.That(d.ReadValue(NtType.Boolean), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void DoubleValue2() - { - byte[] rawData = new byte[] - { - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - var val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - Assert.That(d.ReadValue(NtType.Double), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void StringValue2() - { - byte[] rawData = new byte[] - { - 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x00, 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - var val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(v_string.Val)); - - var vFalse = Value.MakeString("bye"); - val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.String), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArray2() - { - byte[] b = { 0x03, 0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0xff }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArray.Val)); - - var boolArray2 = Value.MakeBooleanArray(true, false); - val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(boolArray2.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArrayBig2() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - - - [Test] - public void ReadDoubleArray2() - { - byte[] b = - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55 - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadDoubleArrayBig2() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255 * 8; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArray2() - { - List b = new List() - { - 0x02, - 0x00, - 0x05 - }; - b.AddRange(Encoding.UTF8.GetBytes("hello")); - b.Add(0x00); - b.Add(0x07); - b.AddRange(Encoding.UTF8.GetBytes("goodbye")); - b.Add(0x55); - MemoryStream stream = new MemoryStream(b.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArrayBig2() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x00); - s.Add(0x01); - s.Add((byte)'h'); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadValueError2() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0200); - Assert.That(d.ReadValue(NtType.Unassigned), Is.Null); - Assert.That(d.Error, Is.Not.Null); - - d.Reset(); - Assert.That(d.ReadValue(NtType.Raw), Is.Null); - Assert.That(d.Error, Is.Not.Null); - - Assert.That(d.ReadValue(NtType.Rpc), Is.Null); - Assert.That(d.Error, Is.Not.Null); - } - - [Test] - public void BooleanValue3() - { - byte[] rawData = new byte[] { 0x01, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(v_boolean.Val)); - - var vFalse = Value.MakeBoolean(false); - val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - Assert.That(d.ReadValue(NtType.Boolean), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void DoubleValue3() - { - byte[] rawData = new byte[] - { - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - Assert.That(d.ReadValue(NtType.Double), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void StringValue3() - { - byte[] rawData = new byte[] - { - 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(v_string.Val)); - - var vFalse = Value.MakeString("bye"); - val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.String), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void RawValue3() - { - byte[] rawData = new byte[] - { - 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Raw); - Assert.That(val.Type, Is.EqualTo(NtType.Raw)); - Assert.That(val.Val, Is.EqualTo(v_raw.Val)); - - var vFalse = Value.MakeRaw((byte)'b', (byte)'y', (byte)'e'); - val = d.ReadValue(NtType.Raw); - Assert.That(val.Type, Is.EqualTo(NtType.Raw)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.Raw), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void RpcValue3() - { - byte[] rawData = new byte[] - { - 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Rpc); - Assert.That(val.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(val.Val, Is.EqualTo(v_rpc.Val)); - - var vFalse = Value.MakeRaw((byte)'b', (byte)'y', (byte)'e'); - val = d.ReadValue(NtType.Rpc); - Assert.That(val.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.Rpc), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArray3() - { - byte[] b = { 0x03, 0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0xff }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArray.Val)); - - var boolArray2 = Value.MakeBooleanArray(true, false); - val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(boolArray2.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArrayBig3() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - - - [Test] - public void ReadDoubleArray3() - { - byte[] b = - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55 - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadDoubleArrayError3() - { - byte[] b = - { - 0x02, - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val, Is.Null); - } - - [Test] - public void ReadStringArrayError3() - { - byte[] b = - { - 0x02, - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val, Is.Null); - } - - [Test] - public void ReadDoubleArrayBig3() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255 * 8; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArray3() - { - List b = new List() - { - 0x02, - 0x05 - }; - b.AddRange(Encoding.UTF8.GetBytes("hello")); - b.Add(0x07); - b.AddRange(Encoding.UTF8.GetBytes("goodbye")); - b.Add(0x55); - MemoryStream stream = new MemoryStream(b.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArrayBig3() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x01); - s.Add((byte)'h'); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadValueError3() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0300); - Assert.That(d.ReadValue(NtType.Unassigned), Is.Null); - Assert.That(d.Error, Is.Not.Null); - } - - [Test] - public void ReadStringError2() - { - MemoryStream stream = new MemoryStream(new byte[] { 0x00, 0x05 }); - WireDecoder d = new WireDecoder(stream, 0x0200); - string str = ""; - Assert.That(d.ReadString(ref str), Is.False); - } - - [Test] - public void ReadString2() - { - byte[] sNormalBytes = Encoding.UTF8.GetBytes(s_normal); - byte[] sLongBytes = Encoding.UTF8.GetBytes(s_long); - byte[] sBigBytes = Encoding.UTF8.GetBytes(s_big2); - List s = new List(); - s.AddRange(new byte[] { 0x00, 0x05 }); - s.AddRange(sNormalBytes); - s.AddRange(new byte[] { 0x00, 0x80 }); - s.AddRange(sLongBytes); - s.AddRange(new byte[] { 0xff, 0xff }); - s.AddRange(sBigBytes); - s.Add(0x55); - - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - string outs = null; - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_normal)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_long)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_big2)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadString(ref outs), Is.False); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringError3() - { - MemoryStream stream = new MemoryStream(new byte[] { 0x05 }); - WireDecoder d = new WireDecoder(stream, 0x0300); - string str = ""; - Assert.That(d.ReadString(ref str), Is.False); - } - - [Test] - public void ReadRawError3() - { - MemoryStream stream = new MemoryStream(new byte[] { 0x05 }); - WireDecoder d = new WireDecoder(stream, 0x0300); - byte[] str = null; - Assert.That(d.ReadRaw(ref str), Is.False); - } - - [Test] - public void ReadString3() - { - byte[] sNormalBytes = Encoding.UTF8.GetBytes(s_normal); - byte[] sLongBytes = Encoding.UTF8.GetBytes(s_long); - byte[] sBigBytes = Encoding.UTF8.GetBytes(s_big); - List s = new List(); - s.Add(0x05); - s.AddRange(sNormalBytes); - s.AddRange(new byte[] { 0x80, 0x01 }); - s.AddRange(sLongBytes); - s.AddRange(new byte[] { 0x81, 0x80, 0x04 }); - s.AddRange(sBigBytes); - s.Add(0x55); - - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - string outs = null; - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_normal)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_long)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_big)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadString(ref outs), Is.False); - Assert.That(d.Error, Is.Null); - } - } -} diff --git a/test/NetworkTables.Core.Test/TestWireEncoder.cs b/test/NetworkTables.Core.Test/TestWireEncoder.cs deleted file mode 100644 index 64a0f2b..0000000 --- a/test/NetworkTables.Core.Test/TestWireEncoder.cs +++ /dev/null @@ -1,617 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NetworkTables.Wire; -using NUnit.Framework; - -namespace NetworkTables.Core.Test -{ - [TestFixture] - public class WireEncoderTest - { - private const int BUFSIZE = 1024; - - [Test] - public void WireEncoderWrite8() - { - int off = BUFSIZE - 1; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.Write8(5); - unchecked - { - e.Write8((byte)0x101u); - } - e.Write8(0); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(3)); - byte[] checkArray = { 0x05, 0x01, 0x00 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void Construct() - { - WireEncoder d = new WireEncoder(0x0300); - Assert.That(d.Error, Is.Null); - Assert.That(d.ProtoRev, Is.EqualTo(0x0300)); - } - - [Test] - public void SetProtoRev() - { - WireEncoder d = new WireEncoder(0x0300); - d.ProtoRev = 0x0200; - Assert.That(d.ProtoRev, Is.EqualTo(0x0200)); - } - - [Test] - public void WireEncoderWrite16() - { - int off = BUFSIZE - 2; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.Write16(5); - unchecked - { - e.Write16((ushort)0x10001u); - } - e.Write16(0x4567); - e.Write16(0); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(8)); - byte[] checkArray = { 0x00, 0x05, 0x00, 0x01, 0x45, 0x67, 0x00, 0x00 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void WireEncoderWrite32() - { - int off = BUFSIZE - 4; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.Write32(5); - e.Write32(1); - e.Write32(0xabcd); - e.Write32(0x12345678); - e.Write32(0); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(20)); - byte[] checkArray = { 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xab, 0xcd, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - - [Test] - public void WireEncoderWriteDouble() - { - int off = BUFSIZE - 8; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.WriteDouble(0.0); - e.WriteDouble(2.3e5); - e.WriteDouble(double.PositiveInfinity); - e.WriteDouble(2.2250738585072014e-308);//Minimum double size - e.WriteDouble(double.MaxValue); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(40)); - byte[] checkArray = - { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x41, 0x0c, 0x13, 0x80, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void WireEncoderWriteLeb128() - { - int off = BUFSIZE - 2; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.WriteUleb128(0ul); - e.WriteUleb128(0x7ful); - e.WriteUleb128(0x80ul); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(4)); - byte[] checkArray = { 0x00, 0x7f, 0x80, 0x01 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - - [Test] - public void WireEncoderWriteType() - { - int off = BUFSIZE - 1; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.WriteType(NtType.Boolean); - e.WriteType(NtType.Double); - e.WriteType(NtType.String); - e.WriteType(NtType.Raw); - e.WriteType(NtType.BooleanArray); - e.WriteType(NtType.DoubleArray); - e.WriteType(NtType.StringArray); - e.WriteType(NtType.Rpc); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(8)); - byte[] checkArray = { 0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x20 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void WriteTypeError() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteType(NtType.Unassigned); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.EqualTo("unrecognized Type")); - - e.Reset(); - e.WriteType(NtType.Raw); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.EqualTo("raw type not supported in protocol < 3.0")); - - e.Reset(); - e.WriteType(NtType.Rpc); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.EqualTo("RPC type not supported in protocol < 3.0")); - } - - [Test] - public void Reset() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteType(NtType.Unassigned); - Assert.That(e.Error, Is.Not.Null); - e.Reset(); - Assert.That(e.Error, Is.Null); - - e.Write8(0); - Assert.That(e.Buffer.Length, Is.EqualTo(1)); - e.Reset(); - Assert.That(e.Buffer, Is.Empty); - } - - private readonly Value v_empty = Value.MakeEmpty(); - private readonly Value v_boolean = Value.MakeBoolean(true); - private readonly Value v_double = Value.MakeDouble(1.0); - private readonly Value v_string = Value.MakeString("hello"); - private readonly Value v_raw = Value.MakeRaw((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - private readonly Value v_rpc = Value.MakeRpc((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - private readonly Value v_boolArray = Value.MakeBooleanArray(false, true, false); - private readonly Value v_boolArrayBig = Value.MakeBooleanArray(new bool[256]); - private readonly Value v_doubleArray = Value.MakeDoubleArray(0.5, 0.25); - private readonly Value v_doubleArrayBig = Value.MakeDoubleArray(new double[256]); - - private readonly Value v_stringArray = Value.MakeStringArray("hello", "goodbye"); - private readonly Value v_stringArrayBig; - - private readonly string s_normal = "hello"; - - private readonly string s_long; - private readonly string s_big; - - public WireEncoderTest() - { - List sa = new List(); - for (int i = 0; i < 256; i++) - { - sa.Add("a"); - } - v_stringArrayBig = Value.MakeStringArray(sa.ToArray()); - - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < 127; i++) - { - builder.Append('*'); - } - builder.Append('x'); - s_long = builder.ToString(); - - builder.Clear(); - for (int i = 0; i < 65534; i++) - { - builder.Append('*'); - } - builder.Append('x'); - builder.Append('x'); - builder.Append('x'); - s_big = builder.ToString(); - - } - - [Test] - public void GetValueSize2() - { - WireEncoder e = new WireEncoder(0x0200); - Assert.That(e.GetValueSize(null), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_empty), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_boolean), Is.EqualTo(1)); - Assert.That(e.GetValueSize(v_double), Is.EqualTo(8)); - Assert.That(e.GetValueSize(v_string), Is.EqualTo(7)); - Assert.That(e.GetValueSize(v_raw), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_rpc), Is.EqualTo(0)); - - Assert.That(e.GetValueSize(v_boolArray), Is.EqualTo(1 + 3)); - Assert.That(e.GetValueSize(v_boolArrayBig), Is.EqualTo(1 + 255)); - Assert.That(e.GetValueSize(v_doubleArray), Is.EqualTo(1 + 2 * 8)); - Assert.That(e.GetValueSize(v_doubleArrayBig), Is.EqualTo(1 + 255 * 8)); - Assert.That(e.GetValueSize(v_stringArray), Is.EqualTo(1 + 7 + 9)); - Assert.That(e.GetValueSize(v_stringArrayBig), Is.EqualTo(1 + 255 * 3)); - } - - [Test] - public void WriteBooleanValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_boolean); - var v_false = Value.MakeBoolean(false); - e.WriteValue(v_false); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(2)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x01, 0x00 })); - } - - [Test] - public void WriteDoubleValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_double); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })); - } - - [Test] - public void WriteStringValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_string); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(7)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteBooleanArrayValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_boolArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 3)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x03, 0x00, 0x01, 0x00 })); - - e.Reset(); - e.WriteValue(v_boolArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteDoubleArrayValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_doubleArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 2 * 8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - })); - - e.Reset(); - e.WriteValue(v_doubleArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 8)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteStringArrayValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_stringArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 7 + 9)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x00, 0x07, (byte)'g', (byte)'o', (byte)'o', (byte)'d', (byte)'b', (byte)'y', (byte)'e' - })); - - e.Reset(); - e.WriteValue(v_stringArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 3)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2] }, Is.EquivalentTo(new byte[] { 0xff, 0x00, 0x01 })); - } - - [Test] - public void GetStringSize2() - { - WireEncoder e = new WireEncoder(0x0200); - Assert.That(e.GetStringSize(s_normal), Is.EqualTo(7)); - Assert.That(e.GetStringSize(s_long), Is.EqualTo(130)); - Assert.That(e.GetStringSize(s_big), Is.EqualTo(65537)); - } - - [Test] - public void WriteString2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteString(s_normal); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(7)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - - e.Reset(); - e.WriteString(s_long); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(130)); - byte[] arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0x00, 0x80, (byte)'*', (byte)'*' })); - Assert.That(e.Buffer[128], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[129], Is.EqualTo((byte)'x')); - - e.Reset(); - e.WriteString(s_big); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(65537)); - arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0xff, 0xff, (byte)'*', (byte)'*' })); - Assert.That(e.Buffer[65535], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[65536], Is.EqualTo((byte)'x')); - } - - [Test] - public void WriteValueError2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_empty); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - - e.Reset(); - e.WriteValue(v_raw); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - - e.Reset(); - e.WriteValue(v_rpc); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - - [Test] - public void WriteValueNull2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(null); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - - - - [Test] - public void GetValueSize3() - { - WireEncoder e = new WireEncoder(0x0300); - Assert.That(e.GetValueSize(null), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_empty), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_boolean), Is.EqualTo(1)); - Assert.That(e.GetValueSize(v_double), Is.EqualTo(8)); - Assert.That(e.GetValueSize(v_string), Is.EqualTo(6)); - Assert.That(e.GetValueSize(v_raw), Is.EqualTo(6)); - Assert.That(e.GetValueSize(v_rpc), Is.EqualTo(6)); - - Assert.That(e.GetValueSize(v_boolArray), Is.EqualTo(1 + 3)); - Assert.That(e.GetValueSize(v_boolArrayBig), Is.EqualTo(1 + 255)); - Assert.That(e.GetValueSize(v_doubleArray), Is.EqualTo(1 + 2 * 8)); - Assert.That(e.GetValueSize(v_doubleArrayBig), Is.EqualTo(1 + 255 * 8)); - Assert.That(e.GetValueSize(v_stringArray), Is.EqualTo(1 + 6 + 8)); - Assert.That(e.GetValueSize(v_stringArrayBig), Is.EqualTo(1 + 255 * 2)); - } - - [Test] - public void WriteBooleanValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_boolean); - var v_false = Value.MakeBoolean(false); - e.WriteValue(v_false); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(2)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x01, 0x00 })); - } - - [Test] - public void WriteDoubleValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_double); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })); - } - - [Test] - public void WriteStringValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_string); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteRawArray3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_raw); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteRpcArray3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_rpc); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteBooleanArrayValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_boolArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 3)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x03, 0x00, 0x01, 0x00 })); - - e.Reset(); - e.WriteValue(v_boolArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteDoubleArrayValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_doubleArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 2 * 8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - })); - - e.Reset(); - e.WriteValue(v_doubleArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 8)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteStringArrayValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_stringArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 6 + 8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x07, (byte)'g', (byte)'o', (byte)'o', (byte)'d', (byte)'b', (byte)'y', (byte)'e' - })); - - e.Reset(); - e.WriteValue(v_stringArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 2)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x01 })); - } - - [Test] - public void GetStringSize3() - { - WireEncoder e = new WireEncoder(0x0300); - Assert.That(e.GetStringSize(s_normal), Is.EqualTo(6)); - Assert.That(e.GetStringSize(s_long), Is.EqualTo(130)); - Assert.That(e.GetStringSize(s_big), Is.EqualTo(65540)); - } - - [Test] - public void WriteString3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteString(s_normal); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - - e.Reset(); - e.WriteString(s_long); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(130)); - byte[] arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0x80, 0x01, (byte)'*', (byte)'*' })); - Assert.That(e.Buffer[128], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[129], Is.EqualTo((byte)'x')); - - e.Reset(); - e.WriteString(s_big); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(65540)); - arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0x81, 0x80, 0x04, (byte)'*' })); - Assert.That(e.Buffer[65536], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[65537], Is.EqualTo((byte)'x')); - Assert.That(e.Buffer[65538], Is.EqualTo((byte)'x')); - Assert.That(e.Buffer[65539], Is.EqualTo((byte)'x')); - } - - [Test] - public void WriteValueError3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_empty); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - - [Test] - public void WriteValueNull3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(null); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - } -} diff --git a/test/NetworkTables.Test/BitConverterTests.cs b/test/NetworkTables.Test/BitConverterTests.cs deleted file mode 100644 index 05f8aa4..0000000 --- a/test/NetworkTables.Test/BitConverterTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading.Tasks; -using NetworkTables.Wire; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture(true)] - [TestFixture(false)] - public class BitConverterTests - { - private IFastBitConverter m_bitConverter; - - private bool m_useBE; - - public BitConverterTests(bool useBE) - { - m_useBE = useBE; - if (useBE) - { - m_bitConverter = new FastBitConverterBE(); - } - else - { - m_bitConverter = new FastBitConverterLE(); - } - } - - [Test] - public void AddUShort() - { - ushort valNotConverted = 254; - ushort val = valNotConverted; - if (m_useBE) - { - val = (ushort) IPAddress.HostToNetworkOrder((short) val); - } - - byte[] frameworkArray = BitConverter.GetBytes(val); - - List customArray = new List(2); - m_bitConverter.AddUShort(customArray, valNotConverted); - - Assert.That(customArray, Is.EquivalentTo(frameworkArray)); - } - - [Test] - public void AddShort() - { - short valNotConverted = 254; - short val = valNotConverted; - if (m_useBE) - { - val = (short)IPAddress.HostToNetworkOrder((short)val); - } - - byte[] frameworkArray = BitConverter.GetBytes(val); - - List customArray = new List(2); - m_bitConverter.AddShort(customArray, valNotConverted); - - Assert.That(customArray, Is.EquivalentTo(frameworkArray)); - } - - [Test] - public void AddInt() - { - int valNotConverted = 254; - int val = valNotConverted; - if (m_useBE) - { - val = (int)IPAddress.HostToNetworkOrder((int)val); - } - - byte[] frameworkArray = BitConverter.GetBytes(val); - - List customArray = new List(2); - m_bitConverter.AddInt(customArray, valNotConverted); - - Assert.That(customArray, Is.EquivalentTo(frameworkArray)); - } - - [Test] - public void AddUInt() - { - uint valNotConverted = 254; - uint val = valNotConverted; - if (m_useBE) - { - val = (uint)IPAddress.HostToNetworkOrder((int)val); - } - - byte[] frameworkArray = BitConverter.GetBytes(val); - - List customArray = new List(2); - m_bitConverter.AddUInt(customArray, valNotConverted); - - Assert.That(customArray, Is.EquivalentTo(frameworkArray)); - } - - [Test] - public void AddULong() - { - ulong valNotConverted = 254; - ulong val = valNotConverted; - if (m_useBE) - { - val = (ulong)IPAddress.HostToNetworkOrder((long)val); - } - - byte[] frameworkArray = BitConverter.GetBytes(val); - - List customArray = new List(2); - m_bitConverter.AddULong(customArray, valNotConverted); - - Assert.That(customArray, Is.EquivalentTo(frameworkArray)); - } - - [Test] - public void AddLong() - { - long valNotConverted = 254; - long val = valNotConverted; - if (m_useBE) - { - val = (long)IPAddress.HostToNetworkOrder((long)val); - } - - byte[] frameworkArray = BitConverter.GetBytes(val); - - List customArray = new List(2); - m_bitConverter.AddLong(customArray, valNotConverted); - - Assert.That(customArray, Is.EquivalentTo(frameworkArray)); - } - - [Test] - public void AddDouble() - { - double valNotConverted = 254.254; - double val = valNotConverted; - if (m_useBE) - { - val = BitConverter.Int64BitsToDouble(IPAddress.HostToNetworkOrder(BitConverter.DoubleToInt64Bits(val))); - } - - byte[] frameworkArray = BitConverter.GetBytes(val); - - List customArray = new List(8); - m_bitConverter.AddDouble(customArray, valNotConverted); - - Assert.That(customArray, Is.EquivalentTo(frameworkArray)); - } - } -} diff --git a/test/NetworkTables.Test/ConnectionTesting/ClientServerTest.cs b/test/NetworkTables.Test/ConnectionTesting/ClientServerTest.cs deleted file mode 100644 index 4589e79..0000000 --- a/test/NetworkTables.Test/ConnectionTesting/ClientServerTest.cs +++ /dev/null @@ -1,305 +0,0 @@ -using System; -using NUnit.Framework; -using System.Threading; - -namespace NetworkTables.Test.ConnectionTesting -{ - /* - internal class MockDispatcher : DispatcherBase - { - internal MockDispatcher(Storage storage, Notifier notifier) - : base(storage, notifier) - { - - } - - public void StartServer(string persistentFilename, string listenAddress, int port) - { - StartServer(persistentFilename, new TcpAcceptor(port, listenAddress)); - } - - public void StartClient(string serverName, int port) - { - StartClient(() => TcpConnector.Connect(serverName, port, 1)); - } - } - */ - - [TestFixture] - public class ClientServerTest - { - private RpcServer m_clientRpc; - private Storage m_clientStorage; - private Notifier m_clientNotifier; - private Dispatcher m_clientDispatcher; - - private RpcServer m_serverRpc; - private Storage m_serverStorage; - private Notifier m_serverNotifier; - private Dispatcher m_serverDispatcher; - - [OneTimeSetUp] - public void OneTimeSetUp() - { - m_clientRpc = new RpcServer(); - m_clientNotifier = new Notifier(); - m_clientStorage = new Storage(m_clientNotifier, m_clientRpc); - - m_clientDispatcher = new Dispatcher(m_clientStorage, m_clientNotifier); - - m_clientDispatcher.Identity = "TestClient"; - - m_serverRpc = new RpcServer(); - m_serverNotifier = new Notifier(); - m_serverStorage = new Storage(m_serverNotifier, m_serverRpc); - - m_serverDispatcher = new Dispatcher(m_serverStorage, m_serverNotifier); - - m_serverDispatcher.Identity = "TestServer"; - } - - [OneTimeTearDown] - public void OneTimeTearDown() - { - m_clientDispatcher.Dispose(); - m_clientStorage.Dispose(); - m_clientNotifier.Dispose(); - m_clientRpc.Dispose(); - - m_serverDispatcher.Dispose(); - m_serverStorage.Dispose(); - m_serverNotifier.Dispose(); - m_serverRpc.Dispose(); - } - - [TearDown] - public void TearDown() - { - m_clientDispatcher.Stop(); - m_serverDispatcher.Stop(); - } - - [Test] - public void ServerThenClientConnectionTest() - { - Console.WriteLine("ServerThenClient"); - m_serverDispatcher.StartServer("", "", 9999); - Thread.Sleep(500); - m_clientDispatcher.StartClient(); - m_clientDispatcher.SetServer("localhost", 9999); - - Thread.Sleep(2000); - - var serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(1)); - var serverConn = serverConnections[0]; - Assert.That(serverConn.RemoteId, Is.EqualTo("TestClient")); - Assert.That(serverConn.ProtocolVersion, Is.EqualTo(0x0300)); - - var clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(1)); - var clientConn = clientConnections[0]; - Assert.That(clientConn.RemoteId, Is.EqualTo("TestServer")); - Assert.That(clientConn.ProtocolVersion, Is.EqualTo(0x0300)); - } - - [Test] - public void ClientThenServerConnectionTest() - { - Console.WriteLine("ClientThenServer"); - m_clientDispatcher.StartClient(); - m_clientDispatcher.SetServer("localhost", 9999); - Thread.Sleep(500); - m_serverDispatcher.StartServer("", "", 9999); - - Thread.Sleep(2000); - - var serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(1)); - var serverConn = serverConnections[0]; - Assert.That(serverConn.RemoteId, Is.EqualTo("TestClient")); - Assert.That(serverConn.ProtocolVersion, Is.EqualTo(0x0300)); - - var clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(1)); - var clientConn = clientConnections[0]; - Assert.That(clientConn.RemoteId, Is.EqualTo("TestServer")); - Assert.That(clientConn.ProtocolVersion, Is.EqualTo(0x0300)); - } - - [Test] - public void ClientTestNoServer() - { - Console.WriteLine("ClientNoServer"); - m_clientDispatcher.StartClient(); - m_clientDispatcher.SetServer("localhost", 9999); - - Thread.Sleep(2000); - - var serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(0)); - - var clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(0)); - } - - [Test] - public void ServerTestNoClient() - { - Console.WriteLine("ServerNoClient"); - m_serverDispatcher.StartServer("", "", 9999); - - Thread.Sleep(2000); - - var serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(0)); - - var clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(0)); - } - - [Test] - public void ServerTestClientDisconnect() - { - Console.WriteLine("ServerClientDisconnect"); - m_serverDispatcher.StartServer("", "", 9999); - Thread.Sleep(500); - m_clientDispatcher.StartClient(); - m_clientDispatcher.SetServer("localhost", 9999); - - Thread.Sleep(2000); - - var serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(1)); - var serverConn = serverConnections[0]; - Assert.That(serverConn.RemoteId, Is.EqualTo("TestClient")); - Assert.That(serverConn.ProtocolVersion, Is.EqualTo(0x0300)); - - var clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(1)); - var clientConn = clientConnections[0]; - Assert.That(clientConn.RemoteId, Is.EqualTo("TestServer")); - Assert.That(clientConn.ProtocolVersion, Is.EqualTo(0x0300)); - - m_clientDispatcher.Stop(); - - Thread.Sleep(2000); - - serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(0)); - - clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(0)); - } - - [Test] - public void ClientTestServerDisconnect() - { - Console.WriteLine("ClientServerDisconnect"); - m_serverDispatcher.StartServer("", "", 9999); - Thread.Sleep(500); - m_clientDispatcher.StartClient(); - m_clientDispatcher.SetServer("localhost", 9999); - - Thread.Sleep(2000); - - var serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(1)); - var serverConn = serverConnections[0]; - Assert.That(serverConn.RemoteId, Is.EqualTo("TestClient")); - Assert.That(serverConn.ProtocolVersion, Is.EqualTo(0x0300)); - - var clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(1)); - var clientConn = clientConnections[0]; - Assert.That(clientConn.RemoteId, Is.EqualTo("TestServer")); - Assert.That(clientConn.ProtocolVersion, Is.EqualTo(0x0300)); - - m_serverDispatcher.Stop(); - - Thread.Sleep(2000); - - serverConnections = m_serverDispatcher.GetConnections(); - Assert.That(serverConnections, Has.Count.EqualTo(0)); - - clientConnections = m_clientDispatcher.GetConnections(); - Assert.That(clientConnections, Has.Count.EqualTo(0)); - } - - [Test] - public void ServerTestConnectionListener() - { - Console.WriteLine("ServerConnectionListener"); - m_serverDispatcher.StartServer("", "", 9999); - Thread.Sleep(500); - Notifier notifier = m_serverNotifier; - - int retUid = 16666; - bool retConnected = false; - ConnectionInfo retInfo = default(ConnectionInfo); - - // ReSharper disable once UnusedVariable - int uid = notifier.AddConnectionListener((id, connected, connInfo) => - { - retUid = id; - retConnected = connected; - retInfo = connInfo; - }); - notifier.Start(); - m_clientDispatcher.StartClient(); - m_clientDispatcher.SetServer("localhost", 9999); - - Thread.Sleep(2000); - - Assert.That(retUid, Is.EqualTo(1)); - Assert.That(retConnected, Is.True); - Assert.That(retInfo.RemoteId, Is.EqualTo("TestClient")); - - m_clientDispatcher.Stop(); - - Thread.Sleep(2000); - - Assert.That(retUid, Is.EqualTo(1)); - Assert.That(retConnected, Is.False); - Assert.That(retInfo.RemoteId, Is.EqualTo("TestClient")); - } - - [Test] - public void ClientTestConnectionListener() - { - Console.WriteLine("ClientConnectionListener"); - m_clientDispatcher.StartClient(); - m_clientDispatcher.SetServer("localhost", 9999); - - Thread.Sleep(500); - Notifier notifier = m_clientNotifier; - - int retUid = 16666; - bool retConnected = false; - ConnectionInfo retInfo = default(ConnectionInfo); - - int uid = notifier.AddConnectionListener((id, connected, connInfo) => - { - retUid = id; - retConnected = connected; - retInfo = connInfo; - }); - notifier.Start(); - - m_serverDispatcher.StartServer("", "", 9999); - Thread.Sleep(2000); - - Assert.That(retUid, Is.EqualTo(1)); - Assert.That(retConnected, Is.True); - Assert.That(retInfo.RemoteId, Is.EqualTo("TestServer")); - - m_serverDispatcher.Stop(); - - Thread.Sleep(2000); - - Assert.That(retUid, Is.EqualTo(1)); - Assert.That(retConnected, Is.False); - Assert.That(retInfo.RemoteId, Is.EqualTo("TestServer")); - } - } -} diff --git a/test/NetworkTables.Test/ConnectionTesting/RpcRemoteTest.cs b/test/NetworkTables.Test/ConnectionTesting/RpcRemoteTest.cs deleted file mode 100644 index abe801e..0000000 --- a/test/NetworkTables.Test/ConnectionTesting/RpcRemoteTest.cs +++ /dev/null @@ -1,487 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using NetworkTables.Independent; -using NUnit.Framework; - -namespace NetworkTables.Test.ConnectionTesting -{ - [TestFixture] - public class RpcRemoteTest - { - private IndependentNtCore serverNtCore; - private IndependentRemoteProcedureCall serverRemoteProcedureCall; - - private IndependentNtCore clientNtCore; - private IndependentRemoteProcedureCall clientRemoteProcedureCall; - - const int Port = 5578; - - [OneTimeSetUp] - public void FixtureSetUp() - { - serverNtCore = new IndependentNtCore(); - clientNtCore = new IndependentNtCore(); - - serverRemoteProcedureCall = new IndependentRemoteProcedureCall(serverNtCore); - clientRemoteProcedureCall = new IndependentRemoteProcedureCall(clientNtCore); - - serverNtCore.RemoteName = "Server"; - clientNtCore.RemoteName = "Client"; - - serverNtCore.StartServer("rpcPersist.txt", "", Port); - clientNtCore.StartClient("localhost", Port); - - serverNtCore.UpdateRate = 0.01; - clientNtCore.UpdateRate = 0.01; - - int count = 0; - while (true) - { - var conns = serverNtCore.GetConnections(); - if (conns.Count > 0) break; - Thread.Sleep(100); - if (count > 10) - { - Assert.Fail("Could not connect"); - return; - } - count++; - } - Thread.Sleep(500); - // Everything is connected - } - - [OneTimeTearDown] - public void FixtureTearDown() - { - clientNtCore.Dispose(); - serverNtCore.Dispose(); - } - - [Test] - public void TestPolledRpc() - { - Console.WriteLine("TestPolledRpc"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreatePolledRpc("func1", def); - Thread.Sleep(30); - - Console.WriteLine("Calling RPC"); - - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - Thread.Sleep(20); - - RpcCallInfo info; - bool polled = serverRemoteProcedureCall.PollRpc(true, TimeSpan.FromSeconds(1), out info); - Assert.That(polled, Is.True); - - IList toSendBack = Callback1(info.Name, info.Params, new ConnectionInfo()); - Assert.That(toSendBack.Count, Is.Not.EqualTo(0)); - - serverRemoteProcedureCall.PostRpcResponse(info.RpcId, info.CallUid, toSendBack); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - clientRemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = clientRemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - - [Test] - public void TestPolledRpcAsync() - { - Console.WriteLine("TestPolledRpcAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - CancellationTokenSource source = new CancellationTokenSource(); - var task = serverRemoteProcedureCall.PollRpcAsync(source.Token); - bool completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted, Is.True); - Assert.That(task.Result, Is.Not.Null); - Assert.That(task.Result.HasValue); - - IList toSendBack = Callback1(task.Result.Value.Name, task.Result.Value.Params, new ConnectionInfo()); - Assert.That(toSendBack.Count, Is.Not.EqualTo(0)); - - serverRemoteProcedureCall.PostRpcResponse(task.Result.Value.RpcId, task.Result.Value.CallUid, toSendBack); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - clientRemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = clientRemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - - [Test] - public void TestPolledRpcTimeout() - { - Console.WriteLine("TestPolledRpcTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - TimeSpan timeoutTime = TimeSpan.FromSeconds(1); - Stopwatch sw = Stopwatch.StartNew(); - RpcCallInfo info; - bool polled = serverRemoteProcedureCall.PollRpc(true, timeoutTime, out info); - sw.Stop(); - Assert.That(polled, Is.False); - TimeSpan tolerance = TimeSpan.FromSeconds(0.25); - Assert.That(sw.Elapsed < timeoutTime + tolerance); - Assert.That(sw.Elapsed > timeoutTime - tolerance); - } - - [Test] - public void TestPolledRpcNonBlocking() - { - Console.WriteLine("TestPolledRpcNonBlocking"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - RpcCallInfo info; - bool polled = serverRemoteProcedureCall.PollRpc(false, out info); - Assert.That(polled, Is.False); - } - - [Test] - public void TestPolledRpcNonBlockingWithTimeout() - { - Console.WriteLine("TestPolledRpcNonBlockingWithTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - RpcCallInfo info; - bool polled = serverRemoteProcedureCall.PollRpc(false, TimeSpan.FromSeconds(1), out info); - Assert.That(polled, Is.False); - } - - private static IList Callback1(string names, byte[] paramsStr, ConnectionInfo connInfo) - { - var param = RemoteProcedureCall.UnpackRpcValues(paramsStr, new[] { NtType.Double }); - - if (param.Count == 0) - { - Console.Error.WriteLine("Empty Params?"); - return new byte[] { 0 }; - } - double val = param[0].GetDouble(); - - return RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(val + 1.2) }); - } - - [Test] - public void TestRpcLocal() - { - Console.WriteLine("TestRpcLocal"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - clientRemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = clientRemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeed() - { - Console.WriteLine("TestRpcSpeed"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 20; ++i) - { - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", clientRemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - byte[] call1Result = null; - clientRemoteProcedureCall.GetRpcResult(true, call1Uid, out call1Result); - var res = clientRemoteProcedureCall.UnpackRpcValues(call1Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - - } - - [Test] - public void TestRpcLocalTimeoutFailure() - { - Console.WriteLine("LocalTimeoutFailure"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - TimeSpan timeoutTime = TimeSpan.FromSeconds(1); - Stopwatch sw = Stopwatch.StartNew(); - byte[] result = null; - bool success = clientRemoteProcedureCall.GetRpcResult(true, call1Uid, timeoutTime, out result); - sw.Stop(); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - TimeSpan tolerance = TimeSpan.FromSeconds(0.25); - Assert.That(sw.Elapsed < timeoutTime + tolerance); - Assert.That(sw.Elapsed > timeoutTime - tolerance); - } - - [Test] - public void TestRpcLocalNonBlocking() - { - Console.WriteLine("LoclaNonBlocking"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - bool success = clientRemoteProcedureCall.GetRpcResult(false, call1Uid, out result); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - } - - [Test] - public void TestRpcLocalNonBlockingWithTimeout() - { - Console.WriteLine("LocalNonBlockingWithTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - bool success = clientRemoteProcedureCall.GetRpcResult(false, call1Uid, TimeSpan.FromSeconds(1), out result); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - } - - [Test] - public void TestRpcLocalTimeoutSuccess() - { - Console.WriteLine("LocalTimeoutSuccess"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", clientRemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - clientRemoteProcedureCall.GetRpcResult(true, call1Uid, TimeSpan.FromSeconds(1), out result); - Assert.That(result, Is.Not.Null); - var call1Result = clientRemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedTimeoutSuccess() - { - Console.WriteLine("SpeedTimeoutSuccess"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 20; ++i) - { - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", clientRemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - byte[] call1Result = null; - clientRemoteProcedureCall.GetRpcResult(true, call1Uid, TimeSpan.FromSeconds(1), out call1Result); - Assert.That(call1Result, Is.Not.Null); - var res = clientRemoteProcedureCall.UnpackRpcValues(call1Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - - } - - [Test] - public void TestRpcLocalAsync() - { - Console.WriteLine("LocalAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", clientRemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - CancellationTokenSource source = new CancellationTokenSource(); - var task = clientRemoteProcedureCall.GetRpcResultAsync(call1Uid, source.Token); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var call1Result = clientRemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedAsync() - { - Console.WriteLine("SpeedAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 20; ++i) - { - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", clientRemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - CancellationTokenSource source = new CancellationTokenSource(); - var task = clientRemoteProcedureCall.GetRpcResultAsync(call1Uid, source.Token); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var res = clientRemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - } - - [Test] - public void TestRpcLocalAsyncSingleCall() - { - Console.WriteLine("LocalAsyncSingleCall"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - Console.WriteLine("Waiting for RPC Result"); - CancellationTokenSource source = new CancellationTokenSource(); - var task = clientRemoteProcedureCall.CallRpcWithResultAsync("func1", source.Token, clientRemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(2.0) })); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var call1Result = clientRemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedAsyncSingleCall() - { - Console.WriteLine("SpeedAsyncSingleCall"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double) }); - - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 20; ++i) - { - CancellationTokenSource source = new CancellationTokenSource(); - var task = clientRemoteProcedureCall.CallRpcWithResultAsync("func1", source.Token, clientRemoteProcedureCall.PackRpcValues(new[] { Value.MakeDouble(i) })); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var res = clientRemoteProcedureCall.UnpackRpcValues(task.Result, new[] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - } - - private static IList Callback2(string names, byte[] paramsStr, ConnectionInfo connInfo) - { - var param = RemoteProcedureCall.UnpackRpcValues(paramsStr, new[] { NtType.Boolean, NtType.BooleanArray, NtType.Double, NtType.DoubleArray, NtType.Raw, NtType.String, NtType.StringArray }); - - if (param.Count == 0) - { - Console.Error.WriteLine("Empty Params?"); - return new byte[] { 0 }; - } - - return RemoteProcedureCall.PackRpcValues(new[] {Value.MakeBoolean(true), Value.MakeBooleanArray(new[] { true, false }), Value.MakeDouble(2.2), Value.MakeDoubleArray(new[] { 2.8, 6.876 }), - Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 }), Value.MakeString("NewString"), Value.MakeStringArray(new[] { "String1", "String2" }) }); - } - - [Test] - public void TestRpcAllTypes() - { - Console.WriteLine("AllTypes"); - var def = new RpcDefinition(1, "myfunc1", new List - { - new RpcParamDef("param1", Value.MakeBoolean(true)), - new RpcParamDef("param2", Value.MakeBooleanArray(new[] { true, false })), - new RpcParamDef("param3", Value.MakeDouble(0.0)), - new RpcParamDef("param4", Value.MakeDoubleArray(new[] { 2.8, 6.87 })), - new RpcParamDef("param5", Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 })), - new RpcParamDef("param6", Value.MakeString("NewString")), - new RpcParamDef("param7", Value.MakeStringArray(new[] { "String1", "String2" })), - }, new List - { - new RpcResultsDef("result1", NtType.Boolean), - new RpcResultsDef("result2", NtType.BooleanArray), - new RpcResultsDef("result3", NtType.Double), - new RpcResultsDef("result4", NtType.DoubleArray), - new RpcResultsDef("result5", NtType.Raw), - new RpcResultsDef("result6", NtType.String), - new RpcResultsDef("result7", NtType.StringArray), - }); - - serverRemoteProcedureCall.CreateRpc("func1", serverRemoteProcedureCall.PackRpcDefinition(def), Callback2); - - Console.WriteLine("Calling RPC"); - - long call1Uid = clientRemoteProcedureCall.CallRpc("func1", clientRemoteProcedureCall.PackRpcValues(new[] {Value.MakeBoolean(true), Value.MakeBooleanArray(new[] { true, false }), Value.MakeDouble(2.2), Value.MakeDoubleArray(new[] { 2.8, 6.87 }), - Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 }), Value.MakeString("NewString"), Value.MakeStringArray(new[] { "String1", "String2" })})); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - clientRemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = clientRemoteProcedureCall.UnpackRpcValues(result, new[] { NtType.Boolean, NtType.BooleanArray, NtType.Double, NtType.DoubleArray, NtType.Raw, NtType.String, NtType.StringArray }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - } -} diff --git a/test/NetworkTables.Test/Exceptions/PersistentExceptionTest.cs b/test/NetworkTables.Test/Exceptions/PersistentExceptionTest.cs deleted file mode 100644 index 23b9889..0000000 --- a/test/NetworkTables.Test/Exceptions/PersistentExceptionTest.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.IO; -using NetworkTables.Exceptions; -using NUnit.Framework; - -namespace NetworkTables.Test.Exceptions -{ - [TestFixture] - public class PersistentExceptionTest - { - [Test] - public void Persistent() - { - const string message = "Test Error Message"; - PersistentException ex = new PersistentException(message); - Assert.That(ex.Message, Is.EqualTo(message)); - Assert.That(ex is IOException); - } - } -} diff --git a/test/NetworkTables.Test/Exceptions/TableKeyDifferentTypeTest.cs b/test/NetworkTables.Test/Exceptions/TableKeyDifferentTypeTest.cs deleted file mode 100644 index f31ac16..0000000 --- a/test/NetworkTables.Test/Exceptions/TableKeyDifferentTypeTest.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using NetworkTables.Exceptions; -using NUnit.Framework; - -namespace NetworkTables.Test.Exceptions -{ - [TestFixture] - public class TableKeyDifferentTypeTest - { - [Test] - public void TableKeyDifferentTypeNoKey() - { - TableKeyDifferentTypeException ex = new TableKeyDifferentTypeException(NtType.Boolean, NtType.Double); - Assert.That(ex.RequestedKey, Is.EqualTo(string.Empty)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.Boolean)); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Double)); - Assert.That(ex.Message, Is.EqualTo($"Requested Type {NtType.Boolean} does not match actual Type {NtType.Double}.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex is InvalidOperationException); - } - - [Test] - public void TableKeyDifferentTypeKey() - { - const string key = "Test"; - TableKeyDifferentTypeException ex = new TableKeyDifferentTypeException(key, NtType.Boolean, NtType.Double); - Assert.That(ex.RequestedKey, Is.EqualTo(key)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.Boolean)); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Double)); - Assert.That(ex.Message, Is.EqualTo($"Key: {key}, Requested Type: {NtType.Boolean}, Type in Table: {NtType.Double}")); - Assert.That(ex.ThrownByValueGet, Is.False); - Assert.That(ex is InvalidOperationException); - } - } -} diff --git a/test/NetworkTables.Test/Exceptions/TableKeyNotDefinedTest.cs b/test/NetworkTables.Test/Exceptions/TableKeyNotDefinedTest.cs deleted file mode 100644 index fa00406..0000000 --- a/test/NetworkTables.Test/Exceptions/TableKeyNotDefinedTest.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using NetworkTables.Exceptions; -using NUnit.Framework; - -namespace NetworkTables.Test.Exceptions -{ - [TestFixture] - public class TableKeyNotDefinedTest - { - [Test] - public void NotDefinedTest() - { - string key = "Test"; - TableKeyNotDefinedException ex = new TableKeyNotDefinedException(key); - Assert.That(ex.Key, Is.EqualTo(key)); - Assert.That(ex.Message, Is.EqualTo($"Unknown Table Key: {key}")); - Assert.That(ex is InvalidOperationException); - } - } -} diff --git a/test/NetworkTables.Test/InfoStructuresTest.cs b/test/NetworkTables.Test/InfoStructuresTest.cs deleted file mode 100644 index 9b7216f..0000000 --- a/test/NetworkTables.Test/InfoStructuresTest.cs +++ /dev/null @@ -1,41 +0,0 @@ -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture] - public class InfoStructuresTest - { - [Test] - public void ConnectionInfo() - { - string remoteId = "remote"; - string remoteIp = "remoteIp"; - int remotePort = 1234; - int lastUpdate = 50; - int protocolVersion = 3; - ConnectionInfo info = new ConnectionInfo(remoteId, remoteIp, remotePort, lastUpdate, protocolVersion); - - Assert.That(info.RemoteId, Is.EqualTo(remoteId)); - Assert.That(info.RemoteIp, Is.EqualTo(remoteIp)); - Assert.That(info.RemotePort, Is.EqualTo(remotePort)); - Assert.That(info.LastUpdate, Is.EqualTo(lastUpdate)); - Assert.That(info.ProtocolVersion, Is.EqualTo(protocolVersion)); - } - - [Test] - public void EntryInfo() - { - string name = "TestEntryInfo"; - NtType type = NtType.Boolean; - EntryFlags flags = EntryFlags.Persistent; - long lastChange = 55; - - EntryInfo info = new EntryInfo(name, type, flags, lastChange); - - Assert.That(info.Name, Is.EqualTo(name)); - Assert.That(info.Type, Is.EqualTo(type)); - Assert.That(info.Flags, Is.EqualTo(flags)); - Assert.That(info.LastChange, Is.EqualTo(lastChange)); - } - } -} diff --git a/test/NetworkTables.Test/Leb128Test.cs b/test/NetworkTables.Test/Leb128Test.cs deleted file mode 100644 index 3e564f7..0000000 --- a/test/NetworkTables.Test/Leb128Test.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System.Collections.Generic; -using NetworkTables.Wire; -using NUnit.Framework; -using System.IO; - -namespace NetworkTables.Test -{ - [TestFixture] - public class Leb128Test - { - [Test] - public void Leb128Write() - { - ExpectLeb128Eq(0, 0, 0x00); - ExpectLeb128Eq(1, 0, 0x01); - ExpectLeb128Eq(63, 0, 0x3f); - ExpectLeb128Eq(64, 0, 0x40); - ExpectLeb128Eq(0x7f, 0, 0x7f); - ExpectLeb128Eq(0x80, 0, 0x80, 0x01); - ExpectLeb128Eq(0x81, 0, 0x81, 0x01); - ExpectLeb128Eq(0x90, 0, 0x90, 0x01); - ExpectLeb128Eq(0xff, 0, 0xff, 0x01); - ExpectLeb128Eq(0x100, 0, 0x80, 0x02); - ExpectLeb128Eq(0x101, 0, 0x81, 0x02); - } - - public void ExpectLeb128Eq(ulong value, ulong pad, params byte[] expected) - { - List buf = new List(32); - int size = Leb128.WriteUleb128(buf, value); - Assert.That(size, Is.EqualTo(buf.Count)); - Assert.That(expected, Is.EquivalentTo(buf)); - } - - [Test] - public void Leb128Read() - { - ExpectReadLeb128Eq(0, 0x00); - ExpectReadLeb128Eq(1, 0x01); - ExpectReadLeb128Eq(63, 0x3f); - ExpectReadLeb128Eq(64, 0x40); - ExpectReadLeb128Eq(0x7f, 0x7f); - ExpectReadLeb128Eq(0x80, 0x80, 0x01); - ExpectReadLeb128Eq(0x81, 0x81, 0x01); - ExpectReadLeb128Eq(0x90, 0x90, 0x01); - ExpectReadLeb128Eq(0xff, 0xff, 0x01); - ExpectReadLeb128Eq(0x100, 0x80, 0x02); - ExpectReadLeb128Eq(0x101, 0x81, 0x02); - ExpectReadLeb128Eq(8320, 0x80, 0xc1, 0x80, 0x80, 0x10); - } - - public void ExpectReadLeb128Eq(ulong expected, params byte[] value) - { - do - { - int count = 0; - ulong val = 0; - int size = Leb128.ReadUleb128(value, ref count, out val); - Assert.That(size, Is.EqualTo(value.Length)); - Assert.That(val, Is.EqualTo(expected)); - } while (false); - } - - [Test] - public void Leb128Size() - { - Assert.That(Leb128.SizeUleb128(0), Is.EqualTo(1)); - - Assert.That(Leb128.SizeUleb128(0x1UL), Is.EqualTo(1)); - Assert.That(Leb128.SizeUleb128(0x40UL), Is.EqualTo(1)); - Assert.That(Leb128.SizeUleb128(0x7fUL), Is.EqualTo(1)); - - Assert.That(Leb128.SizeUleb128(0x80UL), Is.EqualTo(2)); - Assert.That(Leb128.SizeUleb128(0x2000UL), Is.EqualTo(2)); - Assert.That(Leb128.SizeUleb128(0x3fffUL), Is.EqualTo(2)); - - Assert.That(Leb128.SizeUleb128(0x4000UL), Is.EqualTo(3)); - Assert.That(Leb128.SizeUleb128(0x100000UL), Is.EqualTo(3)); - Assert.That(Leb128.SizeUleb128(0x1fffffUL), Is.EqualTo(3)); - - Assert.That(Leb128.SizeUleb128(0x200000UL), Is.EqualTo(4)); - Assert.That(Leb128.SizeUleb128(0x8000000UL), Is.EqualTo(4)); - Assert.That(Leb128.SizeUleb128(0xfffffffUL), Is.EqualTo(4)); - - Assert.That(Leb128.SizeUleb128(0x10000000UL), Is.EqualTo(5)); - Assert.That(Leb128.SizeUleb128(0x40000000UL), Is.EqualTo(5)); - Assert.That(Leb128.SizeUleb128(0x7fffffffUL), Is.EqualTo(5)); - - Assert.That(Leb128.SizeUleb128(uint.MaxValue), Is.EqualTo(5)); - } - - [Test] - public void ReadInvalidSize() - { - byte[] val = new byte[] {0, 1, 2}; - - ulong ov = 0; - int start = 10; - var ret = Leb128.ReadUleb128(val, ref start, out ov); - Assert.That(ret, Is.EqualTo(0)); - Assert.That(ov, Is.EqualTo(0)); - } - - [Test] - public void ReadInvalidSizeStream() - { - byte[] val = new byte[] { 0, 1, 2 }; - - ulong ov = 0; - int start = 10; - var ret = Leb128.ReadUleb128(val, ref start, out ov); - Assert.That(ret, Is.EqualTo(0)); - Assert.That(ov, Is.EqualTo(0)); - } - - [Test] - public void Leb128ReadStream() - { - ExpectReadLeb128EqStream(0, 0x00); - ExpectReadLeb128EqStream(1, 0x01); - ExpectReadLeb128EqStream(63, 0x3f); - ExpectReadLeb128EqStream(64, 0x40); - ExpectReadLeb128EqStream(0x7f, 0x7f); - ExpectReadLeb128EqStream(0x80, 0x80, 0x01); - ExpectReadLeb128EqStream(0x81, 0x81, 0x01); - ExpectReadLeb128EqStream(0x90, 0x90, 0x01); - ExpectReadLeb128EqStream(0xff, 0xff, 0x01); - ExpectReadLeb128EqStream(0x100, 0x80, 0x02); - ExpectReadLeb128EqStream(0x101, 0x81, 0x02); - ExpectReadLeb128EqStream(8320, 0x80, 0xc1, 0x80, 0x80, 0x10); - } - - public void ExpectReadLeb128EqStream(ulong expected, params byte[] value) - { - MemoryStream stream = new MemoryStream(value); - do - { - ulong val = 0; - bool valid = Leb128.ReadUleb128(stream, out val); - Assert.That(valid, Is.True); - Assert.That(val, Is.EqualTo(expected)); - } while (false); - } - - - //TODO: Add tests for stream based reads - } -} diff --git a/test/NetworkTables.Test/MessageTest.cs b/test/NetworkTables.Test/MessageTest.cs deleted file mode 100644 index d673cf4..0000000 --- a/test/NetworkTables.Test/MessageTest.cs +++ /dev/null @@ -1,702 +0,0 @@ -using NetworkTables.Wire; -using NUnit.Framework; -using System.IO; -using static NetworkTables.Message.MsgType; - -namespace NetworkTables.Test -{ - [TestFixture] - public class MessageTest - { - [Test] - public void CreateParameterless() - { - Message msg = new Message(); - Assert.That(msg.Type, Is.EqualTo(Unknown)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateKeepAlive() - { - Message msg = Message.KeepAlive(); - Assert.That(msg.Type, Is.EqualTo(KeepAlive)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateProtoUnsup() - { - Message msg = Message.ProtoUnsup(); - Assert.That(msg.Type, Is.EqualTo(ProtoUnsup)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateServerHelloDone() - { - Message msg = Message.ServerHelloDone(); - Assert.That(msg.Type, Is.EqualTo(ServerHelloDone)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateClientHelloDone() - { - Message msg = Message.ClientHelloDone(); - Assert.That(msg.Type, Is.EqualTo(ClientHelloDone)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateClearEntries() - { - Message msg = Message.ClearEntries(); - Assert.That(msg.Type, Is.EqualTo(ClearEntries)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateClientHello() - { - string name = "Testing"; - Message msg = Message.ClientHello(name); - Assert.That(msg.Type, Is.EqualTo(ClientHello)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo(name)); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateServerHello() - { - uint flags = 1; - string name = "Testing"; - Message msg = Message.ServerHello(flags, name); - Assert.That(msg.Type, Is.EqualTo(ServerHello)); - Assert.That(msg.Id, Is.EqualTo(0)); - Assert.That(msg.Flags, Is.EqualTo(flags)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo(name)); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateEntryAssign() - { - uint id = 1; - uint seq = 1; - EntryFlags flags = EntryFlags.Persistent; - string name = "Testing"; - Value val = Value.MakeDouble(5); - Message msg = Message.EntryAssign(name, id, seq, val, flags); - Assert.That(msg.Type, Is.EqualTo(EntryAssign)); - Assert.That(msg.Id, Is.EqualTo(id)); - Assert.That(msg.Flags, Is.EqualTo((uint)flags)); - Assert.That(msg.SeqNumUid, Is.EqualTo(seq)); - Assert.That(msg.Str, Is.EqualTo(name)); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.IsDouble()); - Assert.That(msg.Val.GetDouble(), Is.EqualTo(5)); - } - - [Test] - public void CreateEntryUpdate() - { - uint id = 1; - uint seq = 1; - Value val = Value.MakeDouble(5); - Message msg = Message.EntryUpdate(id, seq, val); - Assert.That(msg.Type, Is.EqualTo(EntryUpdate)); - Assert.That(msg.Id, Is.EqualTo(id)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(seq)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.IsDouble()); - Assert.That(msg.Val.GetDouble(), Is.EqualTo(5)); - } - - [Test] - public void CreateFlagsUpdate() - { - EntryFlags flags = EntryFlags.Persistent; - uint id = 1; - Message msg = Message.FlagsUpdate(id, flags); - Assert.That(msg.Type, Is.EqualTo(FlagsUpdate)); - Assert.That(msg.Id, Is.EqualTo(id)); - Assert.That(msg.Flags, Is.EqualTo((uint)flags)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateEntryDelete() - { - uint id = 1; - Message msg = Message.EntryDelete(id); - Assert.That(msg.Type, Is.EqualTo(EntryDelete)); - Assert.That(msg.Id, Is.EqualTo(id)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void CreateExecuteRpc() - { - uint id = 1; - uint uid = 1; - byte[] val = new byte[] { 5, 5, 8, 9, 0, 5 }; - Message msg = Message.ExecuteRpc(id, uid, val); - Assert.That(msg.Type, Is.EqualTo(ExecuteRpc)); - Assert.That(msg.Id, Is.EqualTo(id)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(uid)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.IsRpc()); - byte[] ret = msg.Val.GetRpc(); - Assert.That(ret, Is.EquivalentTo(val)); - } - - [Test] - public void CreateRpcResponse() - { - uint id = 1; - uint uid = 1; - byte[] val = new byte[] { 5, 5, 8, 9, 0, 5 }; - Message msg = Message.RpcResponse(id, uid, val); - Assert.That(msg.Type, Is.EqualTo(RpcResponse)); - Assert.That(msg.Id, Is.EqualTo(id)); - Assert.That(msg.Flags, Is.EqualTo(0)); - Assert.That(msg.SeqNumUid, Is.EqualTo(uid)); - Assert.That(msg.Str, Is.EqualTo("")); - Assert.That(msg.Val, Is.Not.Null); - Assert.That(msg.Val.IsRpc()); - byte[] ret = msg.Val.GetRpc(); - Assert.That(ret, Is.EquivalentTo(val)); - } - - [Test] - public void WriteKeepAlive3() - { - Message msg = Message.KeepAlive(); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(1)); - Assert.That(buf[0], Is.EqualTo((byte)KeepAlive)); - } - - [Test] - public void WriteKeepAlive2() - { - Message msg = Message.KeepAlive(); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(1)); - Assert.That(buf[0], Is.EqualTo((byte)KeepAlive)); - } - - [Test] - public void WriteClientHello3() - { - string name = "Testing"; - Message msg = Message.ClientHello(name); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - ushort u16 = 0; - string str = null; - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ClientHello)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo((ushort)0x0300)); - Assert.That(dec.ReadString(ref str), Is.True); - Assert.That(str, Is.EqualTo(name)); - } - - [Test] - public void WriteClientHello2() - { - string name = "Testing"; - Message msg = Message.ClientHello(name); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0200); - byte u8 = 0; - ushort u16 = 0; - string str = null; - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ClientHello)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo((ushort)0x0200)); - Assert.That(dec.ReadString(ref str), Is.False); - } - - [Test] - public void WriteProtoUnsup3() - { - Message msg = Message.ProtoUnsup(); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - ushort u16 = 0; - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ProtoUnsup)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo((ushort)0x0300)); - } - - [Test] - public void WriteProtUnsup2() - { - Message msg = Message.ProtoUnsup(); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0200); - byte u8 = 0; - ushort u16 = 0; - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ProtoUnsup)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo((ushort)0x0200)); - } - - [Test] - public void WriteServerHelloDone3() - { - Message msg = Message.ServerHelloDone(); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(1)); - Assert.That(buf[0], Is.EqualTo((byte)ServerHelloDone)); - } - - [Test] - public void WriteServerHelloDone2() - { - Message msg = Message.ServerHelloDone(); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(1)); - Assert.That(buf[0], Is.EqualTo((byte)ServerHelloDone)); - } - - [Test] - public void WriteServerHello3() - { - uint flags = 1; - string name = "Testing"; - Message msg = Message.ServerHello(flags, name); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - string str = null; - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ServerHello)); - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)flags)); - Assert.That(dec.ReadString(ref str), Is.True); - Assert.That(str, Is.EqualTo(name)); - } - - [Test] - public void WriteServerHello2() - { - //Server Hello does not do anything on 2 - uint flags = 1; - string name = "Testing"; - Message msg = Message.ServerHello(flags, name); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(0)); - } - - [Test] - public void WriteClientHelloDone3() - { - Message msg = Message.ClientHelloDone(); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ClientHelloDone)); - } - - [Test] - public void WriteClientHelloDone2() - { - //Client Hello Done does not do anything on 2 - Message msg = Message.ClientHelloDone(); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(0)); - } - - [Test] - public void WriteEntryAssign3() - { - uint id = 1; - uint seq = 1; - EntryFlags flags = EntryFlags.Persistent; - string name = "Testing"; - Value val = Value.MakeDouble(5); - Message msg = Message.EntryAssign(name, id, seq, val, flags); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - NtType type = 0; - string str = ""; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)EntryAssign)); - Assert.That(dec.ReadString(ref str), Is.True); - Assert.That(str, Is.EqualTo(name)); - Assert.That(dec.ReadType(ref type), Is.True); - Assert.That(type, Is.EqualTo(NtType.Double)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(seq)); - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)flags)); - val = dec.ReadValue(type); - Assert.That(val, Is.Not.Null); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.GetDouble(), Is.EqualTo(5)); - - } - - [Test] - public void WriteEntryAssign2() - { - uint id = 1; - uint seq = 1; - EntryFlags flags = EntryFlags.Persistent; - string name = "Testing"; - Value val = Value.MakeDouble(5); - Message msg = Message.EntryAssign(name, id, seq, val, flags); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0200); - byte u8 = 0; - NtType type = 0; - string str = ""; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)EntryAssign)); - Assert.That(dec.ReadString(ref str), Is.True); - Assert.That(str, Is.EqualTo(name)); - Assert.That(dec.ReadType(ref type), Is.True); - Assert.That(type, Is.EqualTo(NtType.Double)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(seq)); - val = dec.ReadValue(type); - Assert.That(val, Is.Not.Null); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.GetDouble(), Is.EqualTo(5)); - - } - - [Test] - public void WriteEntryUpdate3() - { - uint id = 1; - uint seq = 1; - Value val = Value.MakeDouble(5); - Message msg = Message.EntryUpdate(id, seq, val); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - NtType type = 0; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)EntryUpdate)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(seq)); - Assert.That(dec.ReadType(ref type), Is.True); - Assert.That(type, Is.EqualTo(NtType.Double)); - val = dec.ReadValue(type); - Assert.That(val, Is.Not.Null); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.GetDouble(), Is.EqualTo(5)); - - } - - [Test] - public void WriteEntryUpdate2() - { - uint id = 1; - uint seq = 1; - Value val = Value.MakeDouble(5); - Message msg = Message.EntryUpdate(id, seq, val); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0200); - byte u8 = 0; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)EntryUpdate)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(seq)); - //Forcing double, as rev 2 has a seperate function to grab - val = dec.ReadValue(NtType.Double); - Assert.That(val, Is.Not.Null); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.GetDouble(), Is.EqualTo(5)); - - } - - [Test] - public void WriteFlagsUpdate3() - { - uint id = 1; - EntryFlags flags = EntryFlags.Persistent; - Message msg = Message.FlagsUpdate(id, flags); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)FlagsUpdate)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)flags)); - } - - [Test] - public void WriteFlagsUpdate2() - { - //Flags not supported in 2 - uint id = 1; - EntryFlags flags = EntryFlags.Persistent; - Message msg = Message.FlagsUpdate(id, flags); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(0)); - - } - - [Test] - public void WriteEntryDelete2() - { - //Flags not supported in 2 - uint id = 1; - Message msg = Message.EntryDelete(id); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(0)); - - } - - [Test] - public void WriteClearEntries2() - { - //Flags not supported in 2 - Message msg = Message.ClearEntries(); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(0)); - - } - - [Test] - public void WriteExecuteRpc2() - { - //Flags not supported in 2 - uint id = 1; - uint seq = 1; - Message msg = Message.ExecuteRpc(id, seq, new byte[1]); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(0)); - - } - - [Test] - public void WriteRpcResponse2() - { - //Flags not supported in 2 - uint id = 1; - uint seq = 1; - Message msg = Message.RpcResponse(id, seq, new byte[1]); - WireEncoder enc = new WireEncoder(0x0200); - msg.Write(enc); - byte[] buf = enc.Buffer; - Assert.That(buf, Has.Length.EqualTo(0)); - - } - - [Test] - public void WriteEntryDelete3() - { - uint id = 1; - Message msg = Message.EntryDelete(id); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)EntryDelete)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - } - - [Test] - public void WriteClearEntries3() - { - Message msg = Message.ClearEntries(); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - uint u32 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ClearEntries)); - Assert.That(dec.Read32(ref u32), Is.True); - Assert.That(u32, Is.EqualTo(0xD06CB27Au)); - } - - [Test] - public void WriteExecuteRpc3() - { - uint id = 1; - uint uid = 1; - byte[] rpc = new byte[] {0,1,2,3,4}; - Message msg = Message.ExecuteRpc(id, uid, rpc); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)ExecuteRpc)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(uid)); - //Force Rpc as ExecuteRpc is Rpc - Value val = dec.ReadValue(NtType.Rpc); - Assert.That(val, Is.Not.Null); - Assert.That(val.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(val.GetRpc(), Is.EquivalentTo(rpc)); - } - - [Test] - public void WriteRpcResponse3() - { - uint id = 1; - uint uid = 1; - byte[] rpc = new byte[] { 0, 1, 2, 3, 4 }; - Message msg = Message.RpcResponse(id, uid, rpc); - WireEncoder enc = new WireEncoder(0x0300); - msg.Write(enc); - byte[] buf = enc.Buffer; - WireDecoder dec = new WireDecoder(new MemoryStream(buf), 0x0300); - byte u8 = 0; - ushort u16 = 0; - - Assert.That(dec.Read8(ref u8), Is.True); - Assert.That(u8, Is.EqualTo((byte)RpcResponse)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(id)); - Assert.That(dec.Read16(ref u16), Is.True); - Assert.That(u16, Is.EqualTo(uid)); - //Force Rpc as ExecuteRpc is Rpc - Value val = dec.ReadValue(NtType.Rpc); - Assert.That(val, Is.Not.Null); - Assert.That(val.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(val.GetRpc(), Is.EquivalentTo(rpc)); - } - } -} diff --git a/test/NetworkTables.Test/NetworkTables.Test.csproj b/test/NetworkTables.Test/NetworkTables.Test.csproj deleted file mode 100644 index 7173193..0000000 --- a/test/NetworkTables.Test/NetworkTables.Test.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net46;netcoreapp1.0 - $(NoWarn);CS0618 - NetworkTables.Test - NetworkTables.Test - true - false - false - false - - - - - - - - - - - - - - - - - - diff --git a/test/NetworkTables.Test/NetworkTablesApi/ErrorsTests.cs b/test/NetworkTables.Test/NetworkTablesApi/ErrorsTests.cs deleted file mode 100644 index 612615a..0000000 --- a/test/NetworkTables.Test/NetworkTablesApi/ErrorsTests.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using NetworkTables.Exceptions; -using NUnit.Framework; - -namespace NetworkTables.Test.NetworkTablesApi -{ - [TestFixture(true)] - [TestFixture(false)] - public class ErrorsTest - { - public ErrorsTest(bool server) - { - NetworkTable.SetIPAddress("localhost"); - NetworkTable.SetPort(10000); - if (server) - { - NetworkTable.SetServerMode(); - } - else - { - NetworkTable.SetClientMode(); - } - - NetworkTable.Initialize(); - } - - [OneTimeTearDown] - public void FixtureTearDown() - { - NetworkTable.Shutdown(); - } - - private NetworkTable m_nt; - - [SetUp] - public void SetUp() - { - TestBase.DeleteAllWithPersistent(); - m_nt = NetworkTable.GetTable(""); - } - - [Test] - public void TestBadPersistentFileRead() - { - Assert.Throws(() => - { - NetworkTable.LoadPersistent("invalid.txt"); - }); - } - - [Test] - public void TestPutEmptyName() - { - bool retVal = m_nt.PutNumber("emptyName", 3.14); - Assert.IsTrue(retVal); - } - - [Test] - public void TestPutNullName() - { - bool retVal = m_nt.PutNumber(null, 3.14); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullString() - { - Assert.Throws(() => - { - m_nt.PutString("nullString", null); - }, "Null string should not be allowed"); - - } - [Test] - public void TestPutEmptyString() - { - bool retVal = m_nt.PutString("emptyString", ""); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullStringArray() - { - Assert.Throws(() => - { - m_nt.PutStringArray("nullStringArray", null); - }, "Null array should not be allowed"); - } - [Test] - public void TestPutEmptyStringArray() - { - bool retVal = m_nt.PutStringArray("emptyStringArray", new string[0]); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullBooleanArray() - { - Assert.Throws(() => - { - m_nt.PutBooleanArray("nullBoolArray", null); - }, "Null array should not be allowed"); - } - [Test] - public void TestPutEmptyBooleanArray() - { - bool retVal = m_nt.PutBooleanArray("emptyBoolArray", new bool[0]); - Assert.IsTrue(retVal); - } - [Test] - public void TestPutNullDoubleArray() - { - Assert.Throws(() => - { - m_nt.PutNumberArray("nullNumberArray", null); - }, "Null array should not be allowed"); - } - [Test] - public void TestPutEmptyDoubleArray() - { - bool retVal = m_nt.PutNumberArray("emptyNumberArray", new double[0]); - Assert.IsTrue(retVal); - } - } -} \ No newline at end of file diff --git a/test/NetworkTables.Test/NetworkTablesApi/InstanceApiTest.cs b/test/NetworkTables.Test/NetworkTablesApi/InstanceApiTest.cs deleted file mode 100644 index 4c7ecdb..0000000 --- a/test/NetworkTables.Test/NetworkTablesApi/InstanceApiTest.cs +++ /dev/null @@ -1,985 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using NetworkTables.Exceptions; -using NetworkTables.Tables; -using NUnit.Framework; - -namespace NetworkTables.Test.NetworkTablesApi -{ - [TestFixture(true)] - [TestFixture(false)] - public class InstanceApiTest - { - private bool m_server = false; - - public InstanceApiTest(bool server) - { - NetworkTable.SetIPAddress("localhost"); - NetworkTable.SetPort(10000); - if (server) - { - NetworkTable.SetServerMode(); - } - else - { - NetworkTable.SetClientMode(); - } - m_server = server; - NetworkTable.Initialize(); - } - - [OneTimeTearDown] - public void FixtureTearDown() - { - NetworkTable.Shutdown(); - } - - private NetworkTable m_table; - - [SetUp] - public void TestSetup() - { - TestBase.DeleteAllWithPersistent(); - - m_table = NetworkTable.GetTable("Table"); - } - - [Test] - public void TestToString() - { - Assert.That(m_table.ToString(), Is.EqualTo("NetworkTable: /Table")); - } - - [Test] - public void TestIsServer() - { - Assert.That(m_table.IsServer, Is.EqualTo(m_server)); - } - - [Test] - public void TestContainsKeyNo() - { - Assert.That(!m_table.ContainsKey("Key")); - } - - [Test] - public void TestContainsKeyYes() - { - string key = "key"; - m_table.PutString(key, "value"); - Assert.That(m_table.ContainsKey(key)); - } - - [Test] - public void TestContainsSubTableFalse() - { - Assert.That(!m_table.ContainsSubTable("SubTable")); - } - - [Test] - public void TestContainsSubTableTrue() - { - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable(subTableName); - subTable.PutBoolean("MyKey", true); - - Assert.That(m_table.ContainsSubTable(subTableName)); - } - - [Test] - public void TestGetKeysAll() - { - string key1 = "FirstKey"; - string key2 = "SecondKey"; - - m_table.PutString(key1, "String1"); - m_table.PutString(key2, "String2"); - - HashSet keys = m_table.GetKeys(); - - Assert.That(keys.Contains(key1)); - Assert.That(keys.Contains(key2)); - } - - [Test] - public void TestGetKeysOnlyPersistent() - { - string key1 = "FirstKey"; - string key2 = "SecondKey"; - - m_table.PutString(key1, "String1"); - m_table.PutNumber(key2, 3.586); - m_table.SetPersistent(key2); - - HashSet keys = m_table.GetKeys(NtType.Double); - - Assert.That(!keys.Contains(key1)); - Assert.That(keys.Contains(key2)); - } - - [Test] - public void TestGetSubTables() - { - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable(subTableName); - subTable.PutBoolean("MyKey", true); - - string subTableName2 = "SubTable2"; - - ITable subTable2 = m_table.GetSubTable(subTableName2); - subTable2.PutBoolean("MyKey2", true); - - HashSet subTables = m_table.GetSubTables(); - - Assert.That(subTables.Contains(subTableName)); - Assert.That(subTables.Contains(subTableName2)); - } - - [Test] - public void TestSetPersistent() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetPersistent(key2); - - Assert.That(m_table.IsPersistent(key2)); - } - - [Test] - public void TestClearPersistent() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetPersistent(key2); - - Assert.That(m_table.IsPersistent(key2)); - - m_table.ClearPersistent(key2); - - Assert.That(!m_table.IsPersistent(key2)); - } - - [Test] - public void TestSetFlags() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetFlags(key2, EntryFlags.Persistent); - - Assert.That(m_table.GetFlags(key2), Is.EqualTo(EntryFlags.Persistent)); - } - - [Test] - public void TestClearFlags() - { - string key2 = "SecondKey"; - - m_table.PutString(key2, "String2"); - m_table.SetFlags(key2, EntryFlags.Persistent); - - Assert.That(m_table.GetFlags(key2), Is.EqualTo(EntryFlags.Persistent)); - - m_table.ClearFlags(key2, EntryFlags.Persistent); - - Assert.That(m_table.GetFlags(key2), Is.Not.EqualTo(EntryFlags.Persistent)); - } - - [Test] - public void TestDeleteKey() - { - string key = "MyKey"; - - m_table.PutString(key, "Value"); - - Assert.That(m_table.GetString(key), Is.EqualTo("Value")); - - m_table.Delete(key); - - Assert.Throws(() => m_table.GetString(key)); - } - - [Test] - public void TestDeleteAllEntries() - { - m_table.PutString("Test1", "val1"); - m_table.PutString("Test2", "val2"); - m_table.PutString("Test3", "val3"); - - Assert.That(m_table.GetKeys().Count, Is.EqualTo(3)); - - NetworkTable.GlobalDeleteAll(); - - Assert.That(m_table.GetKeys().Count, Is.EqualTo(0)); - } - - [Test] - public void TestSavePersistent() - { - string key1 = "key1"; - string toWrite1 = "val1"; - m_table.PutString(key1, toWrite1); - m_table.SetFlags(key1, EntryFlags.Persistent); - - string key2 = "key2"; - m_table.PutBoolean(key2, true); - m_table.SetFlags(key2, EntryFlags.Persistent); - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - NetworkTable.SavePersistent(fileName); - - string[] lines = File.ReadAllLines(fileName); - - Assert.That(lines.Length, Is.GreaterThanOrEqualTo(3)); - Assert.That(lines[0], Contains.Substring("[NetworkTables Storage 3.0]")); - Assert.That(lines[1], Contains.Substring($"string \"/Table/{key1}\"=\"{toWrite1}\"")); - Assert.That(lines[2], Contains.Substring($"boolean \"/Table/{key2}\"=true")); - } - - [Test] - public void TestLoadPersistent() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"/Table/{key1}\"=\"{val1}\"", - $"boolean \"/Table/{key2}\"=true", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NetworkTable.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(0)); - - HashSet entries = m_table.GetKeys(); - - Assert.That(entries.Count, Is.EqualTo(2)); - - Assert.That(m_table.GetString(key1, ""), Is.EqualTo(val1)); - Assert.That(m_table.GetBoolean(key2, false), Is.EqualTo(true)); - } - - [Test] - public void TestPersistentLoadError() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"/Table/{key1}\"=\"{val1}\"", - $"boolean \"/Table/{key2}\"=invalid", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NetworkTable.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(1)); - Assert.That(errors[0], Contains.Substring("3: unrecognized boolean value, not 'true' or 'false'")); - } - - #region Getters and Setters - - [Test] - [TestCase(3.56, ExpectedResult = 3.56)] - [TestCase(true, ExpectedResult = true)] - [TestCase("Hello", ExpectedResult = "Hello")] - [TestCase(new byte[] { 0, 5, 12, 0 }, ExpectedResult = new byte[] { 0, 5, 12, 0 })] - [TestCase(new double[] { 3.56, 5547.545 }, ExpectedResult = new double[] { 3.56, 5547.545 })] - [TestCase(new bool[] { false, true, true }, ExpectedResult = new bool[] { false, true, true })] - public object TestGetValue(object value) - { - string key = "key"; - if (value is double) - { - m_table.PutNumber(key, (double)value); - } - else if (value is string) - { - m_table.PutString(key, (string)value); - } - else if (value is bool) - { - m_table.PutBoolean(key, (bool)value); - } - else if (value is byte[]) - { - m_table.PutRaw(key, (byte[])value); - } - else if (value is double[]) - { - m_table.PutNumberArray(key, (double[])value); - } - else if (value is bool[]) - { - m_table.PutBooleanArray(key, (bool[])value); - } - else if (value is string[]) - { - m_table.PutStringArray(key, (string[])value); - } - else - { - throw new ArgumentException("Value is either null or an invalid type."); - } - return m_table.GetValue(key).GetObjectValue(); - } - - [Test] - public void TestGetValueStringArray() - { - string key = "key"; - string[] array = new[] { "Hello1", "Hello2" }; - - m_table.PutStringArray(key, array); - - var v = m_table.GetValue(key); - Assert.That(v, Is.Not.Null); - - Assert.That(v.GetStringArray(), Is.EquivalentTo(array)); - } - - [Test] - public void TestGetValueInvalid() - { - Assert.Throws(() => m_table.GetValue("key")); - } - - [Test] - [TestCase(3.56, ExpectedResult = 3.56)] - [TestCase(true, ExpectedResult = true)] - [TestCase("Hello", ExpectedResult = "Hello")] - [TestCase(new byte[] { 0, 5, 12, 0 }, ExpectedResult = new byte[] { 0, 5, 12, 0 })] - [TestCase(new double[] { 3.56, 5547.545 }, ExpectedResult = new double[] { 3.56, 5547.545 })] - [TestCase(new bool[] { false, true, true }, ExpectedResult = new bool[] { false, true, true })] - public object TestGetValueDefault(object value) - { - string key = "key"; - if (value is double) - { - m_table.PutNumber(key, (double)value); - } - else if (value is string) - { - m_table.PutString(key, (string)value); - } - else if (value is bool) - { - m_table.PutBoolean(key, (bool)value); - } - else if (value is byte[]) - { - m_table.PutRaw(key, (byte[])value); - } - else if (value is double[]) - { - m_table.PutNumberArray(key, (double[])value); - } - else if (value is bool[]) - { - m_table.PutBooleanArray(key, (bool[])value); - } - else if (value is string[]) - { - m_table.PutStringArray(key, (string[])value); - } - else - { - throw new ArgumentException("Value is either null or an invalid type."); - } - return m_table.GetValue(key, null).GetObjectValue(); - } - - [Test] - public void TestGetValueStringArrayDefault() - { - string key = "key"; - string[] array = new[] { "Hello1", "Hello2" }; - - m_table.PutStringArray(key, array); - - var v = m_table.GetValue(key); - Assert.That(v, Is.Not.Null); - - Assert.That(v.GetStringArray(), Is.EquivalentTo(array)); - } - - [Test] - public void TestGetValueInvalidDefault() - { - Assert.That(m_table.GetValue("key", Value.MakeString("value")), Is.EqualTo(Value.MakeString("value"))); - } - - // TODO: Rewrite - /* - [Test] - [TestCase(3.56, ExpectedResult = 3.56)] - [TestCase(true, ExpectedResult = true)] - [TestCase("Hello", ExpectedResult = "Hello")] - [TestCase(new byte[] { 0, 5, 12, 0 }, ExpectedResult = new byte[] { 0, 5, 12, 0 })] - [TestCase(new double[] { 3.56, 5547.545 }, ExpectedResult = new double[] { 3.56, 5547.545 })] - [TestCase(new bool[] { false, true, true }, ExpectedResult = new bool[] { false, true, true })] - public object TestPutValue(object value) - { - string key = "key"; - m_table.PutValue(key, value); - return m_table.GetValue(key); - } - */ - - [Test] - public void TestPutValueStringArray() - { - string key = "key"; - string[] array = new[] { "Hello1", "Hello2" }; - - m_table.PutValue(key, Value.MakeStringArray(array)); - - var v = m_table.GetValue(key); - Assert.That(v, Is.Not.Null); - - Assert.That(v.GetStringArray(), Is.EquivalentTo(array)); - } - - - [Test] - public void TestPutAndGetNumberValid() - { - string key = "key"; - double setVal = 5.88; - Assert.That(m_table.PutNumber(key, setVal)); - - Assert.That(m_table.GetNumber(key), Is.EqualTo(setVal).Within(0.01)); - } - - [Test] - public void TestPutAndGetNumberValidDefault() - { - string key = "key"; - double setVal = 5.88; - Assert.That(m_table.PutNumber(key, setVal)); - - Assert.That(m_table.GetNumber(key, 3343.232), Is.EqualTo(setVal).Within(0.01)); - } - - [Test] - public void TestPutNumberIntoWrongType() - { - string key = "key"; - double setVal = 5.88; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutNumber(key, setVal)); - } - - [Test] - public void TestGetNumberErrorDefault() - { - string key = "key"; - - double defaultVal = 123322.32123; - Assert.That(m_table.GetNumber(key, defaultVal), Is.EqualTo(defaultVal).Within(0.01)); - } - - [Test] - public void TestGetNumberErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetNumber(key)); - } - - [Test] - public void TestGetNumberErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetNumber(key)); - } - - - - - - - [Test] - public void TestPutAndGetBooleanValid() - { - string key = "key"; - bool setVal = true; - Assert.That(m_table.PutBoolean(key, setVal)); - - Assert.That(m_table.GetBoolean(key), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutAndGetBooleanValidDefault() - { - string key = "key"; - bool setVal = true; - Assert.That(m_table.PutBoolean(key, setVal)); - - Assert.That(m_table.GetBoolean(key, false), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutBooleanIntoWrongType() - { - string key = "key"; - bool setVal = true; - m_table.PutString(key, "string"); - Assert.That(!m_table.PutBoolean(key, setVal)); - } - - [Test] - public void TestGetBooleanErrorDefault() - { - string key = "key"; - - bool defaultVal = true; - Assert.That(m_table.GetBoolean(key, defaultVal), Is.EqualTo(defaultVal)); - } - - [Test] - public void TestGetBooleanErrorThrowsWrongType() - { - string key = "key"; - m_table.PutString(key, "string"); - - Assert.Throws(() => m_table.GetBoolean(key)); - } - - [Test] - public void TestGetBooleanErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetBoolean(key)); - } - - - - - - [Test] - public void TestPutAndGetStringValid() - { - string key = "key"; - string setVal = "string"; - Assert.That(m_table.PutString(key, setVal)); - - Assert.That(m_table.GetString(key), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutAndGetStringValidDefault() - { - string key = "key"; - string setVal = "string"; - Assert.That(m_table.PutString(key, setVal)); - - Assert.That(m_table.GetString(key, "Default"), Is.EqualTo(setVal)); - } - - [Test] - public void TestPutStringIntoWrongType() - { - string key = "key"; - string setVal = "string"; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutString(key, setVal)); - } - - [Test] - public void TestGetStringErrorDefault() - { - string key = "key"; - - string defaultVal = "string"; - Assert.That(m_table.GetString(key, defaultVal), Is.EqualTo(defaultVal)); - } - - [Test] - public void TestGetStringErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetString(key)); - } - - [Test] - public void TestGetStringErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetString(key)); - } - - - - [Test] - public void TestPutAndGetStringArrayValid() - { - string key = "key"; - string[] setVal = { - "string", - "string2", - "string3", - }; - Assert.That(m_table.PutStringArray(key, setVal)); - - Assert.That(m_table.GetStringArray(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetStringArrayValidDefault() - { - string key = "key"; - string[] setVal = { - "string", - "string2", - "string3", - }; - Assert.That(m_table.PutStringArray(key, setVal)); - - Assert.That(m_table.GetStringArray(key, new[] { "Default" }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutStringArrayIntoWrongType() - { - string key = "key"; - string[] setVal = { - "string", - "string2", - "string3", - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutStringArray(key, setVal)); - } - - [Test] - public void TestGetStringArrayErrorDefault() - { - string key = "key"; - - string[] defaultVal = { - "string", - "string2", - "string3", - }; - Assert.That(m_table.GetStringArray(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetStringArrayErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetStringArray(key)); - } - - [Test] - public void TestGetStringArrayErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetStringArray(key)); - } - - - - - [Test] - public void TestPutAndGetNumberArrayValid() - { - string key = "key"; - double[] setVal = { - 123.4, - 5.8, - 6.2, - }; - Assert.That(m_table.PutNumberArray(key, setVal)); - - Assert.That(m_table.GetNumberArray(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetNumberArrayValidDefault() - { - string key = "key"; - double[] setVal = { - 123.4, - 5.8, - 6.2, - }; - Assert.That(m_table.PutNumberArray(key, setVal)); - - Assert.That(m_table.GetNumberArray(key, new[] { 0.0 }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutNumberArrayIntoWrongType() - { - string key = "key"; - double[] setVal = { - 123.4, - 5.8, - 6.2, - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutNumberArray(key, setVal)); - } - - [Test] - public void TestGetNumberArrayErrorDefault() - { - string key = "key"; - - double[] defaultVal = { - 123.4, - 5.8, - 6.2, - }; - Assert.That(m_table.GetNumberArray(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetNumberArrayErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetNumberArray(key)); - } - - [Test] - public void TestGetNumberArrayErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetNumberArray(key)); - } - - - - [Test] - public void TestPutAndGetRawValid() - { - string key = "key"; - byte[] setVal = { - 123, - 5, - 6, - }; - Assert.That(m_table.PutRaw(key, setVal)); - - Assert.That(m_table.GetRaw(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetRawValidDefault() - { - string key = "key"; - byte[] setVal = { - 123, - 5, - 6, - }; - Assert.That(m_table.PutRaw(key, setVal)); - - Assert.That(m_table.GetRaw(key, new byte[] { 0 }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutRawIntoWrongType() - { - string key = "key"; - byte[] setVal = { - 123, - 5, - 6, - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutRaw(key, setVal)); - } - - [Test] - public void TestGetRawErrorDefault() - { - string key = "key"; - - byte[] defaultVal = { - 123, - 5, - 6, - }; - Assert.That(m_table.GetRaw(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetRawErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetRaw(key)); - } - - [Test] - public void TestGetRawErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetRaw(key)); - } - - - - - [Test] - public void TestPutAndGetBooleanArrayValid() - { - string key = "key"; - bool[] setVal = { - true, - false, - true, - }; - Assert.That(m_table.PutBooleanArray(key, setVal)); - - Assert.That(m_table.GetBooleanArray(key), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutAndGetBooleanArrayValidDefault() - { - string key = "key"; - bool[] setVal = { - true, - false, - true, - }; - Assert.That(m_table.PutBooleanArray(key, setVal)); - - Assert.That(m_table.GetBooleanArray(key, new[] { false }), Is.EquivalentTo(setVal)); - } - - [Test] - public void TestPutBooleanArrayIntoWrongType() - { - string key = "key"; - bool[] setVal = { - true, - false, - true, - }; - m_table.PutBoolean(key, true); - Assert.That(!m_table.PutBooleanArray(key, setVal)); - } - - [Test] - public void TestGetBooleanArrayErrorDefault() - { - string key = "key"; - - bool[] defaultVal = { - true, - false, - true, - }; - Assert.That(m_table.GetBooleanArray(key, defaultVal), Is.EquivalentTo(defaultVal)); - } - - [Test] - public void TestGetBooleanArrayErrorThrowsWrongType() - { - string key = "key"; - m_table.PutBoolean(key, true); - - Assert.Throws(() => m_table.GetBooleanArray(key)); - } - - [Test] - public void TestGetBooleanArrayErrorThrowsNotDefined() - { - string key = "key"; - - Assert.Throws(() => m_table.GetBooleanArray(key)); - } - #endregion - - // The below tests have no way to be checked, so we are just making sure they don't throw exceptions. - - - [Test] - public void TestSetNetworkIdentity() - { - NetworkTable.SetNetworkIdentity("UnitTests"); - - Assert.Pass(); - } - - [Test] - public void TestGetConnections() - { - Assert.That(NetworkTable.Connections(), Has.Count.EqualTo(0)); - } - - [Test] - public void TestIsConnected() - { - Assert.That(!m_table.IsConnected); - } - - [Test] - public void TestFlush() - { - NetworkTable.Flush(); - - Assert.Pass(); - } - - [Test] - public void TestSetUpdateRate() - { - NetworkTable.SetUpdateRate(100); - - Assert.Pass(); - } - } -} diff --git a/test/NetworkTables.Test/NetworkTablesApi/ListenersTest.cs b/test/NetworkTables.Test/NetworkTablesApi/ListenersTest.cs deleted file mode 100644 index 19c58d1..0000000 --- a/test/NetworkTables.Test/NetworkTablesApi/ListenersTest.cs +++ /dev/null @@ -1,502 +0,0 @@ -using System; -using System.Threading; -using NetworkTables.Tables; -using NUnit.Framework; - -namespace NetworkTables.Test.NetworkTablesApi -{ - internal class MockTableListener : ITableListener - { - public ITable Source = null; - public string Key = null; - public Value Value = null; - public NotifyFlags Flags = 0; - - public void ValueChanged(ITable source, string key, Value value, NotifyFlags flags) - { - Source = source; - Key = key; - Value = value; - Flags = flags; - } - } - - internal class MockConnectionListener : IRemoteConnectionListener - { - public IRemote ConnectedRemote = null; - public IRemote DisconnectedRemote = null; - - public void Connected(IRemote remote, ConnectionInfo info) - { - ConnectedRemote = remote; - } - - public void Disconnected(IRemote remote, ConnectionInfo info) - { - DisconnectedRemote = remote; - } - } - - - - [TestFixture(true)] - [TestFixture(false)] - public class ListenersTest - { - public ListenersTest(bool server) - { - NetworkTable.SetIPAddress("localhost"); - NetworkTable.SetPort(10000); - if (server) - { - NetworkTable.SetServerMode(); - } - else - { - NetworkTable.SetClientMode(); - } - - NetworkTable.Initialize(); - } - - [OneTimeTearDown] - public void FixtureTearDown() - { - NetworkTable.Shutdown(); - } - - private NetworkTable m_table; - - [SetUp] - public void SetUp() - { - TestBase.DeleteAllWithPersistent(); - m_table = NetworkTable.GetTable("Table"); - } - - [Test] - public void TestAddTableListenerExListenerFlags() - { - MockTableListener listener = new MockTableListener(); - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(listener, f); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(key)); - Assert.That(listener.Value.IsString()); - Assert.That(listener.Value.GetString(), Is.EqualTo(value)); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - string key2 = "key2"; - string val2 = "value2"; - - m_table.PutString(key2, val2); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(key2)); - Assert.That(listener.Value.IsString()); - Assert.That(listener.Value.GetString(), Is.EqualTo(val2)); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerExKeyListenerFlags() - { - MockTableListener listener = new MockTableListener(); - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(key, listener, f); - - m_table.PutString("Key2", "Value2"); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(key)); - Assert.That(listener.Value.IsString()); - Assert.That(listener.Value.GetString(), Is.EqualTo(value)); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddSubTableListenerListenerLocalNotify() - { - MockTableListener listener = new MockTableListener(); - - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable("SubTable"); - - m_table.AddSubTableListener(listener, true); - - string key = "key"; - string value = "Value"; - - subTable.PutString(key, value); - - Thread.Sleep(20); - - Assert.That(listener.Source, Is.EqualTo(m_table)); - Assert.That(listener.Key, Is.EqualTo(subTableName)); - Assert.That(listener.Value, Is.Null); - Assert.That(listener.Flags, Is.EqualTo(NotifyFlags.NotifyLocal | NotifyFlags.NotifyNew)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerEntireTableImmediateNotify() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener(listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerEntireTable() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListenerImmediateNotify() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener("key", listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListener() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddTableListener("key", listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddSubTableListenerNotLocal() - { - MockTableListener listener = new MockTableListener(); - - m_table.AddSubTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerExListenerFlagsDelegate() - { - ITable Source = null; - string Key = null; - Value Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, _f) => - { - Source = s; - Key = k; - Value = v; - Flags = _f; - }; - - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(listener, f); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(key)); - Assert.That(Value.IsString()); - Assert.That(Value.GetString(), Is.EqualTo(value)); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - string key2 = "key2"; - string val2 = "value2"; - - m_table.PutString(key2, val2); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(key2)); - Assert.That(Value.IsString()); - Assert.That(Value.GetString(), Is.EqualTo(val2)); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerExKeyListenerFlagsDelegate() - { - ITable Source = null; - string Key = null; - Value Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, _f) => - { - Source = s; - Key = k; - Value = v; - Flags = _f; - }; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal | NotifyFlags.NotifyImmediate; - - string key = "key"; - string value = "Value"; - - m_table.PutString(key, value); - - m_table.AddTableListenerEx(key, listener, f); - - m_table.PutString("Key2", "Value2"); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(key)); - Assert.That(Value.IsString()); - Assert.That(Value.GetString(), Is.EqualTo(value)); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyImmediate)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddSubTableListenerListenerLocalNotifyDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - string subTableName = "SubTable"; - - ITable subTable = m_table.GetSubTable("SubTable"); - - m_table.AddSubTableListener(listener, true); - - string key = "key"; - string value = "Value"; - - subTable.PutString(key, value); - - Thread.Sleep(20); - - Assert.That(Source, Is.EqualTo(m_table)); - Assert.That(Key, Is.EqualTo(subTableName)); - Assert.That(Value, Is.Null); - Assert.That(Flags, Is.EqualTo(NotifyFlags.NotifyLocal | NotifyFlags.NotifyNew)); - - m_table.RemoveTableListener(listener); - } - - [Test] - public void TestAddTableListenerEntireTableImmediateNotifyDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener(listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerEntireTableDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListenerImmediateNotifyDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener("key", listener, true); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddTableListenerKeyListenerDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddTableListener("key", listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - [Test] - public void TestAddSubTableListenerNotLocalDelegate() - { - ITable Source = null; - string Key = null; - object Value = null; - NotifyFlags Flags = 0; - - Action listener = (s, k, v, f) => - { - Source = s; - Key = k; - Value = v; - Flags = f; - }; - - m_table.AddSubTableListener(listener); - - Thread.Sleep(20); - - m_table.RemoveTableListener(listener); - - Assert.Pass(); - } - - - [Test] - public void TestConnectionListener() - { - MockConnectionListener listener = new MockConnectionListener(); - - m_table.AddConnectionListener(listener, true); - - Thread.Sleep(20); - m_table.RemoveConnectionListener(listener); - - Assert.Pass("If we have gotten here without an exception we pass. Cannot test more without a remote."); - } - } -} \ No newline at end of file diff --git a/test/NetworkTables.Test/NetworkTablesApi/StaticApiTest.cs b/test/NetworkTables.Test/NetworkTablesApi/StaticApiTest.cs deleted file mode 100644 index 32395fd..0000000 --- a/test/NetworkTables.Test/NetworkTablesApi/StaticApiTest.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using NUnit.Framework; - -namespace NetworkTables.Test.NetworkTablesApi -{ - [TestFixture] - public class StaticApiTest - { - [OneTimeSetUp] - public void FixtureSetup() - { - NetworkTable.Shutdown(); - } - - [OneTimeTearDown] - public void FixtureTeardown() - { - NetworkTable.Shutdown(); - NetworkTable.SetIPAddress("localhost"); - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - } - - [SetUp] - public void Setup() - { - NetworkTable.Shutdown(); - NetworkTable.SetIPAddress("localhost"); - } - - [Test] - public void TestDoubleInitializeServer() - { - NetworkTable.SetServerMode(); - Assert.That(NetworkTable.Client, Is.False); - NetworkTable.Initialize(); - Assert.DoesNotThrow(NetworkTable.Initialize); - } - - [Test] - public void TestDoubleInitializeClient() - { - NetworkTable.SetClientMode(); - Assert.That(NetworkTable.Client, Is.True); - NetworkTable.Initialize(); - Assert.DoesNotThrow(NetworkTable.Initialize); - } - - [Test] - public void TestClientShutdown() - { - NetworkTable.SetClientMode(); - NetworkTable.Initialize(); - Assert.That(NetworkTable.Running, Is.True); - NetworkTable.Shutdown(); - Assert.That(NetworkTable.Running, Is.False); - } - - [Test] - public void TestServerShutdown() - { - NetworkTable.SetServerMode(); - NetworkTable.Initialize(); - Assert.That(NetworkTable.Running, Is.True); - NetworkTable.Shutdown(); - Assert.That(NetworkTable.Running, Is.False); - } - - [Test] - public void TestSetClientModeWhileStopped() - { - NetworkTable.SetServerMode(); - Assert.That(NetworkTable.Client, Is.False); - NetworkTable.SetClientMode(); - Assert.That(NetworkTable.Client, Is.True); - NetworkTable.SetClientMode(); - Assert.That(NetworkTable.Client, Is.True); - } - - [Test] - public void TestSetClientModeWhileRunningServer() - { - NetworkTable.SetServerMode(); - Assert.That(NetworkTable.Client, Is.False); - NetworkTable.Initialize(); - Assert.Throws(NetworkTable.SetClientMode); - } - - /* - [Test] - public void TestSetTeam() - { - NetworkTable.SetTeam(1234); - Assert.That(NetworkTable.GetIPAddresses()[0], Is.EqualTo("roboRIO-1234-FRC.local")); - } - - [Test] - public void TestSetIpAddress() - { - NetworkTable.SetIPAddress("127.0.0.1"); - NetworkTable.SetIPAddress("10.12.34.2"); - Assert.That(NetworkTable.GetIPAddresses()[0], Is.EqualTo("10.12.34.2")); - } - */ - - [Test] - public void TestGetTableCausesInitialization() - { - Assert.That(NetworkTable.Running, Is.False); - NetworkTable.GetTable("empty"); - Assert.That(NetworkTable.Running, Is.True); - } - - [Test] - public void TestSetPersistentFilename() - { - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - Assert.That(NetworkTable.PersistentFilename, Is.EqualTo(NetworkTable.DefaultPersistentFileName)); - NetworkTable.SetPersistentFilename("TestFile.txt"); - Assert.That(NetworkTable.PersistentFilename, Is.EqualTo("TestFile.txt")); - NetworkTable.SetPersistentFilename(NetworkTable.DefaultPersistentFileName); - Assert.That(NetworkTable.PersistentFilename, Is.EqualTo(NetworkTable.DefaultPersistentFileName)); - } - - [Test] - public void TestLeadingSlash() - { - NetworkTable.GlobalDeleteAll(); - var nt = NetworkTable.GetTable("leadingslash"); - var nt2 = NetworkTable.GetTable("/leadingslash"); - Assert.That(nt.ContainsKey("testkey"), Is.False); - nt2.PutNumber("testkey", 5); - Assert.That(nt.ContainsKey("testkey"), Is.True); - } - - [Test] - public void TestStaticListeners() - { - NetworkTable.AddGlobalConnectionListener(((remote, info, conn) => - { - Console.WriteLine("Connected"); - }), true); - Assert.Pass(); - } - } -} diff --git a/test/NetworkTables.Test/NtCoreTests/ListenersTest.cs b/test/NetworkTables.Test/NtCoreTests/ListenersTest.cs deleted file mode 100644 index d9f826a..0000000 --- a/test/NetworkTables.Test/NtCoreTests/ListenersTest.cs +++ /dev/null @@ -1,369 +0,0 @@ -using System.Threading; -using NUnit.Framework; - -namespace NetworkTables.Test.NtCoreTests -{ - [TestFixture] - public class ListenersTest - { - [SetUp] - public void Setup() - { - TestBase.DeleteAllWithPersistent(); - } - - [OneTimeTearDown] - public void FixtureTearDown() - { - NtCore.StopNotifier(); - } - - [Test] - public void TestAddEntryListener() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyLocal; - - int listener = NtCore.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - string toWrite2 = "NewNumber"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite2)); - - Thread.Sleep(20); - - Assert.That(count, Is.GreaterThanOrEqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - Assert.That(recievedValue.IsString); - - var retValue = recievedValue.GetString(); - Assert.That(retValue, Is.Not.Null); - Assert.That(retValue, Is.EqualTo(toWrite2)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyLocal)); - - NtCore.RemoveEntryListener(listener); - } - - [Test] - public void TestAddEntryListenerImmediateNotify() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = NtCore.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(20); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - Assert.That(recievedValue.IsString); - - var retValue = recievedValue.GetString(); - Assert.That(retValue, Is.Not.Null); - Assert.That(retValue, Is.EqualTo(toWrite1)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - NtCore.RemoveEntryListener(listener); - } - - [TestCase(true)] - [TestCase(3.5)] - [TestCase("MyString")] - public void TestAddEntryListenerDefaultTypes(object val) - { - string key1 = "testKey"; - - if (val is double) NtCore.SetEntryValue(key1, Value.MakeDouble((double)val)); - else if (val is bool) - NtCore.SetEntryValue(key1, Value.MakeBoolean((bool)val)); - else if (val is string) NtCore.SetEntryValue(key1, Value.MakeString((string)val)); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = NtCore.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(20); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - if (val is double) - { - Assert.That(recievedValue.IsDouble()); - - var retValue = recievedValue.GetDouble(); - Assert.That(retValue, Is.EqualTo((double)val)); - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - } - else if (val is bool) - { - Assert.That(recievedValue.IsBoolean()); - - var retValue = recievedValue.GetBoolean(); - Assert.That(retValue, Is.EqualTo((bool)val)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - } - else if (val is string) - { - Assert.That(recievedValue.IsString); - - var retValue = recievedValue.GetString(); - Assert.That(retValue, Is.Not.Null); - Assert.That(retValue, Is.EqualTo((string)val)); - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - } - else - { - NtCore.RemoveEntryListener(listener); - Assert.Fail("Unknown type"); - return; - } - - NtCore.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerStringArray() - { - string key1 = "testKey"; - string[] toWrite1 = { "write1", "write2", "write3" }; - NtCore.SetEntryValue(key1, Value.MakeStringArray(toWrite1)); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = NtCore.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - Assert.That(recievedValue.IsStringArray()); - - string[] retValue = recievedValue.GetStringArray(); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - NtCore.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerRaw() - { - string key1 = "testKey"; - byte[] toWrite1 = { 56, 88, 92, 0, 0, 1 }; - NtCore.SetEntryValue(key1, Value.MakeRaw(toWrite1)); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = NtCore.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - Assert.That(recievedValue.IsRaw); - - byte[] retValue = recievedValue.GetRaw(); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - NtCore.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerDoubleArray() - { - string key1 = "testKey"; - double[] toWrite1 = { 3.58, 6.825, 454.54 }; - NtCore.SetEntryValue(key1, Value.MakeDoubleArray(toWrite1)); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = NtCore.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - Assert.That(recievedValue.IsDoubleArray); - - double[] retValue = recievedValue.GetDoubleArray(); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - NtCore.RemoveEntryListener(listener); - } - - [Test] - public void TestEntryListenerBooleanArray() - { - string key1 = "testKey"; - bool[] toWrite1 = { true, true, true }; - NtCore.SetEntryValue(key1, Value.MakeBooleanArray(toWrite1)); - - int count = 0; - string recievedKey = ""; - Value recievedValue = null; - NotifyFlags receivedFlags = 0; - - NotifyFlags f = NotifyFlags.NotifyNew | NotifyFlags.NotifyUpdate; - if (true) - f |= NotifyFlags.NotifyImmediate; - - int listener = NtCore.AddEntryListener(key1, (uid, key, value, flags) => - { - count++; - recievedKey = key; - recievedValue = value; - receivedFlags = flags; - }, f); - - Thread.Sleep(300); - - Assert.That(count, Is.EqualTo(1)); - Assert.That(recievedKey, Is.EqualTo(key1)); - Assert.That(recievedValue, Is.Not.Null); - - Assert.That(recievedValue.IsBooleanArray()); - - bool[] retValue = recievedValue.GetBooleanArray(); - - for (int i = 0; i < retValue.Length; i++) - { - Assert.That(retValue[i], Is.EqualTo(toWrite1[i])); - } - - Assert.That(receivedFlags.HasFlag(NotifyFlags.NotifyImmediate)); - - NtCore.RemoveEntryListener(listener); - } - - [Test] - public void TestAddRemoveConnectionListener() - { - ConnectionListenerCallback callback = (uid, connected, conn) => - { - - }; - - int id = NtCore.AddConnectionListener(callback, true); - - Assert.That(id, Is.Not.EqualTo(0)); - - NtCore.RemoveEntryListener(id); - } - } -} diff --git a/test/NetworkTables.Test/NtCoreTests/NativeInterfaceTest.cs b/test/NetworkTables.Test/NtCoreTests/NativeInterfaceTest.cs deleted file mode 100644 index ed01035..0000000 --- a/test/NetworkTables.Test/NtCoreTests/NativeInterfaceTest.cs +++ /dev/null @@ -1,297 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Threading; -using NUnit.Framework; - -namespace NetworkTables.Test.NtCoreTests -{ - [TestFixture] - public class NativeInterfaceTest - { - [SetUp] - public void Setup() - { - TestBase.DeleteAllWithPersistent(); - } - - [Test] - public void TestGetEntries() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - NtCore.SetEntryValue(key2, Value.MakeDouble(toWrite2)); - NtCore.SetEntryFlags(key2, EntryFlags.Persistent); - - string key3 = "testKey3"; - bool toWrite3 = true; - NtCore.SetEntryValue(key3, Value.MakeBoolean(toWrite3)); - - var entries = NtCore.GetEntryInfo("", 0); - - Assert.That(3, Is.EqualTo(entries.Count)); - - Assert.That(entries[0].Name, Is.EqualTo(key1)); - Assert.That(entries[0].Type, Is.EqualTo(NtType.String)); - Assert.That(entries[0].Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(entries[0].LastChange, Is.GreaterThan(0)); - Assert.That(entries[1].Name, Is.EqualTo(key2)); - Assert.That(entries[1].Type, Is.EqualTo(NtType.Double)); - Assert.That(entries[1].Flags, Is.EqualTo(EntryFlags.Persistent)); - Assert.That(entries[1].LastChange, Is.GreaterThan(0)); - Assert.That(entries[2].Name, Is.EqualTo(key3)); - Assert.That(entries[2].Type, Is.EqualTo(NtType.Boolean)); - Assert.That(entries[2].Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(entries[2].LastChange, Is.GreaterThan(0)); - } - - [Test] - public void TestGetEntriesOnlyString() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - NtCore.SetEntryValue(key2, Value.MakeDouble(toWrite2)); - - string key3 = "testKey3"; - bool toWrite3 = true; - NtCore.SetEntryValue(key3, Value.MakeBoolean(toWrite3)); - - Thread.Sleep(20); - - var entries = NtCore.GetEntryInfo("", NtType.String); - - Assert.That(1, Is.EqualTo(entries.Count)); - - Assert.That(entries[0].Name, Is.EqualTo(key1)); - Assert.That(entries[0].Type, Is.EqualTo(NtType.String)); - Assert.That(entries[0].Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(entries[0].LastChange, Is.GreaterThan(0)); - } - - [Test] - public void TestGetConnections() - { - var connection = NtCore.GetConnections(); - Assert.That(connection.Count, Is.EqualTo(0)); - } - - [Test] - public void TestSavePersistent() - { - string key1 = "key1"; - string toWrite1 = "val1"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - NtCore.SetEntryFlags(key1, EntryFlags.Persistent); - - string key2 = "key2"; - NtCore.SetEntryValue(key2, Value.MakeBoolean(true)); - NtCore.SetEntryFlags(key2, EntryFlags.Persistent); - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - NtCore.SavePersistent(fileName); - - string[] lines = File.ReadAllLines(fileName); - - Assert.That(lines.Length, Is.GreaterThanOrEqualTo(3)); - Assert.That(lines[0], Contains.Substring("[NetworkTables Storage 3.0]")); - Assert.That(lines[1], Contains.Substring($"string \"{key1}\"=\"{toWrite1}\"")); - Assert.That(lines[2], Contains.Substring($"boolean \"{key2}\"=true")); - } - - [Test] - public void TestLoadPersistent() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"{key1}\"=\"{val1}\"", - $"boolean \"{key2}\"=true", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NtCore.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(0)); - - var entries = NtCore.GetEntryInfo("", 0); - - Assert.That(entries.Count, Is.EqualTo(2)); - - Assert.That(NtCore.GetEntryValue(key1).GetString(), Is.EqualTo(val1)); - Assert.That(NtCore.GetEntryValue(key2).GetBoolean(), Is.EqualTo(true)); - } - - [Test] - public void TestPersistentLoadError() - { - const string key1 = "key1"; - const string key2 = "key2"; - const string val1 = "val1"; - - string[] toWrite = new[] - { - "[NetworkTables Storage 3.0]", - $"string \"{key1}\"=\"{val1}\"", - $"boolean \"{key2}\"=invalid", - "" - }; - - string fileName = "testfile.txt"; - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - File.WriteAllLines(fileName, toWrite); - - IList errors = NtCore.LoadPersistent(fileName); - - Assert.That(errors.Count, Is.EqualTo(1)); - Assert.That(errors[0], Contains.Substring("3: unrecognized boolean value, not 'true' or 'false'")); - } - - [Test] - public void TestDeleteEntry() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - NtCore.SetEntryValue(key2, Value.MakeDouble(toWrite2)); - - Assert.That(NtCore.GetEntryInfo("", 0).Count, Is.EqualTo(2)); - - NtCore.DeleteEntry(key1); - - Assert.That(NtCore.GetEntryInfo("", 0).Count, Is.EqualTo(1)); - - Assert.That(NtCore.GetEntryValue(key1), Is.Null); - } - - [Test] - public void TestDeleteAllEntries() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - string key2 = "testKey2"; - double toWrite2 = 3.58; - NtCore.SetEntryValue(key2, Value.MakeDouble(toWrite2)); - - Assert.That(NtCore.GetEntryInfo("", 0).Count, Is.EqualTo(2)); - - TestBase.DeleteAllWithPersistent(); - - Assert.That(NtCore.GetEntryInfo("", 0).Count, Is.EqualTo(0)); - - Assert.That(NtCore.GetEntryValue(key1), Is.Null); - Assert.That(NtCore.GetEntryValue(key2), Is.Null); - } - - [Test] - public void TestGetTypeSuccess() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - Assert.That(NtCore.GetType(key1), Is.EqualTo(NtType.String)); - } - - [Test] - public void TestGetTypeNonExistentKey() - { - Assert.That(NtCore.GetType("testKey"), Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void TestContainsKeySuccess() - { - string key1 = "testKey"; - string toWrite1 = "written"; - NtCore.SetEntryValue(key1, Value.MakeString(toWrite1)); - - Assert.That(NtCore.ContainsEntry(key1)); - } - - [Test] - public void TestContainsKeyNonExistentKey() - { - Assert.That(!NtCore.ContainsEntry("testKey")); - } - - [Test] - public void TestGetEntryFlags() - { - string key = "testKey"; - NtCore.SetEntryValue(key, Value.MakeString("value")); - - EntryFlags flags = NtCore.GetEntryFlags(key); - - Assert.That(flags, Is.EqualTo(EntryFlags.None)); - - NtCore.SetEntryFlags(key, EntryFlags.Persistent); - - flags = NtCore.GetEntryFlags(key); - - Assert.That(flags, Is.EqualTo(EntryFlags.Persistent)); - } - - [Test] - public void TestSetNetworkIdentity() - { - NtCore.SetNetworkIdentity("UnitTests"); - - Assert.Pass(); - } - - [Test] - public void TestFlush() - { - NtCore.Flush(); - - Assert.Pass(); - } - - [Test] - public void TestNow() - { - Assert.That(NtCore.Now(), Is.GreaterThan(0)); - } - - [Test] - public void TestSetUpdateRate() - { - NtCore.SetUpdateRate(100); - - Assert.Pass(); - } - } -} diff --git a/test/NetworkTables.Test/Properties/AssemblyInfo.cs b/test/NetworkTables.Test/Properties/AssemblyInfo.cs deleted file mode 100644 index 9175265..0000000 --- a/test/NetworkTables.Test/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("NetworkTables.Test")] -[assembly: AssemblyTrademark("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9b08e511-da74-4ba1-98c4-0b54cc6f0314")] diff --git a/test/NetworkTables.Test/RpcTest.cs b/test/NetworkTables.Test/RpcTest.cs deleted file mode 100644 index b5d28af..0000000 --- a/test/NetworkTables.Test/RpcTest.cs +++ /dev/null @@ -1,439 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture] - public class RpcTest - { - - [OneTimeTearDown] - public void FixtureTearDown() - { - NtCore.StopRpcServer(); - } - - [Test] - public void TestPolledRpc() - { - Console.WriteLine("TestPolledRpc"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(2.0) })); - - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(true, TimeSpan.FromSeconds(1), out info); - Assert.That(polled, Is.True); - - IList toSendBack = Callback1(info.Name, info.Params, new ConnectionInfo()); - Assert.That(toSendBack.Count, Is.Not.EqualTo(0)); - - RemoteProcedureCall.PostRpcResponse(info.RpcId, info.CallUid, toSendBack); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new [] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - - [Test] - public void TestPolledRpcAsync() - { - Console.WriteLine("TestPolledRpcAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(2.0) })); - - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.PollRpcAsync(source.Token); - bool completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted, Is.True); - Assert.That(task.Result, Is.Not.Null); - Assert.That(task.Result.HasValue); - - IList toSendBack = Callback1(task.Result.Value.Name, task.Result.Value.Params, new ConnectionInfo()); - Assert.That(toSendBack.Count, Is.Not.EqualTo(0)); - - RemoteProcedureCall.PostRpcResponse(task.Result.Value.RpcId, task.Result.Value.CallUid, toSendBack); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new [] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - - [Test] - public void TestPolledRpcTimeout() - { - Console.WriteLine("TestPolledRpcTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - TimeSpan timeoutTime = TimeSpan.FromSeconds(1); - Stopwatch sw = Stopwatch.StartNew(); - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(true, timeoutTime, out info); - sw.Stop(); - Assert.That(polled, Is.False); - TimeSpan tolerance = TimeSpan.FromSeconds(0.25); - Assert.That(sw.Elapsed < timeoutTime + tolerance); - Assert.That(sw.Elapsed > timeoutTime - tolerance); - } - - [Test] - public void TestPolledRpcNonBlocking() - { - Console.WriteLine("TestPolledRpcNonBlocking"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(false, out info); - Assert.That(polled, Is.False); - } - - [Test] - public void TestPolledRpcNonBlockingWithTimeout() - { - Console.WriteLine("TestPolledRpcNonBlockingWithTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreatePolledRpc("func1", def); - - Console.WriteLine("Calling RPC"); - - RpcCallInfo info; - bool polled = RemoteProcedureCall.PollRpc(false, TimeSpan.FromSeconds(1), out info); - Assert.That(polled, Is.False); - } - - private static IList Callback1(string names, byte[] paramsStr, ConnectionInfo connInfo) - { - var param = RemoteProcedureCall.UnpackRpcValues(paramsStr, new [] { NtType.Double }); - - if (param.Count == 0) - { - Console.Error.WriteLine("Empty Params?"); - return new byte[] { 0 }; - } - double val = param[0].GetDouble(); - - return RemoteProcedureCall.PackRpcValues(new [] {Value.MakeDouble(val + 1.2)}); - } - - [Test] - public void TestRpcLocal() - { - Console.WriteLine("TestRpcLocal"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new [] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeed() - { - Console.WriteLine("TestRpcSpeed"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1",NtType.Double) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(i) })); - byte[] call1Result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out call1Result); - var res = RemoteProcedureCall.UnpackRpcValues(call1Result, new [] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - - } - - [Test] - public void TestRpcLocalTimeoutFailure() - { - Console.WriteLine("LocalTimeoutFailure"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - TimeSpan timeoutTime = TimeSpan.FromSeconds(1); - Stopwatch sw = Stopwatch.StartNew(); - byte[] result = null; - bool success = RemoteProcedureCall.GetRpcResult(true, call1Uid, timeoutTime, out result); - sw.Stop(); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - TimeSpan tolerance = TimeSpan.FromSeconds(0.25); - Assert.That(sw.Elapsed < timeoutTime + tolerance); - Assert.That(sw.Elapsed > timeoutTime - tolerance); - } - - [Test] - public void TestRpcLocalNonBlocking() - { - Console.WriteLine("LoclaNonBlocking"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - bool success = RemoteProcedureCall.GetRpcResult(false, call1Uid, out result); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - } - - [Test] - public void TestRpcLocalNonBlockingWithTimeout() - { - Console.WriteLine("LocalNonBlockingWithTimeout"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = 585; - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - bool success = RemoteProcedureCall.GetRpcResult(false, call1Uid, TimeSpan.FromSeconds(1), out result); - Assert.That(success, Is.False); - Assert.That(result, Is.Null); - } - - [Test] - public void TestRpcLocalTimeoutSuccess() - { - Console.WriteLine("LocalTimeoutSuccess"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, TimeSpan.FromSeconds(1), out result); - Assert.That(result, Is.Not.Null); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new [] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedTimeoutSuccess() - { - Console.WriteLine("SpeedTimeoutSuccess"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(i) })); - byte[] call1Result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, TimeSpan.FromSeconds(1), out call1Result); - Assert.That(call1Result, Is.Not.Null); - var res = RemoteProcedureCall.UnpackRpcValues(call1Result, new [] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - - } - - [Test] - public void TestRpcLocalAsync() - { - Console.WriteLine("LocalAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(2.0) })); - - Console.WriteLine("Waiting for RPC Result"); - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.GetRpcResultAsync(call1Uid, source.Token); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var call1Result = RemoteProcedureCall.UnpackRpcValues(task.Result, new [] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedAsync() - { - Console.WriteLine("SpeedAsync"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(i) })); - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.GetRpcResultAsync(call1Uid, source.Token); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var res = RemoteProcedureCall.UnpackRpcValues(task.Result, new [] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - } - - [Test] - public void TestRpcLocalAsyncSingleCall() - { - Console.WriteLine("LocalAsyncSingleCall"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - - Console.WriteLine("Calling RPC"); - Console.WriteLine("Waiting for RPC Result"); - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.CallRpcWithResultAsync("func1", source.Token, RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(2.0) })); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var call1Result = RemoteProcedureCall.UnpackRpcValues(task.Result, new [] { NtType.Double }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - - [Test] - public void TestRpcSpeedAsyncSingleCall() - { - Console.WriteLine("SpeedAsyncSingleCall"); - var def = new RpcDefinition(1, "myfunc1", new List { new RpcParamDef("param1", Value.MakeDouble(0.0)) }, new List { new RpcResultsDef("result1", NtType.Double ) }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback1); - Stopwatch sw = new Stopwatch(); - sw.Start(); - for (int i = 0; i < 10000; ++i) - { - CancellationTokenSource source = new CancellationTokenSource(); - var task = RemoteProcedureCall.CallRpcWithResultAsync("func1", source.Token, RemoteProcedureCall.PackRpcValues(new [] { Value.MakeDouble(i) })); - var completed = task.Wait(TimeSpan.FromSeconds(1)); - if (!completed) source.Cancel(); - Assert.That(completed, Is.True); - Assert.That(task.IsCompleted); - var res = RemoteProcedureCall.UnpackRpcValues(task.Result, new [] { NtType.Double }); - Assert.AreNotEqual(0, res.Count, "RPC Result empty"); - } - sw.Stop(); - Console.WriteLine(sw.Elapsed); - } - - private static IList Callback2(string names, byte[] paramsStr, ConnectionInfo connInfo) - { - var param = RemoteProcedureCall.UnpackRpcValues(paramsStr, new [] { NtType.Boolean, NtType.BooleanArray, NtType.Double , NtType.DoubleArray, NtType.Raw, NtType.String, NtType.StringArray }); - - if (param.Count == 0) - { - Console.Error.WriteLine("Empty Params?"); - return new byte[] { 0 }; - } - - return RemoteProcedureCall.PackRpcValues(new [] {Value.MakeBoolean(true), Value.MakeBooleanArray(new[] { true, false }), Value.MakeDouble(2.2), Value.MakeDoubleArray(new[] { 2.8, 6.876 }), - Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 }), Value.MakeString("NewString"), Value.MakeStringArray(new[] { "String1", "String2" }) }); - } - - [Test] - public void TestRpcAllTypes() - { - Console.WriteLine("AllTypes"); - var def = new RpcDefinition(1, "myfunc1", new List - { - new RpcParamDef("param1", Value.MakeBoolean(true)), - new RpcParamDef("param2", Value.MakeBooleanArray(new[] { true, false })), - new RpcParamDef("param3", Value.MakeDouble(0.0)), - new RpcParamDef("param4", Value.MakeDoubleArray(new[] { 2.8, 6.87 })), - new RpcParamDef("param5", Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 })), - new RpcParamDef("param6", Value.MakeString("NewString")), - new RpcParamDef("param7", Value.MakeStringArray(new[] { "String1", "String2" })), - }, new List - { - new RpcResultsDef("result1", NtType.Boolean), - new RpcResultsDef("result2", NtType.BooleanArray), - new RpcResultsDef("result3", NtType.Double), - new RpcResultsDef("result4", NtType.DoubleArray), - new RpcResultsDef("result5", NtType.Raw), - new RpcResultsDef("result6", NtType.String), - new RpcResultsDef("result7", NtType.StringArray), - }); - - RemoteProcedureCall.CreateRpc("func1", RemoteProcedureCall.PackRpcDefinition(def), Callback2); - - Console.WriteLine("Calling RPC"); - - long call1Uid = RemoteProcedureCall.CallRpc("func1", RemoteProcedureCall.PackRpcValues(new [] {Value.MakeBoolean(true), Value.MakeBooleanArray(new[] { true, false }), Value.MakeDouble(2.2), Value.MakeDoubleArray(new[] { 2.8, 6.87 }), - Value.MakeRaw(new byte[] { 52, 0, 89, 0, 0, 98 }), Value.MakeString("NewString"), Value.MakeStringArray(new[] { "String1", "String2" })})); - - Console.WriteLine("Waiting for RPC Result"); - byte[] result = null; - RemoteProcedureCall.GetRpcResult(true, call1Uid, out result); - var call1Result = RemoteProcedureCall.UnpackRpcValues(result, new [] {NtType.Boolean, NtType.BooleanArray, NtType.Double, NtType.DoubleArray, NtType.Raw, NtType.String, NtType.StringArray }); - Assert.AreNotEqual(0, call1Result.Count, "RPC Result empty"); - - Console.WriteLine(call1Result[0].ToString()); - } - } -} diff --git a/test/NetworkTables.Test/SequenceNumberTest.cs b/test/NetworkTables.Test/SequenceNumberTest.cs deleted file mode 100644 index b7be738..0000000 --- a/test/NetworkTables.Test/SequenceNumberTest.cs +++ /dev/null @@ -1,139 +0,0 @@ -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture] - public class SequenceNumberTest - { - [Test] - public void ConstructDefault() - { - SequenceNumber num = default(SequenceNumber); - Assert.That(num.Value, Is.EqualTo(0)); - } - - [Test] - public void ConstructNew() - { - SequenceNumber num = new SequenceNumber(); - Assert.That(num.Value, Is.EqualTo(0)); - } - - [Test] - public void ConstructNewSetValue() - { - SequenceNumber num = new SequenceNumber(58); - Assert.That(num.Value, Is.EqualTo(58)); - } - - [Test] - public void ConstructCopy() - { - SequenceNumber num = new SequenceNumber(58); - Assert.That(num.Value, Is.EqualTo(58)); - SequenceNumber num2 = new SequenceNumber(num); - Assert.That(num.Value, Is.EqualTo(58)); - } - - [Test] - public void OperatorPlusPlusNonOverflow() - { - SequenceNumber num = new SequenceNumber(58); - Assert.That(num.Value, Is.EqualTo(58)); - num++; - Assert.That(num.Value, Is.EqualTo(59)); - } - - [Test] - public void OperatorPlusPlusOverflow() - { - SequenceNumber num = new SequenceNumber(0xFFFF); - Assert.That(num.Value, Is.EqualTo(0xFFFF)); - num++; - Assert.That(num.Value, Is.EqualTo(0)); - } - - [Test] - public void OperatorEquals() - { - SequenceNumber num = new SequenceNumber(58); - SequenceNumber num2 = new SequenceNumber(58); - Assert.That(num == num2); - } - - [Test] - public void OperatorNotEquals() - { - SequenceNumber num = new SequenceNumber(58); - SequenceNumber num2 = new SequenceNumber(59); - Assert.That(num != num2); - } - - [Test] - public void OperatorLessThenOrEqual() - { - SequenceNumber num = new SequenceNumber(58); - SequenceNumber num2 = new SequenceNumber(59); - Assert.That(num <= num2); - num++; - Assert.That(num <= num2); - num++; - Assert.That(num <= num2, Is.False); - } - - - [Test] - public void OperatorGreaterThenOrEqual() - { - SequenceNumber num = new SequenceNumber(58); - SequenceNumber num2 = new SequenceNumber(59); - Assert.That(num2 >= num); - num++; - Assert.That(num2 >= num); - num++; - Assert.That(num2 >= num, Is.False); - } - - [Test] - public void OperatorLessThenNotWrapAround() - { - SequenceNumber num = new SequenceNumber(58); - SequenceNumber num2 = new SequenceNumber(59); - Assert.That(num < num2); - num++; - Assert.That(num < num2, Is.False); - num++; - Assert.That(num < num2, Is.False); - } - - [Test] - public void OperatorGreaterThenNotWrapAround() - { - SequenceNumber num = new SequenceNumber(58); - SequenceNumber num2 = new SequenceNumber(59); - Assert.That(num2 > num); - num++; - Assert.That(num2 > num, Is.False); - num++; - Assert.That(num2 > num, Is.False); - } - - [Test] - public void ObjectEquals() - { - SequenceNumber num = new SequenceNumber(58); - SequenceNumber num2 = new SequenceNumber(58); - SequenceNumber num3 = new SequenceNumber(59); - - object oNum = num; - - Assert.That(num.Equals(num2)); - Assert.That(num.Equals(num)); - Assert.That(oNum.Equals(oNum)); - Assert.That(num.Equals(null), Is.False); - Assert.That(num.Equals(num3), Is.False); - Assert.That(num.Equals(new object()), Is.False); - - } - } -} diff --git a/test/NetworkTables.Test/StorageBaseTest.cs b/test/NetworkTables.Test/StorageBaseTest.cs deleted file mode 100644 index 7023e2a..0000000 --- a/test/NetworkTables.Test/StorageBaseTest.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Collections.Generic; -using static NetworkTables.Storage; - -namespace NetworkTables.Test -{ - public class StorageBaseTest - { - internal Entry tmpEntry; - - internal Storage storage; - - internal struct OutgoingData - { - public Message msg; - public NetworkConnection only; - public NetworkConnection except; - - public OutgoingData(Message m, NetworkConnection o, NetworkConnection e) - { - msg = m; - only = o; - except = e; - } - } - internal bool m_server = false; - - internal List outgoing = new List(); - - internal Dictionary Entries => storage.Entries; - internal List IdMap => storage.IdMap; - - internal Storage.Entry GetEntry(string name) - { - Storage.Entry i = null; - if (Entries.TryGetValue(name, out i)) - { - return i; - } - return tmpEntry; - } - - internal void HookOutgoing() - { - storage.SetOutgoing(QueueOutgoing, m_server); - } - - internal void QueueOutgoing(Message msg, NetworkConnection only, NetworkConnection except) - { - outgoing.Add(new OutgoingData(msg, only, except)); - } - - } -} diff --git a/test/NetworkTables.Test/StorageEmptyTest.cs b/test/NetworkTables.Test/StorageEmptyTest.cs deleted file mode 100644 index c8958b0..0000000 --- a/test/NetworkTables.Test/StorageEmptyTest.cs +++ /dev/null @@ -1,549 +0,0 @@ -using System; -using System.IO; -using System.Text; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture(true)] - [TestFixture(false)] - public class StorageEmptyTest : StorageBaseTest - { - public StorageEmptyTest(bool server) - { - m_server = server; - } - - [SetUp] - public void Clear() - { - tmpEntry = new Storage.Entry("foobar"); - storage?.Dispose(); - storage = new Storage(); - outgoing.Clear(); - - HookOutgoing(); - } - - [Test] - public void EntryInit() - { - - var entry = GetEntry("foo"); - Assert.That(entry.Value, Is.Null); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(entry.Name, Is.EqualTo("foobar")); - Assert.That(entry.Id, Is.EqualTo(0xffffu)); - Assert.That(new SequenceNumber() == entry.SeqNum); - } - - [Test] - public void GetEntryValueNotExist() - { - - Assert.That(storage.GetEntryValue("foo"), Is.Null); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void GetEntyValueExist() - { - - var value = Value.MakeBoolean(true); - storage.SetEntryTypeValue("foo", value); - outgoing.Clear(); - Assert.That(value, Is.EqualTo(storage.GetEntryValue("foo"))); - } - - [Test] - public void SetEntryTypeValueAssignNew() - { - - var value = Value.MakeBoolean(true); - storage.SetEntryTypeValue("foo", value); - Assert.That(value, Is.EqualTo(GetEntry("foo").Value)); - if (m_server) - { - Assert.That(IdMap, Has.Count.EqualTo(1)); - Assert.That(value, Is.EqualTo(IdMap[0].Value)); - } - else - { - Assert.That(IdMap, Is.Empty); - } - - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - - var msg = outgoing[0].msg; - - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryAssign)); - - Assert.That(msg.Str, Is.EqualTo("foo")); - - if (m_server) - { - Assert.That(msg.Id, Is.EqualTo(0u)); - } - else - { - Assert.That(msg.Id, Is.EqualTo(0xffffu)); - } - - Assert.That(msg.SeqNumUid, Is.EqualTo(1u)); - Assert.That(msg.Val, Is.EqualTo(value)); - Assert.That(msg.Flags, Is.EqualTo(0u)); - } - - [Test] - public void SetEntryTypeValueEmptyName() - { - - var value = Value.MakeBoolean(true); - storage.SetEntryTypeValue("", value); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryTypeValueNullName() - { - - var value = Value.MakeBoolean(true); - storage.SetEntryTypeValue(null, value); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryValueEmptyValue() - { - - storage.SetEntryTypeValue(null, null); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetDefaultEntryAssignNew() - { - var value = Value.MakeBoolean(true); - var retVal = storage.SetDefaultEntryValue("foo", value); - Assert.That(retVal, Is.True); - Assert.That(value, Is.EqualTo(GetEntry("foo").Value)); - - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryAssign)); - Assert.That(msg.Str, Is.EqualTo("foo")); - if (m_server) - { - Assert.That(msg.Id, Is.EqualTo(0));//Assigned as server - } - else - { - Assert.That(msg.Id, Is.EqualTo(0xffff)); - } - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Val, Is.EqualTo(value)); - Assert.That(msg.Flags, Is.EqualTo(0)); - } - - [Test] - public void SetDefaultEntryEmptyName() - { - var value = Value.MakeBoolean(true); - var retVal = storage.SetDefaultEntryValue("", value); - Assert.That(retVal, Is.False); - var entry = GetEntry("foo"); - Assert.That(entry.Value, Is.Null); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.None)); - Assert.That("foobar", Is.EqualTo(entry.Name)); // since GetEntry uses the tmp_entry - Assert.That(0xffff, Is.EqualTo(entry.Id)); - Assert.That(new SequenceNumber(), Is.EqualTo(entry.SeqNum)); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetDefaultEntryNullName() - { - var value = Value.MakeBoolean(true); - var retVal = storage.SetDefaultEntryValue(null, value); - Assert.That(retVal, Is.False); - var entry = GetEntry("foo"); - Assert.That(entry.Value, Is.Null); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.None)); - Assert.That("foobar", Is.EqualTo(entry.Name)); // since GetEntry uses the tmp_entry - Assert.That(0xffff, Is.EqualTo(entry.Id)); - Assert.That(new SequenceNumber(), Is.EqualTo(entry.SeqNum)); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetDefaultEntryEmptyValue() - { - var retVal = storage.SetDefaultEntryValue("", null); - Assert.That(retVal, Is.False); - var entry = GetEntry("foo"); - Assert.That(entry.Value, Is.Null); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.None)); - Assert.That("foobar", Is.EqualTo(entry.Name)); // since GetEntry uses the tmp_entry - Assert.That(0xffff, Is.EqualTo(entry.Id)); - Assert.That(new SequenceNumber(), Is.EqualTo(entry.SeqNum)); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryValueAssignNew() - { - - var value = Value.MakeBoolean(true); - Assert.That(storage.SetEntryValue("foo", value), Is.True); - Assert.That(value, Is.EqualTo(GetEntry("foo").Value)); - - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryAssign)); - Assert.That(msg.Str, Is.EqualTo("foo")); - if (m_server) - { - Assert.That(msg.Id, Is.EqualTo(0));//Assigned as server - } - else - { - Assert.That(msg.Id, Is.EqualTo(0xffff)); - } - Assert.That(msg.SeqNumUid, Is.EqualTo(0)); - Assert.That(msg.Val, Is.EqualTo(value)); - Assert.That(msg.Flags, Is.EqualTo(0)); - } - - [Test] - public void SetEntryValueEmptyName() - { - - var value = Value.MakeBoolean(true); - Assert.That(storage.SetEntryValue("", value), Is.True); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryValueNullName() - { - - var value = Value.MakeBoolean(true); - Assert.That(storage.SetEntryValue(null, value), Is.True); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryFlagsNew() - { - - storage.SetEntryFlags("foo", 0); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryFlagsEmptyName() - { - - storage.SetEntryFlags("", EntryFlags.None); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryFlagsNullName() - { - - storage.SetEntryFlags(null, EntryFlags.None); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void GetEntryFlagsNotExist() - { - - Assert.That(storage.GetEntryFlags("foo"), Is.EqualTo(EntryFlags.None)); - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void DeleteEntryNotExist() - { - - storage.DeleteEntry("foo"); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void DeleteAllEntriesEmpty() - { - - storage.DeleteAllEntries(); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void LoadPersistentBadHeader() - { - - int lastLine = -1; - string lastString = string.Empty; - - - - Action warnFunc = (int line, string msg) => - { - lastLine = line; - lastString = msg; - }; - - using (MemoryStream stream = new MemoryStream()) - { - Assert.That(storage.LoadPersistent(stream, warnFunc), Is.False); - Assert.That(lastLine, Is.EqualTo(1)); - Assert.That(lastString, Is.EqualTo("header line mismatch, ignoring rest of file")); - } - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("[NetworkTables"))) - { - Assert.That(storage.LoadPersistent(stream, warnFunc), Is.False); - Assert.That(lastLine, Is.EqualTo(1)); - Assert.That(lastString, Is.EqualTo("header line mismatch, ignoring rest of file")); - } - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void LoadPersistentCommentHeader() - { - - int lastLine = -1; - string lastString = string.Empty; - - Action warnFunc = (int line, string msg) => - { - lastLine = line; - lastString = msg; - }; - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("\n; comment\n# comment\n[NetworkTables Storage 3.0]\n"))) - { - Assert.That(storage.LoadPersistent(stream, warnFunc), Is.True); - Assert.That(lastLine, Is.EqualTo(-1)); - Assert.That(lastString, Is.Empty); - } - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void LoadPersistentEmptyName() - { - - int lastLine = -1; - string lastString = string.Empty; - - Action warnFunc = (int line, string msg) => - { - lastLine = line; - lastString = msg; - }; - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("[NetworkTables Storage 3.0]\nboolean \"\"=true\n"))) - { - Assert.That(storage.LoadPersistent(stream, warnFunc), Is.True); - Assert.That(lastLine, Is.EqualTo(-1)); - Assert.That(lastString, Is.Empty); - } - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void LoadPersistentAssign() - { - - int lastLine = -1; - string lastString = string.Empty; - - Action warnFunc = (int line, string mg) => - { - lastLine = line; - lastString = mg; - }; - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("[NetworkTables Storage 3.0]\nboolean \"foo\"=true\n"))) - { - Assert.That(storage.LoadPersistent(stream, warnFunc), Is.True); - Assert.That(lastLine, Is.EqualTo(-1)); - Assert.That(lastString, Is.Empty); - } - var entry = GetEntry("foo"); - Assert.That(Value.MakeBoolean(true) == entry.Value); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.Persistent)); - - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryAssign)); - Assert.That(msg.Str, Is.EqualTo("foo")); - if (m_server) - { - Assert.That(msg.Id, Is.EqualTo(0)); - } - else - { - Assert.That(msg.Id, Is.EqualTo(0xffff)); - } - Assert.That(msg.SeqNumUid, Is.EqualTo(1)); - Assert.That(Value.MakeBoolean(true) == msg.Val); - - Assert.That(msg.Flags, Is.EqualTo((uint)EntryFlags.Persistent)); - } - - [Test] - public void LoadPersistent() - { - - - int lastLine = -1; - string lastString = String.Empty; - - Action warn_func = (int line, string mg) => - { - lastLine = line; - lastString = mg; - }; - - string specialLargeDigits = "\0\xAE\xFF\n"; - - string i = "[NetworkTables Storage 3.0]\n"; - i += "boolean \"\\x00\\x03\\x05\\n\"=true\n"; - i += "boolean \"\\x00\\xAE\\xFF\\n\"=false\n"; - i += "boolean \"\\x3D\"=true\n"; - i += "boolean \"boolean/false\"=false\n"; - i += "boolean \"boolean/true\"=true\n"; - i += "array boolean \"booleanarr/empty\"=\n"; - i += "array boolean \"booleanarr/one\"=true\n"; - i += "array boolean \"booleanarr/two\"=true,false\n"; - i += "double \"double/big\"=1.3e+08\n"; - i += "double \"double/neg\"=-1.5\n"; - i += "double \"double/zero\"=0\n"; - i += "array double \"doublearr/empty\"=\n"; - i += "array double \"doublearr/one\"=0.5\n"; - i += "array double \"doublearr/two\"=0.5,-0.25\n"; - i += "raw \"raw/empty\"=\n"; - i += "raw \"raw/normal\"=aGVsbG8=\n"; - i += "raw \"raw/special\"=AAMFCg==\n"; - i += "raw \"raw/speciallarge\"=AMKuw78K\n"; - i += "string \"string/empty\"=\"\"\n"; - i += "string \"string/normal\"=\"hello\"\n"; - i += "string \"string/special\"=\"\\x00\\x03\\x05\\n\"\n"; - i += "string \"string/speciallarge\"=\"\\x00\\xAE\\xFF\\n\"\n"; - i += "string \"string/paranth\"=\"M\\\"Q\"\n"; - i += "array string \"stringarr/empty\"=\n"; - i += "array string \"stringarr/one\"=\"hello\"\n"; - i += "array string \"stringarr/two\"=\"hello\",\"world\\n\"\n"; - - using (MemoryStream iss = new MemoryStream()) - { - StreamWriter writer = new StreamWriter(iss); - writer.Write(i); - writer.Flush(); - iss.Position = 0; - Assert.That(storage.LoadPersistent(iss, warn_func), Is.True); - } - Assert.That(Entries, Has.Count.EqualTo(26)); - Assert.That(outgoing, Has.Count.EqualTo(26)); - - string s = "\0\x03\x05\n"; - - Assert.That(Value.MakeBoolean(true) == storage.GetEntryValue("boolean/true")); - Assert.That(Value.MakeBoolean(false) == storage.GetEntryValue("boolean/false")); - Assert.That(Value.MakeDouble(-1.5) == storage.GetEntryValue("double/neg")); - Assert.That(Value.MakeDouble(0.0) == storage.GetEntryValue("double/zero")); - Assert.That(Value.MakeDouble(1.3e8) == storage.GetEntryValue("double/big")); - Assert.That(Value.MakeString("") == storage.GetEntryValue("string/empty")); - Assert.That(Value.MakeString("hello") == storage.GetEntryValue("string/normal")); - Assert.That(Value.MakeString(s) == storage.GetEntryValue("string/special")); - Assert.That(Value.MakeString(specialLargeDigits) == storage.GetEntryValue("string/speciallarge")); - Assert.That(Value.MakeString("M\"Q") == storage.GetEntryValue("string/paranth")); - Assert.That(Value.MakeRaw() == storage.GetEntryValue("raw/empty")); - Assert.That(Value.MakeRaw(Encoding.UTF8.GetBytes("hello")) == storage.GetEntryValue("raw/normal")); - Assert.That(Value.MakeRaw(Encoding.UTF8.GetBytes(s)) == storage.GetEntryValue("raw/special")); - Assert.That(Value.MakeRaw(Encoding.UTF8.GetBytes(specialLargeDigits)) == storage.GetEntryValue("raw/speciallarge")); - Assert.That(Value.MakeBooleanArray() == storage.GetEntryValue("booleanarr/empty")); - Assert.That(Value.MakeBooleanArray(true) == storage.GetEntryValue("booleanarr/one")); - Assert.That(Value.MakeBooleanArray(true, false) == storage.GetEntryValue("booleanarr/two")); - Assert.That(Value.MakeDoubleArray() == storage.GetEntryValue("doublearr/empty")); - Assert.That(Value.MakeDoubleArray(0.5) == storage.GetEntryValue("doublearr/one")); - Assert.That(Value.MakeDoubleArray(0.5, -0.25) == storage.GetEntryValue("doublearr/two")); - Assert.That(Value.MakeStringArray() == storage.GetEntryValue("stringarr/empty")); - Assert.That(Value.MakeStringArray("hello") == storage.GetEntryValue("stringarr/one")); - Assert.That(Value.MakeStringArray("hello", "world\n") == storage.GetEntryValue("stringarr/two")); - Assert.That(Value.MakeBoolean(true) == storage.GetEntryValue(s)); - Assert.That(Value.MakeBoolean(false) == storage.GetEntryValue(specialLargeDigits)); - Assert.That(Value.MakeBoolean(true) == storage.GetEntryValue("=")); - } - - [Test] - public void LoadPersistentWarn() - { - - - int lastLine = -1; - string lastString = string.Empty; - - Action warn_func = (int line, string mg) => - { - lastLine = line; - lastString = mg; - }; - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("[NetworkTables Storage 3.0]\nboolean \"foo\"=foo\n"))) - { - Assert.That(storage.LoadPersistent(stream, warn_func), Is.True); - Assert.That(lastLine, Is.EqualTo(2)); - Assert.That(lastString, Is.EqualTo("unrecognized boolean value, not 'true' or 'false'")); - } - Assert.That(Entries, Is.Empty); - Assert.That(IdMap, Is.Empty); - Assert.That(outgoing, Is.Empty); - } - } -} diff --git a/test/NetworkTables.Test/StorageTestPersistent.cs b/test/NetworkTables.Test/StorageTestPersistent.cs deleted file mode 100644 index 0862e38..0000000 --- a/test/NetworkTables.Test/StorageTestPersistent.cs +++ /dev/null @@ -1,222 +0,0 @@ -using System.IO; -using System.Text; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture(true)] - [TestFixture(false)] - public class StorageTestPersistent : StorageBaseTest - { - public StorageTestPersistent(bool server) - { - m_server = server; - } - - [SetUp] - public void Clear() - { - tmpEntry = new Storage.Entry("foobar"); - storage?.Dispose(); - storage = new Storage(); - outgoing.Clear(); - - HookOutgoing(); - - string s = "\0\x03\x05\n"; - string specialLargeDigits = "\0\xAE\xFF\n"; - - storage.SetEntryTypeValue("boolean/true", Value.MakeBoolean(true)); - storage.SetEntryTypeValue("boolean/false", Value.MakeBoolean(false)); - storage.SetEntryTypeValue("double/neg", Value.MakeDouble(-1.5)); - storage.SetEntryTypeValue("double/zero", Value.MakeDouble(0.0)); - storage.SetEntryTypeValue("double/big", Value.MakeDouble(1.3e8)); - storage.SetEntryTypeValue("string/empty", Value.MakeString("")); - storage.SetEntryTypeValue("string/normal", Value.MakeString("hello")); - storage.SetEntryTypeValue("string/special", - Value.MakeString(s)); - storage.SetEntryTypeValue("string/speciallarge", - Value.MakeString(specialLargeDigits)); - storage.SetEntryTypeValue("string/paranth", Value.MakeString("M\"Q")); - storage.SetEntryTypeValue("raw/empty", Value.MakeRaw()); - storage.SetEntryTypeValue("raw/normal", Value.MakeRaw(Encoding.UTF8.GetBytes("hello"))); - storage.SetEntryTypeValue("raw/special", - Value.MakeRaw(Encoding.UTF8.GetBytes(s))); - storage.SetEntryTypeValue("raw/speciallarge", - Value.MakeRaw(Encoding.UTF8.GetBytes(specialLargeDigits))); - storage.SetEntryTypeValue("booleanarr/empty", - Value.MakeBooleanArray()); - storage.SetEntryTypeValue("booleanarr/one", - Value.MakeBooleanArray(true)); - storage.SetEntryTypeValue("booleanarr/two", - Value.MakeBooleanArray(true, false)); - storage.SetEntryTypeValue("doublearr/empty", - Value.MakeDoubleArray()); - storage.SetEntryTypeValue("doublearr/one", - Value.MakeDoubleArray(0.5)); - storage.SetEntryTypeValue( - "doublearr/two", - Value.MakeDoubleArray(0.5, -0.25)); - storage.SetEntryTypeValue( - "stringarr/empty", Value.MakeStringArray()); - storage.SetEntryTypeValue( - "stringarr/one", - Value.MakeStringArray("hello")); - storage.SetEntryTypeValue( - "stringarr/two", - Value.MakeStringArray("hello", "world\n")); - storage.SetEntryTypeValue(s, - Value.MakeBoolean(true)); - storage.SetEntryTypeValue(specialLargeDigits, - Value.MakeBoolean(false)); - storage.SetEntryTypeValue("=", Value.MakeBoolean(true)); - outgoing.Clear(); - } - - [Test] - public void TestStoragePersistentSavePersistentEmpty() - { - using (var s = new MemoryStream()) - { - storage.SavePersistent(s, false); - s.Position = 0; - using (var r = new StreamReader(s)) - { - Assert.That(r.ReadToEnd(), Is.EqualTo("[NetworkTables Storage 3.0]\n")); - } - } - } - - [Test] - public void TestStoragePersistentSavePersistent() - { - foreach (var entry in Entries) - { - entry.Value.Flags = EntryFlags.Persistent; - } - - using (var s = new MemoryStream()) - { - storage.SavePersistent(s, false); - s.Position = 0; - string o = ""; - using (var r = new StreamReader(s)) - { - o = r.ReadToEnd(); - } - var rem = o; - string[] split = rem.Split(new[] { '\n' }, 2); - var line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("[NetworkTables Storage 3.0]")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("boolean \"\\x00\\x03\\x05\\n\"=true")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("boolean \"\\x00\\xAE\\xFF\\n\"=false")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("boolean \"\\x3D\"=true")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("boolean \"boolean/false\"=false")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("boolean \"boolean/true\"=true")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array boolean \"booleanarr/empty\"=")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array boolean \"booleanarr/one\"=true")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array boolean \"booleanarr/two\"=true,false")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("double \"double/big\"=130000000")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("double \"double/neg\"=-1.5")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("double \"double/zero\"=0")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array double \"doublearr/empty\"=")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array double \"doublearr/one\"=0.5")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array double \"doublearr/two\"=0.5,-0.25")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("raw \"raw/empty\"=")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("raw \"raw/normal\"=aGVsbG8=")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("raw \"raw/special\"=AAMFCg==")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("raw \"raw/speciallarge\"=AMKuw78K")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("string \"string/empty\"=\"\"")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("string \"string/normal\"=\"hello\"")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("string \"string/paranth\"=\"M\\\"Q\"")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("string \"string/special\"=\"\\x00\\x03\\x05\\n\"")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("string \"string/speciallarge\"=\"\\x00\\xAE\\xFF\\n\"")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array string \"stringarr/empty\"=")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array string \"stringarr/one\"=\"hello\"")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - rem = split[1]; - Assert.That(line, Is.EqualTo("array string \"stringarr/two\"=\"hello\",\"world\\n\"")); - split = rem.Split(new[] { '\n' }, 2); - line = split[0]; - Assert.That(line, Is.EqualTo("")); - } - } - } -} diff --git a/test/NetworkTables.Test/StorageTestPopulateOne.cs b/test/NetworkTables.Test/StorageTestPopulateOne.cs deleted file mode 100644 index b992107..0000000 --- a/test/NetworkTables.Test/StorageTestPopulateOne.cs +++ /dev/null @@ -1,122 +0,0 @@ -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture(true)] - [TestFixture(false)] - public class StorageTestPopulateOne : StorageBaseTest - { - public StorageTestPopulateOne(bool server) - { - m_server = server; - } - - [SetUp] - public void Clear() - { - tmpEntry = new Storage.Entry("foobar"); - storage?.Dispose(); - storage = new Storage(); - outgoing.Clear(); - - HookOutgoing(); - - storage.SetEntryTypeValue("foo", Value.MakeBoolean(true)); - outgoing.Clear(); - } - - [Test] - public void SetDefaultEntryExistsSameType() - { - var value = Value.MakeBoolean(true); - var retVal = storage.SetDefaultEntryValue("foo", value); - Assert.That(retVal, Is.True); - Assert.That(!ReferenceEquals(value, GetEntry("foo").Value)); - - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetDefaultEntryExistsDifferentType() - { - // existing entry is boolean - var value = Value.MakeDouble(2.0); - var retVal = storage.SetDefaultEntryValue("foo", value); - Assert.That(retVal, Is.False); - // should not have updated value in table if it already existed - Assert.That(value, Is.Not.EqualTo(GetEntry("foo").Value)); - - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryTypeValueAssignChangeType() - { - var value = Value.MakeDouble(0.0); - storage.SetEntryTypeValue("foo", value); - Assert.That(value, Is.EqualTo(GetEntry("foo").Value)); - - Assert.That(outgoing, Has.Count.EqualTo(1u)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - - var msg = outgoing[0].msg; - - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryAssign)); - - Assert.That(msg.Str, Is.EqualTo("foo")); - - if (m_server) - { - Assert.That(msg.Id, Is.EqualTo(0u)); - } - else - { - Assert.That(msg.Id, Is.EqualTo(0xffffu)); - } - - Assert.That(msg.SeqNumUid, Is.EqualTo(2u)); - Assert.That(msg.Val, Is.EqualTo(value)); - Assert.That(msg.Flags, Is.EqualTo(0u)); - } - - [Test] - public void SetEntryTypeEqualValue() - { - var value = Value.MakeBoolean(true); - storage.SetEntryTypeValue("foo", value); - Assert.That(value, Is.EqualTo(GetEntry("foo").Value)); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryValueAssignTypeChange() - { - //Update with different type reuslts in error and no message - var value = Value.MakeDouble(0.0); - Assert.That(storage.SetEntryValue("foo", value), Is.False); - var entry = GetEntry("foo"); - Assert.That(entry.Value, Is.Not.EqualTo(value)); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetEntryFlagsEqualValue() - { - //update with same value, no update message is issued - storage.SetEntryFlags("foo", 0); - var entry = GetEntry("foo"); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.None)); - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void GetEntryFlagsExist() - { - storage.SetEntryFlags("foo", EntryFlags.Persistent); - outgoing.Clear(); - Assert.That(storage.GetEntryFlags("foo"), Is.EqualTo(EntryFlags.Persistent)); - Assert.That(outgoing, Is.Empty); - } - } -} diff --git a/test/NetworkTables.Test/StorageTestPopulated.cs b/test/NetworkTables.Test/StorageTestPopulated.cs deleted file mode 100644 index 72a2869..0000000 --- a/test/NetworkTables.Test/StorageTestPopulated.cs +++ /dev/null @@ -1,407 +0,0 @@ -using System; -using System.IO; -using System.Text; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture(true)] - [TestFixture(false)] - public class StorageTestPopulated : StorageBaseTest - { - public StorageTestPopulated(bool server) - { - m_server = server; - } - - [SetUp] - public void Clear() - { - tmpEntry = new Storage.Entry("foobar"); - storage?.Dispose(); - storage = new Storage(); - outgoing.Clear(); - - HookOutgoing(); - - storage.SetEntryTypeValue("foo", Value.MakeBoolean(true)); - storage.SetEntryTypeValue("foo2", Value.MakeDouble(0.0)); - storage.SetEntryTypeValue("bar", Value.MakeDouble(1.0)); - storage.SetEntryTypeValue("bar2", Value.MakeBoolean(false)); - - outgoing.Clear(); - } - - [Test] - public void SetDefaultEntryEmptyName() - { - var value = Value.MakeBoolean(true); - var retVal = storage.SetDefaultEntryValue("", value); - Assert.That(retVal, Is.False); - // assert that no entries got added - Assert.That(Entries, Has.Count.EqualTo(4)); - if (m_server) - { - Assert.That(IdMap, Has.Count.EqualTo(4)); - } - else - { - Assert.That(IdMap, Has.Count.EqualTo(0)); - } - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void SetDefaultEntryEmptyValue() - { - var retVal = storage.SetDefaultEntryValue("", null); - Assert.That(retVal, Is.False); - // assert that no entries got added - Assert.That(Entries, Has.Count.EqualTo(4)); - if (m_server) - { - Assert.That(IdMap, Has.Count.EqualTo(4)); - } - else - { - Assert.That(IdMap, Has.Count.EqualTo(0)); - } - Assert.That(outgoing, Is.Empty); - } - - [Test] - public void TestStoragePopulatedSetEntryTypeValueDifferentValue() - { - - var value = Value.MakeDouble(1.0); - storage.SetEntryTypeValue("foo2", value); - Assert.That(value, Is.EqualTo(GetEntry("foo2").Value)); - - if (m_server) - { - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryUpdate)); - Assert.That(msg.Id, Is.EqualTo(1)); - Assert.That(msg.SeqNumUid, Is.EqualTo(2)); - Assert.That(msg.Val, Is.EqualTo(value)); - } - else - { - Assert.That(outgoing, Is.Empty); - Assert.That(GetEntry("foo2").SeqNum.Value, Is.EqualTo(2)); - } - - } - - - [Test] - public void TestStoragePopulatedSetEntryValueDifferentValue() - { - - var value = Value.MakeDouble(1.0); - Assert.That(storage.SetEntryValue("foo2", value), Is.True); - var entry = GetEntry("foo2"); - Assert.That(entry.Value, Is.EqualTo(value)); - - if (m_server) - { - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryUpdate)); - Assert.That(msg.Id, Is.EqualTo(1)); - Assert.That(msg.SeqNumUid, Is.EqualTo(2)); - Assert.That(msg.Val, Is.EqualTo(value)); - } - else - { - Assert.That(outgoing, Is.Empty); - Assert.That(GetEntry("foo2").SeqNum.Value, Is.EqualTo(2)); - } - } - - [Test] - public void TestStoragePopulatedSetEntryFlagsDifferentValue() - { - - storage.SetEntryFlags("foo2", EntryFlags.Persistent); - Assert.That(GetEntry("foo2").Flags, Is.EqualTo(EntryFlags.Persistent)); - - if (m_server) - { - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.FlagsUpdate)); - Assert.That(msg.Id, Is.EqualTo(1)); - Assert.That(msg.Flags, Is.EqualTo(1)); - } - else - { - Assert.That(outgoing, Is.Empty); - } - } - - [Test] - public void TestStoragePopulatedDeleteEntryExist() - { - - storage.DeleteEntry("foo2"); - Assert.That(Entries.ContainsKey("foo2"), Is.False); - - if (m_server) - { - Assert.That(IdMap, Has.Count.GreaterThanOrEqualTo(2)); - Assert.That(IdMap[1], Is.Null); - } - - if (m_server) - { - - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryDelete)); - Assert.That(msg.Id, Is.EqualTo(1)); - } - else - { - Assert.That(outgoing, Is.Empty); - } - } - - [Test] - public void TestStoragePopulatedDeleteAllEntries() - { - - storage.DeleteAllEntries(); - Assert.That(Entries, Is.Empty); - - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.ClearEntries)); - } - - [Test] - public void TestStoragePopulatedDeleteAllEntriesPersistent() - { - GetEntry("foo2").Flags = EntryFlags.Persistent; - storage.DeleteAllEntries(); - Assert.That(Entries, Has.Count.EqualTo(1)); - Assert.That(Entries, Contains.Key("foo2")); - - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.ClearEntries)); - } - - [Test] - public void TestStoragePopulatedGetEntryInfoAll() - { - - var info = storage.GetEntryInfo("", 0); - Assert.That(info, Has.Count.EqualTo(4)); - } - - [Test] - public void TestStoragePopulatedGetEntryInfoAllNullPrefix() - { - - var info = storage.GetEntryInfo(null, 0); - Assert.That(info, Has.Count.EqualTo(4)); - } - - [Test] - public void TestStoragePopulatedGetEntryInfoPrefix() - { - - var info = storage.GetEntryInfo("foo", 0); - Assert.That(info, Has.Count.EqualTo(2)); - - if (info[0].Name == "foo") - { - Assert.That(info[0].Type, Is.EqualTo(NtType.Boolean)); - Assert.That(info[1].Name, Is.EqualTo("foo2")); - Assert.That(info[1].Type, Is.EqualTo(NtType.Double)); - } - else - { - Assert.That(info[0].Name, Is.EqualTo("foo2")); - Assert.That(info[0].Type, Is.EqualTo(NtType.Double)); - Assert.That(info[1].Name, Is.EqualTo("foo")); - Assert.That(info[1].Type, Is.EqualTo(NtType.Boolean)); - } - } - - [Test] - public void TestStoragePopulatedGetEntryInfoTypes() - { - - - var info = storage.GetEntryInfo("", NtType.Double); - Assert.That(info, Has.Count.EqualTo(2)); - Assert.That(info[0].Type, Is.EqualTo(NtType.Double)); - Assert.That(info[1].Type, Is.EqualTo(NtType.Double)); - - if (info[0].Name == "foo2") - { - Assert.That(info[1].Name, Is.EqualTo("bar")); - } - else - { - Assert.That(info[0].Name, Is.EqualTo("bar")); - Assert.That(info[1].Name, Is.EqualTo("foo2")); - } - } - - [Test] - public void TestStoragePopulatedGetEntryInfoPrefixTypes() - { - - var info = storage.GetEntryInfo("bar", NtType.Boolean); - Assert.That(info, Has.Count.EqualTo(1)); - Assert.That(info[0].Name, Is.EqualTo("bar2")); - Assert.That(info[0].Type, Is.EqualTo(NtType.Boolean)); - } - - [Test] - public void TestStoragePopulatedLoadPersistentUpdateFlags() - { - - int lastLine = -1; - string lastString = String.Empty; - - Action warn_func = (int line, string mg) => - { - lastLine = line; - lastString = mg; - }; - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("[NetworkTables Storage 3.0]\ndouble \"foo2\"=0.0\n"))) - { - Assert.That(storage.LoadPersistent(stream, warn_func), Is.True); - Assert.That(lastLine, Is.EqualTo(-1)); - Assert.That(lastString, Is.Empty); - } - var entry = GetEntry("foo2"); - Assert.That(Value.MakeDouble(0.0) == entry.Value); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.Persistent)); - - if (m_server) - { - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.FlagsUpdate)); - Assert.That(msg.Id, Is.EqualTo(1)); - Assert.That(msg.Flags, Is.EqualTo((uint)EntryFlags.Persistent)); - } - else - { - Assert.That(outgoing, Is.Empty); - } - } - - [Test] - public void TestStoragePopulatedLoadPersistentUpdateValue() - { - - int lastLine = -1; - string lastString = String.Empty; - - Action warn_func = (int line, string mg) => - { - lastLine = line; - lastString = mg; - }; - - GetEntry("foo2").Flags = EntryFlags.Persistent; - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("[NetworkTables Storage 3.0]\ndouble \"foo2\"=1.0\n"))) - { - Assert.That(storage.LoadPersistent(stream, warn_func), Is.True); - Assert.That(lastLine, Is.EqualTo(-1)); - Assert.That(lastString, Is.Empty); - } - var entry = GetEntry("foo2"); - Assert.That(Value.MakeDouble(1.0) == entry.Value); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.Persistent)); - - if (m_server) - { - Assert.That(outgoing, Has.Count.EqualTo(1)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryUpdate)); - Assert.That(msg.Id, Is.EqualTo(1)); - Assert.That(msg.SeqNumUid, Is.EqualTo(2)); - Assert.That(Value.MakeDouble(1.0) == msg.Val); - } - else - { - Assert.That(outgoing, Is.Empty); - Assert.That(GetEntry("foo2").SeqNum.Value, Is.EqualTo(2)); - } - } - - [Test] - public void TestStoragePopulatedLoadPersistentUpdateValueFlags() - { - - int lastLine = -1; - string lastString = String.Empty; - - Action warn_func = (int line, string mg) => - { - lastLine = line; - lastString = mg; - }; - - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("[NetworkTables Storage 3.0]\ndouble \"foo2\"=1.0\n"))) - { - Assert.That(storage.LoadPersistent(stream, warn_func), Is.True); - Assert.That(lastLine, Is.EqualTo(-1)); - Assert.That(lastString, Is.Empty); - } - var entry = GetEntry("foo2"); - Assert.That(Value.MakeDouble(1.0) == entry.Value); - Assert.That(entry.Flags, Is.EqualTo(EntryFlags.Persistent)); - - if (m_server) - { - Assert.That(outgoing, Has.Count.EqualTo(2)); - Assert.That(outgoing[0].only, Is.Null); - Assert.That(outgoing[0].except, Is.Null); - var msg = outgoing[0].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.EntryUpdate)); - Assert.That(msg.Id, Is.EqualTo(1)); - Assert.That(msg.SeqNumUid, Is.EqualTo(2)); - Assert.That(Value.MakeDouble(1.0) == msg.Val); - - Assert.That(outgoing[1].only, Is.Null); - Assert.That(outgoing[1].except, Is.Null); - msg = outgoing[1].msg; - Assert.That(msg.Type, Is.EqualTo(Message.MsgType.FlagsUpdate)); - Assert.That(msg.Id, Is.EqualTo(1)); - Assert.That(msg.Flags, Is.EqualTo((uint)EntryFlags.Persistent)); - } - else - { - Assert.That(outgoing, Is.Empty); - Assert.That(GetEntry("foo2").SeqNum.Value, Is.EqualTo(2)); - } - } - } -} diff --git a/test/NetworkTables.Test/TestBase.cs b/test/NetworkTables.Test/TestBase.cs deleted file mode 100644 index 49b0618..0000000 --- a/test/NetworkTables.Test/TestBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace NetworkTables.Test -{ - internal static class TestBase - { - public static void DeleteAllWithPersistent() - { - foreach (var entryInfo in NtCore.GetEntryInfo("", 0)) - { - NtCore.DeleteEntry(entryInfo.Name); - } - } - } -} diff --git a/test/NetworkTables.Test/ValueTest.cs b/test/NetworkTables.Test/ValueTest.cs deleted file mode 100644 index 8e58eae..0000000 --- a/test/NetworkTables.Test/ValueTest.cs +++ /dev/null @@ -1,594 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NetworkTables.Exceptions; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture] - public class ValueTest - { - [Test] - public void TestToStringUnassigned() - { - Value v = new Value(); - Assert.That(v.ToString(), Is.EqualTo("Unassigned")); - } - - [Test] - public void TestToString() - { - Value v = Value.MakeBoolean(true); - Assert.That(v.ToString(), Is.EqualTo("True")); - } - - [Test] - public void EqualsDifferentObject() - { - Assert.That(new Value(), Is.Not.EqualTo("randomstring")); - } - - [Test] - public void EqualsNull() - { - Value v = new Value(); - object o = null; - Assert.That(v.Equals(o), Is.False); - Assert.That(new Value(), Is.Not.EqualTo(null)); - } - - [Test] - public void ConstructEmpty() - { - Value v = new Value(); - Assert.That(v.Type, Is.EqualTo(NtType.Unassigned)); - } - - [Test] - public void Boolean() - { - var v = Value.MakeBoolean(false); - Assert.That(v.IsBoolean(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(v.GetBoolean(), Is.False); - - v = Value.MakeBoolean(true); - Assert.That(v.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(v.GetBoolean(), Is.True); - bool genericSuccess; - var retVal = v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.True); - Assert.That(retVal, Is.True); - } - - [Test] - public void Double() - { - var v = Value.MakeDouble(0.5); - Assert.That(v.IsDouble(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.Double)); - Assert.That(v.GetDouble(), Is.EqualTo(0.5)); - - v = Value.MakeDouble(0.25); - Assert.That(v.Type, Is.EqualTo(NtType.Double)); - Assert.That(v.GetDouble(), Is.EqualTo(0.25)); - bool genericSuccess; - var retVal = v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.True); - Assert.That(retVal, Is.EqualTo(0.25)); - } - - [Test] - public void String() - { - var v = Value.MakeString("hello"); - Assert.That(v.IsString(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.String)); - Assert.That(v.GetString(), Is.EqualTo("hello")); - - v = Value.MakeString("goodbye"); - Assert.That(v.Type, Is.EqualTo(NtType.String)); - Assert.That(v.GetString(), Is.EqualTo("goodbye")); - bool genericSuccess; - var retVal = v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.True); - Assert.That(retVal, Is.EqualTo("goodbye")); - } - - [Test] - public void Raw() - { - byte[] raw = new byte[] { 5, 19, 28 }; - - var v = Value.MakeRaw(raw); - Assert.That(v.IsRaw(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.Raw)); - Assert.That(ReferenceEquals(v.GetRaw(), raw), Is.False); - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = (byte)'a'; - Assert.That(v.GetRaw(), Is.Not.EquivalentTo(raw)); - raw[1] = 19; - - var vR = v.GetRaw(); - vR[1] = (byte)'b'; - - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new byte[] { 0, 28, 53 }; - v = Value.MakeRaw(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Raw)); - Assert.That(ReferenceEquals(v.GetRaw(), raw), Is.False); - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = Encoding.UTF8.GetBytes("goodbye"); - - v = Value.MakeRaw(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Raw)); - Assert.That(ReferenceEquals(v.GetRaw(), raw), Is.False); - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - - bool genericSuccess; - var retVal = v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.True); - Assert.That(retVal, Is.EquivalentTo(raw)); - } - - [Test] - public void Rpc() - { - byte[] raw = new byte[] { 5, 19, 28 }; - - var v = Value.MakeRpc(raw); - Assert.That(v.IsRpc(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(ReferenceEquals(v.GetRpc(), raw), Is.False); - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = (byte)'a'; - Assert.That(v.GetRpc(), Is.Not.EquivalentTo(raw)); - raw[1] = 19; - - var vR = v.GetRpc(); - vR[1] = (byte)'b'; - - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new byte[] { 0, 28, 53 }; - v = Value.MakeRpc(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(ReferenceEquals(v.GetRpc(), raw), Is.False); - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = Encoding.UTF8.GetBytes("goodbye"); - - v = Value.MakeRpc(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(ReferenceEquals(v.GetRpc(), raw), Is.False); - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - } - - [Test] - public void BoolArray() - { - bool[] raw = new bool[] { true, false, true }; - - var v = Value.MakeBooleanArray(raw); - Assert.That(v.IsBooleanArray(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(ReferenceEquals(v.GetBooleanArray(), raw), Is.False); - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = true; - Assert.That(v.GetBooleanArray(), Is.Not.EquivalentTo(raw)); - raw[1] = false; - - var vR = v.GetBooleanArray(); - vR[1] = true; - - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new bool[] { false, true, false }; - v = Value.MakeBooleanArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(ReferenceEquals(v.GetBooleanArray(), raw), Is.False); - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new bool[] { false, true }; - - v = Value.MakeBooleanArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(ReferenceEquals(v.GetBooleanArray(), raw), Is.False); - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - bool genericSuccess; - var retVal = v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.True); - Assert.That(retVal, Is.EquivalentTo(raw)); - } - - [Test] - public void DoubleArray() - { - double[] raw = new double[] { 0.5, 0.25, 0.5 }; - - var v = Value.MakeDoubleArray(raw); - Assert.That(v.IsDoubleArray(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(ReferenceEquals(v.GetDoubleArray(), raw), Is.False); - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = 0.65; - Assert.That(v.GetDoubleArray(), Is.Not.EquivalentTo(raw)); - raw[1] = 0.25; - - var vR = v.GetDoubleArray(); - vR[1] = 0.85; - - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new double[] { 0.25, 0.5, 0.25 }; - v = Value.MakeDoubleArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(ReferenceEquals(v.GetDoubleArray(), raw), Is.False); - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new double[] { 0.5, 0.25 }; - - v = Value.MakeDoubleArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(ReferenceEquals(v.GetDoubleArray(), raw), Is.False); - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - bool genericSuccess; - var retVal = v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.True); - Assert.That(retVal, Is.EquivalentTo(raw)); - } - - [Test] - public void StringArray() - { - string[] raw = new string[] { "hello", "goodbye", "string" }; - - var v = Value.MakeStringArray(raw); - Assert.That(v.IsStringArray(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(ReferenceEquals(v.GetStringArray(), raw), Is.False); - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = "falsehood"; - Assert.That(v.GetStringArray(), Is.Not.EquivalentTo(raw)); - raw[1] = "goodbye"; - - var vR = v.GetStringArray(); - vR[1] = "foobar"; - - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new string[] { "s1", "str2", "string3" }; - v = Value.MakeStringArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(ReferenceEquals(v.GetStringArray(), raw), Is.False); - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new string[] { "short", "er" }; - - v = Value.MakeStringArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(ReferenceEquals(v.GetStringArray(), raw), Is.False); - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - bool genericSuccess; - var retVal = v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.True); - Assert.That(retVal, Is.EquivalentTo(raw)); - } - - - [Test] - public void RawList() - { - List raw = new List { 5, 19, 28 }; - - var v = Value.MakeRaw(raw); - Assert.That(v.IsRaw(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.Raw)); - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = (byte)'a'; - Assert.That(v.GetRaw(), Is.Not.EquivalentTo(raw)); - raw[1] = 19; - - var vR = v.GetRaw(); - vR[1] = (byte)'b'; - - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new List { 0, 28, 53 }; - v = Value.MakeRaw(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Raw)); - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new List(Encoding.UTF8.GetBytes("goodbye")); - - v = Value.MakeRaw(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Raw)); - Assert.That(v.GetRaw(), Is.EquivalentTo(raw)); - } - - [Test] - public void RpcList() - { - List raw = new List { 5, 19, 28 }; - - var v = Value.MakeRpc(raw); - Assert.That(v.IsRpc(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = (byte)'a'; - Assert.That(v.GetRpc(), Is.Not.EquivalentTo(raw)); - raw[1] = 19; - - var vR = v.GetRpc(); - vR[1] = (byte)'b'; - - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new List { 0, 28, 53 }; - v = Value.MakeRpc(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new List(Encoding.UTF8.GetBytes("goodbye")); - - v = Value.MakeRpc(raw); - Assert.That(v.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(v.GetRpc(), Is.EquivalentTo(raw)); - } - - [Test] - public void BoolArrayList() - { - List raw = new List { true, false, true }; - - var v = Value.MakeBooleanArray(raw); - Assert.That(v.IsBooleanArray(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = true; - Assert.That(v.GetBooleanArray(), Is.Not.EquivalentTo(raw)); - raw[1] = false; - - var vR = v.GetBooleanArray(); - vR[1] = true; - - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new List { false, true, false }; - v = Value.MakeBooleanArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new List { false, true }; - - v = Value.MakeBooleanArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(ReferenceEquals(v.GetBooleanArray(), raw), Is.False); - Assert.That(v.GetBooleanArray(), Is.EquivalentTo(raw)); - } - - [Test] - public void DoubleArrayList() - { - List raw = new List { 0.5, 0.25, 0.5 }; - - var v = Value.MakeDoubleArray(raw); - Assert.That(v.IsDoubleArray(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = 0.65; - Assert.That(v.GetDoubleArray(), Is.Not.EquivalentTo(raw)); - raw[1] = 0.25; - - var vR = v.GetDoubleArray(); - vR[1] = 0.85; - - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new List { 0.25, 0.5, 0.25 }; - v = Value.MakeDoubleArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new List { 0.5, 0.25 }; - - v = Value.MakeDoubleArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(v.GetDoubleArray(), Is.EquivalentTo(raw)); - } - - [Test] - public void StringArrayList() - { - List raw = new List { "hello", "goodbye", "string" }; - - var v = Value.MakeStringArray(raw); - Assert.That(v.IsStringArray(), Is.True); - Assert.That(v.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - - //Modify raw, and make sure copies of the array are created - raw[1] = "falsehood"; - Assert.That(v.GetStringArray(), Is.Not.EquivalentTo(raw)); - raw[1] = "goodbye"; - - var vR = v.GetStringArray(); - vR[1] = "foobar"; - - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - - //Assign with same size - raw = new List { "s1", "str2", "string3" }; - v = Value.MakeStringArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - - - //Assign with different size - raw = new List { "short", "er" }; - - v = Value.MakeStringArray(raw); - Assert.That(v.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(v.GetStringArray(), Is.EquivalentTo(raw)); - } - - [Test] - public void ValueAssertions() - { - Value v = new Value(); - - TableKeyDifferentTypeException ex = Assert.Throws(() => - { - v.GetBoolean(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type Boolean does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.Boolean)); - - ex = Assert.Throws(() => - { - v.GetBooleanArray(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type BooleanArray does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.BooleanArray)); - - ex = Assert.Throws(() => - { - v.GetDouble(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type Double does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.Double)); - - ex = Assert.Throws(() => - { - v.GetDoubleArray(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type DoubleArray does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.DoubleArray)); - - ex = Assert.Throws(() => - { - v.GetRaw(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type Raw does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.Raw)); - - ex = Assert.Throws(() => - { - v.GetRpc(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type Rpc does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.Rpc)); - - ex = Assert.Throws(() => - { - v.GetString(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type String does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.String)); - - ex = Assert.Throws(() => - { - v.GetStringArray(); - }); - Assert.That(ex.Message, Is.EqualTo("Requested Type StringArray does not match actual Type Unassigned.")); - Assert.That(ex.ThrownByValueGet, Is.True); - Assert.That(ex.TypeInTable, Is.EqualTo(NtType.Unassigned)); - Assert.That(ex.RequestedType, Is.EqualTo(NtType.StringArray)); - - bool genericSuccess; - v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.False); - v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.False); - v.GetValue>(out genericSuccess); - Assert.That(genericSuccess, Is.False); - v.GetValue(out genericSuccess); - Assert.That(genericSuccess, Is.False); - } - - [Test] - public void MakeRawInvalidSize() - { - byte[] b = new byte[2]; - Assert.That(Value.MakeRpc(b, 10), Is.Null); - } - - [Test] - public void ValueUnassignedComparison() - { - Value v1 = new Value(), v2 = new Value(); - Assert.That(v1, Is.EqualTo(v2)); - } - - [Test] - public void ValueMixedComparison() - { - Value v1 = new Value(), v2 = Value.MakeBoolean(true); - Assert.That(v1, Is.Not.EqualTo(v2)); - Value v3 = Value.MakeDouble(0.5); - Assert.That(v2, Is.Not.EqualTo(v3)); - } - } -} diff --git a/test/NetworkTables.Test/WireDecoderTest.cs b/test/NetworkTables.Test/WireDecoderTest.cs deleted file mode 100644 index 704c6c8..0000000 --- a/test/NetworkTables.Test/WireDecoderTest.cs +++ /dev/null @@ -1,913 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Text; -using NetworkTables.Wire; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture] - class WireDecoderTest - { - readonly Value v_boolean = Value.MakeBoolean(true); - readonly Value v_double = Value.MakeDouble(1.0); - readonly Value v_string = Value.MakeString("hello"); - readonly Value v_raw = Value.MakeRaw((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - readonly Value v_rpc = Value.MakeRpc((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - readonly Value v_boolArray = Value.MakeBooleanArray(false, true, false); - readonly Value v_boolArrayBig = Value.MakeBooleanArray(new bool[255]); - readonly Value v_doubleArray = Value.MakeDoubleArray(0.5, 0.25); - readonly Value v_doubleArrayBig = Value.MakeDoubleArray(new double[255]); - - readonly Value v_stringArray = Value.MakeStringArray("hello", "goodbye"); - readonly Value v_stringArrayBig; - - - readonly string s_normal = "hello"; - - private readonly string s_long; - private readonly string s_big; - - private readonly string s_big2; - - public WireDecoderTest() - { - List sa = new List(); - for (int i = 0; i < 255; i++) - { - sa.Add("h"); - } - v_stringArrayBig = Value.MakeStringArray(sa.ToArray()); - - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < 127; i++) - { - builder.Append('*'); - } - builder.Append('x'); - s_long = builder.ToString(); - - builder.Clear(); - for (int i = 0; i < 65534; i++) - { - builder.Append('*'); - } - builder.Append('x'); - builder.Append('x'); - builder.Append('x'); - s_big = builder.ToString(); - - builder.Clear(); - for (int i = 0; i < 65534; i++) - { - builder.Append('*'); - } - builder.Append('x'); - s_big2 = builder.ToString(); - - } - - [Test] - public void Construct() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0300); - Assert.That(d.Error, Is.Null); - Assert.That(d.ProtoRev, Is.EqualTo(0x0300)); - } - - [Test] - public void SetProtoRev() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0300); - d.ProtoRev = 0x0200; - Assert.That(d.ProtoRev, Is.EqualTo(0x0200)); - } - - [Test] - public void Read8() - { - byte[] rawData = { 0x05, 0x01, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - byte val = 0; - Assert.That(d.Read8(ref val)); - Assert.That(val, Is.EqualTo(5)); - - Assert.That(d.Read8(ref val)); - Assert.That(val, Is.EqualTo(1)); - - Assert.That(d.Read8(ref val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(!d.Read8(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void Read16() - { - byte[] rawData = { 0x00, 0x05, 0x00, 0x01, 0x45, 0x67, 0x00, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - ushort val = 0; - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(5)); - - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(1)); - - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(0x4567)); - - Assert.That(d.Read16(ref val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(!d.Read16(ref val)); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void Read32() - { - byte[] rawData = { 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xab, 0xcd, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - uint val = 0; - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(5)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(1)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(0xabcd)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(0x12345678)); - - Assert.That(d.Read32(ref val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(!d.Read32(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadDouble() - { - byte[] rawData = - { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x41, 0x0c, 0x13, 0x80, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - double val = 0; - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(0.0)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(2.3e5)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(double.PositiveInfinity)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(2.2250738585072014e-308)); - - Assert.That(d.ReadDouble(ref val)); - Assert.That(val, Is.EqualTo(double.MaxValue)); - - Assert.That(!d.ReadDouble(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadUleb128() - { - byte[] rawData = { 0x00, 0x7f, 0x80, 0x01, 0x80 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - ulong val = 0; - Assert.That(d.ReadUleb128(out val)); - Assert.That(val, Is.EqualTo(0)); - - Assert.That(d.ReadUleb128(out val)); - Assert.That(val, Is.EqualTo(0x7f)); - - Assert.That(d.ReadUleb128(out val)); - Assert.That(val, Is.EqualTo(0x80)); - - Assert.That(!d.ReadUleb128(out val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadType() - { - byte[] rawData = { 0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x20 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - NtType val = 0; - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Boolean)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Double)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.String)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Raw)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.BooleanArray)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.DoubleArray)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.StringArray)); - - Assert.That(d.ReadType(ref val)); - Assert.That(val, Is.EqualTo(NtType.Rpc)); - - Assert.That(!d.ReadType(ref val)); - - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadTypeError() - { - byte[] rawData = { 0x30 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - NtType val = 0; - - Assert.That(!d.ReadType(ref val)); - - Assert.That(d.Error, Is.Not.Null); - } - - [Test] - public void Reset() - { - byte[] rawData = { 0x30 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - NtType val = 0; - - Assert.That(!d.ReadType(ref val)); - - Assert.That(d.Error, Is.Not.Null); - d.Reset(); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void HasMoreBytesSuccess() - { - int numBytes = 13; - byte[] data = new byte[numBytes]; - - MemoryStream stream = new MemoryStream(data); - WireDecoder d = new WireDecoder(stream, 0x0300); - - Assert.That(d.HasMoreBytes(numBytes), Is.True); - } - - [Test] - public void HasMoreBytesFailure() - { - int numBytes = 13; - byte[] data = new byte[numBytes - 1]; - - MemoryStream stream = new MemoryStream(data); - WireDecoder d = new WireDecoder(stream, 0x0300); - - Assert.That(d.HasMoreBytes(numBytes), Is.False); - } - - [Test] - public void BooleanValue2() - { - byte[] rawData = new byte[] { 0x01, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - var val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(v_boolean.Val)); - - var vFalse = Value.MakeBoolean(false); - val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - Assert.That(d.ReadValue(NtType.Boolean), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void DoubleValue2() - { - byte[] rawData = new byte[] - { - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - var val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - Assert.That(d.ReadValue(NtType.Double), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void StringValue2() - { - byte[] rawData = new byte[] - { - 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x00, 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0200); - var val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(v_string.Val)); - - var vFalse = Value.MakeString("bye"); - val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.String), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArray2() - { - byte[] b = { 0x03, 0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0xff }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArray.Val)); - - var boolArray2 = Value.MakeBooleanArray(true, false); - val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(boolArray2.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArrayBig2() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - - - [Test] - public void ReadDoubleArray2() - { - byte[] b = - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55 - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadDoubleArrayBig2() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255 * 8; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArray2() - { - List b = new List() - { - 0x02, - 0x00, - 0x05 - }; - b.AddRange(Encoding.UTF8.GetBytes("hello")); - b.Add(0x00); - b.Add(0x07); - b.AddRange(Encoding.UTF8.GetBytes("goodbye")); - b.Add(0x55); - MemoryStream stream = new MemoryStream(b.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArrayBig2() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x00); - s.Add(0x01); - s.Add((byte)'h'); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadValueError2() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0200); - Assert.That(d.ReadValue(NtType.Unassigned), Is.Null); - Assert.That(d.Error, Is.Not.Null); - - d.Reset(); - Assert.That(d.ReadValue(NtType.Raw), Is.Null); - Assert.That(d.Error, Is.Not.Null); - - Assert.That(d.ReadValue(NtType.Rpc), Is.Null); - Assert.That(d.Error, Is.Not.Null); - } - - [Test] - public void BooleanValue3() - { - byte[] rawData = new byte[] { 0x01, 0x00 }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(v_boolean.Val)); - - var vFalse = Value.MakeBoolean(false); - val = d.ReadValue(NtType.Boolean); - Assert.That(val.Type, Is.EqualTo(NtType.Boolean)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - Assert.That(d.ReadValue(NtType.Boolean), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void DoubleValue3() - { - byte[] rawData = new byte[] - { - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - val = d.ReadValue(NtType.Double); - Assert.That(val.Type, Is.EqualTo(NtType.Double)); - Assert.That(val.Val, Is.EqualTo(v_double.Val)); - - Assert.That(d.ReadValue(NtType.Double), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void StringValue3() - { - byte[] rawData = new byte[] - { - 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(v_string.Val)); - - var vFalse = Value.MakeString("bye"); - val = d.ReadValue(NtType.String); - Assert.That(val.Type, Is.EqualTo(NtType.String)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.String), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void RawValue3() - { - byte[] rawData = new byte[] - { - 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Raw); - Assert.That(val.Type, Is.EqualTo(NtType.Raw)); - Assert.That(val.Val, Is.EqualTo(v_raw.Val)); - - var vFalse = Value.MakeRaw((byte)'b', (byte)'y', (byte)'e'); - val = d.ReadValue(NtType.Raw); - Assert.That(val.Type, Is.EqualTo(NtType.Raw)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.Raw), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void RpcValue3() - { - byte[] rawData = new byte[] - { - 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x03, (byte)'b', (byte)'y', (byte)'e', 0x55, - }; - MemoryStream stream = new MemoryStream(rawData); - WireDecoder d = new WireDecoder(stream, 0x0300); - var val = d.ReadValue(NtType.Rpc); - Assert.That(val.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(val.Val, Is.EqualTo(v_rpc.Val)); - - var vFalse = Value.MakeRaw((byte)'b', (byte)'y', (byte)'e'); - val = d.ReadValue(NtType.Rpc); - Assert.That(val.Type, Is.EqualTo(NtType.Rpc)); - Assert.That(val.Val, Is.EqualTo(vFalse.Val)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.Rpc), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArray3() - { - byte[] b = { 0x03, 0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0xff }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArray.Val)); - - var boolArray2 = Value.MakeBooleanArray(true, false); - val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(boolArray2.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadBooleanArrayBig3() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.BooleanArray); - Assert.That(val.Type, Is.EqualTo(NtType.BooleanArray)); - Assert.That(val.Val, Is.EqualTo(v_boolArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.BooleanArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - - - [Test] - public void ReadDoubleArray3() - { - byte[] b = - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55 - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadDoubleArrayError3() - { - byte[] b = - { - 0x02, - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val, Is.Null); - } - - [Test] - public void ReadStringArrayError3() - { - byte[] b = - { - 0x02, - }; - MemoryStream stream = new MemoryStream(b); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val, Is.Null); - } - - [Test] - public void ReadDoubleArrayBig3() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255 * 8; i++) - { - s.Add(0x00); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.DoubleArray); - Assert.That(val.Type, Is.EqualTo(NtType.DoubleArray)); - Assert.That(val.Val, Is.EqualTo(v_doubleArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.DoubleArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArray3() - { - List b = new List() - { - 0x02, - 0x05 - }; - b.AddRange(Encoding.UTF8.GetBytes("hello")); - b.Add(0x07); - b.AddRange(Encoding.UTF8.GetBytes("goodbye")); - b.Add(0x55); - MemoryStream stream = new MemoryStream(b.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArray.Val)); - - byte by = 0; - Assert.That(d.Read8(ref by)); - Assert.That(by, Is.EqualTo(0x55)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringArrayBig3() - { - List s = new List(); - s.Add(0xff); - for (int i = 0; i < 255; i++) - { - s.Add(0x01); - s.Add((byte)'h'); - } - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - var val = d.ReadValue(NtType.StringArray); - Assert.That(val.Type, Is.EqualTo(NtType.StringArray)); - Assert.That(val.Val, Is.EqualTo(v_stringArrayBig.Val)); - - Assert.That(d.ReadValue(NtType.StringArray), Is.Null); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadValueError3() - { - MemoryStream stream = new MemoryStream(new byte[0]); - WireDecoder d = new WireDecoder(stream, 0x0300); - Assert.That(d.ReadValue(NtType.Unassigned), Is.Null); - Assert.That(d.Error, Is.Not.Null); - } - - [Test] - public void ReadStringError2() - { - MemoryStream stream = new MemoryStream(new byte[] { 0x00, 0x05 }); - WireDecoder d = new WireDecoder(stream, 0x0200); - string str = ""; - Assert.That(d.ReadString(ref str), Is.False); - } - - [Test] - public void ReadString2() - { - byte[] sNormalBytes = Encoding.UTF8.GetBytes(s_normal); - byte[] sLongBytes = Encoding.UTF8.GetBytes(s_long); - byte[] sBigBytes = Encoding.UTF8.GetBytes(s_big2); - List s = new List(); - s.AddRange(new byte[] { 0x00, 0x05 }); - s.AddRange(sNormalBytes); - s.AddRange(new byte[] { 0x00, 0x80 }); - s.AddRange(sLongBytes); - s.AddRange(new byte[] { 0xff, 0xff }); - s.AddRange(sBigBytes); - s.Add(0x55); - - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0200); - - string outs = null; - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_normal)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_long)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_big2)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadString(ref outs), Is.False); - Assert.That(d.Error, Is.Null); - } - - [Test] - public void ReadStringError3() - { - MemoryStream stream = new MemoryStream(new byte[] { 0x05 }); - WireDecoder d = new WireDecoder(stream, 0x0300); - string str = ""; - Assert.That(d.ReadString(ref str), Is.False); - } - - [Test] - public void ReadRawError3() - { - MemoryStream stream = new MemoryStream(new byte[] { 0x05 }); - WireDecoder d = new WireDecoder(stream, 0x0300); - byte[] str = null; - Assert.That(d.ReadRaw(ref str), Is.False); - } - - [Test] - public void ReadString3() - { - byte[] sNormalBytes = Encoding.UTF8.GetBytes(s_normal); - byte[] sLongBytes = Encoding.UTF8.GetBytes(s_long); - byte[] sBigBytes = Encoding.UTF8.GetBytes(s_big); - List s = new List(); - s.Add(0x05); - s.AddRange(sNormalBytes); - s.AddRange(new byte[] { 0x80, 0x01 }); - s.AddRange(sLongBytes); - s.AddRange(new byte[] { 0x81, 0x80, 0x04 }); - s.AddRange(sBigBytes); - s.Add(0x55); - - MemoryStream stream = new MemoryStream(s.ToArray()); - WireDecoder d = new WireDecoder(stream, 0x0300); - - string outs = null; - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_normal)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_long)); - - Assert.That(d.ReadString(ref outs)); - Assert.That(outs, Is.EquivalentTo(s_big)); - - byte b = 0; - Assert.That(d.Read8(ref b)); - Assert.That(b, Is.EqualTo(0x55)); - - Assert.That(d.ReadString(ref outs), Is.False); - Assert.That(d.Error, Is.Null); - } - } -} diff --git a/test/NetworkTables.Test/WireEncoderTest.cs b/test/NetworkTables.Test/WireEncoderTest.cs deleted file mode 100644 index 4b51394..0000000 --- a/test/NetworkTables.Test/WireEncoderTest.cs +++ /dev/null @@ -1,617 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NetworkTables.Wire; -using NUnit.Framework; - -namespace NetworkTables.Test -{ - [TestFixture] - public class WireEncoderTest - { - private const int BUFSIZE = 1024; - - [Test] - public void WireEncoderWrite8() - { - int off = BUFSIZE - 1; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.Write8(5); - unchecked - { - e.Write8((byte)0x101u); - } - e.Write8(0); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(3)); - byte[] checkArray = { 0x05, 0x01, 0x00 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void Construct() - { - WireEncoder d = new WireEncoder(0x0300); - Assert.That(d.Error, Is.Null); - Assert.That(d.ProtoRev, Is.EqualTo(0x0300)); - } - - [Test] - public void SetProtoRev() - { - WireEncoder d = new WireEncoder(0x0300); - d.ProtoRev = 0x0200; - Assert.That(d.ProtoRev, Is.EqualTo(0x0200)); - } - - [Test] - public void WireEncoderWrite16() - { - int off = BUFSIZE - 2; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.Write16(5); - unchecked - { - e.Write16((ushort)0x10001u); - } - e.Write16(0x4567); - e.Write16(0); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(8)); - byte[] checkArray = { 0x00, 0x05, 0x00, 0x01, 0x45, 0x67, 0x00, 0x00 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void WireEncoderWrite32() - { - int off = BUFSIZE - 4; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.Write32(5); - e.Write32(1); - e.Write32(0xabcd); - e.Write32(0x12345678); - e.Write32(0); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(20)); - byte[] checkArray = { 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xab, 0xcd, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - - [Test] - public void WireEncoderWriteDouble() - { - int off = BUFSIZE - 8; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.WriteDouble(0.0); - e.WriteDouble(2.3e5); - e.WriteDouble(double.PositiveInfinity); - e.WriteDouble(2.2250738585072014e-308);//Minimum double size - e.WriteDouble(double.MaxValue); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(40)); - byte[] checkArray = - { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x41, 0x0c, 0x13, 0x80, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void WireEncoderWriteLeb128() - { - int off = BUFSIZE - 2; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.WriteUleb128(0ul); - e.WriteUleb128(0x7ful); - e.WriteUleb128(0x80ul); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(4)); - byte[] checkArray = { 0x00, 0x7f, 0x80, 0x01 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - - [Test] - public void WireEncoderWriteType() - { - int off = BUFSIZE - 1; - WireEncoder e = new WireEncoder(0x0300); - for (int i = 0; i < off; i++) - { - e.Write8(0); - } - e.WriteType(NtType.Boolean); - e.WriteType(NtType.Double); - e.WriteType(NtType.String); - e.WriteType(NtType.Raw); - e.WriteType(NtType.BooleanArray); - e.WriteType(NtType.DoubleArray); - e.WriteType(NtType.StringArray); - e.WriteType(NtType.Rpc); - - Assert.That(e.Buffer.Length - off, Is.EqualTo(8)); - byte[] checkArray = { 0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x20 }; - byte[] bufferArray = new byte[checkArray.Length]; - Array.Copy(e.Buffer, off, bufferArray, 0, checkArray.Length); - Assert.That(bufferArray, Is.EquivalentTo(checkArray)); - } - - [Test] - public void WriteTypeError() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteType(NtType.Unassigned); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.EqualTo("unrecognized Type")); - - e.Reset(); - e.WriteType(NtType.Raw); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.EqualTo("raw type not supported in protocol < 3.0")); - - e.Reset(); - e.WriteType(NtType.Rpc); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.EqualTo("RPC type not supported in protocol < 3.0")); - } - - [Test] - public void Reset() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteType(NtType.Unassigned); - Assert.That(e.Error, Is.Not.Null); - e.Reset(); - Assert.That(e.Error, Is.Null); - - e.Write8(0); - Assert.That(e.Buffer.Length, Is.EqualTo(1)); - e.Reset(); - Assert.That(e.Buffer, Is.Empty); - } - - private readonly Value v_empty = Value.MakeEmpty(); - private readonly Value v_boolean = Value.MakeBoolean(true); - private readonly Value v_double = Value.MakeDouble(1.0); - private readonly Value v_string = Value.MakeString("hello"); - private readonly Value v_raw = Value.MakeRaw((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - private readonly Value v_rpc = Value.MakeRpc((byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'); - private readonly Value v_boolArray = Value.MakeBooleanArray(false, true, false); - private readonly Value v_boolArrayBig = Value.MakeBooleanArray(new bool[256]); - private readonly Value v_doubleArray = Value.MakeDoubleArray(0.5, 0.25); - private readonly Value v_doubleArrayBig = Value.MakeDoubleArray(new double[256]); - - private readonly Value v_stringArray = Value.MakeStringArray("hello", "goodbye"); - private readonly Value v_stringArrayBig; - - private readonly string s_normal = "hello"; - - private readonly string s_long; - private readonly string s_big; - - public WireEncoderTest() - { - List sa = new List(); - for (int i = 0; i < 256; i++) - { - sa.Add("a"); - } - v_stringArrayBig = Value.MakeStringArray(sa.ToArray()); - - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < 127; i++) - { - builder.Append('*'); - } - builder.Append('x'); - s_long = builder.ToString(); - - builder.Clear(); - for (int i = 0; i < 65534; i++) - { - builder.Append('*'); - } - builder.Append('x'); - builder.Append('x'); - builder.Append('x'); - s_big = builder.ToString(); - - } - - [Test] - public void GetValueSize2() - { - WireEncoder e = new WireEncoder(0x0200); - Assert.That(e.GetValueSize(null), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_empty), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_boolean), Is.EqualTo(1)); - Assert.That(e.GetValueSize(v_double), Is.EqualTo(8)); - Assert.That(e.GetValueSize(v_string), Is.EqualTo(7)); - Assert.That(e.GetValueSize(v_raw), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_rpc), Is.EqualTo(0)); - - Assert.That(e.GetValueSize(v_boolArray), Is.EqualTo(1 + 3)); - Assert.That(e.GetValueSize(v_boolArrayBig), Is.EqualTo(1 + 255)); - Assert.That(e.GetValueSize(v_doubleArray), Is.EqualTo(1 + 2 * 8)); - Assert.That(e.GetValueSize(v_doubleArrayBig), Is.EqualTo(1 + 255 * 8)); - Assert.That(e.GetValueSize(v_stringArray), Is.EqualTo(1 + 7 + 9)); - Assert.That(e.GetValueSize(v_stringArrayBig), Is.EqualTo(1 + 255 * 3)); - } - - [Test] - public void WriteBooleanValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_boolean); - var v_false = Value.MakeBoolean(false); - e.WriteValue(v_false); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(2)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x01, 0x00 })); - } - - [Test] - public void WriteDoubleValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_double); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })); - } - - [Test] - public void WriteStringValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_string); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(7)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteBooleanArrayValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_boolArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 3)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x03, 0x00, 0x01, 0x00 })); - - e.Reset(); - e.WriteValue(v_boolArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteDoubleArrayValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_doubleArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 2 * 8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - })); - - e.Reset(); - e.WriteValue(v_doubleArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 8)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteStringArrayValue2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_stringArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 7 + 9)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x00, 0x07, (byte)'g', (byte)'o', (byte)'o', (byte)'d', (byte)'b', (byte)'y', (byte)'e' - })); - - e.Reset(); - e.WriteValue(v_stringArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 3)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2] }, Is.EquivalentTo(new byte[] { 0xff, 0x00, 0x01 })); - } - - [Test] - public void GetStringSize2() - { - WireEncoder e = new WireEncoder(0x0200); - Assert.That(e.GetStringSize(s_normal), Is.EqualTo(7)); - Assert.That(e.GetStringSize(s_long), Is.EqualTo(130)); - Assert.That(e.GetStringSize(s_big), Is.EqualTo(65537)); - } - - [Test] - public void WriteString2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteString(s_normal); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(7)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x00, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - - e.Reset(); - e.WriteString(s_long); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(130)); - byte[] arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0x00, 0x80, (byte)'*', (byte)'*' })); - Assert.That(e.Buffer[128], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[129], Is.EqualTo((byte)'x')); - - e.Reset(); - e.WriteString(s_big); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(65537)); - arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0xff, 0xff, (byte)'*', (byte)'*' })); - Assert.That(e.Buffer[65535], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[65536], Is.EqualTo((byte)'x')); - } - - [Test] - public void WriteValueError2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(v_empty); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - - e.Reset(); - e.WriteValue(v_raw); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - - e.Reset(); - e.WriteValue(v_rpc); - Assert.That(e.Count, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - - [Test] - public void WriteValueNull2() - { - WireEncoder e = new WireEncoder(0x0200); - e.WriteValue(null); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - - - - [Test] - public void GetValueSize3() - { - WireEncoder e = new WireEncoder(0x0300); - Assert.That(e.GetValueSize(null), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_empty), Is.EqualTo(0)); - Assert.That(e.GetValueSize(v_boolean), Is.EqualTo(1)); - Assert.That(e.GetValueSize(v_double), Is.EqualTo(8)); - Assert.That(e.GetValueSize(v_string), Is.EqualTo(6)); - Assert.That(e.GetValueSize(v_raw), Is.EqualTo(6)); - Assert.That(e.GetValueSize(v_rpc), Is.EqualTo(6)); - - Assert.That(e.GetValueSize(v_boolArray), Is.EqualTo(1 + 3)); - Assert.That(e.GetValueSize(v_boolArrayBig), Is.EqualTo(1 + 255)); - Assert.That(e.GetValueSize(v_doubleArray), Is.EqualTo(1 + 2 * 8)); - Assert.That(e.GetValueSize(v_doubleArrayBig), Is.EqualTo(1 + 255 * 8)); - Assert.That(e.GetValueSize(v_stringArray), Is.EqualTo(1 + 6 + 8)); - Assert.That(e.GetValueSize(v_stringArrayBig), Is.EqualTo(1 + 255 * 2)); - } - - [Test] - public void WriteBooleanValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_boolean); - var v_false = Value.MakeBoolean(false); - e.WriteValue(v_false); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(2)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x01, 0x00 })); - } - - [Test] - public void WriteDoubleValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_double); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })); - } - - [Test] - public void WriteStringValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_string); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteRawArray3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_raw); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteRpcArray3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_rpc); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - } - - [Test] - public void WriteBooleanArrayValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_boolArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 3)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x03, 0x00, 0x01, 0x00 })); - - e.Reset(); - e.WriteValue(v_boolArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteDoubleArrayValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_doubleArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 2 * 8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x3f, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - })); - - e.Reset(); - e.WriteValue(v_doubleArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 8)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x00 })); - } - - [Test] - public void WriteStringArrayValue3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_stringArray); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 6 + 8)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] - { - 0x02, 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', - 0x07, (byte)'g', (byte)'o', (byte)'o', (byte)'d', (byte)'b', (byte)'y', (byte)'e' - })); - - e.Reset(); - e.WriteValue(v_stringArrayBig); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(1 + 255 * 2)); - Assert.That(new[] { e.Buffer[0], e.Buffer[1] }, Is.EquivalentTo(new byte[] { 0xff, 0x01 })); - } - - [Test] - public void GetStringSize3() - { - WireEncoder e = new WireEncoder(0x0300); - Assert.That(e.GetStringSize(s_normal), Is.EqualTo(6)); - Assert.That(e.GetStringSize(s_long), Is.EqualTo(130)); - Assert.That(e.GetStringSize(s_big), Is.EqualTo(65540)); - } - - [Test] - public void WriteString3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteString(s_normal); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(6)); - Assert.That(e.Buffer, Is.EquivalentTo(new byte[] { 0x05, (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' })); - - e.Reset(); - e.WriteString(s_long); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(130)); - byte[] arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0x80, 0x01, (byte)'*', (byte)'*' })); - Assert.That(e.Buffer[128], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[129], Is.EqualTo((byte)'x')); - - e.Reset(); - e.WriteString(s_big); - Assert.That(e.Error, Is.Null); - Assert.That(e.Buffer.Length, Is.EqualTo(65540)); - arr = new[] { e.Buffer[0], e.Buffer[1], e.Buffer[2], e.Buffer[3] }; - Assert.That(arr, Is.EquivalentTo(new byte[] { 0x81, 0x80, 0x04, (byte)'*' })); - Assert.That(e.Buffer[65536], Is.EqualTo((byte)'*')); - Assert.That(e.Buffer[65537], Is.EqualTo((byte)'x')); - Assert.That(e.Buffer[65538], Is.EqualTo((byte)'x')); - Assert.That(e.Buffer[65539], Is.EqualTo((byte)'x')); - } - - [Test] - public void WriteValueError3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(v_empty); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - - [Test] - public void WriteValueNull3() - { - WireEncoder e = new WireEncoder(0x0300); - e.WriteValue(null); - Assert.That(e.Buffer.Length, Is.EqualTo(0)); - Assert.That(e.Error, Is.Not.Null); - } - } -}