Browse Source

first commit.

master
fajiao 3 years ago
parent
commit
98e74df427
  1. 63
      ConsoleTest.sln
  2. 2
      ConsoleTest.sln.DotSettings
  3. 57
      ConsoleTest/App.config
  4. 204
      ConsoleTest/AutoWeight/FingerPrint/FingerPrintManager.cs
  5. 71
      ConsoleTest/AutoWeight/FingerPrint/FingerPrintParam.cs
  6. 294
      ConsoleTest/AutoWeight/FingerPrint/TesoLiveSDK.cs
  7. 84
      ConsoleTest/AutoWeight/LedTW/LedTWManager.cs
  8. 3689
      ConsoleTest/AutoWeight/LedTW/bxdualsdk.cs
  9. 226
      ConsoleTest/AutoWeight/LedZK/LedZKManager.cs
  10. 966
      ConsoleTest/AutoWeight/LedZK/LedZKSDK.cs
  11. 31
      ConsoleTest/AutoWeight/Light/ILightManager.cs
  12. 35
      ConsoleTest/AutoWeight/Light/ILightRelay.cs
  13. 210
      ConsoleTest/AutoWeight/Light/LightManager.cs
  14. 65
      ConsoleTest/AutoWeight/Light/LightRelay.cs
  15. 206
      ConsoleTest/AutoWeight/Pos/PosManager.cs
  16. 274
      ConsoleTest/AutoWeight/Pos/PosSDK.cs
  17. 82
      ConsoleTest/AutoWeight/Pos/dll.txt
  18. 25
      ConsoleTest/AutoWeight/Pos/need.txt
  19. 20
      ConsoleTest/AutoWeight/Scales/IScales.cs
  20. 27
      ConsoleTest/AutoWeight/Scales/ScaleEventArgs.cs
  21. 61
      ConsoleTest/AutoWeight/Scales/Scales.cs
  22. 47
      ConsoleTest/AutoWeight/Scales/ScalesDefault.cs
  23. 47
      ConsoleTest/AutoWeight/Scales/ScalesHuiZhou.cs
  24. 143
      ConsoleTest/AutoWeight/Scales/ScalesManager.cs
  25. 44
      ConsoleTest/AutoWeight/Scales/ScalesZhuHai.cs
  26. 43
      ConsoleTest/AutoWeight/Some/MyThread.cs
  27. 109
      ConsoleTest/AutoWeight/Speak/SpeakHelper.cs
  28. 74
      ConsoleTest/AutoWeight/Speak/SpeakManager.cs
  29. 71
      ConsoleTest/AutoWeight/YkPos/YkPosManager.cs
  30. 130
      ConsoleTest/AutoWeight/YkPos/YkPosSDK.cs
  31. 213
      ConsoleTest/ConsoleTest.csproj
  32. 156
      ConsoleTest/PTZApi/Entity.cs
  33. 46
      ConsoleTest/PTZApi/IService.cs
  34. 340
      ConsoleTest/PTZApi/Service.cs
  35. 28
      ConsoleTest/PTZApi/Test.cs
  36. 41
      ConsoleTest/PTZApi/Util.cs
  37. 66
      ConsoleTest/Program.cs
  38. 35
      ConsoleTest/Properties/AssemblyInfo.cs
  39. 69
      ConsoleTest/Properties/app.manifest
  40. 93
      ConsoleTest/Test/AutoWeight/LedTest.cs
  41. 70
      ConsoleTest/Test/AutoWeight/LightTest.cs
  42. 106
      ConsoleTest/Test/AutoWeight/PosTest.cs
  43. 37
      ConsoleTest/Test/AutoWeight/WeightTest.cs
  44. 76
      ConsoleTest/Test/AutoWeight/YkPosTest.cs
  45. 310
      ConsoleTest/Test/Other/OtherTest.cs
  46. 44
      ConsoleTest/Test/Other/YuHuo.cs
  47. 184
      ConsoleTest/Util/CommonUtil.cs
  48. 115
      ConsoleTest/Util/ConfigUtil.cs
  49. 65
      ConsoleTest/Util/Encrypt/DesEncrypt.cs
  50. 66
      ConsoleTest/Util/Encrypt/Md5Helper.cs
  51. 50
      ConsoleTest/Util/EnvUtil.cs
  52. 572
      ConsoleTest/Util/HttpMethods.cs
  53. 72
      ConsoleTest/Util/JsonUtil.cs
  54. 180
      ConsoleTest/Util/PortHelper/ECSerialPort.cs
  55. 45
      ConsoleTest/Util/PortHelper/SerialCustomer.cs
  56. 47
      ConsoleTest/Util/PortHelper/SerialPortManager.cs
  57. 61
      ConsoleTest/Util/PortUtil/SerialPortBuilder.cs
  58. 51
      ConsoleTest/Util/PortUtil/SerialPortParam.cs
  59. 170
      ConsoleTest/Util/PortUtil/YcSerialPort.cs
  60. BIN
      ConsoleTest/data/image/logo.bmp
  61. 7
      ConsoleTest/data/light/lightCode.json
  62. 7
      ConsoleTest/data/light/lightCode2.json
  63. 7
      ConsoleTest/data/light/lightCode3.json
  64. 12
      ConsoleTest/data/light/lightCodeTemplate.json
  65. 7
      ConsoleTest/data/test.config
  66. BIN
      ConsoleTest/dll/Led5kSDK.dll
  67. BIN
      ConsoleTest/dll/TesoLive.dll
  68. 11
      ConsoleTest/packages.config
  69. 54
      EC.Helper/CameraSDK/Common/CameraException.cs
  70. 111
      EC.Helper/CameraSDK/Common/CameraStruct.cs
  71. 58
      EC.Helper/CameraSDK/Common/ICameraSDK.cs
  72. 848
      EC.Helper/CameraSDK/DaHua/DaHuaOriSDK.cs
  73. 137
      EC.Helper/CameraSDK/DaHua/DaHuaSDK.cs
  74. 226
      EC.Helper/CameraSDK/HiK/HiKOriSDK.cs
  75. 123
      EC.Helper/CameraSDK/HiK/HiKSDK.cs
  76. 150
      EC.Helper/CameraSDK/YuShi/YuShiOriSDK.cs
  77. 87
      EC.Helper/CameraSDK/YuShi/YuShiSDK.cs
  78. 151
      EC.Helper/EC.Helper.csproj
  79. 9
      EC.Helper/RabbitFunc/Compiler/CompilerException.cs
  80. 57
      EC.Helper/RabbitFunc/Compiler/IndexSpan.cs
  81. 258
      EC.Helper/RabbitFunc/Compiler/Parser.cs
  82. 97
      EC.Helper/RabbitFunc/Compiler/SourceLocation.cs
  83. 20
      EC.Helper/RabbitFunc/Compiler/TokenWithSpan.cs
  84. 403
      EC.Helper/RabbitFunc/Compiler/Tokenizer.cs
  85. 119
      EC.Helper/RabbitFunc/Expressions/BinaryExpression.cs
  86. 32
      EC.Helper/RabbitFunc/Expressions/ConditionalExpression.cs
  87. 29
      EC.Helper/RabbitFunc/Expressions/ConstantExpression.cs
  88. 238
      EC.Helper/RabbitFunc/Expressions/Expression.cs
  89. 146
      EC.Helper/RabbitFunc/Expressions/ExpressionCompiler.cs
  90. 65
      EC.Helper/RabbitFunc/Expressions/ExpressionType.cs
  91. 9
      EC.Helper/RabbitFunc/Expressions/LambdaCompilerException.cs
  92. 75
      EC.Helper/RabbitFunc/Expressions/LambdaExpression.cs
  93. 30
      EC.Helper/RabbitFunc/Expressions/MemberExpression.cs
  94. 88
      EC.Helper/RabbitFunc/Expressions/MethodCallExpression.cs
  95. 45
      EC.Helper/RabbitFunc/Expressions/ParameterExpression.cs
  96. 19
      EC.Helper/RabbitFunc/Expressions/SystemLambdaExpression.cs
  97. 48
      EC.Helper/RabbitFunc/Expressions/UnaryExpression.cs
  98. 21
      EC.Helper/RabbitFunc/Extern/AbsLambdaExpression.cs
  99. 21
      EC.Helper/RabbitFunc/Extern/AcosLambdaExpression.cs
  100. 21
      EC.Helper/RabbitFunc/Extern/AsinLambdaExpression.cs

63
ConsoleTest.sln

@ -0,0 +1,63 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32901.215
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleTest", "ConsoleTest\ConsoleTest.csproj", "{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EC.Helper", "EC.Helper\EC.Helper.csproj", "{83B3DB14-D962-4F46-977D-DA5B81D3248B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTest", "UnitTest\UnitTest.csproj", "{66782776-2FCE-4DCE-AF5A-798C8E56F378}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x86 = Debug|x86
HXFFFFFFFFFFF|Any CPU = HXFFFFFFFFFFF|Any CPU
HXFFFFFFFFFFF|x86 = HXFFFFFFFFFFF|x86
Release|Any CPU = Release|Any CPU
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.Debug|x86.ActiveCfg = Debug|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.HXFFFFFFFFFFF|Any CPU.ActiveCfg = Release|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.HXFFFFFFFFFFF|Any CPU.Build.0 = Release|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.HXFFFFFFFFFFF|x86.ActiveCfg = Release|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.HXFFFFFFFFFFF|x86.Build.0 = Release|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.Release|Any CPU.Build.0 = Release|Any CPU
{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}.Release|x86.ActiveCfg = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Debug|x86.ActiveCfg = Debug|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Debug|x86.Build.0 = Debug|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.HXFFFFFFFFFFF|Any CPU.ActiveCfg = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.HXFFFFFFFFFFF|Any CPU.Build.0 = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.HXFFFFFFFFFFF|x86.ActiveCfg = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.HXFFFFFFFFFFF|x86.Build.0 = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Release|Any CPU.Build.0 = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Release|x86.ActiveCfg = Release|Any CPU
{83B3DB14-D962-4F46-977D-DA5B81D3248B}.Release|x86.Build.0 = Release|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Debug|Any CPU.Build.0 = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Debug|x86.ActiveCfg = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Debug|x86.Build.0 = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.HXFFFFFFFFFFF|Any CPU.ActiveCfg = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.HXFFFFFFFFFFF|Any CPU.Build.0 = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.HXFFFFFFFFFFF|x86.ActiveCfg = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.HXFFFFFFFFFFF|x86.Build.0 = Debug|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Release|Any CPU.ActiveCfg = Release|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Release|Any CPU.Build.0 = Release|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Release|x86.ActiveCfg = Release|Any CPU
{66782776-2FCE-4DCE-AF5A-798C8E56F378}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5932126B-188B-4B1C-A213-C558A7CB5A9A}
EndGlobalSection
EndGlobal

2
ConsoleTest.sln.DotSettings

@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=Recv/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

57
ConsoleTest/App.config

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<!--入场前相机IP-->
<add key="CAMERA_ADDRESS" value="192.168.1.11" />
<add key="CAMERA_SOCKET_PORT" value="80" />
<add key="CAMERA_USERNAME" value="admin" />
<add key="CAMERA_PASSWORD" value="admin" />
<!-- Weight -->
<add key="Weight_Com" value="Com1" />
<add key="Weight_BaudRate" value="9600" />
<add key="Weight_ReceivedBytesThreshold" value="32" />
<!-- Light -->
<add key="Light_Com" value="Com2" />
<add key="Light_BaudRate" value="9600" />
<add key="Light_Code_Name" value="lightCode2.json" />
<!-- Led -->
<add key="Led_Ip" value="192.168.1.15" />
<add key="Led_Port" value="5005" />
<!-- Other -->
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<!--数据库服务WCF配置-->
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="IService_netTcpBinding" maxReceivedMessageSize="2147483647" transferMode="Buffered">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="12000000" />
<security mode="None">
<transport clientCredentialType="None">
</transport>
</security>
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="net.tcp://127.0.0.1:9999/CameraService" binding="netTcpBinding" contract="ConsoleTest.PTZApi.ICameraService" bindingConfiguration="IService_netTcpBinding" />
<endpoint address="net.tcp://127.0.0.1:9999/CruiseCameraService" binding="netTcpBinding" contract="ConsoleTest.PTZApi.ICruiseCameraService" bindingConfiguration="IService_netTcpBinding" />
<endpoint address="net.tcp://127.0.0.1:9999/CameraModelService" binding="netTcpBinding" contract="ConsoleTest.PTZApi.ICameraModelService" bindingConfiguration="IService_netTcpBinding" />
</client>
</system.serviceModel>
</configuration>

204
ConsoleTest/AutoWeight/FingerPrint/FingerPrintManager.cs

@ -0,0 +1,204 @@
using System.Text;
namespace ConsoleTest.AutoWeight.FingerPrint
{
/// <summary>
/// 暂时只测试了 USB 接口
/// </summary>
public class FingerPrintManager
{
//连接参数
private readonly FingerPrintParam _fpParam;
//通讯句柄
private int _handle;
//返回码
private int _ret;
public FingerPrintManager()
{
_fpParam = new FpUsbParam();
}
public FingerPrintManager(FingerPrintParam fpParam)
{
_fpParam = fpParam;
}
#region Start & Stop Server
/// <summary>
/// 开启服务
/// </summary>
/// <returns></returns>
public bool StartServer()
{
_ret = TesoLiveSDK.TcCreateHDL(_fpParam.Port, _fpParam.NPort, _fpParam.NRidx, _fpParam.NSped);
_handle = _ret;
return _ret >= 0;
}
/// <summary>
/// 停止服务
/// </summary>
/// <returns></returns>
public bool StopServer()
{
if (!IsConnected())
return true;
_ret = TesoLiveSDK.TcDeleteHDL(_handle);
if (_ret < 0)
return false;
_handle = -1;
return true;
}
#endregion Start & Stop Server
#region Tool Methods
/// <summary>
/// 获取设备内核号
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public bool GetDevKerNel(ref string data)
{
if (!IsConnected())
return false;
var builder = new StringBuilder();
_ret = TesoLiveSDK.TcGetDevVsin(_handle, builder);
data = _ret >= 0 ? builder.ToString() : string.Empty;
return _ret >= 0;
}
/// <summary>
/// 获取设备序列号
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public bool GetDevSn(ref string data)
{
if (!IsConnected())
return false;
var builder = new StringBuilder();
_ret = TesoLiveSDK.TcReadDevSn(_handle, builder);
data = _ret >= 0 ? builder.ToString() : string.Empty;
return _ret >= 0;
}
/// <summary>
/// 注册窗体默认开启
/// </summary>
/// <param name="able"></param>
/// <returns></returns>
public bool SetRegBoxAble(bool able)
{
if (!IsConnected())
return false;
var nIdx = 16;//#define T_SHOWREG 16 弹出注册窗体
var nVal = able ? 1 : 0;
_ret = TesoLiveSDK.TcExtnEntry(_handle, 0, nIdx, nVal, null);
return _ret >= 0;
}
/// <summary>
/// 认证窗体默认关闭
/// </summary>
/// <param name="able"></param>
/// <returns></returns>
public bool SetVerBoxAble(bool able)
{
if (!IsConnected())
return false;
var nIdx = 17;//#define T_SHOWVER 17 弹出认证窗体
var nVal = able ? 1 : 0;
_ret = TesoLiveSDK.TcExtnEntry(_handle, 0, nIdx, nVal, null);
return _ret >= 0;
}
/// <summary>
/// 控制设备上的 LED 闪灯和 BUZZER 蜂鸣,声光同时提示
/// </summary>
/// <param name="mode">0=短嘀,1=长嘀,2=嘀嘀</param>
/// <returns></returns>
public bool SetBeepLight(int mode)
{
if (!IsConnected())
return false;
mode %= 3;
_ret = TesoLiveSDK.TcBeepLight(_handle, mode);
return _ret >= 0;
}
/// <summary>
/// 获取指纹模板
/// </summary>
/// <param name="regFp"></param>
/// <returns></returns>
public bool GetRegFingerPrint(ref string regFp)
{
if (!IsConnected())
return false;
var builder = new byte[513];
_ret = TesoLiveSDK.TcDoTemplet(_handle, builder);
regFp = Encoding.ASCII.GetString(builder).Trim('\0');
return _ret >= 0;
}
/// <summary>
/// 获取指纹特征
/// </summary>
/// <param name="verFp"></param>
/// <returns></returns>
public bool GetVerFingerPrint(ref string verFp)
{
if (!IsConnected())
return false;
var builder = new byte[513];
_ret = TesoLiveSDK.TcDoFeature(_handle, builder);
verFp = Encoding.ASCII.GetString(builder).Trim('\0');
return _ret >= 0;
}
/// <summary>
/// 对比指纹模板和特征
/// </summary>
/// <param name="regFp"></param>
/// <param name="verFp"></param>
/// <returns></returns>
public bool MatchFingerPrint(string regFp, string verFp)
{
if (!IsConnected())
return false;
if (string.IsNullOrEmpty(regFp) || string.IsNullOrEmpty(verFp))
return false;
_ret = TesoLiveSDK.TcSafeMatch(_handle, verFp, regFp);
return _ret >= 0;
}
/// <summary>
/// 判断设备是否连接
/// </summary>
/// <returns></returns>
public bool IsConnected()
{
if (_handle <= 0)
return false;
return true;
}
/// <summary>
/// 返回函数运行返回码
/// </summary>
/// <returns>返回码</returns>
public int GetResultCode()
{
return _ret;
}
#endregion Tool Methods
}
}

71
ConsoleTest/AutoWeight/FingerPrint/FingerPrintParam.cs

@ -0,0 +1,71 @@
namespace ConsoleTest.AutoWeight.FingerPrint
{
/// <summary>
/// 基础连接参数
/// </summary>
public class FingerPrintParam
{
/// <summary>
/// 协议号(USB=0,COM=2)
/// </summary>
public int NPort { get; set; }
/// <summary>
/// 端口号 通讯端口号(USB=0,COM=[1, 255])
/// </summary>
public int Port { get; set; }
/// <summary>
/// 波特率索引号(波特率级别,默认给 3,即 9600,如表 1 所示)
/// </summary>
public int NRidx { get; set; }
/// <summary>
/// 串口是否提速(USB=0,COM=2)
/// </summary>
public int NSped { get; set; }
public bool IsUsb()
{
return NPort.Equals(0);
}
public bool IsCom()
{
return NPort.Equals(2);
}
public int GetPortType()
{
return NPort.Equals(0) ? 0 : 1;
}
}
/// <summary>
/// USB 连接参数
/// </summary>
public class FpUsbParam : FingerPrintParam
{
public FpUsbParam()
{
NPort = 0;
Port = 0;
NRidx = 3;
NSped = 0;
}
}
/// <summary>
/// Com 连接参数
/// </summary>
public class FpComParam : FingerPrintParam
{
public FpComParam()
{
NPort = 2;
Port = 1;
NRidx = 3;
NSped = 2;
}
}
}

294
ConsoleTest/AutoWeight/FingerPrint/TesoLiveSDK.cs

@ -0,0 +1,294 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleTest.AutoWeight.FingerPrint
{
/// <summary>
/// <para>指纹动态库有两套独立的对外接口,一套是简单接口,一套是复杂接口;</para>
/// <para>简单接口以函数名 FPI 开始,调用接口较少,开发者不用关心底层调用,直接调用对外接口即可,使用非常简单。但是这种方式相呆板,不能够进行配置。</para>
/// <para>复杂接口以函数名 Tc 开始,调用接口较多,需要自己对指纹设备或者算法进行控制,当然,也可以使用默认值。复杂接口可以非常灵活的使用,可以对一些功能进行配置,例如,是否显示对话框,配置超时时间等功能。</para>
/// </summary>
public class TesoLiveSDK
{
#region FPI(No Test)
/// <summary>
/// 获得注册指纹模板。驱动 USB 指纹设备时,可以获得图像
/// </summary>
/// <param name="nPort">端口号,0=USB,1=COM1,2=COM2,3=COM3...</param>
/// <param name="pRegBuf">输出的 B64 模板缓冲,最大 513 字节(含'\0'结束符)</param>
/// <param name="pnRegLen">返回注册指纹模板实际长度(不含'\0'结束符)</param>
/// <param name="pszErrMsg">返回出错时字符串信息,最大 64 字节(含'\0'结束符)</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int FPIGetTemplate(int nPort, byte[] pRegBuf, ref int pnRegLen, byte[] pszErrMsg);
//public static extern int FPIGetTemplate(int nPort, ref string pRegBuf, ref int pnRegLen, ref string pszErrMsg);
//int FPIGetTemplate(int nPort, char* pRegBuf, int* pnRegLen, char* pszErrMsg);
/// <summary>
/// 获得验证用的指纹特征;驱动 USB 指纹设备时,可以获得图像
/// </summary>
/// <param name="nPort">端口号,0=USB,1=COM1,2=COM2,3=COM3...</param>
/// <param name="pVerBuf">输出的 B64 特征缓冲,最大 513 字节(含'\0'结束符)</param>
/// <param name="pnVerLen">返回验证指纹特征实际长度(不含'\0'结束符)</param>
/// <param name="pszErrMsg">返回出错时字符串信息,最大 64 字节(含'\0'结束符)</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int FPIGetFeature(int nPort, ref byte pVerBuf, ref int pnVerLen, ref byte pszErrMsg);
//int FPIGetFeature(int nPort, char* pVerBuf, int* pnVerLen, char* pszErrMsg);
/// <summary>
/// 比对采集时得到的模板和特征数据,可指定安全级
/// </summary>
/// <param name="pRegBuf">输入的 B64 模板数据,最大 513 字节(含'\0'结束符)</param>
/// <param name="pVerBuf">输入的 B64 特征数据,最大 513 字节(含'\0'结束符)</param>
/// <param name="nLevel">全级别,数字[1, 5],默认为 3 级别</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int FPIMatch(string pRegBuf, string pVerBuf, int nLevel = 3);
//int FPIMatch(const char* pRegBuf, const char* pVerBuf,int nLevel);
/// <summary>
/// 取得指纹图像
/// </summary>
/// <param name="nImageIdx">要取得指纹图像的索引数字[1, 3]</param>
/// <returns>成功时:返回B64编码纯数据区图像,失败时:返回NULL</returns>
[DllImport("TesoLive.dll")]
public static extern string FPIGetImageData(int nImageIdx);
//char* FPIGetImageData(int nImageIdx);
/// <summary>
/// 通过前期采集的一幅指纹图象数据,产生验证用特征数据
/// </summary>
/// <param name="pImg">B64 编码图像,请参见 FPIGetImageData 函数中的说明</param>
/// <param name="pVerBuf">输出的B64特征缓冲,最大513字节(含'\0'结束符)</param>
/// <param name="pnVerLen">返回验证指纹特征实际长度(不含'\0'结束符)</param>
/// <param name="pszErrMsg">返回出错时字符串信息,最大 64 字节(含'\0'结束符)</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int FPIGetFeatureByImg(string pImg, ref byte pVerBuf, ref int pnVerLen, ref byte pszErrMsg);
//int FPIGetFeatureByImg(const char* pImg,char* pVerBuf, int* pnVerLen,char* pszErrMsg);
/// <summary>
/// 通过前期采集的三幅指纹图象数据,产生注册用模版数据
/// </summary>
/// <param name="pImg1">B64 编码图像 1,请参见 FPIGetImageData 函数中的说明</param>
/// <param name="pImg2">B64 编码图像 2,请参见 FPIGetImageData 函数中的说明</param>
/// <param name="pImg3">B64 编码图像 3,请参见 FPIGetImageData 函数中的说明</param>
/// <param name="pRegBuf">输出的B64模板缓冲,最大513字节(含'\0'结束符)</param>
/// <param name="pnRegLen">返回注册指纹模板实际长度(不含'\0'结束符)</param>
/// <param name="pszErrMsg">返回出错时字符串信息,最大 64 字节(含'\0'结束符)</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int FPIGetTemplateByImg(string pImg1, string pImg2, string pImg3, ref byte pRegBuf, ref int pnRegLen, ref byte pszErrMsg);
//int FPIGetTemplateByImg(const char* pImg1, const char* pImg2, const char* pImg3, char* pRegBuf, int* pnRegLen,char* pszErrMsg);
#endregion FPI(No Test)
#region Tc(Test)
/// <summary>
/// 创建通讯句柄,并初始化环境
/// </summary>
/// <param name="port">通讯端口号(USB=0,COM=[1, 255])</param>
/// <param name="nPort">协议号(USB=0,COM=2)</param>
/// <param name="nRidx">索引号(波特率级别,默认给 3,如表 1 所示)</param>
/// <param name="nSped">串口是否提速(如果是 USB 则,该值为 0,如果是串口,则该值为 2)</param>
/// <returns>成功时:返回值大于等于0(句柄),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcCreateHDL(int port, int nPort, int nRidx, int nSped);
//int TcCreateHDL(int Port, int nPort, int nRidx, int nSped);
/// <summary>
/// 释放句柄所占用资源,若设备已连接则会自行断开
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcDeleteHDL(int vHdl);
//int TcDeleteHDL(int vHdl);
/// <summary>
/// 连接设备,等待用户按捺 3 或者 4 次直到超时(超时默认 30 秒),成功后返回模板
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="hTpl">返回的模板数据(最大不会超过 513 字节)</param>
/// <returns>成功时:返回值大于等于0(模板长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcDoTemplet(int vHdl, byte[] hTpl);
//int TcDoTemplet(int vHdl, void* hTpl);
/// <summary>
/// 连接设备,等待用户按捺一次直到超时(默认超时 18 秒),成功后返回特征
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="hFea">返回的特征数据(最大不会超过 513 字节)</param>
/// <returns>成功时:返回值大于等于0(特征长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcDoFeature(int vHdl, byte[] hFea);
//int TcDoFeature(int vHdl, void* hFea);
/// <summary>
/// 基于安全级别,比对给定的特征和模板,判断它俩是否匹配
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄(一般传 0 值即可)</param>
/// <param name="hFea">指纹特征数据</param>
/// <param name="hTpl">指纹模板数据</param>
/// <param name="nLvl">安全等级[1-5]</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcSafeMatch(int vHdl, string hFea, string hTpl, int nLvl = 3);
//int TcSafeMatch(int vHdl, const void* hFea,const void* hTpl, int nLvl);
/// <summary>
/// 配置是否弹出对话框,采集指纹特征超时时间等
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="nRead">操作方向(0=设定新值,1=读取配置值)</param>
/// <param name="nIdx">准备要操作的功能代码(详见配置参数宏定义说明)</param>
/// <param name="nVal">要配置的新值(详见配置参数宏定义说明)</param>
/// <param name="hVoid">固定 NULL</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcExtnEntry(int vHdl, int nRead, int nIdx, int nVal, string hVoid);
//int TcExtnEntry(int vHdl, int nRead, int nIdx, int nVal, void* hVoid);
/// <summary>
/// 控制设备上的 LED 闪灯和 BUZZER 蜂鸣,声光同时提示
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="nMode">方式:0=短嘀,1=长嘀,2=嘀嘀</param>
/// <returns>成功时:返回值大于等于0,失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcBeepLight(int vHdl, int nMode);
//int TcBeepLight(int vHdl, int nMode);
/// <summary>
/// 获取设备的 32 字节的 SN 产品序列号+1 字节'\0'
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="chSn">返回的 SN 字符串(建议提供 64 个字节缓存)</param>
/// <returns>成功时:返回值大于等于0( SN 的长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcReadDevSn(int vHdl, StringBuilder chSn);
//int TcReadDevSn(int vHdl, char* chSn);
/// <summary>
/// 获取内核版本
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="devSn">返回的 SN 字符串(建议提供 64 个字节缓存)</param>
/// <returns>成功时:返回值大于等于0( SN 的长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcGetDevVsin(int vHdl, StringBuilder devSn);
#endregion Tc(Test)
#region Tc(No Test)
/// <summary>
/// 读取 Win32 的标准 BMP 文件到内存里
/// </summary>
/// <param name="chFile">要读取的来源 BMP 文件的路径</param>
/// <param name="hFpr">要写入的目标内存缓存区</param>
/// <param name="nStyle">固定为 3</param>
/// <returns>成功时:返回值大于等于0(编码后图像长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcLoadFrBmp(string chFile, IntPtr hFpr, int nStyle);
//int TcLoadFrBmp(const char* chFile, void* hFpr, int nStyle);
/// <summary>
/// 指定句柄内五个图像缓冲区中的一个,获取图像数据区数据;
/// 在调用此函数前,一定要先调用 TcDoTemplet 或者 TcDoFeature。否则调用失败
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="nIdx">图像缓冲号[0, 4],特征区号 128+[0, 4]</param>
/// <param name="hFpr">返回图像或特征数据区数据,如果是图像建议大小 90K 空间大小</param>
/// <returns>成功时:返回值大于等于0(图像/特征数据长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcGetImgDat(int vHdl, int nIdx, IntPtr hFpr);
//int TcGetImgDat(int vHdl, int nIdx, void* hFpr);
/// <summary>
/// 另存指纹图像为 Win32 的标准 BMP 文件格式
/// </summary>
/// <param name="chFile">要保存的目标 BMP 文件,已存在则覆盖</param>
/// <param name="hFpr">由 TcGetImgDat 获取的,将要保存的图像数据</param>
/// <returns>成功时:返回值大于等于0(保存的 BMP 文件字节大小),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcSaveAsBmp(string chFile, IntPtr hFpr);
//int TcSaveAsBmp(const char* chFile, const void* hFpr);
/// <summary>
/// 由给定的一枚指纹图像,提取出一枚指纹特征
/// </summary>
/// <param name="vHdl">TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="hFpr">由 TcGetImgDat 或者 TcLoadFrBmp 的一枚图像数据</param>
/// <param name="hFea">指纹特征数据(最大 513 字节,非定长)</param>
/// <returns>成功时:返回值大于等于0(特征长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcFeaFrmImg(int vHdl, IntPtr hFpr, StringBuilder hFea);
//int TcFeaFrmImg(int vHdl, const void* hFpr, void* hFea);
/// <summary>
/// 由给定的四枚指纹 BMP 图像(或特征),合成出一枚指纹模板
/// </summary>
/// <param name="vHdl">由 TcCreateHDL 获取的上下文控制句柄</param>
/// <param name="hFp0">由 TcGetImgDat 或者 TcLoadFrBmp 获取的四枚图像数据</param>
/// <param name="hFp1"></param>
/// <param name="hFp2"></param>
/// <param name="hFp3">其中第四枚图像可以传入 NULL</param>
/// <param name="hTpl">指纹模板数据(最大 513 字节,非定长)</param>
/// <returns>成功时:返回值大于等于0(模板长度),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcTplFrmImg(int vHdl, IntPtr hFp0, IntPtr hFp1, IntPtr hFp2, IntPtr hFp3, StringBuilder hTpl);
//int TcTplFrmImg(int vHdl, const void* hFp0, const void* hFp1, const void* hFp2, const void* hFp3, void* hTpl);
/// <summary>
/// 给定端口区间,速率,返回首个设备所在的端口号
/// </summary>
/// <param name="nBgn">要搜索的目标端口区间[],0 为 USB,>=1 为 COM</param>
/// <param name="nEnd"></param>
/// <param name="nRidx">串口波特率索引号[0, 7],对应为[1200, 115200]</param>
/// <param name="nMask">默认 0</param>
/// <param name="chFix">BP 盒的前后缀字串儿,可为 NULL,默认用'|'分隔</param>
/// <returns>成功时:返回值大于等于0(0 为 USB,>=1 为 COM,1-com1,2-com2…),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcWhereAreu(int nBgn, int nEnd, int nRidx, int nMask, string chFix);
//int TcWhereAreu(int nBgn, int nEnd, int nRidx, int nMask, const char* chFix);
/// <summary>
/// 判断是否有手指按捺(仅限于 USB 设备使用)
/// </summary>
/// <param name="vHdl">TcCreateHDL 获取的上下文控制句柄</param>
/// <returns>成功时:返回值大于等于0(有手指按捺),失败时:返回值小于0(详见函数返回码说明)</returns>
[DllImport("TesoLive.dll")]
public static extern int TcChkPressed(int vHdl);
//int TcChkPressed(int vHdl);
#endregion Tc(No Test)
}
}

84
ConsoleTest/AutoWeight/LedTW/LedTWManager.cs

@ -0,0 +1,84 @@
using System;
using System.Text;
namespace ConsoleTest.AutoWeight.LedTW
{
public class LedTWManager
{
private byte[] _ip;
private ushort _port;
public LedTWManager()
{
}
public LedTWManager(string ip, ushort port)
{
_ip = Encoding.Default.GetBytes(ip);
_port = port;
}
#region Start & Stop Server
/// <summary>
/// 开启服务
/// </summary>
/// <returns></returns>
public void OpenServer()
{
//初始化动态库
bxdualsdk.bxDual_InitSdk();
}
/// <summary>
/// 停止服务
/// </summary>
/// <returns></returns>
public void CloseServer()
{
//释放动态库
bxdualsdk.bxDual_ReleaseSdk();
}
#endregion Start & Stop Server
//删除节目
public static void DeleteProgram()
{
//初始化动态库
var err = bxdualsdk.bxDual_InitSdk();
Console.WriteLine($"bxDual_InitSdk:\t{err}");
var ip = Encoding.Default.GetBytes("192.168.1.155");
//获取节目列表
var driBlock = new bxdualsdk.GetDirBlock_G56();
err = bxdualsdk.bxDual_cmd_ofsReedDirBlock(ip, 5005, ref driBlock);
//获取节目详细信息
for (var i = 0; i < driBlock.fileNumber; i++)
{
var fileAttr = new bxdualsdk.FileAttribute_G56();
err = bxdualsdk.bxDual_cmd_getFileAttr(ref driBlock, (ushort)i, ref fileAttr);
Console.WriteLine("fileName:" + Encoding.Default.GetString(fileAttr.fileName));
//删除指定节目
err = bxdualsdk.bxDual_cmd_ofsDeleteFormatFile(ip, 5005, 1, fileAttr.fileName);
}
}
//删除节目
public bool DeleteAllProgram()
{
//获取节目列表
var driBlock = new bxdualsdk.GetDirBlock_G56();
var err = bxdualsdk.bxDual_cmd_ofsReedDirBlock(_ip, _port, ref driBlock);
if (err < 0)
return false;
//获取节目详细信息
for (var i = 0; i < driBlock.fileNumber; i++)
{
var fileAttr = new bxdualsdk.FileAttribute_G56();
err = bxdualsdk.bxDual_cmd_getFileAttr(ref driBlock, (ushort)i, ref fileAttr);
err = bxdualsdk.bxDual_cmd_ofsDeleteFormatFile(_ip, _port, 1, fileAttr.fileName);
}
return true;
}
}
}

3689
ConsoleTest/AutoWeight/LedTW/bxdualsdk.cs

File diff suppressed because it is too large

226
ConsoleTest/AutoWeight/LedZK/LedZKManager.cs

@ -0,0 +1,226 @@
using System.Text;
namespace ConsoleTest.AutoWeight.LedZK
{
public class LedZKManager
{
private byte[] _ip;
private ushort _port;
private uint _handle;
private byte _width;
private byte _height;
public LedZKManager()
{
_ip = Encoding.Default.GetBytes("192.168.0.199");
_port = 5005;
}
public LedZKManager(string ip, ushort port)
{
_ip = Encoding.Default.GetBytes(ip);
_port = port;
}
#region Start & Stop Server
/// <summary>
/// 开启服务
/// </summary>
/// <returns></returns>
public void StartServer()
{
//初始化动态库
LedZKSDK.InitSdk(2, 2);
_handle = LedZKSDK.CreateClient(_ip, _port, LedZKSDK.bx_5k_card_type.BX_6K1, 3, 1, null);
ReadScreen();
}
/// <summary>
/// 停止服务
/// </summary>
/// <returns></returns>
public void StopServer()
{
LedZKSDK.Destroy(_handle);
//释放动态库
LedZKSDK.ReleaseSdk();
}
#endregion Start & Stop Server
#region Util Methods
/// <summary>
/// 4x6 或 5x8
/// \C1代表红色,\C2代表绿色,\C3代表黄色
/// </summary>
/// <param name="areaId"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="text"></param>
/// <param name="singleLine">0x01:单行,0x02:多行</param>
/// <param name="newLine">0x01:手动换行,0x02:自动换行</param>
/// <param name="speed"></param>
/// <returns></returns>
public int SendDynamicArea(byte areaId, ushort x, ushort y, ushort width, ushort height, string text,
byte singleLine, byte newLine, byte speed)
{
var outText = Encoding.Default.GetBytes(text);
var header = new LedZKSDK.bx_5k_area_header
{
DynamicAreaLoc = areaId,
AreaType = 0x00,
AreaX = x,
AreaWidth = width,
AreaY = y,
AreaHeight = height,
RunMode = 0,
Timeout = 2,
SingleLine = singleLine,
NewLine = newLine,
Lines_sizes = 0,
DisplayMode = 0x01,
Speed = speed,
StayTime = 35 * 2,
Reserved1 = 0,
Reserved2 = 0,
Reserved3 = 0,
ExitMode = 0x00,
DataLen = outText.Length
};
return LedZKSDK.SCREEN_SendDynamicArea(_handle, header, (ushort)outText.Length, outText);
}
/// <summary>
/// 4x6 或 5x8
/// \C1代表红色,\C2代表绿色,\C3代表黄色
/// </summary>
/// </summary>
/// <param name="areaId"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="text"></param>
/// <param name="singleLine">0x01:单行,0x02:多行</param>
/// <param name="newLine">0x01:手动换行,0x02:自动换行</param>
/// <param name="speed"></param>
/// <returns></returns>
public int SendDynamicMoveArea(byte areaId, ushort x, ushort y, ushort width, ushort height, string text,
byte singleLine, byte newLine, byte speed)
{
var outText = Encoding.Default.GetBytes(text);
var header = new LedZKSDK.bx_5k_area_header
{
DynamicAreaLoc = areaId,
AreaType = 0x00,
AreaX = x,
AreaWidth = width,
AreaY = y,
AreaHeight = height,
RunMode = 0,
Timeout = 2,
SingleLine = singleLine,
NewLine = newLine,
Lines_sizes = 0,
DisplayMode = 0x03,
Speed = speed,
StayTime = 35 * 2,
Reserved1 = 0,
Reserved2 = 0,
Reserved3 = 0,
ExitMode = 0x00,
DataLen = outText.Length
};
return LedZKSDK.SCREEN_SendDynamicArea(_handle, header, (ushort)outText.Length, outText);
}
public void DelAllDynamicArea(byte min, byte max)
{
for (byte i = min; i <= max; i++)
DelDynamicArea(i);
}
public int DelDynamicArea(byte areaId)
{
return LedZKSDK.SCREEN_DelDynamicArea(_handle, areaId);
}
#endregion Util Methods
#region Common Methods
public int ReadScreen()
{
var status = new byte[24];
ushort len = 0;
var ret = LedZKSDK.CON_ReadScreen(_handle, status, ref len);
_width = status[4];
_height = status[6];
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="lightValue">当前亮度,强制调节亮度时有效,亮度值为0-15共16级。亮度值为15时亮度最高</param>
/// <returns></returns>
public int ForceSetBrightness(byte lightValue)
{
lightValue %= 16;
return LedZKSDK.SCREEN_SetBrightness(_handle, 1, lightValue, null);
}
/// <summary>
/// 获取屏号
/// </summary>
/// <param name="screenId"></param>
/// <returns></returns>
public int GetScreenId(ref ushort screenId)
{
return LedZKSDK.CON_ReadScreenID(_handle, ref screenId);
}
/// <summary>
/// 设置屏号
/// </summary>
/// <param name="screenid"></param>
/// <returns></returns>
public int SetScreenId(ushort screenid)
{
return LedZKSDK.CON_SetScreenID(_handle, screenid);
}
/// <summary>
/// 强制开机
/// </summary>
/// <returns></returns>
public int ForceTurnOn()
{
return LedZKSDK.SCREEN_ForceOnOff(_handle, 1);
}
/// <summary>
/// 强制关机
/// </summary>
/// <returns></returns>
public int ForceTurnOff()
{
return LedZKSDK.SCREEN_ForceOnOff(_handle, 2);
}
/// <summary>
/// 若ping命令执行成功,说明与控制卡通信成功
/// </summary>
/// <returns></returns>
public int Ping()
{
return LedZKSDK.CON_PING(_handle); ;
}
#endregion Common Methods
}
}

966
ConsoleTest/AutoWeight/LedZK/LedZKSDK.cs

@ -0,0 +1,966 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace ConsoleTest.AutoWeight.LedZK
{
public class LedZKSDK
{
#region
public class bx5k_err
{
public const int ERR_NO = 0; //No Error
public const int ERR_OUTOFGROUP = 1; //Command Group Error
public const int ERR_NOCMD = 2; //Command Not Found
public const int ERR_BUSY = 3; //The Controller is busy now
public const int ERR_MEMORYVOLUME = 4; //Out of the Memory Volume
public const int ERR_CHECKSUM = 5; //CRC16 Checksum Error
public const int ERR_FILENOTEXIST = 6; //File Not Exist
public const int ERR_FLASH = 7;//Flash Access Error
public const int ERR_FILE_DOWNLOAD = 8; //File Download Error
public const int ERR_FILE_NAME = 9; //Filename Error
public const int ERR_FILE_TYPE = 10;//File type Error
public const int ERR_FILE_CRC16 = 11;//File CRC16 Error
public const int ERR_FONT_NOT_EXIST = 12;//Font Library Not Exist
public const int ERR_FIRMWARE_TYPE = 13;//Firmware Type Error (Check the controller type)
public const int ERR_DATE_TIME_FORMAT = 14;//Date Time format error
public const int ERR_FILE_EXIST = 15;//File Exist for File overwrite
public const int ERR_FILE_BLOCK_NUM = 16;//File block number error
public const int ERR_COMMUNICATE = 100;//通信失败
public const int ERR_PROTOCOL = 101;//协议数据不正确
public const int ERR_TIMEOUT = 102;//通信超时
public const int ERR_NETCLOSE = 103;//通信断开
public const int ERR_INVALID_HAND = 104;//无效句柄
public const int ERR_PARAMETER = 105;//参数错误
public const int ERR_SHOULDREPEAT = 106;//需要重复上次数据包
public const int ERR_FILE = 107;//无效文件
}
#endregion
//串口停止位
public enum serial_stopbits : byte
{
COM_ONESTOPBIT = 0,
COM_ONE5STOPBITS = 1,
COM_TWOSTOPBITS = 2,
}
//串口校验模式
public enum serial_parity : byte
{
COM_NOPARITY = 0,
COM_ODDPARITY = 1,
COM_EVENPARITY = 2,
COM_MARKPARITY = 3,
COM_SPACEPARITY = 4,
}
//串口数据位
public enum serial_databits : byte
{
COM_4BITS = 4,
COM_5BITS = 5,
COM_6BITS = 6,
COM_7BITS = 7,
COM_8BITS = 8,
}
//控制器类型
public enum bx_5k_card_type : byte
{
BX_5K1 = 0x51,
BX_5K2 = 0x58,
BX_5MK2 = 0x53,
BX_5MK1 = 0x54,
BX_5K1Q_YY = 0x5c,
BX_Any = 0xFE,
BX_6K1 = 0x61,
BX_6K2 = 0x62,
BX_6K3 = 0x63,
BX_6K1_YY = 0x64,
BX_6K2_YY = 0x65,
BX_6K3_YY = 0x66,
BX_6K1_4G = 0x67,
BX_6K2_4G = 0x68,
}
//-------区域格式------
// area header | data |
//---------------------
//节目内区域定义
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct bx_5k_area_header
{
public byte AreaType;
public ushort AreaX;
public ushort AreaY;
public ushort AreaWidth;
public ushort AreaHeight;
public byte DynamicAreaLoc;
public byte Lines_sizes;
public byte RunMode;
public short Timeout;
public byte Reserved1;
public byte Reserved2;
public byte Reserved3;
public byte SingleLine;
public byte NewLine;
public byte DisplayMode;
public byte ExitMode;
public byte Speed;
public byte StayTime;
public int DataLen;
}
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct bx_5k_sound
{
public byte StoreFlag;
public byte SoundPerson;//一个字节
public byte SoundVolum;
public byte SoundSpeed;
public byte SoundDataMode;
public int SoundReplayTimes;
public int SoundReplayDelay;
public byte SoundReservedParaLen;
public int SoundDataLen;
}
[System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.StdCall)]
public delegate void CallBackClientClose(uint hand, int err);
//初始化动态库
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern void InitSdk(byte minorVer, byte majorVer);
//释放动态库
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern void ReleaseSdk();
//创建广播通讯模式
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern uint CreateBroadCast(byte[] broad_ip, uint broad_port, bx_5k_card_type card_type, byte[] barcode, byte Option, int mode);
//创建固定IP通讯模式
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern uint CreateClient(byte[] led_ip, uint led_port, bx_5k_card_type card_type, int tmout_sec, int mode, CallBackClientClose pCloseFunc);
//创建TCP Modbus通讯
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern uint CreateTcpModbus(byte[] led_ip, bx_5k_card_type card_type, CallBackClientClose pCloseFunc);
//创建串口通讯
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern uint CreateComClient(byte com, uint baudrate, bx_5k_card_type card_type, int mode, ushort ScreenID);
//创建串口Modbus通讯
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern uint CreateComModbus(byte com, uint baudrate, serial_parity Parity, serial_databits DataBits,
serial_stopbits StopBits, bx_5k_card_type card_type, ushort ScreenID);
//销毁通讯
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern void Destroy(uint dwHand);
//设置通讯超时
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern void SetTimeout(uint dwHand, uint nSec);
//ping
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_PING(uint dwHand);
//复位
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_Reset(uint dwHand);
//
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_ControllerStatus(uint dwHand, byte[] pStatus, ref ushort len);
//查询字库信息
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_CheckCurrentFont(uint dwHand, byte[] fontStatus, ref ushort len);
//回读客户信息
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_CheckCurrentCustomer(uint dwHand, byte[] CustomerStatus, ref ushort len);
//参数回读
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_ReadScreen(uint dwHand, byte[] ScreenStatus, ref ushort len);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_SytemClockCorrect(uint dwHand);
//查询固件状态
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_CheckCurrentFirmware(uint dwHand, byte[] FirmwareName, byte[] FirmwareVersion, byte[] FirmwareDateTime);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_SendFirmWareData(uint dwHand, byte overwrite, byte[] pFileName, byte[] FirmWareData, int FirmWareDataLen, CloseFunc pCloseFunc);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_FirmwareActivate(uint dwHand, byte[] FirmwareName);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_SetScreenID(uint dwHand, ushort newScreenID);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_ReadScreenID(uint dwHand, ref ushort pScreenID);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_ForceOnOff(uint dwHand, byte OnOffFlag);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_TimeTurnOnOff(uint dwHand, byte[] pTimer, int nGroup);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_SetBrightness(uint dwHand, byte BrightnessType, byte CurrentBrightness, byte[] BrightnessValue);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_SetWaitTime(uint dwHand, byte WaitTime);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_LockProgram(uint dwHand, byte LockFlag, byte StoreMode, byte[] ProgramFileName);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_DelDynamicArea(uint dwHand, byte DeleteAreaId);
//动态区
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_SendDynamicArea(uint dwHand, bx_5k_area_header header, ushort TextLen, byte[] AreaText);
//语音
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_SendSound(uint dwHand, bx_5k_sound sound, int TextLen, byte[] AreaText);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_SendSoundDynamicArea(uint dwHand, bx_5k_area_header header, ushort TextLen, byte[] AreaText, byte SoundMode, byte SoundPerson, byte SoundVolume, byte SoundSpeed, int sound_len, byte[] sounddata);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_Test(uint dwHand, byte TestTime);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SCREEN_CancelTimeOnOff(uint dwHand);
#region 设置特殊动态区动态
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_SetSpecialAppDynamic(uint dwHand, ushort AreaX, ushort AreaY, ushort AreaW, ushort AreaH,
byte DataType, byte Pagetotal, byte RunState, ushort Timeout, byte SingleLine, byte Lines_sizes, byte NewLine, ushort StayTime);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_SendPageData(uint dwHand, byte PageNum, ushort PageDataLen, byte[] PageData);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_SendLatticeMessage(uint dwHand, byte BlockFlag, ushort BlockAddr, byte[] BlockData, ushort BlockDataLen);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_DelSpecialAppDynamic(uint dwHand);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_SetIPAddress(uint dwHand, byte ConnnectMode, byte[] ip, byte[] SubnetMask, byte[] Gateway, ushort port,
byte ServerMode, byte[] ServerIPAddress, ushort ServerPort, byte[] ServerAccessPassword, ushort HeartBeatInterval, byte[] NetID);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_SetMACAddress(uint dwHand, byte[] MAC);
//设置特殊动态区动态
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_SetSpecialAppDynamic(int dwHand, ushort AreaX, ushort AreaY, ushort AreaW, ushort AreaH, byte DataType, byte Pagetotal,
byte RunState, ushort Timeout, byte SingleLine, byte Lines_sizes, byte NewLine, ushort StayTime);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_WebSearch(uint dwHand, ref ushort Status, ref ushort Error, byte[] IP,
byte[] SubNetMask, byte[] Gate, ref ushort Port, byte[] Mac, byte[] NetID);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_DelPageData(uint dwHand, byte PageLog);
#endregion
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_Formatting(uint dwHand);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_DeleteFile(uint dwHand, ushort FileNumber, byte[] pFileNameList);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_BeginSendMultiFiles(uint dwHand);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_SendFile(uint dwHand, byte overwrite, byte[] pFilePath);
//发送节目
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_SendFileData(uint dwHand, byte overwrite, byte[] pFileName, ushort DisplayType, byte PlayTimes,
byte[] ProgramLife, byte ProgramWeek, byte ProgramTime, byte[] Period, byte AreaNum, byte[] AreaDataList, int AreaDataListLen);
//添加扫描
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_SendScanData(uint dwHand, byte overwrite, byte[] pFileName, byte[] ScanData, int ScanDataLen);
//添加字库
public delegate void CloseFunc(int total, int sendlen);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_SendFontData(uint dwHand, byte overwrite, byte[] pFileName, byte FontWidth, byte FontHeight,
byte[] LibData, int LibData_len, byte FontEncode, CloseFunc pCloseFunc);
//设置屏参
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_SendScreenData(uint dwHand, byte overwrite, byte[] pFileName, ushort Address, byte Baudrate,
ushort ScreenWith, ushort ScreenHeight, byte Color, byte MirrorMode, byte OE, byte DA, byte RowOrder, byte FreqPar,
byte OEAngle, byte CommTimeout, byte TipLanguage, byte LatticeMode);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_EndSendMultiFiles(uint dwHand);
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int CON_SetDispInfo(uint dwHand, byte DispInfo);
//设置客户信息
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int OFS_SetFontInformation(uint dwHand, byte OverWrite, byte[] ClientMsg);
public delegate void CallBackCon(uint dwHand, string pid);
public delegate void CallBackLedClose(uint dwHand, string pid, int err_code);
//启动gprs服务器
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern bool StartGprsServer(uint port, CallBackCon pCallBackCon, CallBackLedClose pCallBackLedClose);
//关闭gprs服务器
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern void CloseGprsServer();
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern void SetGprsAliveTick(uint dwHand, int time_sec);
//扫描
//返回值:0:发送数据正确;ERR_TIMEOUT:通讯超时;其它:返回错误代码。
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SendAndRecvBuff(uint dwHand, byte cmd_group, byte cmd, byte[] cmd_data, ushort data_len, byte[] recv_data, ref short p_recv_len);
//返回值:0:发送数据正确;ERR_TIMEOUT:通讯超时;其它:返回错误代码。
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int SendBuff(uint dwHand, byte cmd_group, byte cmd, byte[] cmd_data, ushort data_len);
// 网络搜索
[DllImport("Led5kSDK.dll", CharSet = CharSet.Unicode)]
public static extern int BX5MK_WebSearch(uint dwHand, byte[] recv_buff, ushort[] recv_len);
}
public class ItemObject
{
public string Text = "";
public uint Value = 0;//可以多个
public ItemObject(string _text, uint _value)
{
Text = _text;
Value = _value;
}
}
public class Led5kstaticArea
{
public LedZKSDK.bx_5k_area_header header;
public string text;
public byte[] AreaToByteArray()
{
//计算header的大小:结构体bx_5k_area_header的大小
LedZKSDK.bx_5k_area_header tu = new LedZKSDK.bx_5k_area_header();
int hsz = Marshal.SizeOf(tu);
//计算len的大小
text = text.Replace("₩₩F", "\\F");
List<byte[]> Byte_Area = new List<byte[]>();
int Byte_t = 0;
string[] str_Area = text.Split('\\');
int font = 0;
for (int n = 0; n < str_Area.Length; n++)
{
if (n > 0 && str_Area[n].Length > 1)
{
if (str_Area[n].Substring(0, 2).Equals("FK"))
{
font = 1;
if (str_Area[n].Length > 5)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n].Substring(0, 5));
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
string Area_str = str_Area[n].Remove(0, 5);
byte[] Korean = System.Text.Encoding.Unicode.GetBytes(Area_str);
for (int k = 0; k < Korean.Length / 2; k++)
{
byte a = Korean[k * 2];
Korean[k * 2] = Korean[k * 2 + 1];
Korean[k * 2 + 1] = a;
}
Byte_Area.Add(Korean);
Byte_t += Korean.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("Unicode").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
else if (str_Area[n].Substring(0, 2).Equals("FE") || str_Area[n].Substring(0, 2).Equals("FO") || str_Area[n].Substring(0, 2).Equals("WF") || str_Area[n].Substring(0, 2).Equals("WC"))
{
font = 0;
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
else if (str_Area[n].Substring(0, 1).Equals("C") || str_Area[n].Substring(0, 1).Equals("D") || str_Area[n].Substring(0, 1).Equals("B") || str_Area[n].Substring(0, 1).Equals("T"))
{
if (font == 1)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n].Substring(0, 2));
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
string Area_str = str_Area[n].Remove(0, 2);
byte[] Korean = System.Text.Encoding.Unicode.GetBytes(Area_str);
for (int k = 0; k < Korean.Length / 2; k++)
{
byte a = Korean[k * 2];
Korean[k * 2] = Korean[k * 2 + 1];
Korean[k * 2 + 1] = a;
}
Byte_Area.Add(Korean);
Byte_t += Korean.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
else if (str_Area[n].Substring(0, 1).Equals("n"))
{
if (font == 1)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n].Substring(0, 1));
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
string Area_str = str_Area[n].Remove(0, 1);
byte[] Korean = System.Text.Encoding.Unicode.GetBytes(Area_str);
for (int k = 0; k < Korean.Length / 2; k++)
{
byte a = Korean[k * 2];
Korean[k * 2] = Korean[k * 2 + 1];
Korean[k * 2 + 1] = a;
}
Byte_Area.Add(Korean);
Byte_t += Korean.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
else
{
if (font == 1)
{
byte[] Korean = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[Korean.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < Korean.Length; c++)
{
special[c + 1] = Korean[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
}
else
{
if (n > 0)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
else
{
byte[] special = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
}
byte[] tmp = new byte[Byte_t];
int g = 0;
for (int n = 0; n < Byte_Area.Count(); n++)
{
if (n > 0)
{
for (int j = 0; j < Byte_Area[n].Length; j++)
{
tmp[g + j] = Byte_Area[n][j];
}
g += Byte_Area[n].Length;
}
else
{
for (int j = 0; j < Byte_Area[n].Length; j++)
{
tmp[j] = Byte_Area[n][j];
}
g += Byte_Area[n].Length;
}
}
int len = tmp.Length + hsz + 4;
header.DataLen = tmp.Length;
//先copy len
byte[] bt = new byte[len];
//byte[] lenToByte = System.BitConverter.GetBytes(len);
byte[] lenToByte = System.BitConverter.GetBytes(len);
lenToByte.CopyTo(bt, 0);
int index = lenToByte.Length;
//再copy header
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(hsz);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(header, structPtr, false);
//从内存空间拷到AreaDataList数组
Marshal.Copy(structPtr, bt, index, hsz);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//copy text
tmp.CopyTo(bt, index + hsz);
return bt;
}
public int getAreaLen()
{
LedZKSDK.bx_5k_area_header tu = new LedZKSDK.bx_5k_area_header();
int hsz = Marshal.SizeOf(tu);
//再考header
text = text.Replace("₩₩F", "\\F");
List<byte[]> Byte_Area = new List<byte[]>();
int Byte_t = 0;
string[] str_Area = text.Split('\\');
int font = 0;
for (int n = 0; n < str_Area.Length; n++)
{
if (n > 0 && str_Area[n].Length > 1)
{
if (str_Area[n].Substring(0, 2).Equals("FK"))
{
font = 1;
if (str_Area[n].Length > 5)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n].Substring(0, 5));
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
string Area_str = str_Area[n].Remove(0, 5);
byte[] Korean = System.Text.Encoding.Unicode.GetBytes(Area_str);
for (int k = 0; k < Korean.Length / 2; k++)
{
byte a = Korean[k * 2];
Korean[k * 2] = Korean[k * 2 + 1];
Korean[k * 2 + 1] = a;
}
Byte_Area.Add(Korean);
Byte_t += Korean.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("Unicode").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
else if (str_Area[n].Substring(0, 2).Equals("FE") || str_Area[n].Substring(0, 2).Equals("FO") || str_Area[n].Substring(0, 2).Equals("WF") || str_Area[n].Substring(0, 2).Equals("WC"))
{
font = 0;
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
else if (str_Area[n].Substring(0, 1).Equals("C") || str_Area[n].Substring(0, 1).Equals("D") || str_Area[n].Substring(0, 1).Equals("B") || str_Area[n].Substring(0, 1).Equals("T"))
{
if (font == 1)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n].Substring(0, 2));
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
string Area_str = str_Area[n].Remove(0, 2);
byte[] Korean = System.Text.Encoding.Unicode.GetBytes(Area_str);
for (int k = 0; k < Korean.Length / 2; k++)
{
byte a = Korean[k * 2];
Korean[k * 2] = Korean[k * 2 + 1];
Korean[k * 2 + 1] = a;
}
Byte_Area.Add(Korean);
Byte_t += Korean.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
else if (str_Area[n].Substring(0, 1).Equals("n"))
{
if (font == 1)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n].Substring(0, 1));
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
string Area_str = str_Area[n].Remove(0, 1);
byte[] Korean = System.Text.Encoding.Unicode.GetBytes(Area_str);
for (int k = 0; k < Korean.Length / 2; k++)
{
byte a = Korean[k * 2];
Korean[k * 2] = Korean[k * 2 + 1];
Korean[k * 2 + 1] = a;
}
Byte_Area.Add(Korean);
Byte_t += Korean.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
else
{
if (font == 1)
{
byte[] Korean = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[Korean.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < Korean.Length; c++)
{
special[c + 1] = Korean[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
else
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
}
else
{
if (n > 0)
{
byte[] special_1 = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
byte[] special = new byte[special_1.Length + 1];
special[0] = 0x5c;
for (int c = 0; c < special_1.Length; c++)
{
special[c + 1] = special_1[c];
}
Byte_Area.Add(special);
Byte_t += special.Length;
}
else
{
byte[] special = System.Text.Encoding.GetEncoding("GBK").GetBytes(str_Area[n]);
Byte_Area.Add(special);
Byte_t += special.Length;
}
}
}
byte[] tmp = new byte[Byte_t];
int g = 0;
for (int n = 0; n < Byte_Area.Count(); n++)
{
if (n > 0)
{
for (int j = 0; j < Byte_Area[n].Length; j++)
{
tmp[g + j] = Byte_Area[n][j];
}
g += Byte_Area[n].Length;
}
else
{
for (int j = 0; j < Byte_Area[n].Length; j++)
{
tmp[j] = Byte_Area[n][j];
}
g += Byte_Area[n].Length;
}
}
int len = tmp.Length + hsz + 4;
return len;
}
}
public class Led5kProgram
{
public string name;
public bool overwrite;
public ushort DisplayType;
public byte PlayTimes;
public bool IsValidAlways;
public ushort StartYear;
public byte StartMonth;
public byte StartDay;
public ushort EndYear;
public byte EndMonth;
public byte EndDay;
public byte ProgramWeek;
public bool IsPlayOnTime;
public byte StartHour;
public byte StartMinute;
public byte StartSecond;
public byte EndHour;
public byte EndMinute;
public byte EndSecond;
public byte AreaNum;
public List<Led5kstaticArea> m_arealist = new List<Led5kstaticArea>();
#region//转DCB码
public static byte byte2bcd(byte num)
{
int i = num;
return (byte)(i / 10 * 16 + i % 10);
}
public static byte bcd2byte(byte num)
{
int i = num;
return (byte)(i / 16 * 10 + i % 16);
}
public static byte[] short2bcd(ushort num)
{
int i = num;
byte high = (byte)(i / 100);
byte low = (byte)(i % 100);
byte[] tmp = new byte[2];
tmp[0] = byte2bcd(low);
tmp[1] = byte2bcd(high);
return tmp;
}
#endregion
public int SendProgram(uint hand)
{
byte[] ppFileName;
byte[] ProgramLife;
byte PlayPeriodGrpNum;
byte[] Period;
byte[] AreaDataList;
int AreaDataListLen;
int sum = 0;
foreach (Led5kstaticArea s in m_arealist)
{
sum += s.getAreaLen();
}
AreaDataList = new byte[sum];
int index = 0;
foreach (Led5kstaticArea s in m_arealist)
{
byte[] bt = s.AreaToByteArray();
bt.CopyTo(AreaDataList, index);
index += bt.Length;
}
AreaDataListLen = sum;
if (IsValidAlways == true)
{
ProgramLife = new byte[8];
ProgramLife[0] = 0xff;
ProgramLife[1] = 0xff;
ProgramLife[2] = 0xff;
ProgramLife[3] = 0xff;
ProgramLife[4] = 0xff;
ProgramLife[5] = 0xff;
ProgramLife[6] = 0xff;
ProgramLife[7] = 0xff;
}
else
{
ProgramLife = new byte[8];
byte[] tmp = Led5kProgram.short2bcd(StartYear);
ProgramLife[0] = tmp[0];
ProgramLife[1] = tmp[1];
ProgramLife[2] = byte2bcd(StartMonth);
ProgramLife[3] = byte2bcd(StartDay);
byte[] tmp1 = Led5kProgram.short2bcd(EndYear);
ProgramLife[4] = tmp1[0];
ProgramLife[5] = tmp1[1];
ProgramLife[6] = byte2bcd(EndMonth);
ProgramLife[7] = byte2bcd(EndDay);
}
ppFileName = System.Text.Encoding.Default.GetBytes(name);
if (IsPlayOnTime == true)
{
Period = new byte[7];
Period[0] = byte2bcd(StartHour);
Period[1] = byte2bcd(StartMinute);
Period[2] = byte2bcd(StartSecond);
Period[3] = byte2bcd(EndHour);
Period[4] = byte2bcd(EndMinute);
Period[5] = byte2bcd(EndSecond);
Period[6] = 0;
}
else
{
Period = null;
}
PlayPeriodGrpNum = Convert.ToByte(IsPlayOnTime ? 1 : 0);
return LedZKSDK.OFS_SendFileData(hand, 1, ppFileName, DisplayType, PlayTimes, ProgramLife,
ProgramWeek, PlayPeriodGrpNum, Period, AreaNum, AreaDataList, AreaDataListLen);
}
}
}

31
ConsoleTest/AutoWeight/Light/ILightManager.cs

@ -0,0 +1,31 @@
namespace ConsoleTest.AutoWeight.Light
{
public interface ILightManager
{
#region Start & Stop Server
public bool StartServer();
public bool StopServer();
public bool IsOpen();
#endregion Start & Stop Server
#region Control Lights
public bool OpenAllLight();
public bool CloseAllLight();
public bool OpenLight(int index);
public bool CloseLight(int index);
public bool LockLightOn(int index);
public bool LockLightOff(int index);
#endregion Control Lights
}
}

35
ConsoleTest/AutoWeight/Light/ILightRelay.cs

@ -0,0 +1,35 @@
namespace ConsoleTest.AutoWeight.Light
{
public interface ILightRelay
{
/// <summary>
/// 连接设备
/// </summary>
/// <returns></returns>
bool StartServer();
/// <summary>
/// 断开设备
/// </summary>
/// <returns></returns>
bool StopServer();
/// <summary>
/// 是否连接设备
/// </summary>
/// <returns></returns>
bool IsOpen();
/// <summary>
/// 发送 Ascii 编码
/// </summary>
/// <param name="text"></param>
bool SendAscii(string text);
/// <summary>
/// 发送 16进制 编码
/// </summary>
/// <param name="text"></param>
bool SendHex(string text);
}
}

210
ConsoleTest/AutoWeight/Light/LightManager.cs

@ -0,0 +1,210 @@
using ConsoleTest.Util;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
namespace ConsoleTest.AutoWeight.Light
{
public class LightManager : ILightManager
{
private LightRelay _lightRelay;
private string _comName;
private int _baudRate;
private string _fileName;
public LightManager()
{
}
public LightManager(string comName, int baudRate, string fileName)
{
_comName = comName;
_baudRate = baudRate;
_fileName = fileName;
_readCodeFlag = ReadLightCodeJson();
}
#region Start & Stop Server
/// <summary>
/// 开启连接
/// </summary>
/// <returns></returns>
public bool StartServer()
{
_lightRelay = new LightRelay(_comName, _baudRate);
var ret = _lightRelay.StartServer();
return ret;
}
/// <summary>
/// 关闭连接
/// </summary>
/// <returns></returns>
public bool StopServer()
{
_lightRelay?.StopServer();
_lightRelay = null;
return true;
}
public bool IsOpen()
{
return _lightRelay?.IsOpen() ?? false;
}
#endregion Start & Stop Server
#region Control Lights Code
private bool _readCodeFlag;
/// <summary>
/// 控制所有灯编码,1 为开启所有灯,2 为关闭所有灯
/// </summary>
private List<string> _ctrlAllLightCodeList;
/// <summary>
/// 开启某一路灯编码,不互斥,index 互相对应
/// </summary>
private List<string> _openLightCodeList;
/// <summary>
/// 关闭某一路灯编码,不互斥,index 互相对应
/// </summary>
private List<string> _closeLightCodeList;
/// <summary>
/// 互锁编码,控制只有一路灯亮,index 互相对应
/// </summary>
private List<string> _lockLightOnCodeList;
/// <summary>
/// 互锁编码,控制只有一路灯灭,index 互相对应
/// </summary>
private List<string> _lockLightOffCodeList;
private bool ReadLightCodeJson()
{
if (!File.Exists(_fileName)) return false;
JObject obj = JsonUtil.ReadFileJson(_fileName);
_ctrlAllLightCodeList = obj["CtrlAllLightCodeList"].ToObject<List<string>>();
_openLightCodeList = obj["OpenLightCodeList"].ToObject<List<string>>();
_closeLightCodeList = obj["CloseLightCodeList"].ToObject<List<string>>();
_lockLightOnCodeList = obj["LockLightOnCodeList"].ToObject<List<string>>();
_lockLightOffCodeList = obj["LockLightOffCodeList"].ToObject<List<string>>();
return true;
}
public bool IsReadCodeSuccess()
{
return _readCodeFlag;
}
#endregion Control Lights Code
#region Control Lights
/// <summary>
/// 开启所有灯
/// </summary>
/// <returns></returns>
public bool OpenAllLight()
{
var codeList = _ctrlAllLightCodeList;
var index = 1;
if (!IsIndexValid(codeList, index))
return false;
var code = codeList[index];
return _lightRelay.SendHex(code);
}
/// <summary>
/// 关闭所有灯
/// </summary>
/// <returns></returns>
public bool CloseAllLight()
{
var codeList = _ctrlAllLightCodeList;
var index = 2;
if (!IsIndexValid(codeList, index))
return false;
var code = codeList[index];
return _lightRelay.SendHex(code);
}
/// <summary>
/// 开启某一路灯
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public bool OpenLight(int index)
{
var codeList = _openLightCodeList;
if (!IsIndexValid(codeList, index))
return false;
var code = codeList[index];
return _lightRelay.SendHex(code);
}
/// <summary>
/// 关闭某一路灯
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public bool CloseLight(int index)
{
var codeList = _closeLightCodeList;
if (!IsIndexValid(codeList, index))
return false;
var code = codeList[index];
return _lightRelay.SendHex(code);
}
/// <summary>
/// 互斥开某一路灯
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public bool LockLightOn(int index)
{
var codeList = _lockLightOnCodeList;
if (!IsIndexValid(codeList, index))
return false;
var code = codeList[index];
return _lightRelay.SendHex(code);
}
/// <summary>
/// 互斥关某一路灯
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public bool LockLightOff(int index)
{
var codeList = _lockLightOffCodeList;
if (!IsIndexValid(codeList, index))
return false;
var code = codeList[index];
return _lightRelay.SendHex(code);
}
/// <summary>
/// 判断功能码是否可以使用
/// </summary>
/// <param name="codeList"></param>
/// <param name="index"></param>
/// <returns></returns>
public bool IsIndexValid(List<string> codeList, int index)
{
if (codeList == null)
return false;
if (index < 1 || index > codeList.Count - 1)
return false;
return true;
}
#endregion Control Lights
}
}

65
ConsoleTest/AutoWeight/Light/LightRelay.cs

@ -0,0 +1,65 @@
using ConsoleTest.Util.PortUtil;
using System;
namespace ConsoleTest.AutoWeight.Light
{
public class LightRelay : ILightRelay
{
private YcSerialPort _port;
private readonly string _comName;
private readonly int _baudRate;
public LightRelay(string comName, int baudRate)
{
_comName = comName;
_baudRate = baudRate;
}
public bool StartServer()
{
_port = SerialPortBuilder.CreateSerialPort(_comName, _baudRate);
try
{
_port.OpenCom();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
return true;
}
public bool StopServer()
{
_port?.CloseCom();
_port = null;
return true;
}
public bool IsOpen()
{
if (_port == null)
return false;
if (!_port.IsOpen())
return false;
return true;
}
public bool SendAscii(string text)
{
if (!IsOpen())
return false;
_port.SendAscii(text);
return true;
}
public bool SendHex(string text)
{
if (!IsOpen())
return false;
_port.SendHex(text);
return true;
}
}
}

206
ConsoleTest/AutoWeight/Pos/PosManager.cs

@ -0,0 +1,206 @@
namespace ConsoleTest.AutoWeight.Pos
{
public class PosManager
{
private int _portType { get; set; }//0 COM,1 LPT ,2 USB 3 ETH
private int _printer { get; set; }
private int _bitmapType { get; set; }
private int _paperType { get; set; } = 1; //0 88m 1 58m 2 76m
private int _result { get; set; }
public PosManager()
{
}
/// <summary>
/// 打开设备
/// </summary>
/// <param name="portType"></param>
/// <param name="bFile"></param>
/// <param name="path"></param>
/// <returns></returns>
public bool OpenDevice(int portType, bool bFile = false, string path = "")
{
string lpName;
_portType = portType;
switch (portType)
{
case PosSDK.POS_PT_COM:
lpName = "COM1:9600,N,8,1";
break;
case PosSDK.POS_PT_LPT:
lpName = "LPT1";
break;
case PosSDK.POS_PT_USB:
lpName = "SP-USB1";
break;
case PosSDK.POS_PT_NET:
lpName = "192.168.1.114";
break;
default:
lpName = "SP-USB1";
portType = PosSDK.POS_PT_USB;
break;
}
_printer = PosSDK.POS_Port_OpenA(lpName, portType, bFile, path);
SetResult(_printer);
return _printer >= 0;
}
/// <summary>
/// 关闭设备
/// </summary>
/// <returns></returns>
public bool CloseDevice()
{
int ret = PosSDK.POS_Port_Close(_printer);
SetResult(ret);
_printer = PosSDK.POS_ES_INVALIDPARA;
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 设备是否连接
/// </summary>
/// <returns></returns>
public bool IsConnected()
{
return _printer >= 0;
}
public int GetResult()
{
return _result;
}
private void SetResult(int ret)
{
_result = ret;
}
/// <summary>
/// 初始化打印机
/// </summary>
/// <returns></returns>
public bool InitPrinter()
{
int ret = PosSDK.POS_Control_ReSet(_printer);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 选择字符对齐(居左/居中/居右)方式
/// </summary>
/// <param name="alignType">0:左对齐,1:居中,2:右对齐</param>
/// <returns></returns>
public bool SetAlign(int alignType)
{
int ret = PosSDK.POS_Control_AlignType(_printer, alignType);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 设置打印左边距和打印区域
/// </summary>
/// <param name="iLeft">设置左边距,默认值为 0</param>
/// <param name="iWidth">设置打印区域,默认值为 0</param>
/// <returns></returns>
public bool SetLeftMargin(int iLeft, int iWidth)
{
int ret = PosSDK.POS_Control_SetPrintPosition(_printer, iLeft, iWidth);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 缓冲数据
/// </summary>
/// <param name="strBuff"></param>
/// <param name="ilen"></param>
/// <returns></returns>
public bool PrintData(byte[] strBuff, int ilen)
{
int ret = PosSDK.POS_Output_PrintData(_printer, strBuff, ilen);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 打印本地单色位图
/// </summary>
/// <param name="bmpPath">本地单色位图存储路径</param>
/// <returns></returns>
public bool PrintBmp(string bmpPath)
{
int ret = PosSDK.POS_Output_PrintBmpDirectA(_printer, bmpPath);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 打印格式化后的字符串
/// </summary>
/// <param name="iFont">0:选择标准 ASCII 字体A(12×24),1:选择压缩 ASCII 字体B(9×17)</param>
/// <param name="iThick">0:取消加粗模式,1:选择加粗模式</param>
/// <param name="iWidth">0:取消倍宽模式,1:选择倍宽模式</param>
/// <param name="iHeight">0:取消倍高模式,1:选择倍高模式</param>
/// <param name="iUnderLine">0:取消下划线模式,1:选择下划线模式</param>
/// <param name="lpstring">以空字符结尾的字符串</param>
/// <returns></returns>
public bool PrintStr(int iFont, int iThick, int iWidth, int iHeight, int iUnderLine, string lpstring)
{
int ret = PosSDK.POS_Output_PrintFontStringA(_printer, iFont, iThick, iWidth, iHeight, iUnderLine, lpstring);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 打印缓冲区内容,进纸由参数 iLines 设置的行数并切纸
/// </summary>
/// <param name="type">0:全切,1:半切</param>
/// <param name="len">进纸行数</param>
/// <returns></returns>
public bool CutPaper(int type = 0, int len = 1)
{
int ret = PosSDK.POS_Control_CutPaper(_printer, type, len);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
public bool Color24_GrayBW(string path1, string path2)
{
int ret = PosSDK.Color24_GrayBW(path1, path2);
SetResult(ret);
return ret == PosSDK.POS_ES_SUCCESS;
}
/// <summary>
/// 是否纸尽
/// </summary>
/// <returns></returns>
public bool IsPaperExhaust()
{
int ret = PosSDK.POS_Status_RTQueryTypeStatus(_printer, 4);
SetResult(ret);
return ret == PosSDK.POS_ES_PAPEROUT;
}
/// <summary>
/// 是否将纸尽
/// </summary>
/// <returns></returns>
public bool IsPaperWillExhaust()
{
int ret = PosSDK.POS_Status_RTQueryTypeStatus(_printer, 4);
SetResult(ret);
return ret == PosSDK.POS_ES_PAPERENDING;
}
}
}

274
ConsoleTest/AutoWeight/Pos/PosSDK.cs

@ -0,0 +1,274 @@
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleTest.AutoWeight.Pos
{
public class PosSDK
{
#region Custom
public struct PosParam
{
private string lpName;
private string portType;
private bool bFile;
private string path;
}
#endregion Custom
#region Const
// pritner connect way
public const int POS_PT_COM = 1000;
public const int POS_PT_LPT = 1001;
public const int POS_PT_USB = 1002;
public const int POS_PT_NET = 1003;
// printer state
public const int POS_PS_NORMAL = 3001;
public const int POS_PS_PAPEROUT = 3002;
public const int POS_PS_HEAT = 3003;
public const int POS_PS_DOOROPEN = 3004;
public const int POS_PS_BUFFEROUT = 3005;
public const int POS_PS_CUT = 3006;
public const int POS_PS_DRAWERHIGH = 3007;
public const int POS_ES_PAPERENDING = 6; //纸将尽
public const int POS_ES_DRAWERHIGH = 5; //钱箱高电平
public const int POS_ES_CUT = 4; //切刀未复位
public const int POS_ES_DOOROPEN = 3; //纸仓门开
public const int POS_ES_HEAT = 2; //机头过热
public const int POS_ES_PAPEROUT = 1; //打印机缺纸
public const int POS_ES_SUCCESS = 0; //成功/发送成功/状态正常/打印完成
public const int POS_ES_INVALIDPARA = -1; //参数错误
public const int POS_ES_WRITEFAIL = -2; //写失败
public const int POS_ES_READFAIL = -3; //读失败
public const int POS_ES_NONMONOCHROMEBITMAP = -4; //非单色位图
public const int POS_ES_OVERTIME = -5; //超时/写超时/读超时/打印未完成
public const int POS_ES_FILEOPENERROR = -6; //文件/图片打开失败
public const int POS_ES_OTHERERRORS = -100; //其他原因导致的错误
// barcode type
public const int POS_BT_UPCA = 4001;
public const int POS_BT_UPCE = 4002;
public const int POS_BT_JAN13 = 4003;
public const int POS_BT_JAN8 = 4004;
public const int POS_BT_CODE39 = 4005;
public const int POS_BT_ITF = 4006;
public const int POS_BT_CODABAR = 4007;
public const int POS_BT_CODE93 = 4073;
public const int POS_BT_CODE128 = 4074;
// 2D barcode type
public const int POS_BT_PDF417 = 4100;
public const int POS_BT_DATAMATRIX = 4101;
public const int POS_BT_QRCODE = 4102;
// HRI type
public const int POS_HT_NONE = 4011;
public const int POS_HT_UP = 4012;
public const int POS_HT_DOWN = 4013;
public const int POS_HT_BOTH = 4014;
//TSPL
public const int TSPL_PRINTER_STATUS_OUTPAPER = 1;//打印机缺纸
public const int TSPL_PRINTER_STATUS_WORK = 2; //打印中
public const int TSPL_PRINTER_STATUS_ENCLOSURENOCLOSE = 3; //机壳未关
public const int TSPL_PRINTER_STATUS_ERROR = 4; //打印机内部错误
public const int TSPL_PARAM_LESS_EQUAL_ZERO = -2; //参数小于等于0
public const int TSPL_PARAM_GREAT_RANGE = -3; //参数大于指定范围
public const int TSPL_SUCCESS = 0;
public const int TSPL_IDERROR = -1;
#endregion Const
#region Method
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Port_OpenA")]
public static extern int POS_Port_OpenA(string lpName, int iPort, bool bFile, string path);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintstringA")]
public static extern int POS_Output_PrintstringA(int printID, string strBuff);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintData")]
public static extern int POS_Output_PrintData(int printID, byte[] strBuff, int ilen);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Port_Close")]
public static extern int POS_Port_Close(int printID);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_CutPaper")]
public static extern int POS_Control_CutPaper(int printID, int type, int len);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_CashDraw")]
public static extern int POS_Control_CashDraw(int printID, int iNum, int time1, int time2);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Status_QueryStatus")]
public static extern int POS_Status_QueryStatus(int printID);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Status_RTQueryStatus")]
public static extern int POS_Status_RTQueryStatus(int printID);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Status_RTQueryTypeStatus")]
public static extern int POS_Status_RTQueryTypeStatus(int printID, int n);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_DownloadBmpToFlashA")]
public static extern int POS_Output_DownloadBmpToFlashA(int printID, string strPath);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_DownloadBmpToFlashNumA")]
public static extern int POS_Control_DownloadBmpToFlashNumA(int printID, string strPath, int num);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintBmpDirectA")]
public static extern int POS_Output_PrintBmpDirectA(int printID, string strPath);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintFontStringA")]
public static extern int POS_Output_PrintFontStringA(int printID, int iFont, int iThick, int iWidth, int iHeight, int iUnderLine, string lpString);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Input_PrinterId")]
public static extern int POS_Input_PrinterId(int printID, StringBuilder Buff);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_BlackMark")]
public static extern int POS_Control_BlackMark(int printID);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_SetPrintPosition")]
public static extern int POS_Control_SetPrintPosition(int printID, int iLeft, int iWidth);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Status_QueryTaskStatus")]
public static extern int POS_Status_QueryTaskStatus(int printID, int second);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintFlashBmp")]
public static extern int POS_Output_PrintFlashBmp(int printID, int n);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintOneDimensionalBarcodeA")]
public static extern int POS_Output_PrintOneDimensionalBarcodeA(int printID, int iType, int iWidth, int iHeight, int hri, string lpstring);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintTwoDimensionalBarcodeA")]
public static extern int POS_Output_PrintTwoDimensionalBarcodeA(int printID, int iType, int parameter1, int parameter2, int parameter3, string lpstring);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_DownloadRamBmpA")]
public static extern int POS_Output_DownloadRamBmpA(int printID, string lpFilePath);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_PrintRamBmp")]
public static extern int POS_Output_PrintRamBmp(int printID, int n);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_PrintTestpage")]
public static extern int POS_Control_PrintTestpage(int printID);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "Color24_GrayBW")]
public static extern int Color24_GrayBW(string szSourceFile, string szTargetFile);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_SetRotaryPrint")]
public static extern int POS_Control_SetRotaryPrint(int printID, int n);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_OppositeColor")]
public static extern int POS_Control_OppositeColor(int printID, bool bOppsite);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_AlignType")]
public static extern int POS_Control_SetRotaryPrint(int printID, bool iAlignType);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Output_SendLocalFileA")]
public static extern int POS_Output_SendLocalFileA(int printID, string lpFilePath);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_ReSet")]
public static extern int POS_Control_ReSet(int printID);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_SetPrintFontC")]
public static extern int POS_Control_SetPrintFontC(int printID, bool iDoubleWidth, bool iDoubleHeight, bool iUnderLine);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_SetInvertedPrint")]
public static extern int POS_Control_SetInvertedPrint(int printID, int n);
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "POS_Control_AlignType")]
public static extern int POS_Control_AlignType(int printID, int iAlignType);
//--------------ztongli.20170123--------------
//设置页宽页高
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "PageSetupTSPL")]
public static extern int PageSetupTSPL(int printID, int PageWidth, int PageHeight);
//画线
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "DrawLineTSPL")]
public static extern int DrawLineTSPL(int printID, int StartX, int StartY, int LineWidth, int LineHeight);
//TL51打印
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "PrintTSPL")]
public static extern int PrintTSPL(int printID, int Set, int Copy);
//画矩形
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "DrawBorderTSPL")]
public static extern int DrawBorderTSPL(int printID, int LineWidth, int top_left_x, int top_left_y, int bottom_right_x, int bottom_right_y);
//文字
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "DrawTextTSPL")]
public static extern int DrawTextTSPL(int printID, int start_x, int start_y, bool isSimplifiedChinese, int xMultiplication, int yMultiplication, int rotate, string content);
//一维条码
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "DrawBarCodeTSPL")]
public static extern int DrawBarCodeTSPL(int printID, int start_x, int start_y, string type, int height, bool isReadable, int rotate, int narrowWidth, int wideWidth, string content);
////清空缓冲区
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "ClearBuffTSPL")]
public static extern int ClearBuffTSPL(int printID);
//二维条码
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "Draw2DBarCodeTSPL")]
public static extern int Draw2DBarCodeTSPL(int printID, int start_x, int start_y, string Max, string content);
//下载位图
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "DownLoadBitMapTSPL")]
public static extern int DownLoadBitMapTSPL(int printID, bool isMoveFlash, string PathName);
//将图片刷到缓冲区
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "PutBitMapTSPL")]
public static extern int PutBitMapTSPL(int printID, int start_x, int start_y, string fileName);
//得到打印机状态
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "GetPrinterStatusTSPL")]
public static extern int GetPrinterStatusTSPL(int printID);
//控制蜂鸣器发出一声响
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "DriveBeepTSPL")]
public static extern int DriveBeepTSPL(int printID);
//设置国际字符集
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "SetCharsetNameTSPL")]
public static extern int SetCharsetNameTSPL(int printID, string CharsetName);
//控制进纸或退纸距离
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "SetPaperbackOrPaperFeedTSPL")]
public static extern int SetPaperbackOrPaperFeedTSPL(int printID, bool isFeedBack, int mDot);
//指定的区域反相打印命令
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "ReverseAreaTSPL")]
public static extern int ReverseAreaTSPL(int printID, int start_x, int start_y, int width, int height);
//选择字符代码页
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "SelectCodePageTSPL")]
public static extern int SelectCodePageTSPL(int printID, int value);
//设置标签间垂直间距
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "SetGAPTSPL")]
public static extern int SetGAPTSPL(int printID, double value);
//定义标签的参考坐标原点命令
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "SetLabelReferenceTSPL")]
public static extern int SetLabelReferenceTSPL(int printID, int x, int y);
//TL21打印
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "PrintTSPL21")]
public static extern int PrintTSPL21(int printID, int Set);
//用于确认机型是TL21便于内部区别指令以及相关条件
[DllImport("POS_SDK.dll", CharSet = CharSet.Ansi, EntryPoint = "SetIs21")]
public static extern int SetIs21();
#endregion Method
}
}

82
ConsoleTest/AutoWeight/Pos/dll.txt

@ -0,0 +1,82 @@
********************************************
**由于DLL的特殊性,只能查看函数名/功能名!**
********************************************
ClearBuffTSPL
Color24_GrayBW
DownLoadBitMapTSPL
Draw2DBarCodeTSPL
DrawBarCodeTSPL
DrawBorderTSPL
DrawLineTSPL
DrawTextTSPL
DriveBeepTSPL
GetPrinterStatusTSPL
NetGetStatus
NetWrite
NetWriteClose
NetWriteOpen
POS_Control_AlignType
POS_Control_BeginMacro
POS_Control_BlackMark
POS_Control_CancelMacro
POS_Control_CashDraw
POS_Control_ClearBuffer
POS_Control_CutPaper
POS_Control_DuplePrint
POS_Control_EndMacro
POS_Control_FeedLines
POS_Control_OppositeColor
POS_Control_PlayMacro
POS_Control_PrintTestpage
POS_Control_ReSet
POS_Control_SetInvertedPrint
POS_Control_SetLineSpace
POS_Control_SetPrintFontC
POS_Control_SetPrintFontE
POS_Control_SetPrintPosition
POS_Control_SetRotaryPrint
POS_Input_PrinterId
POS_Input_ReadPrinter
POS_Output_DownloadBmpToFlashA
POS_Output_DownloadBmpToFlashNumA
POS_Output_DownloadBmpToFlashW
POS_Output_DownloadRamBmpA
POS_Output_DownloadRamBmpW
POS_Output_PrintBarcodeA
POS_Output_PrintBarcodeW
POS_Output_PrintBmpDirectA
POS_Output_PrintBmpDirectW
POS_Output_PrintBmpInFlash
POS_Output_PrintBuffAndFeedLines
POS_Output_PrintData
POS_Output_PrintFlashBmp
POS_Output_PrintFontStringA
POS_Output_PrintFontStringW
POS_Output_PrintOneDimensionalBarcodeA
POS_Output_PrintOneDimensionalBarcodeW
POS_Output_PrintRamBmp
POS_Output_PrintStringA
POS_Output_PrintStringW
POS_Output_PrintTwoDimensionalBarcodeA
POS_Output_PrintTwoDimensionalBarcodeW
POS_Output_SendLocalFileA
POS_Output_SendLocalFileW
POS_Port_Close
POS_Port_OpenA
POS_Port_OpenW
POS_Status_GetVersion
POS_Status_QueryStatus
POS_Status_QueryTaskStatus
POS_Status_RTQueryStatus
POS_Status_RTQueryTypeStatus
PageSetupTSPL
PrintTSPL21
PrintTSPL51
PutBitMapTSPL
ReverseAreaTSPL
SelectCodePageTSPL
SetCharsetNameTSPL
SetGAPTSPL
SetIs21
SetLabelReferenceTSPL
SetPaperbackOrPaperFeedTSPL

25
ConsoleTest/AutoWeight/Pos/need.txt

@ -0,0 +1,25 @@
OpenDevice();//打开设备1
CloseDevice();//关闭设备1
IsConnected();//是否连接1
IsPaperExhaust();//是否纸尽1
InitPrinter();//初始化 or 重置1
SetAlign();//居中,居左,居右1
PrintRasterBmp();//打印图片1
PrintStr();//打印字符串1
SetEmphasized();//字体加粗1
SetLeftMargin();//设置左边距1
FeedPaper();//走纸,留空隙1
CutPaper();//切纸1
//设置 58mm

20
ConsoleTest/AutoWeight/Scales/IScales.cs

@ -0,0 +1,20 @@
using System;
namespace ConsoleTest.AutoWeight.Scales
{
/// <summary>
/// 秤接口
/// </summary>
public interface IScales
{
bool StartServer();
bool StopServer();
bool IsOpen();
event EventHandler<ScaleEventArgs> OnRecData;
void RecData(object sender, byte[] buf);
}
}

27
ConsoleTest/AutoWeight/Scales/ScaleEventArgs.cs

@ -0,0 +1,27 @@
using System;
namespace ConsoleTest.AutoWeight.Scales
{
/// <summary>
/// 称重事件
/// </summary>
public class ScaleEventArgs : EventArgs
{
/// <summary>
/// 重量
/// </summary>
public decimal Weight { get; }
/// <summary>
/// 重量单位
/// </summary>
public string Units { get; }
//事件参数重载
public ScaleEventArgs(decimal weight, string units = "kg")
{
Weight = weight;
Units = units;
}
}
}

61
ConsoleTest/AutoWeight/Scales/Scales.cs

@ -0,0 +1,61 @@
using ConsoleTest.Util.PortUtil;
using System;
namespace ConsoleTest.AutoWeight.Scales
{
public class Scales : IScales
{
private YcSerialPort _port;
protected string ComName;
protected int BaudRate;
protected int ReceivedBytesThreshold;
public Scales()
{
}
public Scales(string comName, int baudRate)
{
ComName = comName;
BaudRate = baudRate;
ReceivedBytesThreshold = 32;
}
public Scales(string comName, int baudRate, int receivedBytesThreshold)
{
ComName = comName;
BaudRate = baudRate;
ReceivedBytesThreshold = receivedBytesThreshold;
}
public bool StartServer()
{
_port = SerialPortBuilder.CreateSerialPort(ComName, BaudRate, ReceivedBytesThreshold);
_port.OnRecData += RecData;
_port.OpenCom();
return true;
}
public bool StopServer()
{
_port?.CloseCom();
_port = null;
return true;
}
public bool IsOpen()
{
if (_port == null)
return false;
if (!_port.IsOpen())
return false;
return true;
}
public virtual event EventHandler<ScaleEventArgs> OnRecData;
public virtual void RecData(object sender, byte[] buf)
{
}
}
}

47
ConsoleTest/AutoWeight/Scales/ScalesDefault.cs

@ -0,0 +1,47 @@
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleTest.AutoWeight.Scales
{
public class ScalesDefault : Scales
{
public ScalesDefault()
{
}
public ScalesDefault(string comName, int baudRate)
{
ComName = comName;
BaudRate = baudRate;
}
public override event EventHandler<ScaleEventArgs> OnRecData;
public override void RecData(object sender, byte[] buf)
{
var weightBuf = Encoding.UTF8.GetString(buf);
var weightArgs = weightBuf.Split('\n');
var digitLimit = 3;
foreach (var weightArg in weightArgs)
{
var args = Regex.Split(weightArg.Trim(), @"\s+", RegexOptions.IgnoreCase);
if (args.Length != 3)
continue;
if (!(args[0].Equals("+") ^ args[0].Equals("-")))
continue;
var weight = Math.Round(Convert.ToDecimal(args[0] + args[1]), digitLimit);
var units = args[2];
//if (weight <= 0)
// continue;
var scaleArgs = new ScaleEventArgs(weight, units);
OnRecData?.Invoke(sender, scaleArgs);
break;
}
}
}
}

47
ConsoleTest/AutoWeight/Scales/ScalesHuiZhou.cs

@ -0,0 +1,47 @@
using ConsoleTest.Util;
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleTest.AutoWeight.Scales
{
public class ScalesHuiZhou : Scales
{
public ScalesHuiZhou()
{
}
public ScalesHuiZhou(string comName, int baudRate, int receivedBytesThreshold) : base(comName, baudRate, receivedBytesThreshold)
{
}
public override event EventHandler<ScaleEventArgs> OnRecData;
public override void RecData(object sender, byte[] buf)
{
string tempBuf = Encoding.UTF8.GetString(buf);
string[] splitBufArray = tempBuf.Split('\r');
foreach (var item in splitBufArray)
{
if (item.Length != 16) { continue; }
tempBuf = item;
Console.WriteLine($"item:{tempBuf}, length:{tempBuf.Length}");
MatchCollection mc = Regex.Matches(tempBuf, @"(\d+)");
Console.WriteLine($"mc:{mc}, count:{mc.Count}");
for (int i = 0; i < mc.Count; i++)
{
Console.Write($"{i}:{mc[i].Value},");
}
Console.WriteLine();
if (mc.Count != 3) { continue; }
string weightArg = mc[1].Value;
decimal weight = CommonUtil.WeightStrToDec(weightArg) / 1000;
string unit = "t";
Console.WriteLine($"weight:{weight}{unit}");
var scaleArgs = new ScaleEventArgs(weight, unit);
OnRecData?.Invoke(sender, scaleArgs);
break;
}
}
}
}

143
ConsoleTest/AutoWeight/Scales/ScalesManager.cs

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleTest.AutoWeight.Scales
{
public class ScalesManager
{
public Scales Scales;
private string _comName;
private int _baudRate;
public ScalesManager()
{
}
public ScalesManager(string comName, int baudRate)
{
_comName = comName;
_baudRate = baudRate;
}
#region Start & Stop
public bool StartServer()
{
Scales = new ScalesDefault(_comName, _baudRate);
Scales.OnRecData += RecData;
Scales.StartServer();
return true;
}
public void SetCom(string comName, int baudRate)
{
_comName = comName;
_baudRate = baudRate;
}
public bool StopServer()
{
Scales?.StopServer();
Scales = null;
return true;
}
#endregion Start & Stop
#region Set Send
private bool _canSend = false;
public void StartSend()
{
_canSend = true;
}
public void StopSend()
{
_canSend = false;
}
#endregion Set Send
#region Rec Data
public event EventHandler<decimal> OnRecData;
private readonly object lockWeightObj = new object();
public void RecData(object sender, ScaleEventArgs scaleArgs)
{
try
{
Monitor.Enter(lockWeightObj);
if (_canSend != true)
return;
decimal weight = scaleArgs.Weight;
if (weight <= 0)
return;
AppendList(weight);
if (GetListLen() <= lenLimit / 2)
return;
decimal avgWeight = GetAVGWeight();
decimal diff = Math.Abs(weight - avgWeight) / avgWeight;
if (diff <= 0.001m)
{
OnRecData?.Invoke(sender, avgWeight);
StopSend();
ClearList();
}
}
finally
{
Monitor.Exit(lockWeightObj);
}
}
#endregion Rec Data
#region 滤波
private List<decimal> WeightList = new List<decimal>();
private readonly int lenLimit = 10;
private int GetListLen()
{
return WeightList.Count;
}
public void AppendList(decimal inNumber)
{
if (inNumber <= 0)
return;
if (WeightList.Count >= lenLimit)
{
WeightList.RemoveAt(0);
}
WeightList.Add(inNumber);
}
public void ClearList()
{
WeightList = new List<decimal>();
}
public decimal GetAVGWeight()
{
decimal totalWeight = 0.0m;
foreach (decimal value in WeightList)
{
totalWeight += value;
}
decimal avgWeight = totalWeight / GetListLen();
return avgWeight;
}
#endregion 滤波
}
}

44
ConsoleTest/AutoWeight/Scales/ScalesZhuHai.cs

@ -0,0 +1,44 @@
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleTest.AutoWeight.Scales
{
public class ScalesZhuHai : Scales
{
public ScalesZhuHai()
{
}
public ScalesZhuHai(string comName, int baudRate, int receivedBytesThreshold) : base(comName, baudRate, receivedBytesThreshold)
{
}
public override event EventHandler<ScaleEventArgs> OnRecData;
public override void RecData(object sender, byte[] buf)
{
var weightBuf = Encoding.UTF8.GetString(buf);
var weightArgs = weightBuf.Split('\n');
var digitLimit = 4;
foreach (var weightArg in weightArgs)
{
var args = Regex.Split(weightArg.Trim(), @"\s+", RegexOptions.IgnoreCase);
if (args.Length != 3)
continue;
if (!(args[0].Equals("+") ^ args[0].Equals("-")))
continue;
var weight = Math.Round(Convert.ToDecimal(args[0] + args[1]), digitLimit);
var units = args[2];
//if (weight <= 0)
// continue;
var scaleArgs = new ScaleEventArgs(weight, units);
OnRecData?.Invoke(sender, scaleArgs);
break;
}
}
}
}

43
ConsoleTest/AutoWeight/Some/MyThread.cs

@ -0,0 +1,43 @@
using System;
using System.Threading;
namespace ConsoleTest.AutoWeight.Some
{
public class MyThread
{
private Thread _boardThread;
private bool boardThreadStopFlg;
public void StartStationBoard()
{
boardThreadStopFlg = false;
_boardThread = new Thread(StationBoard);
_boardThread.IsBackground = true;//设置为后台线程
_boardThread.Start();
}
public void StopStationBoard()
{
boardThreadStopFlg = true;
//_boardThread?.Abort();
_boardThread = null;
}
private void StationBoard()
{
try
{
var i = 0;
while (!boardThreadStopFlg)
{
Console.WriteLine(++i);
Thread.Sleep(1000);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

109
ConsoleTest/AutoWeight/Speak/SpeakHelper.cs

@ -0,0 +1,109 @@
using System;
using System.Speech.Synthesis;
namespace ConsoleTest.AutoWeight.Speak
{
public class SpeakHelper
{
private static SpeechSynthesizer _curSpeak = new SpeechSynthesizer
{
Volume = 100,//音量 [0, 100]
Rate = 0//语速 [-10, 10]
};
public SpeakHelper()
{
}
#region Start & Stop Server
public static void Open(int volume = 100, int rate = 0)
{
_curSpeak = new SpeechSynthesizer
{
Volume = volume,
Rate = rate
};
}
public static void Close()
{
if (!IsOpen())
return;
_curSpeak.Pause();
_curSpeak.Dispose();
_curSpeak = null;
}
/// <summary>
/// 开启连接
/// 音量 [0, 100]
/// 语速 [-10, 10]
/// </summary>
/// <returns></returns>
public static void ReOpen(int volume = 100, int rate = 0)
{
Close();
Open(volume, rate);
}
#endregion Start & Stop Server
#region
public static bool IsOpen()
{
return _curSpeak != null;
}
/// <summary>
/// Microsoft Huihui Desktop
/// Microsoft Zira Desktop
/// </summary>
/// <param name="name"></param>
public static void SelectVoice(string name)
{
_curSpeak.SelectVoice(name);
}
public static void SelectVoice(VoiceGender gender, VoiceAge age)
{
if (!IsOpen())
return;
_curSpeak.SelectVoiceByHints(gender, age);
}
public static void GetVoices()
{
foreach (var voice in _curSpeak.GetInstalledVoices())
{
var info = voice.VoiceInfo;
Console.WriteLine($"Name:{info.Name}, Culture:{info.Culture}, Gender:{info.Gender}, Age:{info.Age}");
}
}
#endregion
#region Tool Methods
/// <summary>
/// </summary>
public static void Speak(string text)
{
if (!IsOpen())
return;
_curSpeak.Speak(text);
}
public static void SpeakAsync(string text, bool cancelAll = true)
{
if (!IsOpen())
return;
if (cancelAll)
_curSpeak.SpeakAsyncCancelAll();
_curSpeak.SpeakAsync(text);
}
#endregion Tool Methods
}
}

74
ConsoleTest/AutoWeight/Speak/SpeakManager.cs

@ -0,0 +1,74 @@
using System.Speech.Synthesis;
namespace ConsoleTest.AutoWeight.Speak
{
public class SpeakManager
{
private SpeechSynthesizer _curSpeech;
public SpeakManager()
{
}
#region Start & Stop Server
/// <summary>
/// 开启连接
/// </summary>
/// <returns></returns>
public void StartServer()
{
_curSpeech = new SpeechSynthesizer
{
Volume = 100,//音量 [0, 100]
Rate = 0//语速 [-10, 10]
};
}
public void ReStartServer()
{
StopServer();
StartServer();
}
/// <summary>
/// 关闭连接
/// </summary>
/// <returns></returns>
public void StopServer()
{
if (!IsOpen())
return;
_curSpeech.Pause();
_curSpeech.Dispose();
_curSpeech = null;
}
#endregion Start & Stop Server
#region Tool Methods
/// <summary>
/// </summary>
public void Speak(string text)
{
if (!IsOpen())
return;
_curSpeech.Speak(text);
}
public void SpeakAsync(string text, bool cancelAll = true)
{
if (cancelAll)
_curSpeech.SpeakAsyncCancelAll();
_curSpeech.SpeakAsync(text);
}
public bool IsOpen()
{
return _curSpeech != null;
}
#endregion Tool Methods
}
}

71
ConsoleTest/AutoWeight/YkPos/YkPosManager.cs

@ -0,0 +1,71 @@
using System.Text;
namespace ConsoleTest.AutoWeight.YkPos
{
internal class YkPosControl
{
///
// static int iret = 0;
private static bool bIsOpen = false;
public bool IsOpen
{
get { return bIsOpen; }
}
public static int OpenDevice()
{
return YkPosSDK.OpenDevice();
}
public static int CloseDevice()
{
return YkPosSDK.CloseDevice();
}
public static int InitPrinter()
{
return YkPosSDK.InitPrinter();
}
public static int PrintStr(StringBuilder pstr)
{
return YkPosSDK.PrintStr(pstr);
}
public static int IsConnected()
{
return YkPosSDK.IsConnected();
}
public static int FeedPaper()
{
return YkPosSDK.FeedPaper();
}
public static int GetStatus(byte n)
{
return YkPosSDK.GetStatus(n);
}
public static int GetPrinterStatus(byte n)
{
return YkPosSDK.GetPrinterStatus(n);
}
public static int PrintRasterBmp(StringBuilder pBmpFile)
{
return YkPosSDK.PrintRasterBmp(pBmpFile);
}
public static int PrintBitmap(StringBuilder pBmpFile)
{
return YkPosSDK.PrintBitmap(pBmpFile);
}
public static int CutPaper()
{
return YkPosSDK.CutPaper();
}
}
}

130
ConsoleTest/AutoWeight/YkPos/YkPosSDK.cs

@ -0,0 +1,130 @@
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleTest.AutoWeight.YkPos
{
internal class YkPosSDK
{
[DllImport("YkPosdll.dll")]
public static extern int YkOpenDevice(int iport, int baud);
[DllImport("YkPosdll.dll")]
private static extern int YkCloseDevice();
[DllImport("YkPosdll.dll")]
private static extern int YkIsConnected();
[DllImport("YkPosdll.dll")]
private static extern int YkInitPrinter();
[DllImport("YkPosdll.dll", CharSet = CharSet.Ansi, EntryPoint = "YkPrintStr", CallingConvention = CallingConvention.StdCall)]
private static extern int YkPrintStr([MarshalAs(UnmanagedType.LPStr)] StringBuilder pstr);
[DllImport("YkPosdll.dll")]
private static extern int YkFeedPaper();
[DllImport("YkPosdll.dll")]
private static extern int YkGetStatus(byte n);
[DllImport("YkPosdll.dll")]
private static extern int YkGetPrinterStatus(byte n);
[DllImport("YkPosdll.dll", CharSet = CharSet.Ansi, EntryPoint = "YkPrintRasterBmp", CallingConvention = CallingConvention.StdCall)]
private static extern int YkPrintRasterBmp([MarshalAs(UnmanagedType.LPStr)] StringBuilder pBmpFile);
[DllImport("YkPosdll.dll", CharSet = CharSet.Ansi, EntryPoint = "YkPrintBitmap", CallingConvention = CallingConvention.StdCall)]
private static extern int YkPrintBitmap([MarshalAs(UnmanagedType.LPStr)] StringBuilder pBmpFile, int m);
[DllImport("YkPosdll.dll", CharSet = CharSet.Ansi, EntryPoint = "YkPrintBarCode", CallingConvention = CallingConvention.StdCall)]
private static extern int YkPrintBarCode(int m, int n, [MarshalAs(UnmanagedType.LPStr)] StringBuilder barcode);
[DllImport("YkPosdll.dll")]
private static extern int YkCutPaper(int m, int n);
public static int OpenDevice()
{
int i;
i = YkOpenDevice(13, 0);
return i;
}
public static int CloseDevice()
{
int i;
i = YkCloseDevice();
return i;
}
public static int IsConnected()
{
int i;
i = YkIsConnected();
return i;
}
public static int InitPrinter()
{
int i;
i = YkInitPrinter();
return i;
}
public static int PrintStr([MarshalAs(UnmanagedType.LPStr)] StringBuilder pstr)
{
int i;
i = YkPrintStr(pstr);
return i;
}
public static int PrintRasterBmp([MarshalAs(UnmanagedType.LPStr)] StringBuilder pBmpFile)
{
int i;
i = YkPrintRasterBmp(pBmpFile);
return i;
}
public static int PrintBitmap([MarshalAs(UnmanagedType.LPStr)] StringBuilder pBmpFile)
{
int i;
i = YkPrintBitmap(pBmpFile, 33);
return i;
}
public static int FeedPaper()
{
int i;
i = YkFeedPaper();
return i;
}
public static int GetStatus(byte n)
{
int i;
i = YkGetStatus(n);
return i;
}
public static int GetPrinterStatus(byte n)
{
int i;
i = YkGetPrinterStatus(n);
return i;
}
public static int PrintBarCode([MarshalAs(UnmanagedType.LPStr)] StringBuilder barcode)
{
int i;
int n = barcode.Length;
i = YkPrintBarCode(72, n, barcode);
return i;
}
public static int CutPaper()
{
int i;
i = YkCutPaper(66, 0);
return i;
}
}
}

213
ConsoleTest/ConsoleTest.csproj

@ -0,0 +1,213 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{37FD52CA-308E-4CC4-9E9F-4072E1C1C216}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ConsoleTest</RootNamespace>
<AssemblyName>ConsoleTest</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<LangVersion>8.0</LangVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>false</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<PropertyGroup>
<SignManifests>false</SignManifests>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualBasic" />
<Reference Include="NewLife.Core, Version=10.0.2022.1001, Culture=neutral, PublicKeyToken=8343210f0b524456, processorArchitecture=MSIL">
<HintPath>..\packages\NewLife.Core.10.0.2022.1001\lib\net461\NewLife.Core.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Configuration.ConfigurationManager.5.0.0\lib\net461\System.Configuration.ConfigurationManager.dll</HintPath>
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.Data.OracleClient" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Management" />
<Reference Include="System.Net" />
<Reference Include="System.Runtime, Version=4.1.1.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.4.3.1\lib\net462\System.Runtime.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Security" />
<Reference Include="System.Security.AccessControl, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.AccessControl.5.0.0\lib\net461\System.Security.AccessControl.dll</HintPath>
</Reference>
<Reference Include="System.Security.Permissions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Permissions.5.0.0\lib\net461\System.Security.Permissions.dll</HintPath>
</Reference>
<Reference Include="System.Security.Principal.Windows, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Principal.Windows.5.0.0\lib\net461\System.Security.Principal.Windows.dll</HintPath>
</Reference>
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Speech" />
<Reference Include="System.Transactions" />
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="AutoWeight\LedTW\bxdualsdk.cs" />
<Compile Include="AutoWeight\LedTW\LedTWManager.cs" />
<Compile Include="AutoWeight\LedZK\LedZKManager.cs" />
<Compile Include="AutoWeight\LedZK\LedZKSDK.cs" />
<Compile Include="AutoWeight\Light\ILightManager.cs" />
<Compile Include="AutoWeight\Light\ILightRelay.cs" />
<Compile Include="AutoWeight\Light\LightManager.cs" />
<Compile Include="AutoWeight\Light\LightRelay.cs" />
<Compile Include="AutoWeight\Pos\PosManager.cs" />
<Compile Include="AutoWeight\Pos\PosSDK.cs" />
<Compile Include="AutoWeight\Scales\ScalesHuiZhou.cs" />
<Compile Include="AutoWeight\Some\MyThread.cs" />
<Compile Include="AutoWeight\YkPos\YkPosManager.cs" />
<Compile Include="AutoWeight\YkPos\YkPosSDK.cs" />
<Compile Include="PTZApi\Entity.cs" />
<Compile Include="PTZApi\IService.cs" />
<Compile Include="PTZApi\Service.cs" />
<Compile Include="PTZApi\Test.cs" />
<Compile Include="PTZApi\Util.cs" />
<Compile Include="Test\AutoWeight\PosTest.cs" />
<Compile Include="Test\AutoWeight\WeightTest.cs" />
<Compile Include="Test\AutoWeight\LedTest.cs" />
<Compile Include="Test\AutoWeight\LightTest.cs" />
<Compile Include="Test\AutoWeight\YkPosTest.cs" />
<Compile Include="Test\Other\OtherTest.cs" />
<Compile Include="Util\CommonUtil.cs" />
<Compile Include="Util\ConfigUtil.cs" />
<Compile Include="AutoWeight\FingerPrint\FingerPrintManager.cs" />
<Compile Include="AutoWeight\FingerPrint\FingerPrintParam.cs" />
<Compile Include="AutoWeight\FingerPrint\TesoLiveSDK.cs" />
<Compile Include="Util\EnvUtil.cs" />
<Compile Include="Util\HttpMethods.cs" />
<Compile Include="Util\JsonUtil.cs" />
<Compile Include="Util\PortUtil\SerialPortBuilder.cs" />
<Compile Include="Util\PortUtil\SerialPortParam.cs" />
<Compile Include="Util\PortUtil\YcSerialPort.cs" />
<Compile Include="Test\Other\YuHuo.cs" />
<Compile Include="AutoWeight\Scales\ScaleEventArgs.cs" />
<Compile Include="AutoWeight\Scales\ScalesZhuHai.cs" />
<Compile Include="AutoWeight\Scales\ScalesDefault.cs" />
<Compile Include="AutoWeight\Scales\Scales.cs" />
<Compile Include="AutoWeight\Scales\IScales.cs" />
<Compile Include="AutoWeight\Scales\ScalesManager.cs" />
<Compile Include="AutoWeight\Speak\SpeakHelper.cs" />
<Compile Include="AutoWeight\Speak\SpeakManager.cs" />
<Compile Include="Util\Encrypt\Md5Helper.cs" />
<Compile Include="Util\Encrypt\DesEncrypt.cs" />
<Compile Include="Util\PortHelper\SerialCustomer.cs" />
<Compile Include="Util\PortHelper\SerialPortManager.cs" />
<Compile Include="Util\PortHelper\ECSerialPort.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="data\light\lightCode.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="data\light\lightCode2.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="data\light\lightCode3.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="data\light\lightCodeTemplate.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
<None Include="Properties\app.manifest" />
<None Include="data\test.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.7.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.7.2 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Content Include="AutoWeight\Pos\dll.txt" />
<Content Include="AutoWeight\Pos\need.txt" />
<Content Include="data\image\logo.bmp">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

156
ConsoleTest/PTZApi/Entity.cs

@ -0,0 +1,156 @@
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace ConsoleTest.PTZApi
{
[DataContract(IsReference = true)]
public class CameraModel
{
[DataMember]
public int ID { get; set; }
[DataMember]
public int indexID { get; set; }
[DataMember]
public string CamName { get; set; }
[DataMember]
public int CameraTypeID { get; set; }
[DataMember]
public int CameraThreeInfoID { get; set; }
[DataMember]
public string ServerIP { get; set; }
[DataMember]
public int ServerPort { get; set; }
[DataMember]
public string ServerUserName { get; set; }
[DataMember]
public string ServerPwd { get; set; }
[DataMember]
public string ServerId { get; set; }
[DataMember]
public string PTZServerIP { get; set; }
[DataMember]
public int FatherNodeID { get; set; }
[DataMember]
public bool UVConvert { get; set; }
[DataMember]
public double PointLat { get; set; }
[DataMember]
public double PointLng { get; set; }
[DataMember]
public int PlateType { get; set; }
public string BelongIP { get; set; }
}
#region 与ptz服务交互使用结构体
//----------------------------------------------------------------------------------------
// 与ptz服务交互使用结构体
//----------------------------------------------------------------------------------------
//注意这个属性不能少
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct RequestRealControl
{
public int token;
public CameraInfo CameraInfo;
public RealControlType realControlType;
//请求时 状态 true:开始;false:结束 答复时:true:成功;其他:失败
public bool Status;
public PresentInfo PresentInfo;
public PTZPosInfo PTZPositionInfo;
//int数组,SizeConst表示数组的个数,在转换成
//byte数组前必须先初始化数组,再使用,初始化
//的数组长度必须和SizeConst一致,例test = new int[6];
//[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
//public int[] test;
}
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 4)]
public struct CameraInfo
{
public int cameraid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)]
public char[] ip;
public ushort port;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
private char[] user;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
private char[] password;
}
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 4)]
public struct PresentInfo
{
public int presentNo;//预置位编号
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
private char[] PresentName; // 预置位名称
}
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 4)]
public struct PTZPosInfo
{
public int FP;//p信息
public int FT;//T信息
public int FZ;//Z信息
public int TitlePosMin;//描述点垂直参数min
public int ZoomPosMin;//描述点变倍参数min
public float FHorWidth;//水平宽度 精确到小数点后两位 *10000
public float FVerWidth;//垂直宽度 精确到小数点后两位 *10000
public float FFold;//zoom=1没变时的焦距 精确到小数点后两位 *100
public int CameraType;
}
public enum RealControlType
{
MOVE_UP_ = 1,
MOVE_DOWN_,
MOVE_LEFT_,
MOVE_RIGHT_,
MOVE_LEFTUP_,
MOVE_LEFTDOWN_,
MOVE_RIGHTUP_,
MOVE_RIGHTDOWN_,
ZOOM_IN_,
ZOOM_OUT_,
FOCUS_NEAR_,
FOCUS_FAR_,
IRIS_OPEN_,
IRIS_CLOSE_,
PRESET_SET_,
PRESET_CALL_,
PTZINFO_GET_,
PTZINFO_SET_
}
#endregion 与ptz服务交互使用结构体
}

46
ConsoleTest/PTZApi/IService.cs

@ -0,0 +1,46 @@
using System.Collections.Generic;
using System.ServiceModel;
namespace ConsoleTest.PTZApi
{
[ServiceContract]
public interface IOperateService<T> where T : class
{
[OperationContract]
bool Add(T model);
[OperationContract]
bool Update(T model);
[OperationContract]
bool Delete(T model);
[OperationContract]
T Find(object key);
[OperationContract]
IList<T> FindAll();
}
[ServiceContract]
public interface ICameraService : IOperateService<CameraModel>
{
}
[ServiceContract]
public interface ICruiseCameraService : IOperateService<CameraModel>
{
}
[ServiceContract]
public interface ICameraModelService : IOperateService<CameraModel>
{
}
/// <summary>
/// PTZ Api 接口
/// </summary>
public interface IPTZApi
{
}
}

340
ConsoleTest/PTZApi/Service.cs

@ -0,0 +1,340 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.ServiceModel;
namespace ConsoleTest.PTZApi
{
public class ServiceBase
{
protected string Host { get; set; } = "127.0.0.1";
protected string Port { get; set; } = "9999";
protected string Name { get; set; }
public ServiceBase()
{
}
protected virtual EndpointAddress CreateEndPointAddress()
{
string conn = $"net.tcp://{Host}:{Port}/{Name}";
return new EndpointAddress(conn);
}
}
public class CameraService : ServiceBase
{
public static CameraService instance = new CameraService();
public CameraService()
{
Name = "CameraService";
}
public bool DeleteCamera(CameraModel id)
{
try
{
return WcfUtil.UseService((ICameraService args) => args.Delete(id), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public bool UpdateCamera(CameraModel camera)
{
try
{
return WcfUtil.UseService((ICameraService args) => args.Update(camera), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public bool AddCamera(CameraModel camera)
{
try
{
return WcfUtil.UseService((ICameraService args) => args.Add(camera), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public CameraModel GetCamera(object obj)
{
try
{
return WcfUtil.UseService((ICameraService args) => args.Find(obj), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public List<CameraModel> GetAllCamera()
{
List<CameraModel> list = null;
try
{
list = WcfUtil.UseService((ICameraService args) => args.FindAll().ToList(), CreateEndPointAddress());
}
catch (Exception)
{
}
return list != null ? list : new List<CameraModel>();
}
}
public class CruiseCameraService : ServiceBase
{
public static CruiseCameraService instance = new CruiseCameraService();
public CruiseCameraService()
{
Name = "CruiseCameraService";
}
public bool DeleteCamera(CameraModel id)
{
try
{
return WcfUtil.UseService((ICruiseCameraService args) => args.Delete(id), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public bool UpdateCamera(CameraModel camera)
{
try
{
return WcfUtil.UseService((ICruiseCameraService args) => args.Update(camera), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public bool AddCamera(CameraModel camera)
{
try
{
return WcfUtil.UseService((ICruiseCameraService args) => args.Add(camera), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public CameraModel GetCamera(object obj)
{
try
{
return WcfUtil.UseService((ICruiseCameraService args) => args.Find(obj), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public List<CameraModel> GetAllCamera()
{
List<CameraModel> list = null;
try
{
list = WcfUtil.UseService((ICruiseCameraService args) => args.FindAll().ToList(), CreateEndPointAddress());
}
catch (Exception)
{
}
return list != null ? list : new List<CameraModel>();
}
}
public class CameraModelService : ServiceBase
{
public static CameraModelService instance = new CameraModelService();
public CameraModelService()
{
Name = "CameraModelService";
}
public bool DeleteCamera(CameraModel id)
{
try
{
return WcfUtil.UseService((ICameraModelService args) => args.Delete(id), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public bool UpdateCamera(CameraModel camera)
{
try
{
return WcfUtil.UseService((ICameraModelService args) => args.Update(camera), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public bool AddCamera(CameraModel camera)
{
try
{
return WcfUtil.UseService((ICameraModelService args) => args.Add(camera), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public CameraModel GetCamera(object obj)
{
try
{
return WcfUtil.UseService((ICameraModelService args) => args.Find(obj), CreateEndPointAddress());
}
catch (Exception ex)
{
throw ex;
}
}
public List<CameraModel> GetAllCamera()
{
List<CameraModel> list = null;
try
{
list = WcfUtil.UseService((ICameraModelService args) => args.FindAll().ToList(), CreateEndPointAddress());
}
catch (Exception)
{
}
return list != null ? list : new List<CameraModel>();
}
}
public class PTZServerApi : IPTZApi
{
#region Attr
private TcpClient _tcpClient { get; set; }
private NetworkStream _stream { get; set; }
#endregion Attr
public PTZServerApi()
{
Init();
}
private void Init()
{
string ip = "127.0.0.1";
int port = 7022;
_tcpClient = new TcpClient(ip, port);
//创建一个 networkstream 用来写入和读取数据
_stream = _tcpClient.GetStream();
}
public RequestRealControl GetPtzInfo(int cameraId)
{
RequestRealControl realControl = new RequestRealControl();
try
{
string recieve_string = string.Empty;
realControl.token = 666;
realControl.CameraInfo.cameraid = cameraId;
realControl.Status = true;
realControl.realControlType = RealControlType.PTZINFO_GET_;
byte[] data = StructToByte(realControl);
_stream.Write(data, 0, data.Length);
byte[] recieve_byte = new byte[_tcpClient.ReceiveBufferSize];
_stream.Read(recieve_byte, 0, (int)_tcpClient.ReceiveBufferSize);
//stream.BeginRead(recieve_byte, 0, (int)tcp_client.ReceiveBufferSize,EndRead, stream);
realControl = (RequestRealControl)BytetoStruct(recieve_byte, typeof(RequestRealControl));
if (realControl.PTZPositionInfo.FT < 0)
{
realControl.PTZPositionInfo.FT = 3600 + realControl.PTZPositionInfo.FT;
}
}
catch (Exception)
{
realControl = default;
}
return realControl;
}
public static byte[] StructToByte(object structObj)
{
//获取结构体大小
int size = Marshal.SizeOf(structObj);
byte[] data = new byte[size];
//分配内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
// 将结构体数据复制到内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
// 将内存空间的数据拷贝到byte数组
Marshal.Copy(structPtr, data, 0, size);
//释放内存
Marshal.FreeHGlobal(structPtr);
return data;
}
public static object BytetoStruct(byte[] bytes, Type type)
{
object obj = new object();
try
{
byte[] temp = bytes;
// 获取结构体大小
int size = Marshal.SizeOf(type);
if (size > bytes.Length)
return null;
// 分配结构体内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
// 将byte数组内容拷贝到内存中
Marshal.Copy(temp, 0, structPtr, size);
// 将内存空间转化为目标结构体
obj = Marshal.PtrToStructure(structPtr, type);
//释放内存
Marshal.FreeHGlobal(structPtr);
}
catch (Exception)
{
}
return obj;
}
}
}

28
ConsoleTest/PTZApi/Test.cs

@ -0,0 +1,28 @@
using System.Collections.Generic;
namespace ConsoleTest.PTZApi
{
public class Test
{
public static void TestDbApi()
{
List<CameraModel> cameraModelList = CameraService.instance.GetAllCamera();
List<CameraModel> cameraModelList2 = CruiseCameraService.instance.GetAllCamera();
List<CameraModel> cameraModelList3 = CameraModelService.instance.GetAllCamera();
foreach (CameraModel cameraModel in cameraModelList)
{
System.Console.WriteLine(cameraModel);
}
CameraModel m = new CameraModel();
m.PTZServerIP = "111";
CameraService.instance.AddCamera(m);
}
public static void TestPtzApi()
{
PTZServerApi api = new PTZServerApi();
RequestRealControl requestRealControl = api.GetPtzInfo(7);
}
}
}

41
ConsoleTest/PTZApi/Util.cs

@ -0,0 +1,41 @@
using System;
using System.ServiceModel;
namespace ConsoleTest.PTZApi
{
public class WcfUtil
{
public static void UseService<TChannel>(Action<TChannel> action, EndpointAddress address = null)
{
ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>("*");
TChannel val = ((!(address == null)) ? channelFactory.CreateChannel(address) : channelFactory.CreateChannel());
try
{
((IClientChannel)(object)val).Open();
action(val);
((IClientChannel)(object)val).Close();
}
catch
{
((IClientChannel)(object)val).Abort();
}
}
public static TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> func, EndpointAddress address = null)
{
ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>("*");
TChannel val = ((!(address == null)) ? channelFactory.CreateChannel(address) : channelFactory.CreateChannel());
((IClientChannel)(object)val).Open();
TReturn result = func(val);
try
{
((IClientChannel)(object)val).Close();
}
catch (Exception)
{
((IClientChannel)(object)val).Abort();
}
return result;
}
}
}

66
ConsoleTest/Program.cs

@ -0,0 +1,66 @@
using ConsoleTest.Test.AutoWeight;
using ConsoleTest.Util;
using System;
using System.Text.RegularExpressions;
namespace ConsoleTest
{
public class Program
{
private static void Main(string[] args)
{
EnvUtil.InitWorkDirectory();
EnvUtil.AddDllPath(EnvUtil.CombinePath(EnvUtil.GetWorkDirectory(), "dll"));
//AutoWeightTest();
//OtherTests();
//PTZApi.Test.TestPtzApi();
Console.ReadLine();
}
private static void TempTest(string tempBuf)
{
string[] splitBufArray = tempBuf.Split('\r');
foreach (var item in splitBufArray)
{
if (item.Length != 16) { continue; }
Console.WriteLine($"item:{item}");
MatchCollection mc = Regex.Matches(tempBuf, @"(\d+)");
Console.WriteLine($"mc:{mc}, count:{mc.Count}");
for (int i = 0; i < mc.Count; i++)
{
Console.Write($"{i}:{mc[i].Value}");
}
Console.WriteLine();
if (mc.Count != 3) { continue; }
string weightArg = mc[1].Value;
decimal weight = CommonUtil.WeightStrToDec(weightArg) / 1000;
string unit = "t";
Console.WriteLine($"weight:{weight}{unit}");
break;
}
}
private static void AutoWeightTest()
{
try
{
//WeightTest.TestZhuHai();
//WeightTest.TestHuiZhou();
//LedTest.Test();
//LightTest.Test();
PosTest.Test();
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
private static void OtherTest()
{
Test.OtherTest.ConfigTest();
}
}
}

35
ConsoleTest/Properties/AssemblyInfo.cs

@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ConsoleTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleTest")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("37fd52ca-308e-4cc4-9e9f-4072e1c1c216")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

69
ConsoleTest/Properties/app.manifest

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC 清单选项
如果想要更改 Windows 用户帐户控制级别,请使用
以下节点之一替换 requestedExecutionLevel 节点。n
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
指定 requestedExecutionLevel 元素将禁用文件和注册表虚拟化。
如果你的应用程序需要此虚拟化来实现向后兼容性,则删除此
元素。
-->
<!--<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />-->
</requestedPrivileges>
<applicationRequestMinimum>
<defaultAssemblyRequest permissionSetReference="Custom" />
<PermissionSet class="System.Security.PermissionSet" version="1" ID="Custom" SameSite="site" Unrestricted="true" />
</applicationRequestMinimum>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- 设计此应用程序与其一起工作且已针对此应用程序进行测试的
Windows 版本的列表。取消评论适当的元素,
Windows 将自动选择最兼容的环境。 -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
</application>
</compatibility>
<!-- 指示该应用程序可以感知 DPI 且 Windows 在 DPI 较高时将不会对其进行
自动缩放。Windows Presentation Foundation (WPF)应用程序自动感知 DPI,无需
选择加入。选择加入此设置的 Windows 窗体应用程序(目标设定为 .NET Framework 4.6 )还应
在其 app.config 中将 "EnableWindowsFormsHighDpiAutoResizing" 设置设置为 "true"。-->
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>
</application>
-->
<!-- 启用 Windows 公共控件和对话框的主题(Windows XP 和更高版本) -->
<!--
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
-->
</assembly>

93
ConsoleTest/Test/AutoWeight/LedTest.cs

@ -0,0 +1,93 @@
using ConsoleTest.AutoWeight.LedZK;
using ConsoleTest.Util;
using System;
namespace ConsoleTest.Test.AutoWeight
{
public class LedTest
{
public static void Test()
{
string ip = ConfigUtil.GetStringVal("Led_Ip");
ushort port = (ushort)ConfigUtil.GetShortVal("Led_Port");
Console.WriteLine($"Ip : {ip}");
Console.WriteLine($"Port : {port}");
var manager = new LedZKManager(ip, port);
manager.StartServer();
Console.WriteLine($"Start success : {manager.Ping()}");
int ret;
while (true)
{
Console.Write("Please input [0,6] : ");
var read = Console.ReadLine();
//manager.DelAllDynamicArea(0, 4);
switch (read)
{
case "0":
ret = manager.SendDynamicArea(0, 0, 0, 96, 64,
@"\C2粤AAQ841 09:20:51\n\C2粤AAQ842 09:20:52\n\C2粤AAQ843 09:20:53\n\C2粤AAQ844 09:20:54\n\C3粤AAV141,粤AAV142,\C1粤AAM491,粤AAM492",
0x02, 0x01, 10);
Console.WriteLine(ret);
break;
case "1":
ret = manager.SendDynamicMoveArea(0, 0, 0, 96, 24, @"\C2粤AAQ841 09:20:51\n\C2粤AAQ842 09:20:52", 0x02, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(1, 0, 24, 96, 24, @"\C2粤AAQ843 09:20:53\n\C2粤AAQ844 09:20:54", 0x02, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(2, 0, 48, 96, 16, @"\C3粤AAV141,粤AAV142,\C1粤AAM491,粤AAM492", 0x01, 0x01, 10);
Console.WriteLine(ret);
break;
case "2":
ret = manager.SendDynamicMoveArea(0, 0, 0, 96, 48,
@"\C2粤AAQ841 09:20:51\n\C2粤AAQ842 09:20:52\n\C2粤AAQ843 09:20:53\n\C2粤AAQ844 09:20:54", 0x02, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(1, 0, 48, 96, 16, @"\C3粤AAV141,粤AAV142,\C1粤AAM491,粤AAM492", 0x01, 0x01, 10);
Console.WriteLine(ret);
break;
case "3":
ret = manager.SendDynamicMoveArea(0, 0, 0, 96, 64,
@"\C2粤AAQ841 09:20:51\n\C2粤AAQ842 09:20:52\n\C2粤AAQ843 09:20:53\n\C2粤AAQ844 09:20:54\n\C3粤AAV141,粤AAV142,\C1粤AAM491,粤AAM492",
0x02, 0x01, 10);
Console.WriteLine(ret);
break;
case "4":
ret = manager.SendDynamicMoveArea(0, 0, 0, 96, 12, @"\C2粤AAQ841 09:20:51", 0x01, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(1, 0, 12, 96, 12, @"\C2粤AAQ842 09:20:52", 0x01, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(2, 0, 24, 96, 12, @"\C2粤AAQ843 09:20:53", 0x01, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(3, 0, 36, 96, 12, @"\C2粤AAQ844 09:20:54", 0x01, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(4, 0, 48, 96, 16, @"\C3粤AAV141,粤AAV142,\C1粤AAM491,粤AAM492", 0x01, 0x01, 10);
Console.WriteLine(ret);
break;
case "5":
ret = manager.SendDynamicArea(0, 0, 0, 96, 64,
@"\C2粤AAQ841 09:20:51\n\C2粤AAQ842 09:20:52\n\C2粤AAQ843 09:20:53\n\C2粤AAQ844 09:20:54\n\C3粤AAV141,粤AAV142,\C1粤AAM491,粤AAM492",
0x02, 0x01, 10);
Console.WriteLine(ret);
break;
case "6":
ret = manager.SendDynamicMoveArea(0, 0, 0, 96, 24, @"\C2粤AAQ841 09:20:51\n\C2粤AAQ842 09:20:52", 0x02, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(1, 0, 25, 96, 24, @"\C2粤AAQ843 09:20:53\n\C2粤AAQ844 09:20:54", 0x02, 0x01, 10);
Console.WriteLine(ret);
ret = manager.SendDynamicMoveArea(2, 0, 49, 96, 16, @"\C3粤AAV141,粤AAV142,\C1粤AAM491,粤AAM492", 0x01, 0x01, 10);
Console.WriteLine(ret);
break;
}
}
//manager.StopServer();
}
}
}

70
ConsoleTest/Test/AutoWeight/LightTest.cs

@ -0,0 +1,70 @@
using ConsoleTest.AutoWeight.Light;
using ConsoleTest.Util;
using System;
using System.Threading;
namespace ConsoleTest.Test.AutoWeight
{
/// <summary>
/// 2022年6月9日17:39:08
/// </summary>
public class LightTest
{
public static void Test()
{
string comName = ConfigUtil.GetStringVal("Light_Com");
int baudRate = ConfigUtil.GetIntVal("Light_BaudRate");
string lightCodeName = EnvUtil.CombinePath(EnvUtil.GetWorkDirectory(), "data", "light", ConfigUtil.GetStringVal("Light_Code_Name"));
Console.WriteLine($"Com : {comName}");
Console.WriteLine($"BaudRate : {baudRate}");
Console.WriteLine($"LightCodeName : {lightCodeName}");
LightManager lightManager = new LightManager(comName, baudRate, lightCodeName);
const int interval = 600;
bool ret = lightManager.StartServer();
Console.WriteLine($"Start success : {ret}");
Console.WriteLine($"Is open : {lightManager.IsOpen()}");
Console.WriteLine($"Read data success : {lightManager.IsReadCodeSuccess()}");
lightManager.CloseAllLight();
Thread.Sleep(interval);
lightManager.OpenAllLight();
Thread.Sleep(interval);
lightManager.CloseAllLight();
Thread.Sleep(interval);
for (var i = 1; i < 5; i++)
{
lightManager.OpenLight(i);
Thread.Sleep(interval);
}
for (var i = 1; i < 5; i++)
{
lightManager.CloseLight(i);
Thread.Sleep(interval);
}
for (var i = 1; i < 5; i++)
{
lightManager.LockLightOn(i);
Thread.Sleep(interval);
}
for (var i = 1; i < 5; i++)
{
lightManager.LockLightOff(i);
Thread.Sleep(interval);
}
lightManager.CloseAllLight();
Thread.Sleep(interval);
lightManager.OpenAllLight();
Thread.Sleep(interval);
lightManager.CloseAllLight();
Thread.Sleep(interval);
lightManager.StopServer();
}
}
}

106
ConsoleTest/Test/AutoWeight/PosTest.cs

@ -0,0 +1,106 @@
using ConsoleTest.AutoWeight.Pos;
using ConsoleTest.Util;
using System;
using System.Text;
namespace ConsoleTest.Test.AutoWeight
{
public class PosTest
{
public static void Test()
{
PosManager posManager = new PosManager();
bool flag;
// 打开设备
flag = posManager.OpenDevice(PosSDK.POS_PT_USB);
Console.WriteLine($"OpenDevice:{flag}");
flag = posManager.IsConnected();
Console.WriteLine($"IsConnected:{flag}");
flag = posManager.IsPaperExhaust();
Console.WriteLine($"IsPaperExhaust:{flag},{posManager.GetResult()}");
flag = posManager.IsPaperWillExhaust();
Console.WriteLine($"IsPaperWillExhaust:{flag},{posManager.GetResult()}");
flag = posManager.InitPrinter();
Console.WriteLine($"InitPrinter:{flag}");
string bmpPath2 = EnvUtil.CombinePath(EnvUtil.GetWorkDirectory(), "data", "image", "logom.bmp");
if (!EnvUtil.ExistFile(bmpPath2))
{
string bmpPath1 = EnvUtil.CombinePath(EnvUtil.GetWorkDirectory(), "data", "image", "logo.bmp");
flag = posManager.Color24_GrayBW(bmpPath1, bmpPath2);
Console.WriteLine($"IsPaperExhaust:{flag}");
}
// 打印票头
//flag = posManager.SetLeftMargin(150, 0);
//Console.WriteLine($"SetLeftMargin:{flag}");
flag = posManager.PrintBmp(bmpPath2);
Console.WriteLine($"PrintBmp:{flag},{posManager.GetResult()}");
flag = posManager.InitPrinter();
// 缓冲区
byte[] cmd = new byte[] { 0x1c, 0x26 };
posManager.PrintData(cmd, 2);
// 打印公司
flag = posManager.SetAlign(1);
flag = posManager.PrintStr(0, 1, 0, 0, 0, "惠州航油公司\r\n");
Console.WriteLine($"PrintStr:{flag}");
// 打印分隔符
flag = posManager.PrintStr(0, 0, 0, 0, 0, "================================\r\n");
// 打印运单信息
flag = posManager.SetAlign(0);
var content = new StringBuilder();
content.Append($"场地:\tcd000\r\n");
content.Append($"运单号:\tydh000\r\n");
content.Append($"供应商:\tgys000\r\n");
content.Append($"运输车:\tysc000\r\n");
content.Append($"挂车:\tgc000\n");
content.Append($"运输员:\tysy000\n");
content.Append($"押运员:\tyyy000\n");
content.Append($"料号:\tlh000\n");
flag = posManager.PrintStr(0, 0, 0, 0, 0, content.ToString());
// 打印分隔符
flag = posManager.SetAlign(1);
flag = posManager.PrintStr(0, 0, 0, 0, 0, "================================\r\n");
//// 缓冲区
//cmd = new byte[] { 0x1c, 0x26 };
//posManager.PrintData(cmd, 2);
// 打印进出场信息
flag = posManager.SetAlign(0);
content = new StringBuilder();
content.Append($"运单重量:\t30吨\n");
content.Append($"入场重量:\t40吨\n");
content.Append($"出场重量:\t10吨\n");
content.Append($"实际重量:\t30吨\n");
content.Append($"达标率:\t100%\n");
content.Append($"入场时间:\t{DateTime.Now:yyyy/MM/dd HH:mm:ss}\n");
content.Append($"出场时间:\t{DateTime.Now:yyyy/MM/dd HH:mm:ss}\n");
content.Append($"运单状态:\t出场结束\n");
flag = posManager.PrintStr(0, 0, 0, 0, 0, content.ToString());
//打印分隔符
flag = posManager.SetAlign(1);
flag = posManager.PrintStr(0, 0, 0, 0, 0, "================================\r\n");
//打印票尾
flag = posManager.SetAlign(2);
flag = posManager.PrintStr(0, 0, 0, 0, 0, $"出票时间:{DateTime.Now:yyyy/MM/dd HH:mm:ss}\r\n");
flag = posManager.InitPrinter();
//切纸
flag = posManager.CutPaper(1, 3);
Console.WriteLine($"CutPaper:{flag}");
//关闭
flag = posManager.CloseDevice();
Console.WriteLine($"CloseDevice:{flag}");
}
}
}

37
ConsoleTest/Test/AutoWeight/WeightTest.cs

@ -0,0 +1,37 @@
using ConsoleTest.AutoWeight.Scales;
using ConsoleTest.Util;
using System;
namespace ConsoleTest.Test.AutoWeight
{
public class WeightTest
{
public static void TestZhuHai()
{
string com = ConfigUtil.GetStringVal("Weight_Com");
int baudrate = ConfigUtil.GetIntVal("Weight_BaudRate");
int receivedBytesThreshold = ConfigUtil.GetIntVal("Weight_ReceivedBytesThreshold");
Console.WriteLine($"Com : {com}");
Console.WriteLine($"BaudRate : {baudrate}");
Console.WriteLine($"ReceivedBytesThreshold : {receivedBytesThreshold}");
Scales scales = new ScalesHuiZhou(com, baudrate, receivedBytesThreshold);
bool ret = scales.StartServer();
Console.WriteLine($"Start success : {ret}");
}
public static void TestHuiZhou()
{
string com = ConfigUtil.GetStringVal("Weight_Com");
int baudrate = ConfigUtil.GetIntVal("Weight_BaudRate");
int receivedBytesThreshold = ConfigUtil.GetIntVal("Weight_ReceivedBytesThreshold");
Console.WriteLine($"Com : {com}");
Console.WriteLine($"BaudRate : {baudrate}");
Console.WriteLine($"ReceivedBytesThreshold : {receivedBytesThreshold}");
Scales scales = new ScalesHuiZhou(com, baudrate, receivedBytesThreshold);
bool ret = scales.StartServer();
Console.WriteLine($"Start success : {ret}");
}
}
}

76
ConsoleTest/Test/AutoWeight/YkPosTest.cs

@ -0,0 +1,76 @@
namespace ConsoleTest.Test.AutoWeight
{
public class YkPosTest
{
public static void Test()
{
//if (!YkPosManager.IsConnected() || YkPosManager.IsPaperExhaust())
//{
// var msg = "打印接口纸尽,请联系管理人员";
// _mainServer?.SetScrollLabelText(msg);
// _mainServer?.ShowRecvMessage(msg);
// return;
//}
//if (billEntity == null)
// return;
//YkPosManager.InitPrinter();
//var bmpPath = EnvUtil.CombinePath(EnvUtil.GetWorkDirectory(), "data", "image", "logo.bmp");
//YkPosManager.SetAlign(1);//居中
//YkPosManager.PrintRasterBmp(new StringBuilder(bmpPath));//打印图片
////YkPosManager.InitPrinter();//重置
////YkPosManager.SetAlign(1);//居中
//YkPosManager.SetEmphasized(1);//字体加粗
//YkPosManager.PrintStr(new StringBuilder($"{_mainServer.LocalAttrCenter.Company.F_FullName}\n"));//打印公司名
//YkPosManager.InitPrinter();//重置
//YkPosManager.SetAlign(1);//居中
//YkPosManager.PrintStr(new StringBuilder("========================================\n"));//打印分隔符
////YkPosManager.InitPrinter();//重置
//YkPosManager.SetAlign(0);//居左
//YkPosManager.SetLeftMargin(8 * 8, 0);//设置左边距
//var content = new StringBuilder();
//content.Append($"场地:\t{billEntity.SiteName}\n");
//content.Append($"运单号:\t{billEntity.SerialNumber}\n");
//content.Append($"供应商:\t{billEntity.SupplierName}\n");
//content.Append($"运输车:\t{billEntity.LicensePlate}\n");
//content.Append($"挂车:\t{billEntity.TrailerPlate}\n");
//content.Append($"运输员:\t{billEntity.DriverName}\n");
//content.Append($"押运员:\t{billEntity.Driver2Name}\n");
//content.Append($"料号:\t{billEntity.MaterialNo}\n");
//YkPosManager.PrintStr(content);//打印内容
//YkPosManager.InitPrinter();//重置
//YkPosManager.SetAlign(1);//居中
//YkPosManager.PrintStr(new StringBuilder("----------------------------------------\n"));//打印分隔符
////YkPosManager.InitPrinter();//重置
//YkPosManager.SetAlign(0);//居左
//YkPosManager.SetLeftMargin(8 * 8, 0);//设置左边距
//content = new StringBuilder();
//content.Append($"运单重量:\t{billEntity.BillWeight}吨\n");
//content.Append($"入场重量:\t{billEntity.InWeight}吨\n");
//content.Append($"出场重量:\t{billEntity.OutWeight}吨\n");
//content.Append($"实际重量:\t{billEntity.NetWeight}吨\n");
//content.Append($"达标率:\t{billEntity.StandardRate}%\n");
//content.Append($"入场时间:\t{billEntity.InStartTime:yyyy/MM/dd HH:mm:ss}\n");
//content.Append($"出场时间:\t{billEntity.OutFinishTime:yyyy/MM/dd HH:mm:ss}\n");
////content.Append($"运单状态:\t{BillStateExt.GetBillStateDesc(billEntity.State)}\n");
//YkPosManager.PrintStr(content);//打印内容
//YkPosManager.InitPrinter();//重置
//YkPosManager.SetAlign(1);//居中
//YkPosManager.PrintStr(new StringBuilder("========================================\n"));
////YkPosManager.InitPrinter();//重置
//YkPosManager.SetAlign(2);//居右
// //YkPosManager.PrintStr(new StringBuilder($"管理员:{user?.F_RealName}\n"));
//YkPosManager.PrintStr(new StringBuilder($"出票时间:{DateTime.Now:yyyy/MM/dd HH:mm:ss}\n"));//打印页脚
//YkPosManager.FeedPaper();//走纸,留空隙
//YkPosManager.CutPaper();//切纸
}
}
}

310
ConsoleTest/Test/Other/OtherTest.cs

@ -0,0 +1,310 @@
using ConsoleTest.AutoWeight.FingerPrint;
using ConsoleTest.AutoWeight.Some;
using ConsoleTest.AutoWeight.Speak;
using ConsoleTest.Util;
using ConsoleTest.Util.Encrypt;
using System;
using System.Collections.Generic;
using System.IO;
using System.Speech.Synthesis;
using System.Text.RegularExpressions;
namespace ConsoleTest.Test
{
public class OtherTest
{
private static void HttpTest()
{
var url = "http://192.168.1.200:8080/military/videoRecorder/qryCameraList";
var respStr = HttpMethods.HttpGet(url);
var respObj = JsonUtil.ToJObject(respStr);
var success = (bool)respObj["success"];
var message = (string)respObj["message"];
var code = (int)respObj["code"];
var rObj = respObj["result"];
var rStr = rObj.ToJson();
//var result = JsonUtil.ToList<MsVideoRecorder>(rStr);
var timestamp = (string)respObj["timestamp"];
}
private static void StartCheckPhotoSaveCycle(bool once)
{
if (once)
CheckPhotoSaveCycle();
var now = DateTime.Now;
var next = now.AddDays(1);
//var timeSpan = next - now;
var timeSpan = new DateTime(next.Year, next.Month, next.Day) - now;
CommonUtil.SetTimeout(() =>
{
CheckPhotoSaveCycle();
StartCheckPhotoSaveCycle(false);
}, timeSpan.TotalMilliseconds);
}
public static void CheckPhotoSaveCycle()
{
var now = DateTime.Now;
var workPath = Directory.GetCurrentDirectory();
var capDir = new DirectoryInfo(Path.Combine(workPath, "cap"));
if (!capDir.Exists)
return;
foreach (var yearDir in capDir.GetDirectories())
{
if (!yearDir.Exists || !IsInt(yearDir.Name))
continue;
var year = int.Parse(yearDir.Name);
foreach (var monthDir in yearDir.GetDirectories())
{
if (!monthDir.Exists || !IsInt(monthDir.Name))
continue;
var month = int.Parse(monthDir.Name);
foreach (var dayDir in monthDir.GetDirectories())
{
if (!dayDir.Exists || !IsInt(dayDir.Name))
continue;
var day = int.Parse(dayDir.Name);
var curTime = new DateTime(year, month, day);
var timeSpan = now - curTime;
var diff = timeSpan.Days + 1;
var SavePhotoDay = 90;
if (diff > SavePhotoDay)
dayDir.Delete(true);
}
if (monthDir.GetDirectories().Length <= 0)
monthDir.Delete();
}
if (yearDir.GetDirectories().Length <= 0)
yearDir.Delete();
}
}
public static bool IsInt(string value)
{
return Regex.IsMatch(value, @"^[-+]?\d+(\.\d+)?$");
}
public static decimal WeightStrToDec(string str, int afterLimit = 3)
{
try
{
return Math.Round(Convert.ToDecimal(str), afterLimit);
}
catch (Exception)
{
return 0m;
}
}
/// <summary>
/// 车牌预处理
/// </summary>
public static string PretreatPlate(string oldPlate)
{
oldPlate = oldPlate.ToUpper();
if (oldPlate.Length < 7)
return oldPlate;
var newPlate = oldPlate.Length > 7 ? oldPlate.Substring(0, 7) : oldPlate;
var dict = new Dictionary<string, string> { { "O", "0" }, { "I", "1" } };
newPlate = SubRepString(newPlate, 3, newPlate.Length, dict);
dict = new Dictionary<string, string> { { "D", "0" } };
newPlate = SubRepString(newPlate, newPlate.Length - 3, newPlate.Length, dict);
return newPlate;
}
/// <summary>
/// 2021-04-25 15:12:24
/// </summary>
/// <param name="str"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="dict"></param>
/// <returns></returns>
public static string SubRepString(string str, int start, int end, Dictionary<string, string> dict)
{
var beforeStr = str.Substring(0, start);
var changeStr = str.Substring(start, end - start);
var afterStr = str.Substring(end, str.Length - end);
foreach (var key in dict.Keys)
{
changeStr = changeStr.Replace(key, dict[key]);
}
return beforeStr + changeStr + afterStr;
}
/// <summary>
/// 2021-03-02 09:19:04
/// </summary>
public static void ListTest()
{
var list = new List<int>();
for (var i = 0; i < 10; i++)
{
list.Add(i);
}
for (var i = 10; i < 20; i++)
{
list.Add(i);
}
Console.WriteLine(list);
}
/// <summary>
/// 2021-02-23 14:50:45
/// </summary>
public static void ExceptionCatch()
{
try
{
ExceptionTest();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.WriteLine(e.Message);
Console.WriteLine(e.Data);
Console.WriteLine(e.Data["t"]);
Console.WriteLine(e.Data["test"]);
}
}
/// <summary>
/// 2021-02-23 14:41:43
/// </summary>
public static void ExceptionTest()
{
var e = new Exception("Exception Test");
e.Data["test"] = "test";
throw e;
}
/// <summary>
/// 2021-02-03 14:19:46
/// </summary>
public static void SpeakTest()
{
var chText = "你好,世界";
var enText = "Hello, World";
SpeakHelper.SelectVoice("Microsoft Zira Desktop");
SpeakHelper.GetVoices();
SpeakHelper.Speak(chText);
SpeakHelper.Speak(enText);
SpeakHelper.SelectVoice(VoiceGender.Male, VoiceAge.Child);
SpeakHelper.Speak(chText);
SpeakHelper.Speak(enText);
}
/// <summary>
/// 2021-02-02 17:36:34
/// </summary>
/// <returns></returns>
public static void EncryptTest()
{
var pwd = Md5Helper.Encrypt(Console.ReadLine(), 32).ToLower();
//var key = Md5Helper.Encrypt(Md5Helper.CreateNo(), 16).ToLower();
var key = "cb0d8213f3d570c8";
var enStr = DesEncrypt.Encrypt(pwd, key).ToLower();
//var deStr = DesEncrypt.Decrypt(enStr, key).ToLower();
var enPwd = Md5Helper.Encrypt(enStr, 32).ToLower();
Console.WriteLine(new { pwd, key, enStr, enPwd });
var rePwd = Md5Helper.Encrypt(Console.ReadLine(), 32).ToLower();
var reEnStr = DesEncrypt.Encrypt(rePwd, key).ToLower();
var reEnPwd = Md5Helper.Encrypt(reEnStr, 32).ToLower();
Console.WriteLine(new { rePwd, key, reEnStr, reEnPwd });
Console.WriteLine(string.Equals(enPwd, reEnPwd));
}
/// <summary>
/// 2021-01-18 15:42:47
/// </summary>
public static void ConfigTest()
{
var config = ConfigUtil.GetConfiguration(Path.Combine(EnvUtil.GetWorkDirectory(), "data", "test.config"));
Console.WriteLine(ConfigUtil.GetValue(config, "WT_COM"));
ConfigUtil.SetValue(config, "WT_COM", "com1");
Console.WriteLine(ConfigUtil.GetValue(config, "WT_COM"));
ConfigUtil.ReadAllSettings(config);
}
/// <summary>
/// 2021-01-12 10:12:59
/// </summary>
public static string WeightDecToStr(decimal dec, int afterLimit = 3, char patch = '#')
{
return dec.ToString("0.".PadRight(afterLimit + 2, patch));
}
/// <summary>
/// 2021-01-12 09:02:59
/// </summary>
public static void FingerPrintTest()
{
var manager = new FingerPrintManager();
//开启服务
manager.StartServer();
//获取设备内核版本
var kernel = string.Empty;
manager.GetDevKerNel(ref kernel);
//获取设备序列号
var sn = string.Empty;
manager.GetDevSn(ref sn);
////设置模板弹框关闭
//manager.SetRegBoxAble(false);
//获取指纹模板
var regBuf = string.Empty;
manager.GetRegFingerPrint(ref regBuf);
//设置特征弹框开启
manager.SetVerBoxAble(true);
//获取指纹特征
var verBuf = string.Empty;
manager.GetVerFingerPrint(ref verBuf);
//对比模板和特征
var ret = manager.MatchFingerPrint(regBuf, verBuf);
//for (var i = 0; i < 10; i++)
//{
// Thread.Sleep(1000);
// manager.SetBeepLight(i);
//}
//关闭服务
manager.StopServer();
Console.WriteLine(new { kernel, sn });
Console.WriteLine(new { regBuf.Length, regBuf });
Console.WriteLine(new { verBuf.Length, verBuf });
Console.WriteLine(new { ret });
}
/// <summary>
/// 2021-01-02 09:03:07
/// </summary>
public static void YuHuoTest()
{
YuHuo.Yu();
YuHuo.Huo();
YuHuo.YiHuo();
}
}
}

44
ConsoleTest/Test/Other/YuHuo.cs

@ -0,0 +1,44 @@
using System;
namespace ConsoleTest.AutoWeight.Some
{
internal class YuHuo
{
public static void Yu()
{
Console.WriteLine("--------------------");
Console.WriteLine(0 & 0);
Console.WriteLine(0 & 1);
Console.WriteLine(1 & 0);
Console.WriteLine(1 & 1);
Console.WriteLine("--------------------");
}
public static void Huo()
{
Console.WriteLine("--------------------");
Console.WriteLine(0 | 0);
Console.WriteLine(0 | 1);
Console.WriteLine(1 | 0);
Console.WriteLine(1 | 1);
Console.WriteLine("--------------------");
}
public static void YiHuo()
{
Console.WriteLine("--------------------");
Console.WriteLine(0 ^ 0);
Console.WriteLine(0 ^ 1);
Console.WriteLine(1 ^ 0);
Console.WriteLine(1 ^ 1);
Console.WriteLine("--------------------");
}
public static void Ping()
{
var ping = new System.Net.NetworkInformation.Ping();
var result = ping.Send("www.baidu.com");
Console.WriteLine(result);
}
}
}

184
ConsoleTest/Util/CommonUtil.cs

@ -0,0 +1,184 @@
using System;
using System.Text.RegularExpressions;
namespace ConsoleTest.Util
{
public class CommonUtil
{
/// <summary>
/// 将 DateTime 转换为 UnixTime 单位秒
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static int DateTimeToUnixTime(DateTime dateTime)
{
return (int)(dateTime - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;
}
/// <summary>
/// 将 UnixTime 转换为 DateTime 单位秒
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static DateTime UnixTimeToDateTime(int time)
{
if (time < 0)
throw new ArgumentOutOfRangeException("time is out of range");
return TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddSeconds(time);
}
/// <summary>
/// 小数字符串去零
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Trim0(string str)
{
string result = str.TrimEnd('0');
if (result.EndsWith("."))
{
result = result.Remove(result.Length - 1);
}
return result;
}
/// <summary>
/// 判断车牌是否正确
/// </summary>
/// <param name="plate"></param>
/// <returns></returns>
public static bool IsSuccessPlate(string plate)
{
int len = plate.Length;
if (len == 7)
{
if (plate[0] > 127)
{//汉字
for (int i = 1; i < 7; i++)
{
if (plate[i] > 127)
{
return false;
}
}
return true;
}
}
return false;
}
/// <param name="str">要舍入的字符串小数</param>
public static decimal StrToDec(string str)
{
try
{
return !string.IsNullOrEmpty(str) ? Convert.ToDecimal(str.Trim()) : 0m;
}
catch (Exception)
{
return 0m;
}
}
/// <summary>
///
/// </summary>
/// <param name="dec"></param>
/// <param name="afterLimit"></param>
/// <param name="patch"># or 0</param>
/// <returns></returns>
public static string WeightDecToStr(decimal dec, int afterLimit = 3, char patch = '#')
{
return dec.ToString("0.".PadRight(afterLimit + 2, patch));
}
/// <param name="str">要舍入的字符串小数</param>
/// <param name="afterLimit">指定数字要舍入到的小数位数的值,范围从 0 到 28。</param>
public static decimal WeightStrToDec(string str, int afterLimit = 3)
{
try
{
return Math.Round(Convert.ToDecimal(str), afterLimit);
}
catch (Exception)
{
return 0m;
}
}
public static string Reverse(string original)
{
var arr = original.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
public static bool IsNumber(string value)
{
return Regex.IsMatch(value, @"^[-+]?\d+(\.\d+)?$");
}
public static bool IsInt(string value)
{
return Regex.IsMatch(value, @"^[-+]?\d+(\.\d+)?$");
}
/// <summary>
/// 在指定时间过后执行指定的表达式
/// </summary>
/// <param name="interval">时间(以毫秒为单位)</param>
/// <param name="action">要执行的表达式</param>
/// <return>返回timer对象</return>
public static void SetTimeout(Action action, double interval)
{
var timer = new System.Timers.Timer(interval);
timer.Elapsed += (sender, e) =>
{
timer.Enabled = false;
action();
timer.Dispose();
timer.Close();
timer = null;
};
timer.Enabled = true;
}
/// <summary>
/// 在指定时间周期重复执行指定的表达式
/// </summary>
/// <param name="interval">时间(以毫秒为单位)</param>
/// <param name="action">要执行的表达式</param>
public static void SetInterval(Action action, double interval)
{
var timer = new System.Timers.Timer(interval);
timer.Elapsed += (sender, e) => { action(); };
timer.Enabled = true;
}
///<summary>
///生成随机字符串
///</summary>
///<param name="length">目标字符串的长度</param>
///<param name="useNum">是否包含数字,1=包含,默认为包含</param>
///<param name="useLow">是否包含小写字母,1=包含,默认为包含</param>
///<param name="useUpp">是否包含大写字母,1=包含,默认为包含</param>
///<param name="useSpe">是否包含特殊字符,1=包含,默认为不包含</param>
///<returns>指定长度的随机字符串</returns>
public static string GetRandomString(int length, bool useNum = true, bool useLow = true, bool useUpp = true, bool useSpe = true)
{
var b = new byte[4];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
var r = new Random(BitConverter.ToInt32(b, 0));
string s = string.Empty, str = string.Empty;
if (useNum == true) { str += "0123456789"; }
if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
for (int i = 0; i < length; i++)
{
s += str.Substring(r.Next(0, str.Length - 1), 1);
}
return s;
}
}
}

115
ConsoleTest/Util/ConfigUtil.cs

@ -0,0 +1,115 @@
using System;
using System.Configuration;
namespace ConsoleTest.Util
{
public class ConfigUtil
{
#region App.config (*.exe.config)
private static string GetValue(string key)
{
return ConfigurationManager.AppSettings[key];
}
public static string GetStringVal(string key)
{
return GetValue(key);
}
public static short GetShortVal(string key)
{
bool ret = short.TryParse(GetValue(key), out short val);
return ret ? val : (short)0;
}
public static int GetIntVal(string key)
{
bool ret = int.TryParse(GetValue(key), out int val);
return ret ? val : 0;
}
public static double GetDoubleVal(string key)
{
bool ret = double.TryParse(GetValue(key), out double val);
return ret ? val : 0;
}
public static bool GetBoolVal(string key)
{
bool ret = bool.TryParse(GetValue(key), out bool val);
return ret ? val : false;
}
public static void SetValue(string key, string value)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
// Save the configuration file.
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings");
}
public static void ReadAllSettings()
{
var appSettings = ConfigurationManager.AppSettings;
if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
}
}
}
#endregion App.config (*.exe.config)
#region other.config
/// <summary>
/// 打开指定的配置文件;
/// </summary>
public static Configuration GetConfiguration(string configFile)
{
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
}
public static string GetValue(Configuration config, string key)
{
return config.AppSettings.Settings[key].Value.Trim();
}
public static void SetValue(Configuration config, string key, string value)
{
config.AppSettings.Settings[key].Value = value;
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
public static void ReadAllSettings(Configuration config)
{
var appSettings = config.AppSettings.Settings;
if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key].Value);
}
}
}
#endregion other.config
}
}

65
ConsoleTest/Util/Encrypt/DesEncrypt.cs

@ -0,0 +1,65 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleTest.Util.Encrypt
{
/// <summary>
/// 加密、解密帮助类
/// </summary>
public static class DesEncrypt
{
/// <summary>
/// 加密数据
/// </summary>
/// <param name="str">需要加密的内容</param>
/// <param name="key">秘钥</param>
/// <returns></returns>
public static string Encrypt(string str, string key)
{
var des = new DESCryptoServiceProvider();
des.Key = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
des.IV = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
var ms = new System.IO.MemoryStream();
var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
var byteArray = Encoding.Default.GetBytes(str);
cs.Write(byteArray, 0, byteArray.Length);
cs.FlushFinalBlock();
var builder = new StringBuilder();
foreach (var b in ms.ToArray())
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
/// <summary>
/// 解密数据
/// </summary>
/// <param name="str">需要解密的内容</param>
/// <param name="key">秘钥</param>
/// <returns></returns>
public static string Decrypt(string str, string key)
{
var byteArray = new byte[str.Length / 2];
for (var i = 0; i < byteArray.Length; i++)
{
byteArray[i] = (byte)Convert.ToInt32(str.Substring(i * 2, 2), 16);
}
var des = new DESCryptoServiceProvider();
des.Key = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
des.IV = Encoding.ASCII.GetBytes(Md5Helper.Hash(key).ToUpper().Substring(0, 8));
var ms = new System.IO.MemoryStream();
var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(byteArray, 0, byteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
}
}

66
ConsoleTest/Util/Encrypt/Md5Helper.cs

@ -0,0 +1,66 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleTest.Util.Encrypt
{
/// <summary>
/// md5加密
/// </summary>
public class Md5Helper
{
/// <summary>
/// MD5加密
/// </summary>
/// <param name="str">加密字符</param>
/// <param name="len">加密位数16/32</param>
/// <returns></returns>
public static string Encrypt(string str, int len)
{
string encryptStr;
switch (len)
{
case 16:
encryptStr = Hash(str).Substring(8, 16);
break;
case 32:
encryptStr = Hash(str);
break;
default:
encryptStr = Hash(str);
break;
}
return encryptStr;
}
/// <summary>
/// 32位MD5加密(小写)
/// </summary>
/// <param name="str">输入字段</param>
/// <returns></returns>
public static string Hash(string str)
{
var md5Hasher = new MD5CryptoServiceProvider();
var byteArray = md5Hasher.ComputeHash(Encoding.Default.GetBytes(str));
var builder = new StringBuilder();
foreach (var b in byteArray)
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
/// <summary>
/// 生成编号,形如201008251145409865
/// </summary>
/// <returns></returns>
public static string CreateNo()
{
var randomStr = new Random().Next(1000, 10000).ToString(); //生成编号
var number = DateTime.Now.ToString("yyyyMMddHHmmss") + randomStr;
return number;
}
}
}

50
ConsoleTest/Util/EnvUtil.cs

@ -0,0 +1,50 @@
using System;
using System.IO;
using System.Reflection;
namespace ConsoleTest.Util
{
public class EnvUtil
{
private static string workDirectory;
public static void InitWorkDirectory()
{
Directory.SetCurrentDirectory(GetWorkDirectory());
}
public static string GetWorkDirectory()
{
workDirectory = string.IsNullOrEmpty(workDirectory) ? Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) : workDirectory;
return workDirectory;
}
public static bool AddDllPath(string dllPath)
{
if (!Directory.Exists(dllPath)) { return false; }
string envPath = Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable("PATH", envPath + ";" + dllPath);
return true;
}
public static string CombinePath(string path1, string path2)
{
return Path.Combine(path1, path2);
}
public static string CombinePath(params string[] paths)
{
return Path.Combine(paths);
}
public static bool ExistFile(string file)
{
return File.Exists(file);
}
public static bool ExistDirectory(string dir)
{
return Directory.Exists(dir);
}
}
}

572
ConsoleTest/Util/HttpMethods.cs

@ -0,0 +1,572 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace ConsoleTest.Util
{
public class HttpMethods
{
#region POST
/// <summary>
/// HTTP POST方式请求数据
/// </summary>
/// <param name="url">URL.</param>
/// <param name="param">POST的数据</param>
/// <returns></returns>
public static string HttpPost(string url, string param = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return true; //总是接受
}
public static string BuildRequest(string strUrl, Dictionary<string, string> dicPara, string fileName)
{
string contentType = "image/jpeg";
//待请求参数数组
FileStream Pic = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] PicByte = new byte[Pic.Length];
Pic.Read(PicByte, 0, PicByte.Length);
int lengthFile = PicByte.Length;
//构造请求地址
//设置HttpWebRequest基本信息
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
//设置请求方式:get、post
request.Method = "POST";
//设置boundaryValue
string boundaryValue = DateTime.Now.Ticks.ToString("x");
string boundary = "--" + boundaryValue;
request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
//设置KeepAlive
request.KeepAlive = true;
//设置请求数据,拼接成字符串
StringBuilder sbHtml = new StringBuilder();
foreach (KeyValuePair<string, string> key in dicPara)
{
sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" +
key.Value + "\r\n");
}
sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
sbHtml.Append(fileName);
sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
string postHeader = sbHtml.ToString();
//将请求数据字符串类型根据编码格式转换成字节流
Encoding code = Encoding.GetEncoding("UTF-8");
byte[] postHeaderBytes = code.GetBytes(postHeader);
byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
//设置长度
long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
request.ContentLength = length;
//请求远程HTTP
Stream requestStream = request.GetRequestStream();
Stream myStream = null;
try
{
//发送数据请求服务器
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
requestStream.Write(PicByte, 0, lengthFile);
requestStream.Write(boundayBytes, 0, boundayBytes.Length);
HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
myStream = HttpWResp.GetResponseStream();
}
catch (WebException)
{
//LogResult(e.Message);
return "";
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
}
//读取处理结果
StreamReader reader = new StreamReader(myStream, code);
StringBuilder responseData = new StringBuilder();
String line;
while ((line = reader.ReadLine()) != null)
{
responseData.Append(line);
}
myStream.Close();
Pic.Close();
return responseData.ToString();
}
#endregion POST
#region Put
/// <summary>
/// HTTP Put方式请求数据.
/// </summary>
/// <param name="url">URL.</param>
/// <returns></returns>
public static string HttpPut(string url, string param = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
#endregion Put
#region Delete
/// <summary>
/// HTTP Delete方式请求数据.
/// </summary>
/// <param name="url">URL.</param>
/// <returns></returns>
public static string HttpDelete(string url, string param = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "Delete";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
return responseStr;
}
#endregion Delete
#region Get
/// <summary>
/// HTTP GET方式请求数据.
/// </summary>
/// <param name="url">URL.</param>
/// <returns></returns>
public static string HttpGet(string url, Hashtable headht = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "GET";
//request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
WebResponse response = null;
string responseStr = null;
if (headht != null)
{
foreach (DictionaryEntry item in headht)
{
request.Headers.Add(item.Key.ToString(), item.Value.ToString());
}
}
try
{
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
return responseStr;
}
public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "GET";
//request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
WebResponse response = null;
string responseStr = null;
if (headht != null)
{
foreach (DictionaryEntry item in headht)
{
request.Headers.Add(item.Key.ToString(), item.Value.ToString());
}
}
try
{
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
return responseStr;
}
#endregion Get
#region Post With Pic
private string HttpPost(string url, IDictionary<object, object> param, string filePath)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string responseStr = null;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in param.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate =
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "pic", filePath, "text/plain");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
responseStr = reader2.ReadToEnd();
//logger.Debug(string.Format("File uploaded, server response is: {0}", responseStr));
}
catch (Exception)
{
//logger.Error("Error uploading file", ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
throw;
}
return responseStr;
}
#endregion Post With Pic
#region Post With Pic
/// <summary>
/// HTTP POST方式请求数据(带图片)
/// </summary>
/// <param name="url">URL</param>
/// <param name="param">POST的数据</param>
/// <param name="fileByte">图片</param>
/// <returns></returns>
public static string HttpPost(string url, IDictionary<object, object> param, byte[] fileByte)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string responseStr = null;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in param.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate =
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "pic", fileByte, "text/plain"); //image/jpeg
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
rs.Write(fileByte, 0, fileByte.Length);
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
responseStr = reader2.ReadToEnd();
// logger.Error(string.Format("File uploaded, server response is: {0}", responseStr));
}
catch (Exception)
{
//logger.Error("Error uploading file", ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
throw;
}
return responseStr;
}
#endregion Post With Pic
#region HttpsClient
/// <summary>
/// 创建HttpClient
/// </summary>
/// <returns></returns>
public static HttpClient CreateHttpClient(string url)
{
HttpClient httpclient;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
httpclient = new HttpClient();
}
else
{
httpclient = new HttpClient();
}
return httpclient;
}
#endregion HttpsClient
}
}

72
ConsoleTest/Util/JsonUtil.cs

@ -0,0 +1,72 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
namespace ConsoleTest.Util
{
/// <summary>
/// Json操作
/// </summary>
public static class JsonUtil
{
public static object ToJson(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject(Json);
}
public static string ToJson(this object obj)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
return JsonConvert.SerializeObject(obj, timeConverter);
}
public static string ToJson(this object obj, string datetimeformats)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
return JsonConvert.SerializeObject(obj, timeConverter);
}
public static T ToObject<T>(this string Json)
{
return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
}
public static List<T> ToList<T>(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
}
public static DataTable ToTable(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
}
public static JObject ToJObject(this string Json)
{
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
}
/// <summary>
/// 读取JSON文件
/// </summary>
public static JObject ReadFileJson(string jsonFile)
{
try
{
using StreamReader file = File.OpenText(jsonFile);
using JsonTextReader reader = new JsonTextReader(file);
JObject jObject = (JObject)JToken.ReadFrom(reader);
return jObject;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
}
}

180
ConsoleTest/Util/PortHelper/ECSerialPort.cs

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleTest.Util.PortHelper
{
/// <summary>
/// 返回数据类型
/// </summary>
public enum ReturnDateType
{
/// <summary>
/// 返回byte[]
/// </summary>
Bytes = 0,
HexStr = 1,
Str = 2,
}
/// <summary>
/// EC 串口类
/// </summary>
public class ECSerialPort
{
private System.IO.Ports.SerialPort comm = new System.IO.Ports.SerialPort();//声明一个串口
private SerialCustomer serialCustomer = null;
private bool openFlag = false;// 是否打开成功
public long ReceivedCount { get; set; }//接收计数
public long RendCount { get; set; }//发送计数
public ECSerialPort(SerialCustomer serialCustomer)
{
this.serialCustomer = serialCustomer;
}
public bool OpenCom()
{
//根据当前串口对象,来判断操作
if (comm.IsOpen)
{
//打开时点击,则关闭串口
comm.Close();
openFlag = false;
}
else
{
if (serialCustomer.ComName == "")
{
throw new Exception("请插入串口设备!");
}
//关闭时点击,则设置好端口,波特率后打开
//获得串口端口信息为: COM1:通讯端口
comm.PortName = serialCustomer.ComName;
comm.BaudRate = serialCustomer.BaudRate;// int.Parse(comboBaudrate.Text);//波特率
comm.DataBits = serialCustomer.DataBits;//数据位
comm.Parity = (Parity)serialCustomer.Parity;//奇偶校验0-4=no,odd,even,mark,space
comm.StopBits = (StopBits)Convert.ToInt32(serialCustomer.StopBits);//停止位
comm.ReadTimeout = 2000;//写超时
comm.WriteTimeout = 500;//读超时
//comm.WriteBufferSize = 1024;
//comm.ReadBufferSize = 1024;
comm.ReceivedBytesThreshold = 128;//128Btye时触发一次事件,设置为1时易造成线程死锁。
comm.RtsEnable = true;
comm.DtrEnable = true;
// comm.Handshake = Handshake.None;
//添加事件注册
comm.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);
comm.Open();
}
openFlag = comm.IsOpen ? true : false;
return openFlag;
}
/// <summary>
/// 关闭串口
/// </summary>
public void CloseCom()
{
comm.Close();
openFlag = false;
}
public bool IsOpen()
{
return comm.IsOpen;
}
public event EventHandler<byte[]> OnRecData; //定义一个委托类型的事件
private void Comm_DataReceived(object sender, EventArgs e)
{
int n = comm.BytesToRead;//获取缓存区字节数
byte[] buf = new byte[n];//存储串口数据用
ReceivedCount += n;//接收计数
comm.Read(buf, 0, n);//读取缓冲数据
//OnRecData?.BeginInvoke(this, buf, null, null);
OnRecData?.Invoke(this, buf);
}
/// <summary>
/// 发送串口
/// </summary>
/// <param name="checkBoxHexSend"></param>
/// <param name="sendtext"></param>
/// <param name="newLine"></param>
public void Send(bool checkBoxHexSend, string sendtext, bool newLine = false)
{
;
//定义一个变量,记录发送了几个字节
int n = 0;
//16进制发送
if (checkBoxHexSend)
{
//正则得到有效的十六进制数(?i)对大小写不敏感,[/da-f],{2}连续出现2次
// MatchCollection mc = Regex.Matches(txSend.Text, @"(?i)[/da-f]{2}");
MatchCollection mc = Regex.Matches(sendtext, @"(?i)[\da-f]{2}");
List<byte> buf = new List<byte>();//填充到这个临时列表中
//依次添加到列表中
foreach (Match m in mc)
{
buf.Add(byte.Parse(m.Value, System.Globalization.NumberStyles.HexNumber));
}
//转换列表为数组后发送
comm.Write(buf.ToArray(), 0, buf.Count);
if (newLine == true)
{ //记录发送的字节数
comm.WriteLine("\r\n");
n = buf.Count + 2;
}
else
n = buf.Count;
}
else//ascii编码直接发送
{
if (newLine == true)
{
comm.Write(sendtext + "\r\n");
n = sendtext.Length + 2;
}
else//不包含换行符
{
comm.Write(sendtext);
n = sendtext.Length;
}
}
RendCount += n;//累加发送字节数
}
/// <summary>
/// 16进制发送
/// </summary>
/// <param name="buf"></param>
/// <param name="newline"></param>
public void SendHex(byte[] buf, bool newline = false)
{
//定义一个变量,记录发送了几个字节
int n = 0;
int bufLen = buf.Count();
comm.Write(buf, 0, bufLen);
//if (newline == true)
//{ //记录发送的字节数
//comm.WriteLine("\n");
//n = bufLen + 2;
//}
//else
// n = bufLen;
RendCount += n;//累加发送字节数
}
}
}

45
ConsoleTest/Util/PortHelper/SerialCustomer.cs

@ -0,0 +1,45 @@
namespace ConsoleTest.Util.PortHelper
{
/// <summary>
/// 串口参数类
/// </summary>
public class SerialCustomer
{
public SerialCustomer()
{
BaudRate = 9600;
Parity = 0;
DataBits = 8;
StopBits = 1;
}
/// <summary>
/// 串口名称
/// </summary>
public string ComName { get; set; }
/// <summary>
///波特率
/// </summary>
public int BaudRate { get; set; }
/// <summary>
/// 奇偶校验0-4=no,odd,even,mark,space
/// </summary>
public int Parity { get; set; }
///// <summary>
///// 校验位对应值
///// </summary>
//public int ParityValue { get; set; }//
/// <summary>
///数据位 默认
/// </summary>
public int DataBits { get; set; } = 8;
/// <summary>
/// 停止位
/// </summary>
public int StopBits { get; set; }
}
}

47
ConsoleTest/Util/PortHelper/SerialPortManager.cs

@ -0,0 +1,47 @@
namespace ConsoleTest.Util.PortHelper
{
/// <summary>
/// EC 串口管理类
/// </summary>
public class SerialPortManager
{
/// <summary>
/// 根据参数对象创建
/// </summary>
/// <param name="serialCustomer"></param>
/// <returns></returns>
public static ECSerialPort CreateSerialPort(SerialCustomer serialCustomer)
{
return new ECSerialPort(serialCustomer);
}
/// <summary>
/// 获取默认参数串口
/// </summary>
/// <returns></returns>
public static ECSerialPort CreateSerialPort(string comName)
{
SerialCustomer serialCustomer = new SerialCustomer
{
ComName = comName
};
return new ECSerialPort(serialCustomer);
}
/// <summary>
/// 根据不同波特率创建串口
/// </summary>
/// <param name="comName"></param>
/// <param name="baudRate"></param>
/// <returns></returns>
public static ECSerialPort CreateSerialPort(string comName, int baudRate)
{
SerialCustomer serialCustomer = new SerialCustomer
{
ComName = comName,
BaudRate = baudRate
};
return new ECSerialPort(serialCustomer);
}
}
}

61
ConsoleTest/Util/PortUtil/SerialPortBuilder.cs

@ -0,0 +1,61 @@
namespace ConsoleTest.Util.PortUtil
{
/// <summary>
/// 串口构建类
/// </summary>
public class SerialPortBuilder
{
/// <summary>
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static YcSerialPort CreateSerialPort(SerialPortParam param)
{
return new YcSerialPort(param);
}
/// <summary>
/// </summary>
/// <param name="comName"></param>
public static YcSerialPort CreateSerialPort(string comName)
{
var param = new SerialPortParam
{
ComName = comName
};
return new YcSerialPort(param);
}
/// <summary>
/// </summary>
/// <param name="comName"></param>
/// <param name="baudRate"></param>
/// <returns></returns>
public static YcSerialPort CreateSerialPort(string comName, int baudRate)
{
var param = new SerialPortParam
{
ComName = comName,
BaudRate = baudRate
};
return new YcSerialPort(param);
}
/// <summary>
/// </summary>
/// <param name="comName"></param>
/// <param name="baudRate"></param>
/// <param name="receivedBytesThreshold"></param>
/// <returns></returns>
public static YcSerialPort CreateSerialPort(string comName, int baudRate, int receivedBytesThreshold)
{
var param = new SerialPortParam
{
ComName = comName,
BaudRate = baudRate,
ReceivedBytesThreshold = receivedBytesThreshold
};
return new YcSerialPort(param);
}
}
}

51
ConsoleTest/Util/PortUtil/SerialPortParam.cs

@ -0,0 +1,51 @@
namespace ConsoleTest.Util.PortUtil
{
/// <summary>
/// 串口参数类
/// </summary>
public class SerialPortParam
{
public SerialPortParam()
{
BaudRate = 9600;
Parity = 0;
DataBits = 8;
StopBits = 1;
ReceivedBytesThreshold = 128;
}
/// <summary>
/// 串口名称
/// </summary>
public string ComName { get; set; }
/// <summary>
///波特率
/// </summary>
public int BaudRate { get; set; }
/// <summary>
/// 奇偶校验0-4=no,odd,even,mark,space
/// </summary>
public int Parity { get; set; }
///// <summary>
///// 校验位对应值
///// </summary>
//public int ParityValue { get; set; }//
/// <summary>
///数据位 默认
/// </summary>
public int DataBits { get; set; }
/// <summary>
/// 停止位
/// </summary>
public int StopBits { get; set; }
/// <summary>
/// ?Byte时,触发一次事件。设置为1时,易造成线程死锁
/// </summary>
public int ReceivedBytesThreshold { get; set; }
}
}

170
ConsoleTest/Util/PortUtil/YcSerialPort.cs

@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleTest.Util.PortUtil
{
/// <summary>
/// 串口类
/// </summary>
public class YcSerialPort
{
private SerialPort _port;//声明一个串口
private readonly SerialPortParam _param;
public long RecCount { get; set; }//接收计数
public long SendCount { get; set; }//发送计数
public YcSerialPort()
{
}
public YcSerialPort(SerialPortParam param)
{
_param = param;
}
/// <summary>
/// 打开串口
/// </summary>
/// <returns></returns>
public bool OpenCom()
{
if (IsOpen())
CloseCom();
if (string.IsNullOrEmpty(_param.ComName))
throw new Exception("请插入串口设备!");
_port = new SerialPort
{
PortName = _param.ComName,//串口名
BaudRate = _param.BaudRate,//波特率
DataBits = _param.DataBits,//数据位
Parity = (Parity)_param.Parity,//奇偶校验0-4=no,odd,even,mark,space
StopBits = (StopBits)Convert.ToInt32(_param.StopBits),//停止位
ReadTimeout = 500,//读超时
WriteTimeout = 2000,//写超时
//ReadBufferSize = 1024,
//WriteBufferSize = 1024,
ReceivedBytesThreshold = _param.ReceivedBytesThreshold,//128Byte时触发一次事件,设置为1时易造成线程死锁。
RtsEnable = true,
DtrEnable = true,
};
_port.DataReceived += RecData;
//port.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);
_port.Open();
return IsOpen();
}
/// <summary>
/// 关闭串口
/// </summary>
public bool CloseCom()
{
if (IsOpen())
{
_port.Close();
_port = null;
}
return !IsOpen();
}
public bool IsOpen()
{
if (_port == null)
return false;
if (!_port.IsOpen)
return false;
return true;
}
public event EventHandler<byte[]> OnRecData; //定义一个委托类型的事件
private void RecData(object sender, EventArgs e)
{
var count = _port.BytesToRead;//获取缓存区字节数
var buf = new byte[count];//存储串口数据用
_port.Read(buf, 0, count);//读取缓冲数据
RecCount += count;//接收计数
OnRecData?.Invoke(this, buf);
}
/// <summary>
/// 发送 Ascii
/// </summary>
/// <param name="text"></param>
/// <param name="newLine"></param>
public void SendAscii(string text, bool newLine = false)
{
//定义一个变量,记录发送了几个字节
int count;
if (newLine)
{
_port.Write(text + "\r\n");
count = text.Length + 2;
}
else//不包含换行符
{
_port.Write(text);
count = text.Length;
}
SendCount += count;//累加发送字节数
}
/// <summary>
/// 发送 Hex
/// </summary>
/// <param name="text"></param>
/// <param name="newLine"></param>
public void SendHex(string text, bool newLine = false)
{
int count;//定义一个变量,记录发送了几个字节
var mc = Regex.Matches(text, @"(?i)[\da-f]{2}");//正则得到有效的十六进制数(?i)对大小写不敏感,[/da-f],{2}连续出现2次
var buf = new List<byte>();//填充到这个临时列表中
foreach (Match m in mc)
{
buf.Add(byte.Parse(m.Value, System.Globalization.NumberStyles.HexNumber));//依次添加到列表中
}
_port.Write(buf.ToArray(), 0, buf.Count);//转换列表为数组后发送
if (newLine)
{
_port.Write("\r\n");
count = buf.Count + 2;
}
else//不包含换行符
{
count = buf.Count;
}
SendCount += count;//累加发送字节数
}
/// <summary>
/// 发送 Hex
/// </summary>
/// <param name="buf"></param>
/// <param name="newline"></param>
public void SendHex(byte[] buf, bool newline = false)
{
int count;//定义一个变量,记录发送了几个字节
var bufLen = buf.Count();
_port.Write(buf, 0, bufLen);
if (newline)
{ //记录发送的字节数
_port.WriteLine("\n");
count = bufLen + 2;
}
else
{
count = bufLen;
}
SendCount += count;//累加发送字节数
}
}
}

BIN
ConsoleTest/data/image/logo.bmp

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

7
ConsoleTest/data/light/lightCode.json

@ -0,0 +1,7 @@
{
"CtrlAllLightCodeList": [ "", "3301140000000048", "3301130000000047" ],
"OpenLightCodeList": [ "", "3301120000000147", "3301120000000248", "3301120000000349", "330112000000044A" ],
"CloseLightCodeList": [ "", "3301110000000146", "3301110000000247", "3301110000000348", "3301110000000449" ],
"LockLightOnCodeList": [ "", "33011500000E045B", "33011500000D045A", "33011500000B0458", "3301150000070454" ],
"LockLightOffCodeList": [ "", "330115000001044E", "330115000002044F", "3301150000040451", "3301150000080455" ]
}

7
ConsoleTest/data/light/lightCode2.json

@ -0,0 +1,7 @@
{
"CtrlAllLightCodeList": [ "", "01108050000204020F0804A0ED", "011080500002040200080490EE" ],
"OpenLightCodeList": [ "", "01050000FF008C3A", "01050001FF00DDFA", "01050002FF002DFA", "01050003FF007C3A" ],
"CloseLightCodeList": [ "", "010500000000CDCA", "0105000100009C0A", "0105000200006C0A", "0105000300003DCA" ],
"LockLightOnCodeList": [ "", "0110805000020402010804C12E", "0110805000020402020804312E", "0110805000020402040804D12F", "0110805000020402080804112C" ],
"LockLightOffCodeList": [ "", "01108050000204020E0804F12D", "01108050000204020D0804012D", "01108050000204020B0804E12C", "0110805000020402070804212F" ]
}

7
ConsoleTest/data/light/lightCode3.json

@ -0,0 +1,7 @@
{
"CtrlAllLightCodeList": [ "", "010F0500000401003EC3", "010F05000004010F7EC7" ],
"OpenLightCodeList": [ "" ],
"CloseLightCodeList": [ "" ],
"LockLightOnCodeList": [ "", "010F050000040101FF03", "010F050000040102BF02", "010F0500000401043F00", "010F0500000401083F05" ],
"LockLightOffCodeList": [ "", "010F05000004010EBF07", "010F05000004010DFF06", "010F05000004010B7F04", "010F0500000401077F01" ]
}

12
ConsoleTest/data/light/lightCodeTemplate.json

@ -0,0 +1,12 @@
{
// еƱ1 Ϊеƣ2 Ϊرе
"CtrlAllLightCodeList": [ "" ],
// ijһ·Ʊindex Ӧ
"OpenLightCodeList": [ "" ],
// رijһ·Ʊ,index Ӧ
"CloseLightCodeList": [ "" ],
// ֻһ·index Ӧ
"LockLightOnCodeList": [ "" ],
// ֻһ·index Ӧ
"LockLightOffCodeList": [ "" ]
}

7
ConsoleTest/data/test.config

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="WT_COM" value="COM4" />
<add key="WT_BaudRate" value="9600" />
</appSettings>
</configuration>

BIN
ConsoleTest/dll/Led5kSDK.dll

Binary file not shown.

BIN
ConsoleTest/dll/TesoLive.dll

Binary file not shown.

11
ConsoleTest/packages.config

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NewLife.Core" version="10.0.2022.1001" targetFramework="net472" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net472" />
<package id="System.Configuration.ConfigurationManager" version="5.0.0" targetFramework="net472" />
<package id="System.Runtime" version="4.3.1" targetFramework="net472" />
<package id="System.Security.AccessControl" version="5.0.0" targetFramework="net472" />
<package id="System.Security.Permissions" version="5.0.0" targetFramework="net472" />
<package id="System.Security.Principal.Windows" version="5.0.0" targetFramework="net472" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net472" />
</packages>

54
EC.Helper/CameraSDK/Common/CameraException.cs

@ -0,0 +1,54 @@
namespace EC.Helper.CameraSDK;
/// <summary>
/// 相机异常
/// </summary>
public class CameraException : Exception
{
public CameraException() : base()
{
}
public CameraException(string? message) : base(message)
{
}
public CameraException(string? message, Exception? innerException) : base(message, innerException)
{
}
protected class CameraExceptionObj
{
public CameraType Type { get; set; }
public int ErrCode { get; set; }
public string? ErrMsg { get; set; }
public override string? ToString()
{
return $"Type:{Type}, ErrCode:{ErrCode}, ErrMsg:{ErrMsg}";
}
}
public static CameraException New(CameraType type, int errCode)
{
CameraExceptionObj obj = new()
{
Type = type,
ErrCode = errCode
};
return new CameraException(obj.ToString());
}
public static CameraException New(CameraType type, int errCode, string errMsg)
{
CameraExceptionObj obj = new()
{
Type = type,
ErrCode = errCode,
ErrMsg = errMsg
};
return new CameraException(obj.ToString());
}
}

111
EC.Helper/CameraSDK/Common/CameraStruct.cs

@ -0,0 +1,111 @@
namespace EC.Helper.CameraSDK;
/// <summary>
/// 相机信息
/// </summary>
public class CameraInfo
{
#region Attr
/// <summary>
/// 相机类型
/// </summary>
public int Type { get; set; }
/// <summary>
/// ip 地址
/// </summary>
public string Ip { get; set; } = string.Empty;
/// <summary>
/// 端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 账号
/// </summary>
public string UserName { get; set; } = string.Empty;
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; } = string.Empty;
#endregion Attr
public static CameraInfo New(int type, string ip, int port, string userName, string password)
{
CameraInfo info = new() { Type = type, Ip = ip, Port = port, UserName = userName, Password = password };
if (port <= 0)
throw new Exception("Camera type not support.");
return info;
}
public static CameraInfo New(int type, string ip, string userName, string password)
{
CameraInfo info = new() { Type = type, Ip = ip, UserName = userName, Password = password };
int port = (CameraType)type switch
{
CameraType.HiK => CameraPort.HiK,
CameraType.DaHua => CameraPort.DaHua,
CameraType.YuShi => CameraPort.YuShi,
_ => -1,
};
info.Port = port;
if (port <= 0)
throw new Exception("Camera type not support.");
return info;
}
}
/// <summary>
/// 相机类型
/// </summary>
public enum CameraType
{
HiK = 0,
DaHua = 1,
YuShi = 2,
}
/// <summary>
/// 相机默认连接端口
/// </summary>
public class CameraPort
{
public const int HiK = 8000;
public const int DaHua = 37777;
public const int YuShi = 8800;
}
/// <summary>
/// Ptz 信息
/// </summary>
public class PtzInfo
{
#region Attr
public double Pan { get; set; }
public double Tilt { get; set; }
public double Zoom { get; set; }
#endregion Attr
public PtzInfo(double pan, double tilt, double zoom)
{
Pan = pan;
Tilt = tilt;
Zoom = zoom;
}
public static PtzInfo Default
{
get { return new(0, 0, 0); }
}
public static PtzInfo New(double pan, double tilt, double zoom)
{
return new PtzInfo(pan, tilt, zoom);
}
}

58
EC.Helper/CameraSDK/Common/ICameraSDK.cs

@ -0,0 +1,58 @@
namespace EC.Helper.CameraSDK;
public abstract class ICameraSDK
{
#region Attr
protected CameraInfo CameraInfo { get; set; }
#endregion Attr
public ICameraSDK(CameraInfo cameraInfo)
{
CameraInfo = cameraInfo;
}
#region Base Method
/// <summary>
/// 初始化资源
/// </summary>
/// <returns></returns>
public abstract bool Init();
/// <summary>
/// 释放资源
/// </summary>
/// <returns></returns>
public abstract bool Destory();
/// <summary>
/// 连接是否成功
/// </summary>
/// <returns></returns>
public abstract bool ConnectSuccess();
/// <summary>
/// 构建异常
/// </summary>
public abstract void BuildException();
#endregion Base Method
#region Main Method
/// <summary>
/// 获取 ptz
/// </summary>
/// <returns></returns>
public abstract PtzInfo GetPtzInfo();
/// <summary>
/// 获取 ptz
/// </summary>
/// <returns></returns>
public abstract bool TryGetPtzInfo(out PtzInfo ptzInfo);
#endregion Main Method
}

848
EC.Helper/CameraSDK/DaHua/DaHuaOriSDK.cs

@ -0,0 +1,848 @@
//#define Linux32
//#define Linux64
//#define Win32
//#define Win64
using System.Runtime.InteropServices;
namespace EC.Helper.CameraSDK;
public static class DaHuaOriSDK
{
#region Lib Attr
#if (Linux32)
private const string LibDhNetSDK = @"./libs/dahua/linux32/libdhnetsdk.so";
#elif (Linux64)
private const string LibDhNetSDK = @"./libs/dahua/linux64/libdhnetsdk.so";
#elif (Win32)
private const string LibDhNetSDK = @"./libs/dahua/win32/dhnetsdk.dll";
#elif (Win64)
private const string LibDhNetSDK = @"./libs/dahua/win64/dhnetsdk.dll";
#endif
#endregion Lib Attr
static DaHuaOriSDK()
{
GlobalInit();
}
#region Global
public static bool InitSuccess { get; private set; }
public static bool GlobalInit()
{
if (InitSuccess) return true;
bool ret = CLIENT_InitEx(null, IntPtr.Zero, IntPtr.Zero);
InitSuccess = ret;
if (!ret) throw new Exception("DaHuaOriSDK global init failure.");
return ret;
}
public static bool GlobalDestory()
{
if (!InitSuccess) return true;
CLIENT_Cleanup();
InitSuccess = false;
return true;
}
#endregion Global
#region SDK Enum
/// <summary>
/// login device mode enumeration
/// 登陆设备方式枚举
/// </summary>
public enum EM_LOGIN_SPAC_CAP_TYPE
{
/// <summary>
/// TCP login, default
/// TCP登陆, 默认方式
/// </summary>
TCP = 0,
/// <summary>
/// No criteria login
/// 无条件登陆
/// </summary>
ANY = 1,
/// <summary>
/// auto sign up login
/// 主动注册的登入
/// </summary>
SERVER_CONN = 2,
/// <summary>
/// multicast login, default
/// 组播登陆
/// </summary>
MULTICAST = 3,
/// <summary>
/// UDP method login
/// UDP方式下的登入
/// </summary>
UDP = 4,
/// <summary>
/// only main connection login
/// 只建主连接下的登入
/// </summary>
MAIN_CONN_ONLY = 6,
/// <summary>
/// SSL encryption login
/// SSL加密方式登陆
/// </summary>
SSL = 7,
/// <summary>
/// login IVS box remote device
/// 登录智能盒远程设备
/// </summary>
INTELLIGENT_BOX = 9,
/// <summary>
/// login device do not config
/// 登录设备后不做取配置操作
/// </summary>
NO_CONFIG = 10,
/// <summary>
/// USB key device login
/// 用U盾设备的登入
/// </summary>
U_LOGIN = 11,
/// <summary>
/// LDAP login
/// LDAP方式登录
/// </summary>
LDAP = 12,
/// <summary>
/// AD login
/// AD(ActiveDirectory)登录方式
/// </summary>
AD = 13,
/// <summary>
/// Radius login
/// Radius 登录方式
/// </summary>
RADIUS = 14,
/// <summary>
/// Socks5 login
/// Socks5登陆方式
/// </summary>
SOCKET_5 = 15,
/// <summary>
/// cloud login
/// 云登陆方式
/// </summary>
CLOUD = 16,
/// <summary>
/// dual authentication loin
/// 二次鉴权登陆方式
/// </summary>
AUTH_TWICE = 17,
/// <summary>
/// TS stream client login
/// TS码流客户端登陆方式
/// </summary>
TS = 18,
/// <summary>
/// web private login
/// 为P2P登陆方式
/// </summary>
P2P = 19,
/// <summary>
/// mobile client login
/// 手机客户端登陆
/// </summary>
MOBILE = 20,
/// <summary>
/// invalid login
/// 无效的登陆方式
/// </summary>
INVALID = 21,
}
/// <summary>
/// device type enumeration
/// 设备类型枚举
/// </summary>
public enum EM_NET_DEVICE_TYPE
{
/// <summary>
/// Unknow
// 未知
/// </summary>
NET_PRODUCT_NONE = 0,
/// <summary>
/// Non real-time MACE
/// 非实时MACE
/// </summary>
NET_DVR_NONREALTIME_MACE,
/// <summary>
/// Non real-time
/// 非实时
/// </summary>
NET_DVR_NONREALTIME,
/// <summary>
/// Network video server
/// 网络视频服务器
/// </summary>
NET_NVS_MPEG1,
/// <summary>
/// MPEG1 2-ch DVR
/// MPEG1二路录像机
/// </summary>
NET_DVR_MPEG1_2,
/// <summary>
/// MPEG1 8-ch DVR
/// MPEG1八路录像机
/// </summary>
NET_DVR_MPEG1_8,
/// <summary>
/// MPEG4 8-ch DVR
/// MPEG4八路录像机
/// </summary>
NET_DVR_MPEG4_8,
/// <summary>
/// MPEG4 16-ch DVR
/// MPEG4 十六路录像机
/// </summary>
NET_DVR_MPEG4_16,
/// <summary>
/// LB series DVR
/// LB系列录像机
/// </summary>
NET_DVR_MPEG4_SX2,
/// <summary>
/// GB series DVR
/// GB系列录像机
/// </summary>
NET_DVR_MEPG4_ST2,
/// <summary>
/// HB series DVR
/// HB系列录像机
/// </summary>
NET_DVR_MEPG4_SH2,
/// <summary>
/// GBE series DVR
/// GBE系列录像机
/// </summary>
NET_DVR_MPEG4_GBE,
/// <summary>
/// II network video server
/// II代网络视频服务器
/// </summary>
NET_DVR_MPEG4_NVSII,
/// <summary>
/// New standard configuration protocol
/// 新标准配置协议
/// </summary>
NET_DVR_STD_NEW,
/// <summary>
/// DDNS server
/// DDNS服务器
/// </summary>
NET_DVR_DDNS,
/// <summary>
/// ATM series
/// ATM机
/// </summary>
NET_DVR_ATM,
/// <summary>
/// 2nd non real-time NB series DVR
/// 二代非实时NB系列机器
/// </summary>
NET_NB_SERIAL,
/// <summary>
/// LN series
/// LN系列产品
/// </summary>
NET_LN_SERIAL,
/// <summary>
/// BAV series
/// BAV系列产品
/// </summary>
NET_BAV_SERIAL,
/// <summary>
/// SDIP series
/// SDIP系列产品
/// </summary>
NET_SDIP_SERIAL,
/// <summary>
/// IPC series
/// IPC系列产品
/// </summary>
NET_IPC_SERIAL,
/// <summary>
/// NVS B series
/// NVS B系列
/// </summary>
NET_NVS_B,
/// <summary>
/// NVS H series
/// NVS H系列
/// </summary>
NET_NVS_C,
/// <summary>
/// NVS S series
/// NVS S系列
/// </summary>
NET_NVS_S,
/// <summary>
/// NVS E series
/// NVS E系列
/// </summary>
NET_NVS_E,
/// <summary>
/// Search device type from QueryDevState. it is in string format
/// 从QueryDevState中查询设备类型,以字符串格式
/// </summary>
NET_DVR_NEW_PROTOCOL,
/// <summary>
/// NVD
/// 解码器
/// </summary>
NET_NVD_SERIAL,
/// <summary>
/// N5
/// N5
/// </summary>
NET_DVR_N5,
/// <summary>
/// HDVR
/// 混合DVR
/// </summary>
NET_DVR_MIX_DVR,
/// <summary>
/// SVR series
/// SVR系列
/// </summary>
NET_SVR_SERIAL,
/// <summary>
/// SVR-BS
/// SVR-BS
/// </summary>
NET_SVR_BS,
/// <summary>
/// NVR series
/// NVR系列
/// </summary>
NET_NVR_SERIAL,
/// <summary>
/// N51
/// N51
/// </summary>
NET_DVR_N51,
/// <summary>
/// ITSE Intelligent Analysis Box
/// ITSE 智能分析盒
/// </summary>
NET_ITSE_SERIAL,
/// <summary>
/// Intelligent traffic camera equipment
/// 智能交通像机设备
/// </summary>
NET_ITC_SERIAL,
/// <summary>
/// radar speedometer HWS
/// 雷达测速仪HWS
/// </summary>
NET_HWS_SERIAL,
/// <summary>
/// portable video record
/// 便携式音视频录像机
/// </summary>
NET_PVR_SERIAL,
/// <summary>
/// IVS(intelligent video server series)
/// IVS(智能视频服务器系列)
/// </summary>
NET_IVS_SERIAL,
/// <summary>
/// universal intelligent detect video server series
/// 通用智能视频侦测服务器
/// </summary>
NET_IVS_B,
/// <summary>
/// face recognisation server
/// 人脸识别服务器
/// </summary>
NET_IVS_F,
/// <summary>
/// video quality diagnosis server
/// 视频质量诊断服务器
/// </summary>
NET_IVS_V,
/// <summary>
/// matrix
/// 矩阵
/// </summary>
NET_MATRIX_SERIAL,
/// <summary>
/// N52
/// N52
/// </summary>
NET_DVR_N52,
/// <summary>
/// N56
/// N56
/// </summary>
NET_DVR_N56,
/// <summary>
/// ESS
/// ESS
/// </summary>
NET_ESS_SERIAL,
/// <summary>
/// 人数统计服务器
/// </summary>
NET_IVS_PC,
/// <summary>
/// pc-nvr
/// pc-nvr
/// </summary>
NET_PC_NVR,
/// <summary>
/// screen controller
/// 大屏控制器
/// </summary>
NET_DSCON,
/// <summary>
/// network video storage server
/// 网络视频存储服务器
/// </summary>
NET_EVS,
/// <summary>
/// an embedded intelligent video analysis system
/// 嵌入式智能分析视频系统
/// </summary>
NET_EIVS,
/// <summary>
/// DVR-N6
/// DVR-N6
/// </summary>
NET_DVR_N6,
/// <summary>
/// K-Lite Codec Pack
/// 万能解码器
/// </summary>
NET_UDS,
/// <summary>
/// Bank alarm host
/// 银行报警主机
/// </summary>
NET_AF6016,
/// <summary>
/// Video network alarm host
/// 视频网络报警主机
/// </summary>
NET_AS5008,
/// <summary>
/// Network alarm host
/// 网络报警主机
/// </summary>
NET_AH2008,
/// <summary>
/// Alarm host series
/// 报警主机系列
/// </summary>
NET_A_SERIAL,
/// <summary>
/// Access control series of products
/// 门禁系列产品
/// </summary>
NET_BSC_SERIAL,
/// <summary>
/// NVS series product
/// NVS系列产品
/// </summary>
NET_NVS_SERIAL,
/// <summary>
/// VTO series product
/// VTO系列产品
/// </summary>
NET_VTO_SERIAL,
/// <summary>
/// VTNC series product
/// VTNC系列产品
/// </summary>
NET_VTNC_SERIAL,
/// <summary>
/// TPC series product, it is the thermal device
/// TPC系列产品, 即热成像设备
/// </summary>
NET_TPC_SERIAL,
/// <summary>
/// ASM series product
/// 无线中继设备
/// </summary>
NET_ASM_SERIAL,
/// <summary>
/// VTS series product
/// 管理机
/// </summary>
NET_VTS_SERIAL,
/// <summary>
/// Alarm host-ARC2016C
/// 报警主机ARC2016C
/// </summary>
NET_ARC2016C,
/// <summary>
/// ASA Attendance machine
/// 考勤机
/// </summary>
NET_ASA,
/// <summary>
/// Industry terminal walkie-talkie
/// 行业对讲终端
/// </summary>
NET_VTT_SERIAL,
/// <summary>
/// Alarm column
/// 报警柱
/// </summary>
NET_VTA_SERIAL,
/// <summary>
/// SIP Server
/// SIP服务器
/// </summary>
NET_VTNS_SERIAL,
/// <summary>
/// Indoor unit
/// 室内机
/// </summary>
NET_VTH_SERIAL,
}
/// <summary>
/// 查询设备信息参数
/// </summary>
public enum EM_DEVICE_STATE
{
/// <summary>
/// Query device online state(return a DWORD value, 1-online, 0-offline)
/// 查询设备的在线状态(返回一个DWORD, 1表示在线, 0表示断线)
/// </summary>
ONLINE = 0x0035,
/// <summary>
/// Query ptz state(struct DH_PTZ_LOCATION_INFO)
/// 查询云台状态信息(对应结构体 DH_PTZ_LOCATION_INFO)
/// </summary>
PTZ_LOCATION = 0x0036,
}
/// <summary>
/// 预置点状态枚举
/// </summary>
public enum EM_DH_PTZ_PRESET_STATUS
{
UNKNOWN, // 未知
REACH, // 预置点到达
UNREACH, // 预置点未到达
}
#endregion SDK Enum
#region SDK Struct
/// <summary>
/// CLIENT_LoginWithHighLevelSecurity 输入参数
/// </summary>
public struct NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY
{
public uint dwSize;// 结构体大小
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string szIP; // IP
public int nPort; // 端口
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string szUserName; // 用户名
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string szPassword; // 密码
public EM_LOGIN_SPAC_CAP_TYPE emSpecCap; // 登录模式
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] byReserved; // 字节对齐
public IntPtr pCapParam; // 见 CLIENT_LoginEx 接口 pCapParam 与 nSpecCap 关系
}
/// <summary>
/// device information structure
/// 设备信息结构体
/// </summary>
public struct NET_DEVICEINFO_Ex
{
/// <summary>
/// serial number
/// 序列号
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)]
public string sSerialNumber;
/// <summary>
/// count of alarm input
/// 报警输入个数
/// </summary>
public int nAlarmInPortNum;
/// <summary>
/// count of alarm output
/// 报警输出个数
/// </summary>
public int nAlarmOutPortNum;
/// <summary>
/// number of disk
/// 硬盘个数
/// </summary>
public int nDiskNum;
/// <summary>
/// device type, refer to EM_NET_DEVICE_TYPE
/// 设备类型,见枚举NET_DEVICE_TYPE
/// </summary>
public EM_NET_DEVICE_TYPE nDVRType;
/// <summary>
/// number of channel
/// 通道个数
/// </summary>
public int nChanNum;
/// <summary>
/// Online Timeout, Not Limited Access to 0, not 0 Minutes Limit Said
/// 在线超时时间,为0表示不限制登陆,非0表示限制的分钟数
/// </summary>
public byte byLimitLoginTime;
/// <summary>
/// When login failed due to password error, notice user by this parameter.This parameter is invalid when remaining login times is zero
/// 当登陆失败原因为密码错误时,通过此参数通知用户,剩余登陆次数,为0时表示此参数无效
/// </summary>
public byte byLeftLogTimes;
/// <summary>
/// keep bytes for aligned
/// 保留字节,字节对齐
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] bReserved;
/// <summary>
/// when log in failed,the left time for users to unlock (seconds), -1 indicate the device haven't set the parameter
/// 当登陆失败,用户解锁剩余时间(秒数), -1表示设备未设置该参数
/// </summary>
public int nLockLeftTime;
/// <summary>
/// reserved
/// 保留字节
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
public byte[] Reserved;
}
/// <summary>
/// CLIENT_LoginWithHighLevelSecurity 输出参数
/// </summary>
public struct NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY
{
public uint dwSize;// 结构体大小
public NET_DEVICEINFO_Ex stuDeviceInfo; // 设备信息
public int nError; // 错误码,见 CLIENT_Login 接口错误码
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 132)]
public byte[] byReserved; // 保留字节
}
/// <summary>
/// 云台定位中非归一化坐标和变倍
/// </summary>
public struct NET_PTZSPACE_UNNORMALIZED
{
public int nPosX; // x坐标
public int nPosY; // y坐标
public int nZoom; // 放大倍率
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 52)]
public byte[] byReserved; // 预留字节
}
/// <summary>
/// 云台定位信息
/// </summary>
//云台定位信息
public struct DH_PTZ_LOCATION_INFO
{
public int nChannelID; // 通道号
public int nPTZPan; // 云台水平运动位置,有效范围:[0,3600]
public int nPTZTilt; // 云台垂直运动位置,有效范围:[-1800,1800]
public int nPTZZoom; // 云台光圈变动位置,有效范围:[0,128]
public byte bState; // 云台运动状态, 0-未知 1-运动 2-空闲
public byte bAction; // 云台动作,255-未知,0-预置点,1-线扫,2-巡航,3-巡迹,4-水平旋转,5-普通移动,6-巡迹录制,7-全景云台扫描,8-热度图
// 9-精确定位,10-设备校正,11-智能配置,12-云台重启
public byte bFocusState; // 云台聚焦状态, 0-未知, 1-运动状态, 2-空闲
public byte bEffectiveInTimeSection; // 在时间段内预置点状态是否有效
//如果当前上报的预置点是时间段内的预置点,则为1,其他情况为0
public int nPtzActionID; // 巡航ID号
public uint dwPresetID; // 云台所在预置点编号
public float fFocusPosition; // 聚焦位置
public byte bZoomState; // 云台ZOOM状态,0-未知,1-ZOOM,2-空闲
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public byte[] bReserved; // 对齐
public uint dwSequence; // 包序号,用于校验是否丢包
public uint dwUTC; // 对应的UTC(1970-1-1 00:00:00)秒数。
public EM_DH_PTZ_PRESET_STATUS emPresetStatus; // 预置点位置
/// <summary>
/// 保留字段
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 248)]
public int[] reserved;
};
#endregion SDK Struct
#region Common Method
/// <summary>
/// network disconnection callback function original shape
/// 断线回调函数
/// </summary>
/// <param name="lLoginID">user LoginID:Login's returns value 登陆ID</param>
/// <param name="pchDVRIP">device IP 设备IP</param>
/// <param name="nDVRPort">device prot 设备端口</param>
/// <param name="dwUser">user data from Init function 用户数据</param>
public delegate void fDisConnectCallBack(IntPtr lLoginID, IntPtr pchDVRIP, int nDVRPort, IntPtr dwUser);
/// <summary>
/// network re-connection callback function original shape
/// 重连回调函数
/// </summary>
/// <param name="lLoginID">user LoginID:Login's returns value 登陆ID</param>
/// <param name="pchDVRIP">device IP,string type 设备IP</param>
/// <param name="nDVRPort">device prot 设备端口</param>
/// <param name="dwUser">user data from SetAutoReconnect function 用户数据</param>
public delegate void fHaveReConnectCallBack(IntPtr lLoginID, IntPtr pchDVRIP, int nDVRPort, IntPtr dwUser);
[DllImport(LibDhNetSDK)]
public static extern bool CLIENT_InitEx(fDisConnectCallBack? cbDisConnect, IntPtr dwUser, IntPtr lpInitParam);
[DllImport(LibDhNetSDK)]
public static extern void CLIENT_Cleanup();
[DllImport(LibDhNetSDK)]
public static extern int CLIENT_GetLastError();
[DllImport(LibDhNetSDK)]
public static extern IntPtr CLIENT_LoginWithHighLevelSecurity(ref NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstInParam, ref NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam);
[DllImport(LibDhNetSDK)]
public static extern bool CLIENT_Logout(IntPtr lLoginID);
[DllImport(LibDhNetSDK)]
public static extern void CLIENT_SetAutoReconnect(fHaveReConnectCallBack cbAutoConnect, IntPtr dwUser);
[DllImport(LibDhNetSDK)]
public static extern bool CLIENT_QueryDevState(IntPtr lLoginID, int nType, IntPtr pBuf, int nBufLen, ref int pRetLen, int waittime);
#endregion Common Method
}

137
EC.Helper/CameraSDK/DaHua/DaHuaSDK.cs

@ -0,0 +1,137 @@
using System.Runtime.InteropServices;
namespace EC.Helper.CameraSDK;
public class DaHuaSDK : ICameraSDK
{
#region Attr
private IntPtr LoginId { get; set; } = IntPtr.Zero;
#endregion Attr
public DaHuaSDK(CameraInfo cameraInfo) : base(cameraInfo)
{
}
#region Base Method
public override bool Init()
{
bool ret = ConnectSuccess();
if (ret) return true;
DaHuaOriSDK.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY stuInParam = new();
stuInParam.dwSize = (uint)Marshal.SizeOf(stuInParam);
stuInParam.szIP = CameraInfo.Ip;
stuInParam.nPort = CameraInfo.Port;
stuInParam.szUserName = CameraInfo.UserName;
stuInParam.szPassword = CameraInfo.Password;
stuInParam.emSpecCap = DaHuaOriSDK.EM_LOGIN_SPAC_CAP_TYPE.TCP;
stuInParam.pCapParam = IntPtr.Zero;
DaHuaOriSDK.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY stuOutParam = new();
stuOutParam.dwSize = (uint)Marshal.SizeOf(stuOutParam);
LoginId = DaHuaOriSDK.CLIENT_LoginWithHighLevelSecurity(ref stuInParam, ref stuOutParam);
ret = ConnectSuccess();
if (ret) DaHuaOriSDK.CLIENT_SetAutoReconnect(delegate (IntPtr lLoginID, IntPtr pchDVRIP, int nDVRPort, IntPtr dwUser)
{
LoginId = lLoginID;
}, IntPtr.Zero);
return ret;
}
public override bool Destory()
{
bool ret = ConnectSuccess();
if (!ret) return true;
ret = DaHuaOriSDK.CLIENT_Logout(LoginId);
if (ret) LoginId = IntPtr.Zero;
return ret;
}
public override bool ConnectSuccess()
{
return LoginId != IntPtr.Zero;
}
public override void BuildException()
{
uint errCode = (uint)DaHuaOriSDK.CLIENT_GetLastError();
if (errCode == 0) return;
errCode -= 0x80000000;
throw CameraException.New(CameraType.DaHua, (int)errCode);
}
#endregion Base Method
#region Main Method
private static class GPIParams
{
public static int Size { get; private set; }
public static Type Type { get; private set; }
static GPIParams()
{
DaHuaOriSDK.DH_PTZ_LOCATION_INFO info = new();
Size = Marshal.SizeOf(info);
Type = info.GetType();
}
}
public override PtzInfo GetPtzInfo()
{
bool ret = ConnectSuccess();
if (!ret) return PtzInfo.Default;
DaHuaOriSDK.DH_PTZ_LOCATION_INFO entity = new();
int nBufLen = GPIParams.Size;
int pRetLen = 0;
IntPtr ptrBuf = Marshal.AllocHGlobal(GPIParams.Size);
Marshal.StructureToPtr(entity, ptrBuf, true);
try
{
ret = DaHuaOriSDK.CLIENT_QueryDevState(LoginId, (int)DaHuaOriSDK.EM_DEVICE_STATE.PTZ_LOCATION, ptrBuf, nBufLen, ref pRetLen, 3000);
if (!ret) { BuildException(); return PtzInfo.Default; }
object? objBuf = Marshal.PtrToStructure(ptrBuf, GPIParams.Type);
if (objBuf == null) return PtzInfo.Default;
entity = (DaHuaOriSDK.DH_PTZ_LOCATION_INFO)objBuf;
return PtzInfo.New(entity.nPTZPan, entity.nPTZTilt, entity.nPTZZoom);
}
finally
{
Marshal.FreeHGlobal(ptrBuf);
}
}
public override bool TryGetPtzInfo(out PtzInfo ptzInfo)
{
bool ret = ConnectSuccess();
if (!ret) { ptzInfo = PtzInfo.Default; return false; }
DaHuaOriSDK.DH_PTZ_LOCATION_INFO entity = new();
int nBufLen = GPIParams.Size;
int pRetLen = 0;
IntPtr ptrBuf = Marshal.AllocHGlobal(GPIParams.Size);
Marshal.StructureToPtr(entity, ptrBuf, true);
try
{
ret = DaHuaOriSDK.CLIENT_QueryDevState(LoginId, (int)DaHuaOriSDK.EM_DEVICE_STATE.PTZ_LOCATION, ptrBuf, nBufLen, ref pRetLen, 3000);
if (!ret) { BuildException(); ptzInfo = PtzInfo.Default; return false; }
object? objBuf = Marshal.PtrToStructure(ptrBuf, GPIParams.Type);
if (objBuf == null) { ptzInfo = PtzInfo.Default; return false; }
entity = (DaHuaOriSDK.DH_PTZ_LOCATION_INFO)objBuf;
ptzInfo = PtzInfo.New(entity.nPTZPan, entity.nPTZTilt, entity.nPTZZoom);
return true;
}
finally
{
Marshal.FreeHGlobal(ptrBuf);
}
}
#endregion Main Method
}

226
EC.Helper/CameraSDK/HiK/HiKOriSDK.cs

@ -0,0 +1,226 @@
//#define Linux32
//#define Linux64
//#define Win32
//#define Win64
using System.Runtime.InteropServices;
namespace EC.Helper.CameraSDK;
public static class HiKOriSDK
{
#region Lib Attr
#if (Linux32)
public const string LibHcNetSDK = @"./libs/hik/linux32/libhcnetsdk.so";
#elif (Linux64)
public const string LibHcNetSDK = @"./libs/hik/linux64/libhcnetsdk.so";
#elif (Win32)
public const string LibHcNetSDK = @"./libs/hik/win32/HCNetSDK.dll";
#elif (Win64)
public const string LibHcNetSDK = @"./libs/hik/win64/HCNetSDK.dll";
#endif
#endregion Lib Attr
static HiKOriSDK()
{
GlobalInit();
}
#region Global
public static bool InitSuccess { get; private set; }
public static bool GlobalInit()
{
if (InitSuccess) return true;
bool ret = NET_DVR_Init();
InitSuccess = ret;
if (!ret) throw new Exception("HiKOriSDK global init failure.");
return ret;
}
public static bool GlobalDestory()
{
if (!InitSuccess) return true;
bool ret = NET_DVR_Cleanup();
if (ret) InitSuccess = false;
return ret;
}
#endregion Global
#region SDK Const
public const int SERIALNO_LEN = 48; //序列号长度
#region 用于 NET_DVR_SetDVRConfig 和 NET_DVR_GetDVRConfig
public const int NET_DVR_SET_PTZPOS = 292; //云台设置PTZ位置
public const int NET_DVR_GET_PTZPOS = 293; //云台获取PTZ位置
public const int NET_DVR_GET_PTZSCOPE = 294; //云台获取PTZ范围
#endregion 用于 NET_DVR_SetDVRConfig 和 NET_DVR_GetDVRConfig
#endregion SDK Const
#region SDK Struct
//NET_DVR_Login()参数结构
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct NET_DVR_DEVICEINFO
{
[MarshalAsAttribute(
UnmanagedType.ByValArray,
SizeConst = SERIALNO_LEN,
ArraySubType = UnmanagedType.I1
)]
public byte[] sSerialNumber; //序列号
public byte byAlarmInPortNum; //DVR报警输入个数
public byte byAlarmOutPortNum; //DVR报警输出个数
public byte byDiskNum; //DVR硬盘个数
public byte byDVRType; //DVR类型, 1:DVR 2:ATM DVR 3:DVS ......
public byte byChanNum; //DVR 通道个数
public byte byStartChan; //起始通道号,例如DVS-1,DVR - 1
}
//NET_DVR_Login_V30()参数结构
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct NET_DVR_DEVICEINFO_V30
{
[MarshalAsAttribute(
UnmanagedType.ByValArray,
SizeConst = SERIALNO_LEN,
ArraySubType = UnmanagedType.I1
)]
public byte[] sSerialNumber; //序列号
public byte byAlarmInPortNum; //报警输入个数
public byte byAlarmOutPortNum; //报警输出个数
public byte byDiskNum; //硬盘个数
public byte byDVRType; //设备类型, 1:DVR 2:ATM DVR 3:DVS ......
public byte byChanNum; //模拟通道个数
public byte byStartChan; //起始通道号,例如DVS-1,DVR - 1
public byte byAudioChanNum; //语音通道数
public byte byIPChanNum; //最大数字通道个数,低位
public byte byZeroChanNum; //零通道编码个数 //2010-01-16
public byte byMainProto; //主码流传输协议类型 0-private, 1-rtsp,2-同时支持private和rtsp
public byte bySubProto; //子码流传输协议类型0-private, 1-rtsp,2-同时支持private和rtsp
public byte bySupport; //能力,位与结果为0表示不支持,1表示支持,
//bySupport & 0x1, 表示是否支持智能搜索
//bySupport & 0x2, 表示是否支持备份
//bySupport & 0x4, 表示是否支持压缩参数能力获取
//bySupport & 0x8, 表示是否支持多网卡
//bySupport & 0x10, 表示支持远程SADP
//bySupport & 0x20, 表示支持Raid卡功能
//bySupport & 0x40, 表示支持IPSAN 目录查找
//bySupport & 0x80, 表示支持rtp over rtsp
public byte bySupport1; // 能力集扩充,位与结果为0表示不支持,1表示支持
//bySupport1 & 0x1, 表示是否支持snmp v30
//bySupport1 & 0x2, 支持区分回放和下载
//bySupport1 & 0x4, 是否支持布防优先级
//bySupport1 & 0x8, 智能设备是否支持布防时间段扩展
//bySupport1 & 0x10, 表示是否支持多磁盘数(超过33个)
//bySupport1 & 0x20, 表示是否支持rtsp over http
//bySupport1 & 0x80, 表示是否支持车牌新报警信息2012-9-28, 且还表示是否支持NET_DVR_IPPARACFG_V40结构体
public byte bySupport2; /*00
bySupport2 & 0x1, URL取流解码
bySupport2 & 0x2, FTPV40
bySupport2 & 0x4, ANR
bySupport2 & 0x8, CCD的通道参数配置
bySupport2 & 0x10,
bySupport2 & 0x20,
bySupport2 & 0x40, */
public ushort wDevType; //设备型号
public byte bySupport3; //能力集扩展,位与结果为0表示不支持,1表示支持
//bySupport3 & 0x1, 表示是否多码流
// bySupport3 & 0x4 表示支持按组配置, 具体包含 通道图像参数、报警输入参数、IP报警输入、输出接入参数、
// 用户参数、设备工作状态、JPEG抓图、定时和时间抓图、硬盘盘组管理
//bySupport3 & 0x8为1 表示支持使用TCP预览、UDP预览、多播预览中的"延时预览"字段来请求延时预览(后续都将使用这种方式请求延时预览)。而当bySupport3 & 0x8为0时,将使用 "私有延时预览"协议。
//bySupport3 & 0x10 表示支持"获取报警主机主要状态(V40)"。
//bySupport3 & 0x20 表示是否支持通过DDNS域名解析取流
public byte byMultiStreamProto; //是否支持多码流,按位表示,0-不支持,1-支持,bit1-码流3,bit2-码流4,bit7-主码流,bit-8子码流
public byte byStartDChan; //起始数字通道号,0表示无效
public byte byStartDTalkChan; //起始数字对讲通道号,区别于模拟对讲通道号,0表示无效
public byte byHighDChanNum; //数字通道个数,高位
public byte bySupport4;
public byte byLanguageType; // 支持语种能力,按位表示,每一位0-不支持,1-支持
// byLanguageType 等于0 表示 老设备
// byLanguageType & 0x1表示支持中文
// byLanguageType & 0x2表示支持英文
[MarshalAsAttribute(
UnmanagedType.ByValArray,
SizeConst = 9,
ArraySubType = UnmanagedType.I1
)]
public byte[] byRes2; //保留
}
//球机位置信息
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct NET_DVR_PTZPOS
{
public ushort wAction; //获取时该字段无效
public ushort wPanPos; //水平参数
public ushort wTiltPos; //垂直参数
public ushort wZoomPos; //变倍参数
}
//球机范围信息
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct NET_DVR_PTZSCOPE
{
public ushort wPanPosMin; //水平参数min
public ushort wPanPosMax; //水平参数max
public ushort wTiltPosMin; //垂直参数min
public ushort wTiltPosMax; //垂直参数max
public ushort wZoomPosMin; //变倍参数min
public ushort wZoomPosMax; //变倍参数max
}
#endregion SDK Struct
#region Common Method
[DllImport(LibHcNetSDK)]
public static extern bool NET_DVR_Init();
[DllImport(LibHcNetSDK)]
public static extern bool NET_DVR_Cleanup();
[DllImport(LibHcNetSDK)]
public static extern uint NET_DVR_GetLastError();
[DllImport(LibHcNetSDK)]
public static extern int NET_DVR_Login_V30(
string sDVRIP,
int wDVRPort,
string sUserName,
string sPassword,
ref NET_DVR_DEVICEINFO_V30 lpDeviceInfo
);
[DllImport(LibHcNetSDK)]
public static extern bool NET_DVR_Logout(int iUserID);
//参数配置 begin
[DllImport(LibHcNetSDK)]
public static extern bool NET_DVR_GetDVRConfig(
int lUserID,
uint dwCommand,
int lChannel,
IntPtr lpOutBuffer,
uint dwOutBufferSize,
ref uint lpBytesReturned
);
#endregion Common Method
}

123
EC.Helper/CameraSDK/HiK/HiKSDK.cs

@ -0,0 +1,123 @@
using System.Runtime.InteropServices;
namespace EC.Helper.CameraSDK;
public class HiKSDK : ICameraSDK
{
#region Attr
private int LoginId { get; set; } = -1;
#endregion Attr
public HiKSDK(CameraInfo cameraInfo) : base(cameraInfo)
{
}
#region Base Method
public override bool Init()
{
bool ret = ConnectSuccess();
if (ret) return true;
HiKOriSDK.NET_DVR_DEVICEINFO_V30 deviceInfo = new();
LoginId = HiKOriSDK.NET_DVR_Login_V30(CameraInfo.Ip, CameraInfo.Port, CameraInfo.UserName, CameraInfo.Password, ref deviceInfo);
ret = ConnectSuccess();
return ret;
}
public override bool Destory()
{
bool ret = ConnectSuccess();
if (!ret) return true;
ret = HiKOriSDK.NET_DVR_Logout(LoginId);
if (ret) LoginId = -1;
return ret;
}
public override bool ConnectSuccess()
{
return LoginId >= 0;
}
public override void BuildException()
{
uint errCode = HiKOriSDK.NET_DVR_GetLastError();
if (errCode == 0) return;
throw CameraException.New(CameraType.HiK, (int)errCode);
}
#endregion Base Method
#region Main Method
private static class GPIParams
{
public static int Size { get; private set; }
public static Type Type { get; private set; }
static GPIParams()
{
HiKOriSDK.NET_DVR_PTZPOS ptzPos = new();
Size = Marshal.SizeOf(ptzPos);
Type = ptzPos.GetType();
}
}
public override PtzInfo GetPtzInfo()
{
bool ret = ConnectSuccess();
if (!ret) return PtzInfo.Default;
HiKOriSDK.NET_DVR_PTZPOS entity = new();
int dwSize = GPIParams.Size;
uint dwReturned = 0;
IntPtr ptrBuf = Marshal.AllocHGlobal(dwSize);
Marshal.StructureToPtr(entity, ptrBuf, true);
try
{
ret = HiKOriSDK.NET_DVR_GetDVRConfig(LoginId, HiKOriSDK.NET_DVR_GET_PTZPOS, 0, ptrBuf, (uint)dwSize, ref dwReturned);
if (!ret) { BuildException(); return PtzInfo.Default; }
object? objBuf = Marshal.PtrToStructure(ptrBuf, GPIParams.Type);
if (objBuf == null) return PtzInfo.Default;
entity = (HiKOriSDK.NET_DVR_PTZPOS)objBuf;
return PtzInfo.New(entity.wPanPos, entity.wTiltPos, entity.wZoomPos);
}
finally
{
Marshal.FreeHGlobal(ptrBuf);
}
}
public override bool TryGetPtzInfo(out PtzInfo ptzInfo)
{
bool ret = ConnectSuccess();
if (!ret) { ptzInfo = PtzInfo.Default; return false; }
HiKOriSDK.NET_DVR_PTZPOS entity = new();
int dwSize = GPIParams.Size;
uint dwReturned = 0;
IntPtr ptrBuf = Marshal.AllocHGlobal(dwSize);
Marshal.StructureToPtr(entity, ptrBuf, true);
try
{
ret = HiKOriSDK.NET_DVR_GetDVRConfig(LoginId, HiKOriSDK.NET_DVR_GET_PTZPOS, 0, ptrBuf, (uint)dwSize, ref dwReturned);
if (!ret) { BuildException(); ptzInfo = PtzInfo.Default; return false; }
object? objBuf = Marshal.PtrToStructure(ptrBuf, GPIParams.Type);
if (objBuf == null) { ptzInfo = PtzInfo.Default; return false; }
entity = (HiKOriSDK.NET_DVR_PTZPOS)objBuf;
ptzInfo = PtzInfo.New(entity.wPanPos, entity.wTiltPos, entity.wZoomPos);
return true;
}
finally
{
Marshal.FreeHGlobal(ptrBuf);
}
}
#endregion Main Method
}

150
EC.Helper/CameraSDK/YuShi/YuShiOriSDK.cs

@ -0,0 +1,150 @@
//#define Linux32
//#define Linux64
//#define Win32
//#define Win64
using System.Runtime.InteropServices;
namespace EC.Helper.CameraSDK;
public static class YuShiOriSDK
{
#region Lib Attr
#if (Linux32)
public const string LibYsNetSDK = @"./libs/yushi/linux64/libNetDEVSDK.so";
#elif (Linux64)
public const string LibYsNetSDK = @"./libs/yushi/linux64/libNetDEVSDK.so";
#elif (Win32)
public const string LibYsNetSDK = @"./libs/yushi/win32/NetDEVSDK.dll";
#elif (Win64)
public const string LibYsNetSDK = @"./libs/yushi/win64/NetDEVSDK.dll";
#endif
#endregion Lib Attr
static YuShiOriSDK()
{
GlobalInit();
}
#region Global
public static bool InitSuccess { get; private set; }
public static bool GlobalInit()
{
if (InitSuccess) return true;
bool ret = NETDEV_Init();
InitSuccess = ret;
if (!ret) throw new Exception("YuShiOriSDK global init failure.");
return ret;
}
public static bool GlobalDestory()
{
if (!InitSuccess) return true;
bool ret = NETDEV_Cleanup();
if (ret) InitSuccess = false;
return ret;
}
#endregion Global
#region SDK Const
/* Common length */
public const int NETDEV_LEN_64 = 64;
public const int NETDEV_LEN_128 = 128;
public const int NETDEV_LEN_132 = 132;
public const int NETDEV_LEN_260 = 260;
#endregion SDK Const
#region SDK Struct
[StructLayout(LayoutKind.Sequential)]
public struct NETDEV_DEVICE_LOGIN_INFO_S
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NETDEV_LEN_260)]
public string szIPAddr; /* IP地址/域名 */
public Int32 dwPort; /* 端口号 */
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NETDEV_LEN_132)]
public string szUserName; /* 用户名 */
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NETDEV_LEN_128)]
public string szPassword; /* 密码 */
public Int32 dwLoginProto; /* 登录协议, 参见NETDEV_LOGIN_PROTO_E */
public Int32 dwDeviceType; /* 设备类型, 参见NETDEV_DEVICE_TYPE_E */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public byte[] byRes; /* Reserved */
};
[StructLayout(LayoutKind.Sequential)]
public struct NETDEV_SELOG_INFO_S
{
public Int32 dwSELogCount;
public Int32 dwSELogTime;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] byRes;
};
[StructLayout(LayoutKind.Sequential)]
public struct NETDEV_VIDEO_CHL_DETAIL_INFO_S
{
public Int32 dwChannelID;
public Int32 bPtzSupported; /* Whether ptz is supported */
public Int32 enStatus; /* Channel status */
public Int32 dwStreamNum; /* Number of streams */
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NETDEV_LEN_64)]
public string szChnName; /* Device serial number */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] szReserve;
}
[StructLayout(LayoutKind.Sequential)]
public struct NETDEV_PTZ_STATUS_S
{
public float fPanTiltX; /* 绝对水平坐标 Absolute horizontal coordinates*/
public float fPanTiltY; /* 绝对竖直坐标 Absolute vertical coordinates*/
public float fZoomX; /* 绝对聚焦倍数 Absolute multiples*/
public Int32 enPanTiltStatus;/* 云台状态 PTZ Status*/
public Int32 enZoomStatus; /* 聚焦状态 Focus Status*/
};
#endregion SDK Struct
#region Common Method
[DllImport(LibYsNetSDK, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern bool NETDEV_Init();
[DllImport(LibYsNetSDK, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern bool NETDEV_Cleanup();
[DllImport(LibYsNetSDK, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int NETDEV_GetLastError();
[DllImport(LibYsNetSDK, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr NETDEV_Login_V30(ref NETDEV_DEVICE_LOGIN_INFO_S pstDevLoginInfo, ref NETDEV_SELOG_INFO_S pstSELogInfo);
[DllImport(LibYsNetSDK, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern bool NETDEV_Logout(IntPtr lpUserID);
[DllImport(LibYsNetSDK, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern Int32 NETDEV_QueryVideoChlDetailList(IntPtr lpUserID, ref int pdwChlCount, IntPtr pstVideoChlList);
[DllImport(LibYsNetSDK, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern bool NETDEV_PTZGetStatus(IntPtr lpUserID, int dwChannelID, ref NETDEV_PTZ_STATUS_S pstPTZStaus);
//public boolean NETDEV_GetDevConfig(Pointer lpUserID, int dwChannelID, int dwCommand, Pointer lpOutBuffer, int dwOutBufferSize, IntByReference pdwBytesReturned);
#endregion Common Method
}

87
EC.Helper/CameraSDK/YuShi/YuShiSDK.cs

@ -0,0 +1,87 @@
namespace EC.Helper.CameraSDK;
public class YuShiSDK : ICameraSDK
{
#region Attr
private IntPtr LoginId { get; set; } = IntPtr.Zero;
#endregion Attr
public YuShiSDK(CameraInfo cameraInfo) : base(cameraInfo)
{
}
#region Base Method
public override bool Init()
{
bool ret = ConnectSuccess();
if (ret) return true;
YuShiOriSDK.NETDEV_DEVICE_LOGIN_INFO_S loginInfo = new();
loginInfo.szIPAddr = CameraInfo.Ip;
loginInfo.dwPort = CameraInfo.Port;
loginInfo.szUserName = CameraInfo.UserName;
loginInfo.szPassword = CameraInfo.Password;
YuShiOriSDK.NETDEV_SELOG_INFO_S logInfo = new();
LoginId = YuShiOriSDK.NETDEV_Login_V30(ref loginInfo, ref logInfo);
ret = ConnectSuccess();
return ret;
}
public override bool Destory()
{
bool ret = ConnectSuccess();
if (!ret) return true;
ret = YuShiOriSDK.NETDEV_Logout(LoginId);
if (ret) LoginId = IntPtr.Zero;
return ret;
}
public override bool ConnectSuccess()
{
return LoginId != IntPtr.Zero;
}
public override void BuildException()
{
int errCode = YuShiOriSDK.NETDEV_GetLastError();
if (errCode == 0) return;
throw CameraException.New(CameraType.YuShi, (int)errCode);
}
#endregion Base Method
#region Main Method
public override PtzInfo GetPtzInfo()
{
bool ret = ConnectSuccess();
if (!ret) return PtzInfo.Default;
YuShiOriSDK.NETDEV_PTZ_STATUS_S entity = new();
ret = YuShiOriSDK.NETDEV_PTZGetStatus(LoginId, 1, ref entity);
if (!ret) { BuildException(); return PtzInfo.Default; }
return PtzInfo.New(entity.fPanTiltX, entity.fPanTiltY, entity.fZoomX);
}
public override bool TryGetPtzInfo(out PtzInfo ptzInfo)
{
bool ret = ConnectSuccess();
if (!ret) { ptzInfo = PtzInfo.Default; return false; }
YuShiOriSDK.NETDEV_PTZ_STATUS_S entity = new();
ret = YuShiOriSDK.NETDEV_PTZGetStatus(LoginId, 1, ref entity);
if (!ret) { BuildException(); ptzInfo = PtzInfo.Default; return false; }
ptzInfo = PtzInfo.New(entity.fPanTiltX, entity.fPanTiltY, entity.fZoomX);
return true;
}
#endregion Main Method
}

151
EC.Helper/EC.Helper.csproj

@ -0,0 +1,151 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants)TRACE;Win64</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DefineConstants>$(DefineConstants)TRACE;Win64</DefineConstants>
</PropertyGroup>
<ItemGroup>
<None Remove="libs\dahua\linux32\libdhnetsdk.so" />
<None Remove="libs\dahua\linux64\libdhnetsdk.so" />
<None Remove="libs\dahua\win32\dhnetsdk.dll" />
<None Remove="libs\dahua\win64\dhnetsdk.dll" />
<None Remove="libs\hik\linux32\HCNetSDKCom\libHCCoreDevCfg.so" />
<None Remove="libs\hik\linux32\HCNetSDKCom\libHCPreview.so" />
<None Remove="libs\hik\linux32\libcrypto.so.1.1" />
<None Remove="libs\hik\linux32\libHCCore.so" />
<None Remove="libs\hik\linux32\libhcnetsdk.so" />
<None Remove="libs\hik\linux32\libssl.so.1.1" />
<None Remove="libs\hik\linux64\HCNetSDKCom\libHCCoreDevCfg.so" />
<None Remove="libs\hik\linux64\HCNetSDKCom\libHCPreview.so" />
<None Remove="libs\hik\linux64\libcrypto.so.1.1" />
<None Remove="libs\hik\linux64\libHCCore.so" />
<None Remove="libs\hik\linux64\libhcnetsdk.so" />
<None Remove="libs\hik\linux64\libssl.so.1.1" />
<None Remove="libs\hik\win32\HCNetSDKCom\HCCoreDevCfg.dll" />
<None Remove="libs\hik\win32\HCNetSDKCom\HCPreview.dll" />
<None Remove="libs\hik\win32\HCCore.dll" />
<None Remove="libs\hik\win32\HCNetSDK.dll" />
<None Remove="libs\hik\win32\libcrypto-1_1.dll" />
<None Remove="libs\hik\win32\libssl-1_1.dll" />
<None Remove="libs\hik\win64\HCNetSDKCom\HCCoreDevCfg.dll" />
<None Remove="libs\hik\win64\HCNetSDKCom\HCPreview.dll" />
<None Remove="libs\hik\win64\HCCore.dll" />
<None Remove="libs\hik\win64\HCNetSDK.dll" />
<None Remove="libs\hik\win64\libcrypto-1_1-x64.dll" />
<None Remove="libs\hik\win64\libssl-1_1-x64.dll" />
<None Remove="libs\yushi\linux64\libNetDEVSDK.so" />
<None Remove="libs\yushi\win32\NetDEVSDK.dll" />
<None Remove="libs\yushi\win64\NetDEVSDK.dll" />
</ItemGroup>
<ItemGroup>
<Content Include="libs\dahua\linux32\libdhnetsdk.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\dahua\linux64\libdhnetsdk.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\dahua\win32\dhnetsdk.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\dahua\win64\dhnetsdk.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux32\HCNetSDKCom\libHCCoreDevCfg.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux32\HCNetSDKCom\libHCPreview.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux32\libcrypto.so.1.1">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux32\libHCCore.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux32\libhcnetsdk.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux32\libssl.so.1.1">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux64\HCNetSDKCom\libHCCoreDevCfg.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux64\HCNetSDKCom\libHCPreview.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux64\libcrypto.so.1.1">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux64\libHCCore.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux64\libhcnetsdk.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\linux64\libssl.so.1.1">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win32\HCNetSDKCom\HCCoreDevCfg.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win32\HCNetSDKCom\HCPreview.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win32\HCCore.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win32\HCNetSDK.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win32\libcrypto-1_1.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win32\libssl-1_1.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win64\HCNetSDKCom\HCCoreDevCfg.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win64\HCNetSDKCom\HCPreview.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win64\HCCore.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win64\HCNetSDK.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win64\libcrypto-1_1-x64.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\hik\win64\libssl-1_1-x64.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\yushi\linux64\libNetDEVSDK.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\yushi\win32\NetDEVSDK.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libs\yushi\win64\NetDEVSDK.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="libs\yushi\linux32\" />
</ItemGroup>
</Project>

9
EC.Helper/RabbitFunc/Compiler/CompilerException.cs

@ -0,0 +1,9 @@
namespace EC.Helper.RabbitFunc.Compiler;
[Serializable]
public class CompilerException : Exception
{
public CompilerException(SourceLocation location, string message)
: base(string.Format("line:{0} column:{1}: {2}", location.Line, location.Column, message))
{ }
}

57
EC.Helper/RabbitFunc/Compiler/IndexSpan.cs

@ -0,0 +1,57 @@
namespace EC.Helper.RabbitFunc.Compiler;
[Serializable]
public readonly struct IndexSpan : IEquatable<IndexSpan>
{
private readonly int start;
private readonly int length;
public IndexSpan(int start, int length)
{
if (start < 0)
throw new ArgumentOutOfRangeException(nameof(start));
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
this.start = start;
this.length = length;
}
public int Start => start;
public int End => start + length;
public int Length => length;
public bool IsEmpty => length == 0;
public static bool operator ==(IndexSpan left, IndexSpan right)
{
return left.start == right.start && left.length == right.length;
}
public static bool operator !=(IndexSpan left, IndexSpan right)
{
return left.start != right.start || left.length != right.length;
}
public bool Equals(IndexSpan other)
{
return other.start == start && other.length == length;
}
public override bool Equals(object obj)
{
return obj is IndexSpan other && Equals(other);
}
public override int GetHashCode()
{
return (start.GetHashCode() << 16) ^ length.GetHashCode();
}
public override string ToString()
{
return string.Format("{{start:{0} length:{1}}}", start, length);
}
}

258
EC.Helper/RabbitFunc/Compiler/Parser.cs

@ -0,0 +1,258 @@
using EC.Helper.RabbitFunc.Expressions;
using EC.Helper.RabbitFunc.Syntax;
namespace EC.Helper.RabbitFunc.Compiler;
internal class Parser
{
private readonly Tokenizer tokenizer;
private TokenWithSpan lookahead;
private TokenWithSpan token;
public Parser(Tokenizer tokenizer)
{
if (tokenizer == null)
throw new ArgumentNullException(nameof(tokenizer));
this.tokenizer = tokenizer;
Initialize();
}
private void Initialize()
{
FetchLookahead();
}
private Token NextToken()
{
token = lookahead;
FetchLookahead();
return token.Token;
}
private Token PeekToken()
{
return this.lookahead.Token;
}
private void FetchLookahead()
{
lookahead = new TokenWithSpan(tokenizer.NextToken(), tokenizer.TokenSpan);
}
private bool PeekToken(TokenKind kind)
{
return PeekToken().Kind == kind;
}
private bool PeekToken(Token check)
{
return PeekToken() == check;
}
private bool MaybeEat(TokenKind kind)
{
if (PeekToken().Kind == kind)
{
NextToken();
return true;
}
return false;
}
private LambdaExpression ParseStatement()
{
while (true)
{
switch (PeekToken().Kind)
{
case TokenKind.Comment:
case TokenKind.NewLine:
NextToken();
continue;
case TokenKind.EndOfFile:
return null;
default:
return ParseLambdaExpression();
}
}
}
private ExpressionType GetBinaryOperator(TokenKind kind)
{
return kind switch
{
TokenKind.Add => ExpressionType.Add,
TokenKind.Subtract => ExpressionType.Subtract,
TokenKind.Multiply => ExpressionType.Multiply,
TokenKind.Divide => ExpressionType.Divide,
TokenKind.Mod => ExpressionType.Modulo,
TokenKind.Power => ExpressionType.Power,
TokenKind.LessThan => ExpressionType.LessThan,
TokenKind.LessThanOrEqual => ExpressionType.LessThanOrEqual,
TokenKind.Equal => ExpressionType.Equal,
TokenKind.GreaterThanOrEqual => ExpressionType.GreaterThanOrEqual,
TokenKind.GreaterThan => ExpressionType.GreaterThan,
TokenKind.NotEqual => ExpressionType.NotEqual,
_ => throw new CompilerException(tokenizer.Position, string.Format("operator TokenKind:{0} error!", kind.ToString())),
};
}
private IList<Expression> ParseArguments()
{
List<Expression> list = new List<Expression>();
if (PeekToken().Kind != TokenKind.RightParen)
{
do
{
list.Add(ParseExpression());
} while (MaybeEat(TokenKind.Comma));
}
return list;
}
private Expression ParseTerm()
{
Expression expr = null;
Token token = NextToken();
switch (token.Kind)
{
case TokenKind.Constant:
expr = Expression.Constant(token.Value);
break;
case TokenKind.Subtract:
expr = Expression.Negate(ParseExpression());
break;
case TokenKind.LeftParen:
expr = ParseExpression();
if (!MaybeEat(TokenKind.RightParen))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
break;
case TokenKind.Identifier:
switch (PeekToken().Kind)
{
case TokenKind.LeftParen:
NextToken();
expr = Expression.Call(null, token.Text, ParseArguments());
if (!MaybeEat(TokenKind.RightParen))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
break;
case TokenKind.Dot:
expr = Expression.Parameter(null, token.Text);
while (MaybeEat(TokenKind.Dot))
{
token = NextToken();
if (token.Kind != TokenKind.Identifier)
throw new CompilerException(tokenizer.Position, PeekToken().Text);
if (PeekToken().Kind == TokenKind.LeftParen)
{
expr = Expression.Call(expr, token.Text, ParseArguments());
if (!MaybeEat(TokenKind.RightParen))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
break;
}
expr = Expression.Member(expr, token.Text);
}
if (MaybeEat(TokenKind.LeftParen))
{
expr = Expression.Call(expr, token.Text, ParseArguments());
if (!MaybeEat(TokenKind.RightParen))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
}
break;
default:
expr = Expression.Parameter(typeof(double), token.Text);
break;
}
break;
case TokenKind.Not:
return Expression.Not(ParseExpression());
case TokenKind.IF:
if (!MaybeEat(TokenKind.LeftParen))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
var test = ParseExpression();
if (!MaybeEat(TokenKind.Comma))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
var trueExpre = ParseExpression();
if (!MaybeEat(TokenKind.Comma))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
var falseExpre = ParseExpression();
if (!MaybeEat(TokenKind.RightParen))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
expr = Expression.Condition(test, trueExpre, falseExpre);
break;
}
return expr;
}
private Expression ParseExpression(byte precedence = 0)
{
Expression leftOperand = ParseTerm();
while (true)
{
Token token = PeekToken();
if (token is OperatorToken operatorToken && operatorToken.Precedence >= precedence)
{
NextToken();
Expression rightOperand = ParseExpression(checked((byte)(operatorToken.Precedence + 1)));
ExpressionType @operator = GetBinaryOperator(token.Kind);
leftOperand = new BinaryExpression(@operator, leftOperand, rightOperand);
continue;
}
break;
}
return leftOperand;
}
private LambdaExpression ParseLambdaExpression()
{
Token token = NextToken();
if (token.Kind != TokenKind.Identifier)
throw new CompilerException(tokenizer.Position, token.Text);
var name = token.Text;
var parameters = new List<ParameterExpression>();
if (MaybeEat(TokenKind.LeftParen))
{
if (!MaybeEat(TokenKind.RightParen))
{
do
{
token = NextToken();
if (token.Kind != TokenKind.Identifier)
throw new CompilerException(tokenizer.Position, token.Text);
parameters.Add(Expression.Parameter(typeof(double), token.Text));
} while (MaybeEat(TokenKind.Comma));
if (!MaybeEat(TokenKind.RightParen))
throw new CompilerException(tokenizer.Position, token.Text);
}
}
if (!MaybeEat(TokenKind.Assign))
throw new CompilerException(tokenizer.Position, PeekToken().Text);
Expression body = ParseExpression();
return Expression.Lambda(name, body, parameters);
}
public LambdaExpression Parse()
{
return ParseStatement();
}
}

97
EC.Helper/RabbitFunc/Compiler/SourceLocation.cs

@ -0,0 +1,97 @@
namespace EC.Helper.RabbitFunc.Compiler;
[Serializable]
public readonly struct SourceLocation : IEquatable<SourceLocation>
{
public static readonly SourceLocation None = new SourceLocation(0, 16707566, 0, true);
public static readonly SourceLocation Invalid = new SourceLocation(0, 0, 0, true);
public static readonly SourceLocation MinValue = new SourceLocation(0, 1, 1);
private readonly int index;
private readonly int line;
private readonly int column;
public SourceLocation(int index, int line, int column)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (line < 1)
throw new ArgumentOutOfRangeException(nameof(line));
if (column < 1)
throw new ArgumentOutOfRangeException(nameof(column));
this.index = index;
this.line = line;
this.column = column;
}
private SourceLocation(int index, int line, int column, bool _)
{
this.index = index;
this.line = line;
this.column = column;
}
public int Index => index;
public int Line => line;
public int Column => column;
public bool IsValid => line != 0 && column != 0;
public static bool operator ==(SourceLocation left, SourceLocation right)
{
return left.index == right.index && left.line == right.line && left.column == right.column;
}
public static bool operator !=(SourceLocation left, SourceLocation right)
{
return left.index != right.index || left.line != right.line || left.column != right.column;
}
public static bool operator <(SourceLocation left, SourceLocation right)
{
return left.index < right.index;
}
public static bool operator >(SourceLocation left, SourceLocation right)
{
return left.index > right.index;
}
public static bool operator <=(SourceLocation left, SourceLocation right)
{
return left.index <= right.index;
}
public static bool operator >=(SourceLocation left, SourceLocation right)
{
return left.index >= right.index;
}
public static int Compare(SourceLocation left, SourceLocation right)
{
return left > right ? 1 : left < right ? -1 : 0;
}
public bool Equals(SourceLocation other)
{
return other.index == index && other.line == line && other.column == column;
}
public override bool Equals(object obj)
{
return obj is SourceLocation other && Equals(other);
}
public override int GetHashCode()
{
return (line << 16) ^ column;
}
public override string ToString()
{
return string.Format("{{index:{0} line:{1} column:{2}}}", index, line, column);
}
}

20
EC.Helper/RabbitFunc/Compiler/TokenWithSpan.cs

@ -0,0 +1,20 @@
using EC.Helper.RabbitFunc.Syntax;
namespace EC.Helper.RabbitFunc.Compiler;
[Serializable]
internal readonly struct TokenWithSpan
{
private readonly Token token;
private readonly IndexSpan span;
public TokenWithSpan(Token token, IndexSpan span)
{
this.token = token;
this.span = span;
}
public IndexSpan Span => span;
public Token Token => token;
}

403
EC.Helper/RabbitFunc/Compiler/Tokenizer.cs

@ -0,0 +1,403 @@
using EC.Helper.RabbitFunc.Syntax;
namespace EC.Helper.RabbitFunc.Compiler;
internal class Tokenizer
{
#region Attr
private const int DefaultBufferCapacity = 1024;
private readonly TextReader reader;
private char[] buffer;
private int start;
private int end;
private int position;
private bool endOfStream;
private bool multiEolns;
private int tokenEnd;
private int tokenStartIndex;
private int tokenEndIndex;
private List<int> newLineLocations;
private SourceLocation initialLocation;
public bool EndOfStream => endOfStream;
public int Index => tokenStartIndex + Math.Min(position, end) - start;
public SourceLocation Position => IndexToLocation(Index);
public IndexSpan TokenSpan => new(tokenStartIndex, tokenEndIndex - tokenStartIndex);
private int TokenLength => tokenEnd - start;
#endregion Attr
public Tokenizer(TextReader reader)
{
this.reader = reader;
Init(DefaultBufferCapacity);
}
private void Init(int bufferCapacity)
{
multiEolns = true;
buffer = new char[bufferCapacity];
newLineLocations = new List<int>();
initialLocation = SourceLocation.MinValue;
}
private static void ResizeInternal(ref char[] array, int newSize, int start, int count)
{
char[] array2 = (newSize != array.Length) ? new char[newSize] : array;
Buffer.BlockCopy(array, start * 2, array2, 0, count * 2);
array = array2;
}
private static bool IsNameStart(int ch)
{
return char.IsLetter((char)ch) || ch == 95;
}
private static bool IsNamePart(int ch)
{
return char.IsLetterOrDigit((char)ch) || ch == 95;
}
private static Token BadChar(int ch)
{
return Token.Error(((char)ch).ToString());
}
private void RefillBuffer()
{
if (end == buffer.Length)
{
int newSize = Math.Max(Math.Max((end - start) * 2, buffer.Length), position);
ResizeInternal(ref buffer, newSize, start, end - start);
end -= start;
position -= start;
start = 0;
//_bufferResized = true;
}
end += reader.Read(buffer, end, buffer.Length - end);
}
private int Peek()
{
if (position >= end)
{
RefillBuffer();
if (position >= end)
{
endOfStream = true;
return -1;
}
}
return buffer[position];
}
private bool NextChar(int ch)
{
if (Peek() == ch)
{
position++;
return true;
}
return false;
}
private int NextChar()
{
int result = Peek();
position++;
return result;
}
private int ReadLine()
{
int num;
do
{
num = NextChar();
} while (num != -1 && !IsEoln(num));
if (num == 10)
{
newLineLocations.Add(Index);
}
BufferBack();
return num;
}
private bool IsEoln(int current)
{
return current == 10 || (current == 13 && multiEolns);
}
private void BufferBack()
{
SeekRelative(-1);
}
private void SeekRelative(int disp)
{
position += disp;
}
private void MarkTokenEnd()
{
tokenEnd = Math.Min(position, end);
int num = tokenEnd - start;
tokenEndIndex = tokenStartIndex + num;
}
private void DiscardToken()
{
if (tokenEnd == -1)
{
MarkTokenEnd();
}
start = tokenEnd;
tokenStartIndex = tokenEndIndex;
tokenEnd = -1;
}
private string GetTokenString()
{
return new string(buffer, start, tokenEnd - start);
}
private string GetTokenSubstring(int offset)
{
return GetTokenSubstring(offset, tokenEnd - start - offset);
}
private string GetTokenSubstring(int offset, int length)
{
return new string(buffer, start + offset, length);
}
private int SkipWhiteSpace()
{
int num;
do
{
num = NextChar();
} while (num == 32 || num == 9);
BufferBack();
DiscardToken();
SeekRelative(1);
return num;
}
private SourceLocation IndexToLocation(int index)
{
int num = newLineLocations.BinarySearch(index);
if (num < 0)
{
if (num == -1)
{
int column = checked(index + initialLocation.Column);
if (TokenLength > 0) column -= TokenLength;
return new SourceLocation(index + initialLocation.Index, initialLocation.Line, column);
}
num = ~num - 1;
}
int fcolumn = index - newLineLocations[num] + initialLocation.Column;
if (TokenLength > 0) fcolumn -= TokenLength;
return new SourceLocation(index + initialLocation.Index, num + 1 + initialLocation.Line, fcolumn);
}
private Token ReadName()
{
BufferBack();
int num = NextChar();
if (!IsNameStart(num))
return BadChar(num);
while (IsNamePart(num))
{
num = this.NextChar();
}
BufferBack();
MarkTokenEnd();
return Token.Identifier(GetTokenString());
}
private Token ReadNumber()
{
int num;
do
{
num = NextChar();
} while (48 <= num && num <= 57);
if (num == 46)
{
do
{
num = NextChar();
} while (48 <= num && num <= 57);
}
BufferBack();
MarkTokenEnd();
return Token.Constant(double.Parse(GetTokenString()));
}
private Token ReadComment()
{
BufferBack();
int num = NextChar();
if (num == 42)
{
do
{
num = NextChar();
if (num == 10)
{
newLineLocations.Add(Index);
}
} while (!(num == 42 && NextChar(47)));
SeekRelative(-2);
MarkTokenEnd();
SeekRelative(2);
return Token.Comment(GetTokenSubstring(2));
}
else
{
ReadLine();
MarkTokenEnd();
return Token.Comment(GetTokenSubstring(2));
}
}
public Token NextToken()
{
DiscardToken();
int num = NextChar();
while (true)
{
switch (num)
{
case -1:
return Tokens.EndOfFileToken;
case 10://'\n'
newLineLocations.Add(Index);
num = SkipWhiteSpace();
continue;
case 13://'\r'
case 32://' '
num = SkipWhiteSpace();
continue;
case 33://!
var notToken = NextChar(61) ? Tokens.NotEqualToken : Tokens.NotToken;
MarkTokenEnd();
return notToken;
case 37://'%'
MarkTokenEnd();
return Tokens.ModToken;
case 40://'('
MarkTokenEnd();
return Tokens.LeftParenToken;
case 41://')'
MarkTokenEnd();
return Tokens.RightParenToken;
case 42://'*'
MarkTokenEnd();
return Tokens.MultiplyToken;
case 43://'+'
MarkTokenEnd();
return Tokens.AddToken;
case 44://','
MarkTokenEnd();
return Tokens.CommaToken;
case 45://'-'
MarkTokenEnd();
return Tokens.SubtractToken;
case 46://'.'
MarkTokenEnd();
return Tokens.DotToken;
case 47://'/'
if (NextChar(42) || NextChar(47))
{
return ReadComment();
}
MarkTokenEnd();
return Tokens.DivideToken;
case 48://'0'
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57://'9'
return ReadNumber();
case 59://';'
MarkTokenEnd();
return Tokens.NewLineToken;
case 60://<
var lessToken = NextChar(61) ? Tokens.LessThanOrEqualToken : Tokens.LessThanToken;
MarkTokenEnd();
return lessToken;
case 61://'='
var assignOrEqualToken = NextChar(61) ? Tokens.EqualToken : Tokens.AssignToken;
MarkTokenEnd();
return assignOrEqualToken;
case 62://>
var greaterToken = NextChar(61) ? Tokens.GreaterThanOrEqualToken : Tokens.GreaterThanToken;
MarkTokenEnd();
return greaterToken;
case 91://'['
MarkTokenEnd();
return Tokens.LeftBracketToken;
case 93://']'
MarkTokenEnd();
return Tokens.RightBracketToken;
case 94://'^'
MarkTokenEnd();
return Tokens.PowerToken;
case 105://i
if (NextChar(102))
{
MarkTokenEnd();
return Tokens.IFToken;
}
return ReadName();
default:
return ReadName();
}
}
}
}

119
EC.Helper/RabbitFunc/Expressions/BinaryExpression.cs

@ -0,0 +1,119 @@
using EC.Helper.RabbitFunc.Runtime;
using System.Text;
namespace EC.Helper.RabbitFunc.Expressions;
public class BinaryExpression : Expression
{
internal BinaryExpression(ExpressionType nodeType, Expression left, Expression right)
: base(nodeType)
{
Left = left;
Right = right;
}
public Expression Left { get; }
public Expression Right { get; }
public override object Eval(RuntimeContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var leftResult = Left.Eval(context);
var rightResult = Right.Eval(context);
return NodeType switch
{
ExpressionType.Add => System.Convert.ToDouble(leftResult) + System.Convert.ToDouble(rightResult),
ExpressionType.Subtract => System.Convert.ToDouble(leftResult) - System.Convert.ToDouble(rightResult),
ExpressionType.Multiply => System.Convert.ToDouble(leftResult) * System.Convert.ToDouble(rightResult),
ExpressionType.Divide => System.Convert.ToDouble(leftResult) / System.Convert.ToDouble(rightResult),
ExpressionType.Modulo => System.Convert.ToDouble(leftResult) % System.Convert.ToDouble(rightResult),
ExpressionType.Power => Math.Pow(System.Convert.ToDouble(leftResult), System.Convert.ToDouble(rightResult)),
ExpressionType.LessThan => System.Convert.ToDouble(leftResult) < System.Convert.ToDouble(rightResult),
ExpressionType.LessThanOrEqual => System.Convert.ToDouble(leftResult) <= System.Convert.ToDouble(rightResult),
ExpressionType.Equal => leftResult is bool ? System.Convert.ToBoolean(leftResult) == System.Convert.ToBoolean(rightResult) : System.Convert.ToDouble(leftResult) == System.Convert.ToDouble(rightResult),
ExpressionType.GreaterThanOrEqual => System.Convert.ToDouble(leftResult) >= System.Convert.ToDouble(rightResult),
ExpressionType.GreaterThan => System.Convert.ToDouble(leftResult) > System.Convert.ToDouble(rightResult),
ExpressionType.NotEqual => leftResult is bool ? System.Convert.ToBoolean(leftResult) != System.Convert.ToBoolean(rightResult) : System.Convert.ToDouble(leftResult) != System.Convert.ToDouble(rightResult),
_ => throw new RuntimeException("unknown operator:" + NodeType.ToString()),
};
}
public override string ToString()
{
var sb = new StringBuilder();
if (Left is BinaryExpression)
{
sb.Append('(');
sb.Append(Left.ToString());
sb.Append(')');
}
else
{
sb.Append(Left.ToString());
}
switch (NodeType)
{
case ExpressionType.Add:
sb.Append('+');
break;
case ExpressionType.Subtract:
sb.Append('-');
break;
case ExpressionType.Multiply:
sb.Append('*');
break;
case ExpressionType.Divide:
sb.Append('/');
break;
case ExpressionType.Modulo:
sb.Append('%');
break;
case ExpressionType.Power:
sb.Append('^');
break;
case ExpressionType.LessThan:
sb.Append('<');
break;
case ExpressionType.LessThanOrEqual:
sb.Append("<=");
break;
case ExpressionType.Equal:
sb.Append("==");
break;
case ExpressionType.GreaterThanOrEqual:
sb.Append(">=");
break;
case ExpressionType.GreaterThan:
sb.Append('>');
break;
case ExpressionType.NotEqual:
sb.Append("!=");
break;
default:
throw new RuntimeException("unknown operator:" + NodeType.ToString());
}
if (Right is BinaryExpression)
sb.Append('(');
sb.Append(Right.ToString());
if (Right is BinaryExpression)
sb.Append(')');
return sb.ToString();
}
}

32
EC.Helper/RabbitFunc/Expressions/ConditionalExpression.cs

@ -0,0 +1,32 @@
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Expressions;
public class ConditionalExpression : Expression
{
internal ConditionalExpression(Expression test, Expression trueExpression, Expression falseExpression)
: base(ExpressionType.MethodCall)
{
Test = test;
TrueExpression = trueExpression;
FalseExpression = falseExpression;
}
public override ExpressionType NodeType => ExpressionType.Conditional;
public Expression Test { get; }
public Expression TrueExpression { get; }
public Expression FalseExpression { get; }
public override object Eval(RuntimeContext context)
{
return (bool)Test.Eval(context) ? TrueExpression.Eval(context) : FalseExpression.Eval(context);
}
public override string ToString()
{
return string.Format("if({0},{1},{2})", Test, TrueExpression, FalseExpression);
}
}

29
EC.Helper/RabbitFunc/Expressions/ConstantExpression.cs

@ -0,0 +1,29 @@
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Expressions;
public class ConstantExpression : Expression
{
internal ConstantExpression(object value)
: base(ExpressionType.Constant)
{
Value = value;
}
public object Value { get; }
public override Type Type => Value?.GetType();
public override object Eval(RuntimeContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
return Value;
}
public override string ToString()
{
return Value.ToString();
}
}

238
EC.Helper/RabbitFunc/Expressions/Expression.cs

@ -0,0 +1,238 @@
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Expressions;
public abstract class Expression
{
protected Expression()
{ }
protected Expression(ExpressionType nodeType)
{
NodeType = nodeType;
}
public virtual ExpressionType NodeType { get; }
public virtual Type Type { get; }
public static ParameterExpression Parameter(Type type, string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return new ParameterExpression(ExpressionType.Parameter, type, name);
}
public static ParameterExpression Variable(Type type, string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return new ParameterExpression(ExpressionType.Variable, type, name);
}
public static MemberExpression Member(Expression instance, string name)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (name == null)
throw new ArgumentNullException(nameof(name));
return new MemberExpression(instance, name);
}
public static MemberExpression Field(Expression instance, string name)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (name == null)
throw new ArgumentNullException(nameof(name));
return new MemberExpression(instance, name);
}
public static MemberExpression Property(Expression instance, string name)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (name == null)
throw new ArgumentNullException(nameof(name));
return new MemberExpression(instance, name);
}
public static BinaryExpression Assign(Expression left, Expression right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
return new BinaryExpression(ExpressionType.Assign, left, right);
}
public static ConstantExpression Constant(object value)
{
return new ConstantExpression(value);
}
public static UnaryExpression Convert(Expression expression, Type type)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
if (type == null)
throw new ArgumentNullException(nameof(type));
return new UnaryExpression(ExpressionType.Constant, expression);
}
public static BinaryExpression Add(Expression left, Expression right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
return new BinaryExpression(ExpressionType.Add, left, right);
}
public static BinaryExpression Subtract(Expression left, Expression right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
return new BinaryExpression(ExpressionType.Subtract, left, right);
}
public static BinaryExpression Multiply(Expression left, Expression right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
return new BinaryExpression(ExpressionType.Multiply, left, right);
}
public static BinaryExpression Divide(Expression left, Expression right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
return new BinaryExpression(ExpressionType.Divide, left, right);
}
public static BinaryExpression Modulo(Expression left, Expression right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
return new BinaryExpression(ExpressionType.Modulo, left, right);
}
public static BinaryExpression Power(Expression left, Expression right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
return new BinaryExpression(ExpressionType.Power, left, right);
}
public static UnaryExpression Negate(Expression expression)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
return new UnaryExpression(ExpressionType.Negate, expression);
}
public static BinaryExpression ArrayIndex(Expression array, Expression index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index == null)
throw new ArgumentNullException(nameof(index));
return new BinaryExpression(ExpressionType.ArrayIndex, array, index);
}
public static UnaryExpression ArrayLength(Expression array)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
return new UnaryExpression(ExpressionType.ArrayLength, array);
}
public static MethodCallExpression Call(Expression instance, string methodName, params Expression[] arguments)
{
if (methodName == null)
throw new ArgumentNullException(nameof(methodName));
return new MethodCallExpression(instance, methodName, arguments);
}
public static MethodCallExpression Call(Expression instance, string methodName, IList<Expression> arguments)
{
if (methodName == null)
throw new ArgumentNullException(nameof(methodName));
if (arguments == null)
throw new ArgumentNullException(nameof(arguments));
return new MethodCallExpression(instance, methodName, arguments);
}
public static LambdaExpression Lambda(string name, Expression body, params ParameterExpression[] parameters)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (body == null)
throw new ArgumentNullException(nameof(body));
return new LambdaExpression(name, body, parameters);
}
public static LambdaExpression Lambda(string name, Expression body, IList<ParameterExpression> parameters)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (body == null)
throw new ArgumentNullException(nameof(body));
return new LambdaExpression(name, body, parameters.ToArray());
}
public static UnaryExpression Not(Expression expression)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
return new UnaryExpression(ExpressionType.Not, expression);
}
public static ConditionalExpression Condition(Expression condition, Expression trueExpression, Expression falseExpression)
{
if (condition == null)
throw new ArgumentNullException(nameof(condition));
if (trueExpression == null)
throw new ArgumentNullException(nameof(trueExpression));
if (falseExpression == null)
throw new ArgumentNullException(nameof(falseExpression));
return new ConditionalExpression(condition, trueExpression, falseExpression);
}
public virtual object Eval(RuntimeContext context)
{
throw new NotSupportedException();
}
}

146
EC.Helper/RabbitFunc/Expressions/ExpressionCompiler.cs

@ -0,0 +1,146 @@
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Expressions;
internal class ExpressionCompiler
{
private readonly Dictionary<string, LambdaCompiler> lambdas = new Dictionary<string, LambdaCompiler>();
private LambdaCompiler GetLambdaCompiler(LambdaExpression expression)
{
if (!lambdas.TryGetValue(expression.Name, out var lambda))
{
lambda = new LambdaCompiler(this, expression);
lambdas.Add(expression.Name, lambda);
}
return lambda;
}
public Delegate Compile(LambdaExpression expression, Type delegateType = null)
{
var lambda = new LambdaCompiler(this, expression);
lambdas.Add(lambda.Name, lambda);
return lambda.Compile(delegateType);
}
private sealed class LambdaCompiler
{
private readonly ExpressionCompiler compiler;
private readonly LambdaExpression expression;
private readonly List<System.Linq.Expressions.ParameterExpression> parameters;
public LambdaCompiler(ExpressionCompiler compiler, LambdaExpression expression)
{
this.compiler = compiler;
this.expression = expression;
this.parameters = new List<System.Linq.Expressions.ParameterExpression>();
foreach (var parameter in expression.Parameters)
{
parameters.Add(System.Linq.Expressions.Expression.Parameter(parameter.Type, parameter.Name));
}
}
public string Name => expression.Name;
private System.Linq.Expressions.Expression EmitExpression(Expression expression)
{
switch (expression)
{
case ConditionalExpression conditionExpression:
{
var test = EmitExpression(conditionExpression.Test);
var trueExpression = EmitExpression(conditionExpression.TrueExpression);
var falseExpression = EmitExpression(conditionExpression.FalseExpression);
return System.Linq.Expressions.Expression.Condition(test, trueExpression, falseExpression);
}
case BinaryExpression binaryExpression:
{
var left = EmitExpression(binaryExpression.Left);
var right = EmitExpression(binaryExpression.Right);
return expression.NodeType switch
{
ExpressionType.Add => System.Linq.Expressions.Expression.Add(left, right),
ExpressionType.Subtract => System.Linq.Expressions.Expression.Subtract(left, right),
ExpressionType.Multiply => System.Linq.Expressions.Expression.Multiply(left, right),
ExpressionType.Divide => System.Linq.Expressions.Expression.Divide(left, right),
ExpressionType.Modulo => System.Linq.Expressions.Expression.Modulo(left, right),
ExpressionType.Power => System.Linq.Expressions.Expression.Power(left, right),
ExpressionType.LessThan => System.Linq.Expressions.Expression.LessThan(left, right),
ExpressionType.LessThanOrEqual => System.Linq.Expressions.Expression.LessThanOrEqual(left, right),
ExpressionType.Equal => System.Linq.Expressions.Expression.Equal(left, right),
ExpressionType.GreaterThanOrEqual => System.Linq.Expressions.Expression.GreaterThanOrEqual(left, right),
ExpressionType.GreaterThan => System.Linq.Expressions.Expression.GreaterThan(left, right),
ExpressionType.NotEqual => System.Linq.Expressions.Expression.NotEqual(left, right),
_ => throw new LambdaCompilerException("unknown operator char:" + expression.NodeType.ToString()),
};
}
case ConstantExpression constantExpression:
return System.Linq.Expressions.Expression.Constant(constantExpression.Value);
case MethodCallExpression methodCallExpression:
{
var lambda = methodCallExpression.GetLambda(this.expression.Domain);
if (lambda == null) throw new LambdaCompilerException(string.Format("missing method:{0}", methodCallExpression.MethodName));
if (lambda is SystemLambdaExpression systemLambda)
{
var arguments = new List<System.Linq.Expressions.Expression>();
foreach (var argument in methodCallExpression.Arguments)
{
arguments.Add(EmitExpression(argument));
}
return System.Linq.Expressions.Expression.Call(null, systemLambda.Method, arguments);
}
else
{
var elementType = typeof(object);
var customLambda = compiler.GetLambdaCompiler(lambda);
var arguments = new System.Linq.Expressions.Expression[customLambda.parameters.Count];
for (var i = 0; i < arguments.Length; i++)
{
var parameter = customLambda.parameters[i];
var argument = EmitExpression(methodCallExpression.Arguments[i]);
arguments[i] = parameter.Type != elementType
? System.Linq.Expressions.Expression.Convert(argument, elementType)
: argument;
}
var custom = customLambda.Compile();
return System.Linq.Expressions.Expression.Convert(
System.Linq.Expressions.Expression.Call(
System.Linq.Expressions.Expression.Constant(custom),
typeof(Delegate).GetMethod(nameof(Delegate.DynamicInvoke)),
System.Linq.Expressions.Expression.NewArrayInit(elementType, arguments)),
lambda.Type);
}
}
case ParameterExpression parameterExpression:
{
var parameter = parameters.Find(p => p.Name == parameterExpression.Name);
if (parameter == null) throw new RuntimeException("Missing member:" + parameterExpression.Name);
return parameter;
}
case UnaryExpression unaryExpression:
{
var operand = EmitExpression(unaryExpression.Operand);
return unaryExpression.NodeType switch
{
ExpressionType.Negate => System.Linq.Expressions.Expression.Negate(operand),
ExpressionType.Not => System.Linq.Expressions.Expression.Not(operand),
_ => throw new RuntimeException("unknown NodeType:" + unaryExpression.NodeType.ToString()),
};
}
default:
return null;
}
}
public Delegate Compile(Type delegateType = null)
{
var body = EmitExpression(this.expression.Body);
var lambda = delegateType == null
? System.Linq.Expressions.Expression.Lambda(body, this.expression.Name, parameters)
: System.Linq.Expressions.Expression.Lambda(delegateType, body, this.expression.Name, parameters);
return lambda.Compile();
}
}
}

65
EC.Helper/RabbitFunc/Expressions/ExpressionType.cs

@ -0,0 +1,65 @@
namespace EC.Helper.RabbitFunc.Expressions;
public enum ExpressionType : byte
{
None,
Add,
Subtract,
Multiply,
Divide,
Modulo,
Power,
Constant,
ArrayIndex,
ArrayLength,
Negate,
Convert,
Assign,
MemberAccess,
Variable,
Parameter,
Lambda,
MethodCall,
/// <summary>
/// &lt;
/// </summary>
LessThan,
/// <summary>
/// &lt;=
/// </summary>
LessThanOrEqual,
/// <summary>
/// ==
/// </summary>
Equal,
/// <summary>
/// &gt;=
/// </summary>
GreaterThanOrEqual,
/// <summary>
/// &gt;
/// </summary>
GreaterThan,
/// <summary>
/// !=
/// </summary>
NotEqual,
/// <summary>
/// !
/// </summary>
Not,
/// <summary>
/// IF
/// </summary>
Conditional,
}

9
EC.Helper/RabbitFunc/Expressions/LambdaCompilerException.cs

@ -0,0 +1,9 @@
namespace EC.Helper.RabbitFunc.Expressions;
[Serializable]
public class LambdaCompilerException : Exception
{
public LambdaCompilerException(string message)
: base(message)
{ }
}

75
EC.Helper/RabbitFunc/Expressions/LambdaExpression.cs

@ -0,0 +1,75 @@
using EC.Helper.RabbitFunc.Runtime;
using System.Collections.ObjectModel;
using System.Text;
namespace EC.Helper.RabbitFunc.Expressions;
public class LambdaExpression : Expression
{
internal LambdaExpression(string name, Expression body, params ParameterExpression[] parameters)
: base(ExpressionType.Lambda)
{
Name = name;
Parameters = new ReadOnlyCollection<ParameterExpression>(parameters);
Body = body;
}
public RabbitDomain Domain { get; internal set; }
public string Name { get; }
public ReadOnlyCollection<ParameterExpression> Parameters { get; }
public Expression Body { get; }
public override Type Type => typeof(double);
public Delegate Compile(Type deletageType = null)
{
var lambdaCompiler = new ExpressionCompiler();
return lambdaCompiler.Compile(this, deletageType);
}
public T Compile<T>()
{
return (T)(object)Compile(typeof(T));
}
public override object Eval(RuntimeContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var lambdaContext = new RuntimeContext(context);
lambdaContext.Domain = Domain;
for (int i = 0; i < Parameters.Count; i++)
{
var parameter = Parameters[i];
var value = parameter.Eval(context);
lambdaContext.Variable(parameter.Name, value);
}
return Body.Eval(lambdaContext);
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(Name).Append('(');
using (var e = Parameters.GetEnumerator())
{
if (e.MoveNext())
{
sb.Append(e.Current.Name);
while (e.MoveNext())
{
sb.Append(',');
sb.Append(e.Current.Name);
}
}
}
sb.Append(")=").Append(Body.ToString());
return sb.ToString();
}
}

30
EC.Helper/RabbitFunc/Expressions/MemberExpression.cs

@ -0,0 +1,30 @@
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Expressions;
public class MemberExpression : Expression
{
internal MemberExpression(Expression instance, string name)
: base(ExpressionType.MemberAccess)
{
Instance = instance;
Name = name;
}
public Expression Instance { get; }
public string Name { get; }
public override object Eval(RuntimeContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
return default(double);
}
public override string ToString()
{
return Instance == null ? Name : Instance.ToString() + "." + Name;
}
}

88
EC.Helper/RabbitFunc/Expressions/MethodCallExpression.cs

@ -0,0 +1,88 @@
using EC.Helper.RabbitFunc.Runtime;
using System.Collections.ObjectModel;
using System.Text;
using MissingMethodException = EC.Helper.RabbitFunc.Runtime.MissingMethodException;
namespace EC.Helper.RabbitFunc.Expressions;
public class MethodCallExpression : Expression
{
internal MethodCallExpression(Expression instance, string methodName, IList<Expression> arguments)
: base(ExpressionType.MethodCall)
{
Instance = instance;
MethodName = methodName;
Arguments = new ReadOnlyCollection<Expression>(arguments);
}
public Expression Instance { get; }
public string MethodName { get; }
public ReadOnlyCollection<Expression> Arguments { get; }
internal LambdaExpression GetLambda(RabbitDomain domain)
{
LambdaExpression lambda;
if (domain != null)
{
lambda = domain.GetLambda(MethodName);
}
else
{
lambda = Rabbit.GetSystemLambda(MethodName);
}
return lambda;
}
public override object Eval(RuntimeContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (Instance == null)
{
var lambdaExpression = GetLambda(context.Domain);
if (lambdaExpression == null)
throw new MissingMethodException(string.Format("missing method:{0}", MethodName));
if (Arguments.Count != lambdaExpression.Parameters.Count)
throw new RuntimeException(string.Format("method:{0}. parame count error!", MethodName));
var lambdaContext = new RuntimeContext(context);
for (int i = 0; i < Arguments.Count; i++)
{
var parameter = lambdaExpression.Parameters[i];
var argument = Arguments[i];
var value = argument.Eval(context);
lambdaContext.Variable(parameter.Name, value);
}
return lambdaExpression.Body.Eval(lambdaContext);
}
else
{
throw new NotSupportedException();
}
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(MethodName).Append('(');
using (var e = Arguments.GetEnumerator())
{
if (e.MoveNext())
{
sb.Append(e.Current.ToString());
while (e.MoveNext())
{
sb.Append(',');
sb.Append(e.Current.ToString());
}
}
}
sb.Append(')');
return sb.ToString();
}
}

45
EC.Helper/RabbitFunc/Expressions/ParameterExpression.cs

@ -0,0 +1,45 @@
using EC.Helper.RabbitFunc.Runtime;
using MissingMemberException = EC.Helper.RabbitFunc.Runtime.MissingMemberException;
namespace EC.Helper.RabbitFunc.Expressions;
public class ParameterExpression : Expression
{
internal ParameterExpression(ExpressionType nodeType, Type type, string name)
: base(nodeType)
{
Type = type;
Name = name;
}
public override Type Type { get; }
public string Name { get; }
internal static object Access(RuntimeContext context, string name)
{
var value = context.Access(name);
if (value == null)
throw new MissingMemberException(string.Format("missing member:{0}", name));
return value.Value;
}
internal static T Access<T>(RuntimeContext context, string name)
{
return (T)Access(context, name);
}
public override object Eval(RuntimeContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
return Access(context, Name);
}
public override string ToString()
{
return Name;
}
}

19
EC.Helper/RabbitFunc/Expressions/SystemLambdaExpression.cs

@ -0,0 +1,19 @@
using System.Reflection;
namespace EC.Helper.RabbitFunc.Expressions;
public abstract class SystemLambdaExpression : LambdaExpression
{
internal SystemLambdaExpression(MethodInfo method, string name, Expression body, params ParameterExpression[] parameters)
: base(name, body, parameters)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
Method = method;
}
public MethodInfo Method { get; }
public override Type Type => Method.ReturnType;
}

48
EC.Helper/RabbitFunc/Expressions/UnaryExpression.cs

@ -0,0 +1,48 @@
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Expressions;
public class UnaryExpression : Expression
{
internal UnaryExpression(ExpressionType type, Expression operand)
: base(type)
{
Operand = operand;
}
public Expression Operand { get; }
public override object Eval(RuntimeContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
object value = Operand.Eval(context);
switch (NodeType)
{
case ExpressionType.Negate:
return (-(double)value);
case ExpressionType.Not:
return (!(bool)value);
default:
throw new RuntimeException("unknown unary:" + NodeType.ToString());
}
}
public override string ToString()
{
switch (NodeType)
{
case ExpressionType.Negate:
return Operand is BinaryExpression ? "-(" + Operand.ToString() + ")" : "-" + Operand.ToString();
case ExpressionType.Not:
return Operand is BinaryExpression ? "!(" + Operand.ToString() + ")" : "!" + Operand.ToString();
default:
throw new RuntimeException("unknown operator:" + NodeType.ToString());
}
}
}

21
EC.Helper/RabbitFunc/Extern/AbsLambdaExpression.cs

@ -0,0 +1,21 @@
using EC.Helper.RabbitFunc.Expressions;
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Extern;
[ExternLambda]
internal class AbsLambdaExpression : SystemLambdaExpression
{
public AbsLambdaExpression()
: base(typeof(Math).GetMethod(nameof(Math.Abs), new Type[] { typeof(double) }), "abs", new BodyExpression(),
Expression.Parameter(typeof(double), "x"))
{ }
private class BodyExpression : Expression
{
public override object Eval(RuntimeContext context)
{
return Math.Abs(ParameterExpression.Access<double>(context, "x"));
}
}
}

21
EC.Helper/RabbitFunc/Extern/AcosLambdaExpression.cs

@ -0,0 +1,21 @@
using EC.Helper.RabbitFunc.Expressions;
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Extern;
[ExternLambda]
internal class AcosLambdaExpression : SystemLambdaExpression
{
public AcosLambdaExpression()
: base(typeof(Math).GetMethod(nameof(Math.Acos), new Type[] { typeof(double) }), "acos", new BodyExpression(),
Expression.Parameter(typeof(double), "x"))
{ }
private class BodyExpression : Expression
{
public override object Eval(RuntimeContext context)
{
return Math.Acos(ParameterExpression.Access<double>(context, "x"));
}
}
}

21
EC.Helper/RabbitFunc/Extern/AsinLambdaExpression.cs

@ -0,0 +1,21 @@
using EC.Helper.RabbitFunc.Expressions;
using EC.Helper.RabbitFunc.Runtime;
namespace EC.Helper.RabbitFunc.Extern;
[ExternLambda]
internal class AsinLambdaExpression : SystemLambdaExpression
{
public AsinLambdaExpression()
: base(typeof(Math).GetMethod(nameof(Math.Asin), new Type[] { typeof(double) }), "asin", new BodyExpression(),
Expression.Parameter(typeof(double), "x"))
{ }
private class BodyExpression : Expression
{
public override object Eval(RuntimeContext context)
{
return Math.Asin(ParameterExpression.Access<double>(context, "x"));
}
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save