Browse Source

[feat] 对接完成

master
fajiao 1 year ago
parent
commit
1aeb6d394e
  1. 4
      EC.Util/CameraSDK/Common/CameraStruct.cs
  2. 2
      EC.Util/CameraSDK/DaHua/DaHuaOriSDK.cs
  3. 31
      EC.Util/CameraSDK/DaHua/DaHuaSDK.cs
  4. 148
      EC.Util/CameraSDK/HiK/HiKOriSDK.cs
  5. 47
      EC.Util/CameraSDK/HiK/HiKSDK.cs
  6. 2
      EC.Util/CameraSDK/YuShi/YuShiOriSDK.cs
  7. 36
      EC.Util/CameraSDK/YuShi/YuShiSDK.cs
  8. 36
      EC.Util/Common/NetworkUtil.cs
  9. 65
      JiLinApp.Docking/FenceAlarm/Service/UdpManager.cs
  10. 2
      JiLinApp.Docking/FenceAlarm/Service/UdpServer.cs
  11. 4
      JiLinApp.Docking/Military/Config.cs
  12. 18
      JiLinApp.Docking/Military/MilitaryService.cs
  13. 67
      JiLinApp.Docking/VibrateAlarm/Entity/ClientMessage.cs
  14. 151
      JiLinApp.Docking/VibrateAlarm/Service/AsyncTcpServer.cs
  15. 26
      JiLinApp.Docking/VibrateAlarm/Service/TcpClientState.cs
  16. 4
      JiLinApp.Docking/VibrateAlarm/Service/TcpDatagramReceivedEventArgs.cs
  17. 492
      JiLinApp.Docking/VibrateAlarm/Service/TcpManager.cs
  18. 4
      JiLinApp/Components/CameraRealPlay.xaml.cs
  19. 22
      JiLinApp/Pages/FenceServerManage/Main.xaml.cs
  20. 1
      JiLinApp/Pages/PtzManage/Main.xaml
  21. 54
      JiLinApp/Pages/PtzManage/Main.xaml.cs
  22. 9
      JiLinApp/Pages/PtzManage/MainViewModel.cs
  23. 6
      JiLinApp/config/config.json

4
EC.Util/CameraSDK/Common/CameraStruct.cs

@ -12,6 +12,8 @@ public class CameraInfo
/// </summary> /// </summary>
public string Id { get; set; } = string.Empty; public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
/// <summary> /// <summary>
/// 相机厂商 /// 相机厂商
/// </summary> /// </summary>
@ -103,7 +105,7 @@ public enum CameraPort : int
{ {
HiK = 8000, HiK = 8000,
DaHua = 37777, DaHua = 37777,
YuShi = 8800, YuShi = 80,
} }
/// <summary> /// <summary>

2
EC.Util/CameraSDK/DaHua/DaHuaOriSDK.cs

@ -8,6 +8,8 @@ public static class DaHuaOriSDK
private const string LibDhNetSDK = @"./libs/dh-win64/dhnetsdk.dll"; private const string LibDhNetSDK = @"./libs/dh-win64/dhnetsdk.dll";
private const bool Debug = true;
#endregion Lib Attr #endregion Lib Attr
static DaHuaOriSDK() static DaHuaOriSDK()

31
EC.Util/CameraSDK/DaHua/DaHuaSDK.cs

@ -10,6 +10,8 @@ public class DaHuaSDK : ICameraSDK
private IntPtr RealplayHandle { get; set; } = IntPtr.Zero; private IntPtr RealplayHandle { get; set; } = IntPtr.Zero;
private int Channel { get; } = 1;
#endregion Fields #endregion Fields
public DaHuaSDK(CameraInfo cameraInfo) : base(cameraInfo) public DaHuaSDK(CameraInfo cameraInfo) : base(cameraInfo)
@ -22,7 +24,6 @@ public class DaHuaSDK : ICameraSDK
{ {
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (ret) return true; if (ret) return true;
DaHuaOriSDK.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY stuInParam = new(); DaHuaOriSDK.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY stuInParam = new();
stuInParam.dwSize = (uint)Marshal.SizeOf(stuInParam); stuInParam.dwSize = (uint)Marshal.SizeOf(stuInParam);
stuInParam.szIP = CameraInfo.Ip; stuInParam.szIP = CameraInfo.Ip;
@ -39,7 +40,7 @@ public class DaHuaSDK : ICameraSDK
{ {
LoginId = lLoginID; LoginId = lLoginID;
}, IntPtr.Zero); }, IntPtr.Zero);
else BuildException();
return ret; return ret;
} }
@ -47,10 +48,9 @@ public class DaHuaSDK : ICameraSDK
{ {
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (!ret) return true; if (!ret) return true;
ret = DaHuaOriSDK.CLIENT_Logout(LoginId); ret = DaHuaOriSDK.CLIENT_Logout(LoginId);
if (ret) LoginId = IntPtr.Zero; if (ret) LoginId = IntPtr.Zero;
else BuildException();
return ret; return ret;
} }
@ -138,20 +138,18 @@ public class DaHuaSDK : ICameraSDK
public override bool PtzMove(int cmd, int stop, int speed) public override bool PtzMove(int cmd, int stop, int speed)
{ {
if (!ConnectSuccess()) return false; if (!ConnectSuccess()) return false;
int channel = 0; bool stopret = stop == 1;
bool stopFlag = stop == 1; bool ret = DaHuaOriSDK.CLIENT_DHPTZControlEx2(LoginId, Channel, (uint)cmd, speed, speed, 0, stopret, IntPtr.Zero);
bool flag = DaHuaOriSDK.CLIENT_DHPTZControlEx2(LoginId, channel, (uint)cmd, speed, speed, 0, stopFlag, IntPtr.Zero); if (!ret) BuildException();
//if (flag) BuildException(); return ret;
return flag;
} }
public override bool PtzPreset(int cmd, int presetId) public override bool PtzPreset(int cmd, int presetId)
{ {
if (!ConnectSuccess()) return false; if (!ConnectSuccess()) return false;
int channel = 0; bool ret = DaHuaOriSDK.CLIENT_DHPTZControlEx2(LoginId, Channel, (uint)DaHuaOriSDK.EM_EXTPTZ_ControlType.POINT_MOVE, 0, presetId, 0, false, IntPtr.Zero);
bool flag = DaHuaOriSDK.CLIENT_DHPTZControlEx2(LoginId, channel, (uint)DaHuaOriSDK.EM_EXTPTZ_ControlType.POINT_MOVE, 0, presetId, 0, false, IntPtr.Zero); if (!ret) BuildException();
if (flag) BuildException(); return ret;
return flag;
} }
#endregion Ptz Method #endregion Ptz Method
@ -161,17 +159,16 @@ public class DaHuaSDK : ICameraSDK
public override void StartPlay(IntPtr hwnd) public override void StartPlay(IntPtr hwnd)
{ {
if (!ConnectSuccess() || IsPlaying()) return; if (!ConnectSuccess() || IsPlaying()) return;
int channel = 1; RealplayHandle = DaHuaOriSDK.CLIENT_RealPlayEx(LoginId, Channel, hwnd, DaHuaOriSDK.EM_RealPlayType.Realplay);
RealplayHandle = DaHuaOriSDK.CLIENT_RealPlayEx(LoginId, channel, hwnd, DaHuaOriSDK.EM_RealPlayType.Realplay);
if (RealplayHandle == IntPtr.Zero) BuildException(); if (RealplayHandle == IntPtr.Zero) BuildException();
} }
public override void StopPlay() public override void StopPlay()
{ {
if (!IsPlaying()) return; if (!IsPlaying()) return;
bool flag = DaHuaOriSDK.CLIENT_StopRealPlayEx(RealplayHandle); bool ret = DaHuaOriSDK.CLIENT_StopRealPlayEx(RealplayHandle);
RealplayHandle = IntPtr.Zero; RealplayHandle = IntPtr.Zero;
if (flag) BuildException(); if (!ret) BuildException();
} }
public override bool IsPlaying() public override bool IsPlaying()

148
EC.Util/CameraSDK/HiK/HiKOriSDK.cs

@ -6,7 +6,10 @@ public static class HiKOriSDK
{ {
#region Lib Attr #region Lib Attr
public const string LibHcNetSDK = @"./libs/hk-win64/HCNetSDK.dll"; public const string LibHkNetSDK = @"./libs/hk-win64/HCNetSDK.dll";
//public const string LibHkNetSDK = @"./libs/hk-win64/libhcnetsdk.so";
private const bool Debug = true;
#endregion Lib Attr #endregion Lib Attr
@ -25,6 +28,7 @@ public static class HiKOriSDK
bool ret = NET_DVR_Init(); bool ret = NET_DVR_Init();
InitSuccess = ret; InitSuccess = ret;
if (!ret) throw new Exception("HiKOriSDK global init failure."); if (!ret) throw new Exception("HiKOriSDK global init failure.");
if (Debug) NET_DVR_SetLogToFile(3, Path.Combine("./log", "hikSdkLog"), true);
return ret; return ret;
} }
@ -45,6 +49,10 @@ public static class HiKOriSDK
public const int PtzSpeedMin = 1; public const int PtzSpeedMin = 1;
public const int PtzSpeedMax = 7; public const int PtzSpeedMax = 7;
public const int NET_DVR_DEV_ADDRESS_MAX_LEN = 129;
public const int NET_DVR_LOGIN_USERNAME_MAX_LEN = 64;
public const int NET_DVR_LOGIN_PASSWD_MAX_LEN = 64;
#region 用于 NET_DVR_SetDVRConfig 和 NET_DVR_GetDVRConfig #region 用于 NET_DVR_SetDVRConfig 和 NET_DVR_GetDVRConfig
public const int NET_DVR_SET_PTZPOS = 292; //云台设置PTZ位置 public const int NET_DVR_SET_PTZPOS = 292; //云台设置PTZ位置
@ -176,6 +184,62 @@ public static class HiKOriSDK
public byte[] byRes2; //保留 public byte[] byRes2; //保留
} }
public delegate void LOGINRESULTCALLBACK(int lUserID, int dwResult, IntPtr lpDeviceInfo, IntPtr pUser);
[StructLayout(LayoutKind.Sequential)]
public struct NET_DVR_USER_LOGIN_INFO
{
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = NET_DVR_DEV_ADDRESS_MAX_LEN, ArraySubType = UnmanagedType.I1)]
public byte[] sDeviceAddress;
public byte byUseTransport;
public ushort wPort;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = NET_DVR_LOGIN_USERNAME_MAX_LEN, ArraySubType = UnmanagedType.I1)]
public byte[] sUserName;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = NET_DVR_LOGIN_PASSWD_MAX_LEN, ArraySubType = UnmanagedType.I1)]
public byte[] sPassword;
public LOGINRESULTCALLBACK cbLoginResult;
public IntPtr pUser;
public bool bUseAsynLogin;
public byte byProxyType; //0:不使用代理,1:使用标准代理,2:使用EHome代理
public byte byUseUTCTime; //0-不进行转换,默认,1-接口上输入输出全部使用UTC时间,SDK完成UTC时间与设备时区的转换,2-接口上输入输出全部使用平台本地时间,SDK完成平台本地时间与设备时区的转换
public byte byLoginMode; //0-Private, 1-ISAPI, 2-自适应
public byte byHttps; //0-不适用tls,1-使用tls 2-自适应
public int iProxyID; //代理服务器序号,添加代理服务器信息时,相对应的服务器数组下表值
public byte byVerifyMode; //认证方式,0-不认证,1-双向认证,2-单向认证;认证仅在使用TLS的时候生效;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 119, ArraySubType = UnmanagedType.I1)]
public byte[] byRes3;
}
[StructLayout(LayoutKind.Sequential)]
public struct NET_DVR_DEVICEINFO_V40
{
public NET_DVR_DEVICEINFO_V30 struDeviceV30;
public byte bySupportLock; //设备支持锁定功能,该字段由SDK根据设备返回值来赋值的。bySupportLock为1时,dwSurplusLockTime和byRetryLoginTime有效
public byte byRetryLoginTime; //剩余可尝试登陆的次数,用户名,密码错误时,此参数有效
public byte byPasswordLevel; //admin密码安全等级0-无效,1-默认密码,2-有效密码,3-风险较高的密码。当用户的密码为出厂默认密码(12345)或者风险较高的密码时,上层客户端需要提示用户更改密码。
public byte byProxyType;//代理类型,0-不使用代理, 1-使用socks5代理, 2-使用EHome代理
public uint dwSurplusLockTime; //剩余时间,单位秒,用户锁定时,此参数有效
public byte byCharEncodeType; //字符编码类型(SDK所有接口返回的字符串编码类型,透传接口除外):0- 无字符编码信息(老设备),1- GB2312(简体中文),2- GBK,3- BIG5(繁体中文),4- Shift_JIS(日文),5- EUC-KR(韩文),6- UTF-8,7- ISO8859-1,8- ISO8859-2,9- ISO8859-3,…,依次类推,21- ISO8859-15(西欧)
public byte bySupportDev5;//支持v50版本的设备参数获取,设备名称和设备类型名称长度扩展为64字节
public byte bySupport; //能力集扩展,位与结果:0- 不支持,1- 支持
// bySupport & 0x1: 保留
// bySupport & 0x2: 0-不支持变化上报 1-支持变化上报
public byte byLoginMode; //登录模式 0-Private登录 1-ISAPI登录
public int dwOEMCode;
public int iResidualValidity; //该用户密码剩余有效天数,单位:天,返回负值,表示密码已经超期使用,例如“-3表示密码已经超期使用3天”
public byte byResidualValidity; // iResidualValidity字段是否有效,0-无效,1-有效
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 243, ArraySubType = UnmanagedType.I1)]
public byte[] byRes2;
}
//球机位置信息 //球机位置信息
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct NET_DVR_PTZPOS public struct NET_DVR_PTZPOS
@ -242,54 +306,39 @@ public static class HiKOriSDK
#region Common Method #region Common Method
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern bool NET_DVR_Init(); public static extern bool NET_DVR_Init();
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern bool NET_DVR_Cleanup(); public static extern bool NET_DVR_Cleanup();
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern bool NET_DVR_SetLogToFile(int bLogEnable, string strLogDir, bool bAutoDel);
[DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern uint NET_DVR_GetLastError(); public static extern uint NET_DVR_GetLastError();
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern int NET_DVR_Login_V30( public static extern int NET_DVR_Login_V30(string sDVRIP, int wDVRPort, string sUserName, string sPassword, ref NET_DVR_DEVICEINFO_V30 lpDeviceInfo);
string sDVRIP,
int wDVRPort,
string sUserName,
string sPassword,
ref NET_DVR_DEVICEINFO_V30 lpDeviceInfo
);
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern int NET_DVR_Login_V40(ref NET_DVR_USER_LOGIN_INFO pLoginInfo, ref NET_DVR_DEVICEINFO_V40 lpDeviceInfo);
[DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern bool NET_DVR_Logout(int iUserID); public static extern bool NET_DVR_Logout(int iUserID);
[DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern bool NET_DVR_SetReconnect(uint dwInterval, int bEnableRecon);
//参数配置 begin //参数配置 begin
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern bool NET_DVR_GetDVRConfig( public static extern bool NET_DVR_GetDVRConfig(int lUserID, uint dwCommand, int lChannel, IntPtr lpOutBuffer, uint dwOutBufferSize, ref uint lpBytesReturned);
int lUserID,
uint dwCommand, [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
int lChannel, public static extern bool NET_DVR_PTZControlWithSpeed_Other(int lUserID, int lChannel, uint dwPTZCommand, uint dwStop, uint dwSpeed);
IntPtr lpOutBuffer,
uint dwOutBufferSize, [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
ref uint lpBytesReturned public static extern bool NET_DVR_PTZPreset_Other(int lUserID, int lChannel, uint dwPTZPresetCmd, uint dwPresetIndex);
);
[DllImport(LibHcNetSDK)]
public static extern bool NET_DVR_PTZControlWithSpeed_Other(
int lUserID,
int lChannel,
uint dwPTZCommand,
uint dwStop,
uint dwSpeed
);
[DllImport(LibHcNetSDK)]
public static extern bool NET_DVR_PTZPreset_Other(
int lUserID,
int lChannel,
uint dwPTZPresetCmd,
uint dwPresetIndex
);
/********************************************************* /*********************************************************
Function: REALDATACALLBACK Function: REALDATACALLBACK
@ -303,13 +352,7 @@ public static class HiKOriSDK
Return: void Return: void
**********************************************************/ **********************************************************/
public delegate void REALDATACALLBACK( public delegate void RealDataCallBack(int lRealHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize, IntPtr pUser);
int lRealHandle,
uint dwDataType,
IntPtr pBuffer,
uint dwBufSize,
IntPtr pUser
);
/********************************************************* /*********************************************************
Function: NET_DVR_RealPlay_V40 Function: NET_DVR_RealPlay_V40
@ -322,16 +365,9 @@ public static class HiKOriSDK
Return: 1NET_DVR_StopRealPlay等函数的句柄参数 Return: 1NET_DVR_StopRealPlay等函数的句柄参数
**********************************************************/ **********************************************************/
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern int NET_DVR_RealPlay_V40( public static extern int NET_DVR_RealPlay_V40(int iUserID, ref NET_DVR_PREVIEWINFO lpPreviewInfo, RealDataCallBack fRealDataCallBack_V30, IntPtr pUser);
int iUserID,
ref NET_DVR_PREVIEWINFO lpPreviewInfo,
REALDATACALLBACK fRealDataCallBack_V30,
IntPtr pUser
);
// [DllImport(@".\HCNetSDK.dll")]
// public static extern int NET_DVR_GetRealPlayerIndex(int lRealHandle);
/********************************************************* /*********************************************************
Function: NET_DVR_StopRealPlay Function: NET_DVR_StopRealPlay
Desc: Desc:
@ -340,7 +376,7 @@ public static class HiKOriSDK
Return: Return:
**********************************************************/ **********************************************************/
[DllImport(LibHcNetSDK)] [DllImport(LibHkNetSDK, CallingConvention = CallingConvention.StdCall)]
public static extern bool NET_DVR_StopRealPlay(int iRealHandle); public static extern bool NET_DVR_StopRealPlay(int iRealHandle);
#endregion Common Method #endregion Common Method

47
EC.Util/CameraSDK/HiK/HiKSDK.cs

@ -1,4 +1,5 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text;
namespace EC.Util.CameraSDK; namespace EC.Util.CameraSDK;
@ -10,6 +11,8 @@ public class HiKSDK : ICameraSDK
private int RealplayHandle { get; set; } = -1; private int RealplayHandle { get; set; } = -1;
private int Channel { get; } = 1;
#endregion Fields #endregion Fields
public HiKSDK(CameraInfo cameraInfo) : base(cameraInfo) public HiKSDK(CameraInfo cameraInfo) : base(cameraInfo)
@ -22,11 +25,24 @@ public class HiKSDK : ICameraSDK
{ {
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (ret) return true; if (ret) return true;
HiKOriSDK.NET_DVR_USER_LOGIN_INFO loginInfo = new()
HiKOriSDK.NET_DVR_DEVICEINFO_V30 deviceInfo = new(); {
LoginId = HiKOriSDK.NET_DVR_Login_V30(CameraInfo.Ip, CameraInfo.Port, CameraInfo.UserName, CameraInfo.Password, ref deviceInfo); bUseAsynLogin = false,
sDeviceAddress = new byte[129],
wPort = (ushort)CameraInfo.Port,
sUserName = new byte[64],
sPassword = new byte[64]
};
Encoding.Default.GetBytes(CameraInfo.Ip).CopyTo(loginInfo.sDeviceAddress, 0);
Encoding.Default.GetBytes(CameraInfo.UserName).CopyTo(loginInfo.sUserName, 0);
Encoding.Default.GetBytes(CameraInfo.Password).CopyTo(loginInfo.sPassword, 0);
HiKOriSDK.NET_DVR_DEVICEINFO_V40 deviceInfo = new();
LoginId = HiKOriSDK.NET_DVR_Login_V40(ref loginInfo, ref deviceInfo);
ret = ConnectSuccess(); ret = ConnectSuccess();
if (ret) HiKOriSDK.NET_DVR_SetReconnect(10000, 1);
else BuildException();
//HiKOriSDK.NET_DVR_DEVICEINFO_V30 deviceInfo = new();
//LoginId = HiKOriSDK.NET_DVR_Login_V30(CameraInfo.Ip, CameraInfo.Port, CameraInfo.UserName, CameraInfo.Password, ref deviceInfo);
return ret; return ret;
} }
@ -34,10 +50,9 @@ public class HiKSDK : ICameraSDK
{ {
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (!ret) return true; if (!ret) return true;
ret = HiKOriSDK.NET_DVR_Logout(LoginId); ret = HiKOriSDK.NET_DVR_Logout(LoginId);
if (ret) LoginId = -1; if (ret) LoginId = -1;
else BuildException();
return ret; return ret;
} }
@ -124,19 +139,17 @@ public class HiKSDK : ICameraSDK
public override bool PtzMove(int cmd, int stop, int speed) public override bool PtzMove(int cmd, int stop, int speed)
{ {
if (!ConnectSuccess()) return false; if (!ConnectSuccess()) return false;
int lChannel = 1; bool ret = HiKOriSDK.NET_DVR_PTZControlWithSpeed_Other(LoginId, Channel, (uint)cmd, (uint)stop, (uint)speed);
bool flag = HiKOriSDK.NET_DVR_PTZControlWithSpeed_Other(LoginId, lChannel, (uint)cmd, (uint)stop, (uint)speed); if (!ret) BuildException();
if (flag) BuildException(); return ret;
return flag;
} }
public override bool PtzPreset(int cmd, int presetId) public override bool PtzPreset(int cmd, int presetId)
{ {
if (!ConnectSuccess()) return false; if (!ConnectSuccess()) return false;
int lChannel = 1; bool ret = HiKOriSDK.NET_DVR_PTZPreset_Other(LoginId, Channel, (uint)cmd, (uint)presetId);
bool flag = HiKOriSDK.NET_DVR_PTZPreset_Other(LoginId, lChannel, (uint)cmd, (uint)presetId); if (!ret) BuildException();
if (flag) BuildException(); return ret;
return flag;
} }
#endregion Ptz Method #endregion Ptz Method
@ -149,7 +162,7 @@ public class HiKSDK : ICameraSDK
HiKOriSDK.NET_DVR_PREVIEWINFO previewInfo = new() HiKOriSDK.NET_DVR_PREVIEWINFO previewInfo = new()
{ {
hPlayWnd = hwnd, //预览窗口 hPlayWnd = hwnd, //预览窗口
lChannel = 1, //预览的设备通道 lChannel = Channel, //预览的设备通道
dwStreamType = 0, //码流类型:0-主码流,1-子码流,2-码流3,3-码流4,以此类推 dwStreamType = 0, //码流类型:0-主码流,1-子码流,2-码流3,3-码流4,以此类推
dwLinkMode = 0, //连接方式:0- TCP方式,1- UDP方式,2- 多播方式,3- RTP方式,4-RTP/RTSP,5-RSTP/HTTP dwLinkMode = 0, //连接方式:0- TCP方式,1- UDP方式,2- 多播方式,3- RTP方式,4-RTP/RTSP,5-RSTP/HTTP
bBlocked = true, //0- 非阻塞取流,1- 阻塞取流 bBlocked = true, //0- 非阻塞取流,1- 阻塞取流
@ -165,9 +178,9 @@ public class HiKSDK : ICameraSDK
public override void StopPlay() public override void StopPlay()
{ {
if (!IsPlaying()) return; if (!IsPlaying()) return;
bool flag = HiKOriSDK.NET_DVR_StopRealPlay(RealplayHandle); bool ret = HiKOriSDK.NET_DVR_StopRealPlay(RealplayHandle);
RealplayHandle = -1; RealplayHandle = -1;
if (!flag) BuildException(); if (!ret) BuildException();
} }
public override bool IsPlaying() public override bool IsPlaying()

2
EC.Util/CameraSDK/YuShi/YuShiOriSDK.cs

@ -8,6 +8,8 @@ public static class YuShiOriSDK
public const string LibYsNetSDK = @"./libs/ys-win64/NetDEVSDK.dll"; public const string LibYsNetSDK = @"./libs/ys-win64/NetDEVSDK.dll";
private const bool Debug = true;
#endregion Lib Attr #endregion Lib Attr
static YuShiOriSDK() static YuShiOriSDK()

36
EC.Util/CameraSDK/YuShi/YuShiSDK.cs

@ -8,6 +8,8 @@ public class YuShiSDK : ICameraSDK
private IntPtr RealplayHandle { get; set; } = IntPtr.Zero; private IntPtr RealplayHandle { get; set; } = IntPtr.Zero;
private int Channel { get; } = 1;
#endregion Fields #endregion Fields
public YuShiSDK(CameraInfo cameraInfo) : base(cameraInfo) public YuShiSDK(CameraInfo cameraInfo) : base(cameraInfo)
@ -20,7 +22,6 @@ public class YuShiSDK : ICameraSDK
{ {
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (ret) return true; if (ret) return true;
YuShiOriSDK.NETDEV_DEVICE_LOGIN_INFO_S loginInfo = new(); YuShiOriSDK.NETDEV_DEVICE_LOGIN_INFO_S loginInfo = new();
loginInfo.szIPAddr = CameraInfo.Ip; loginInfo.szIPAddr = CameraInfo.Ip;
loginInfo.dwPort = CameraInfo.Port; loginInfo.dwPort = CameraInfo.Port;
@ -29,7 +30,7 @@ public class YuShiSDK : ICameraSDK
YuShiOriSDK.NETDEV_SELOG_INFO_S logInfo = new(); YuShiOriSDK.NETDEV_SELOG_INFO_S logInfo = new();
LoginId = YuShiOriSDK.NETDEV_Login_V30(ref loginInfo, ref logInfo); LoginId = YuShiOriSDK.NETDEV_Login_V30(ref loginInfo, ref logInfo);
ret = ConnectSuccess(); ret = ConnectSuccess();
if(!ret) BuildException();
return ret; return ret;
} }
@ -37,10 +38,9 @@ public class YuShiSDK : ICameraSDK
{ {
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (!ret) return true; if (!ret) return true;
ret = YuShiOriSDK.NETDEV_Logout(LoginId); ret = YuShiOriSDK.NETDEV_Logout(LoginId);
if (ret) LoginId = IntPtr.Zero; if (ret) LoginId = IntPtr.Zero;
else BuildException();
return ret; return ret;
} }
@ -65,7 +65,7 @@ public class YuShiSDK : ICameraSDK
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (!ret) return PtzInfo.Default; if (!ret) return PtzInfo.Default;
YuShiOriSDK.NETDEV_PTZ_STATUS_S entity = new(); YuShiOriSDK.NETDEV_PTZ_STATUS_S entity = new();
ret = YuShiOriSDK.NETDEV_PTZGetStatus(LoginId, 1, ref entity); ret = YuShiOriSDK.NETDEV_PTZGetStatus(LoginId, Channel, ref entity);
if (!ret) { BuildException(); return PtzInfo.Default; } if (!ret) { BuildException(); return PtzInfo.Default; }
return PtzInfo.New(entity.fPanTiltX, entity.fPanTiltY, entity.fZoomX); return PtzInfo.New(entity.fPanTiltX, entity.fPanTiltY, entity.fZoomX);
} }
@ -75,7 +75,7 @@ public class YuShiSDK : ICameraSDK
bool ret = ConnectSuccess(); bool ret = ConnectSuccess();
if (!ret) { ptzInfo = PtzInfo.Default; return false; } if (!ret) { ptzInfo = PtzInfo.Default; return false; }
YuShiOriSDK.NETDEV_PTZ_STATUS_S entity = new(); YuShiOriSDK.NETDEV_PTZ_STATUS_S entity = new();
ret = YuShiOriSDK.NETDEV_PTZGetStatus(LoginId, 1, ref entity); ret = YuShiOriSDK.NETDEV_PTZGetStatus(LoginId, Channel, ref entity);
if (!ret) { BuildException(); ptzInfo = PtzInfo.Default; return false; } if (!ret) { BuildException(); ptzInfo = PtzInfo.Default; return false; }
ptzInfo = PtzInfo.New(entity.fPanTiltX, entity.fPanTiltY, entity.fZoomX); ptzInfo = PtzInfo.New(entity.fPanTiltX, entity.fPanTiltY, entity.fZoomX);
return true; return true;
@ -85,21 +85,19 @@ public class YuShiSDK : ICameraSDK
{ {
if (!ConnectSuccess()) return false; if (!ConnectSuccess()) return false;
if (stop == 1) cmd = YuShiOriSDK.ALLSTOP; if (stop == 1) cmd = YuShiOriSDK.ALLSTOP;
int channel = 0; int retNum = YuShiOriSDK.NETDEV_PTZControl_Other(LoginId, Channel, cmd, speed);
int ret = YuShiOriSDK.NETDEV_PTZControl_Other(LoginId, channel, cmd, speed); bool ret = retNum == YuShiOriSDK.TRUE;
bool flag = ret == YuShiOriSDK.TRUE; if (!ret) BuildException();
if (!flag) BuildException(); return ret;
return flag;
} }
public override bool PtzPreset(int cmd, int presetId) public override bool PtzPreset(int cmd, int presetId)
{ {
if (!ConnectSuccess()) return false; if (!ConnectSuccess()) return false;
int channel = 0; int retNum = YuShiOriSDK.NETDEV_PTZPreset_Other(LoginId, Channel, cmd, Array.Empty<byte>(), presetId);
int ret = YuShiOriSDK.NETDEV_PTZPreset_Other(LoginId, channel, cmd, Array.Empty<byte>(), presetId); bool ret = retNum == YuShiOriSDK.TRUE;
bool flag = ret == YuShiOriSDK.TRUE; if (!ret) BuildException();
if (!flag) BuildException(); return ret;
return flag;
} }
#endregion Ptz Method #endregion Ptz Method
@ -112,7 +110,7 @@ public class YuShiSDK : ICameraSDK
YuShiOriSDK.NETDEV_PREVIEWINFO_S stPreviewInfo = new() YuShiOriSDK.NETDEV_PREVIEWINFO_S stPreviewInfo = new()
{ {
hPlayWnd = hwnd, hPlayWnd = hwnd,
dwChannelID = 1, dwChannelID = Channel,
dwStreamType = 0, // YuShiOriSDK.NETDEV_LIVE_STREAM_INDEX_E dwStreamType = 0, // YuShiOriSDK.NETDEV_LIVE_STREAM_INDEX_E
dwLinkMode = 1, // YuShiOriSDK.NETDEV_PROTOCAL_E dwLinkMode = 1, // YuShiOriSDK.NETDEV_PROTOCAL_E
dwFluency = 0, // YuShiOriSDK.NETDEV_PICTURE_FLUENCY_E dwFluency = 0, // YuShiOriSDK.NETDEV_PICTURE_FLUENCY_E
@ -124,9 +122,9 @@ public class YuShiSDK : ICameraSDK
public override void StopPlay() public override void StopPlay()
{ {
if (!IsPlaying()) return; if (!IsPlaying()) return;
int flag = YuShiOriSDK.NETDEV_StopRealPlay(RealplayHandle); int ret = YuShiOriSDK.NETDEV_StopRealPlay(RealplayHandle);
RealplayHandle = IntPtr.Zero; RealplayHandle = IntPtr.Zero;
if (flag == YuShiOriSDK.FALSE) BuildException(); if (ret == YuShiOriSDK.FALSE) BuildException();
} }
public override bool IsPlaying() public override bool IsPlaying()

36
EC.Util/Common/NetworkUtil.cs

@ -0,0 +1,36 @@
using System.Net.Sockets;
namespace EC.Util.Common;
public static class NetworkUtil
{
public static string LocalAddr(this TcpClient client)
{
return client.Client.LocalEndPoint?.ToString() ?? ":";
}
public static string LocalIp(this TcpClient client)
{
return LocalAddr(client).Split(':')[0];
}
public static string LocalPort(this TcpClient client)
{
return LocalAddr(client).Split(':')[1];
}
public static string ClientAddr(this TcpClient client)
{
return client.Client.RemoteEndPoint?.ToString() ?? ":";
}
public static string ClientIp(this TcpClient client)
{
return ClientAddr(client).Split(':')[0];
}
public static string ClientPort(this TcpClient client)
{
return ClientAddr(client).Split(':')[1];
}
}

65
JiLinApp.Docking/FenceAlarm/Service/UdpManager.cs

@ -49,7 +49,7 @@ public class UdpManager
Server.DatagramReceived += Server_DatagramReceived; Server.DatagramReceived += Server_DatagramReceived;
Server.Start(); Server.Start();
PtzCheckTimer.Interval = 1000;//1s PtzCheckTimer.Interval = 3000;//3s
PtzCheckTimer.Elapsed += PTZCheckTimer_Elapsed; PtzCheckTimer.Elapsed += PTZCheckTimer_Elapsed;
PtzCheckTimer.Enabled = true; PtzCheckTimer.Enabled = true;
@ -92,7 +92,7 @@ public class UdpManager
foreach (var key in DeviceDict.Keys) foreach (var key in DeviceDict.Keys)
{ {
UdpAlarmHost device = DeviceDict[key]; UdpAlarmHost device = DeviceDict[key];
if (device.KeepLive >= 0) device.KeepLive--; if (device.KeepLive > 0) device.KeepLive--;
else ProcessDeviceStateEvent(ref device, 0, device.DefenceState); else ProcessDeviceStateEvent(ref device, 0, device.DefenceState);
} }
} }
@ -101,9 +101,10 @@ public class UdpManager
{ {
IPEndPoint ipep = e.Ipep; IPEndPoint ipep = e.Ipep;
//解码 //解码
//byte[] msg = e.Datagram;
byte[] msg = AlarmEncode.DecodeMessage(e.Datagram); byte[] msg = AlarmEncode.DecodeMessage(e.Datagram);
bool vaild = msg.Length >= 8 && msg[2] == AlarmEncode.Head[0] && msg[3] == AlarmEncode.Head[1]; bool vaild = msg.Length >= 8 && msg[2] == AlarmEncode.Head[0] && msg[3] == AlarmEncode.Head[1];
Console.WriteLine("Recv from {0}:{1} => {2}, {3}", ipep.Address.ToString(), ipep.Port, DataMessage.ToHexString(msg), vaild); Console.WriteLine("Recv from {0}:{1} => {2}, {3}, {4}", ipep.Address.ToString(), ipep.Port, DataMessage.ToHexString(e.Datagram), DataMessage.ToHexString(msg), vaild);
if (!vaild) return; if (!vaild) return;
//解析 //解析
DeviceCmd deviceCmd = (DeviceCmd)msg[4]; DeviceCmd deviceCmd = (DeviceCmd)msg[4];
@ -161,6 +162,8 @@ public class UdpManager
AddDevice(deviceId, ref device); AddDevice(deviceId, ref device);
} }
byte defenceState = msg[17]; byte defenceState = msg[17];
//在线状态
device.KeepLive = Config.DeviceHeartKeep;
ProcessDeviceStateEvent(ref device, 1, defenceState); ProcessDeviceStateEvent(ref device, 1, defenceState);
device.WorkState = msg[18]; device.WorkState = msg[18];
//设备状态1 //设备状态1
@ -185,8 +188,6 @@ public class UdpManager
device.DevideType = msg[23]; device.DevideType = msg[23];
device.SignalIntensity = msg[24]; device.SignalIntensity = msg[24];
device.SectorTotal = msg[25]; device.SectorTotal = msg[25];
//在线状态
device.KeepLive = Config.DeviceHeartKeep;
} }
private void AnalysisAlarmMessage(IPEndPoint ipep, byte[] msg) private void AnalysisAlarmMessage(IPEndPoint ipep, byte[] msg)
@ -312,10 +313,18 @@ public class UdpManager
{ {
bool reportFlag = false; bool reportFlag = false;
if (device.OnlineState != onlineState) if (device.OnlineState != onlineState)
{
if (onlineState == 0 && device.KeepLive < 0)
{ {
reportFlag = true; reportFlag = true;
device.OnlineState = onlineState; device.OnlineState = onlineState;
} }
else if (onlineState == 1 && device.KeepLive >= 0)
{
reportFlag = true;
device.OnlineState = onlineState;
}
}
if (device.DefenceState != defenceState) if (device.DefenceState != defenceState)
{ {
reportFlag = true; reportFlag = true;
@ -361,8 +370,52 @@ public class UdpManager
{ {
if (!IsRunning()) return false; if (!IsRunning()) return false;
byte[] bytes = new byte[] { 0x08, 0x12, 0xF0, 0xFA, 0x8F, 0x06, 0x6B, 0x0D }; byte[] bytes = new byte[] { 0x08, 0x12, 0xF0, 0xFA, 0x8F, 0x06, 0x6B, 0x0D };
//byte[] bytes = AlarmEncode.GetSendMessage(0x8F, Array.Empty<byte>()); ////byte[] bytes = AlarmEncode.GetSendMessage(0x8F, Array.Empty<byte>());
return Server.SendMessage(ipep.Address.ToString(), ipep.Port, AlarmEncode.EncodeMessage(bytes)); return Server.SendMessage(ipep.Address.ToString(), ipep.Port, AlarmEncode.EncodeMessage(bytes));
//Console.WriteLine();
//byte[] bytes = new byte[] {
// 0x24, 0x12, 0xF0, 0xFA,
// 0x02,
// 0x77, 0x35, 0x94, 0x01,
// 0x07, 0x5B, 0xCD, 0x15,
// 0x00, 0x01, 0xE2, 0x40,
// 0x23, 0x05, 0x18, 0x17, 0x12, 0x34,
// 0x01, 0x00, 0x00, 0x01,
// 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
// 0x0F, 0x41, 0x0D };
//Console.WriteLine(DataMessage.ToHexString(AlarmEncode.EncodeMessage(bytes))); bytes = new byte[] {
// 0x24, 0x12, 0xF0, 0xFA,
// 0x02,
// 0x77, 0x35, 0x94, 0x01,
// 0x07, 0x5B, 0xCD, 0x15,
// 0x00, 0x01, 0xE2, 0x40,
// 0x23, 0x05, 0x18, 0x17, 0x12, 0x34,
// 0x01, 0x00, 0x00, 0x02,
// 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
// 0x3C, 0x05, 0x0D };
//Console.WriteLine(DataMessage.ToHexString(AlarmEncode.EncodeMessage(bytes))); bytes = new byte[] {
// 0x24, 0x12, 0xF0, 0xFA,
// 0x02,
// 0x77, 0x35, 0x94, 0x01,
// 0x07, 0x5B, 0xCD, 0x15,
// 0x00, 0x01, 0xE2, 0x40,
// 0x23, 0x05, 0x18, 0x17, 0x12, 0x34,
// 0x01, 0x00, 0x00, 0x01,
// 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
// 0x0E, 0x35, 0x0D };
//Console.WriteLine(DataMessage.ToHexString(AlarmEncode.EncodeMessage(bytes))); bytes = new byte[] {
// 0x24, 0x12, 0xF0, 0xFA,
// 0x02,
// 0x77, 0x35, 0x94, 0x01,
// 0x07, 0x5B, 0xCD, 0x15,
// 0x00, 0x01, 0xE2, 0x40,
// 0x23, 0x05, 0x18, 0x17, 0x12, 0x34,
// 0x01, 0x00, 0x00, 0x02,
// 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
// 0x3C, 0xC9, 0x0D };
//Console.WriteLine(DataMessage.ToHexString(AlarmEncode.EncodeMessage(bytes)));
//Server.SendMessage(ipep.Address.ToString(), ipep.Port, AlarmEncode.EncodeMessage(bytes));
//return true;
} }
/// <summary> /// <summary>

2
JiLinApp.Docking/FenceAlarm/Service/UdpServer.cs

@ -118,7 +118,7 @@ public class UdpServer
IPEndPoint ipep = new(IPAddress.Parse(ip), port); IPEndPoint ipep = new(IPAddress.Parse(ip), port);
int result = SendUdp.Send(msg, msg.Length, ipep); int result = SendUdp.Send(msg, msg.Length, ipep);
bool flag = result == msg.Length; bool flag = result == msg.Length;
Console.WriteLine("Send to {0}:{1} => {2}, {3}", ip, port, DataMessage.ToHexString(AlarmEncode.DecodeMessage(msg)), flag); Console.WriteLine("Send to {0}:{1} => {2}, {3}, {4}", ip, port, DataMessage.ToHexString(msg), DataMessage.ToHexString(AlarmEncode.DecodeMessage(msg)), flag);
return flag; return flag;
} }

4
JiLinApp.Docking/Military/Config.cs

@ -10,7 +10,7 @@ public class MilitaryConfig
public string Password { get; set; } public string Password { get; set; }
public int RequestRetryTime { get; set; } public int RequestTryTime { get; set; }
public int RequestRetryInterval { get; set; } public int RequestTryInterval { get; set; }
} }

18
JiLinApp.Docking/Military/MilitaryService.cs

@ -46,13 +46,13 @@ public class MilitaryService
password = Config.Password, password = Config.Password,
}; };
JObject response = new(); JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++) for (int i = 0; i < Config.RequestTryTime; i++)
{ {
response = WithToken(url).PostJsonAsync(data).ReceiveJson<JObject>().Result; response = WithToken(url).PostJsonAsync(data).ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean(); bool success = response["success"].ToBoolean();
if (!success) if (!success)
{ {
Thread.Sleep(Config.RequestRetryInterval); Thread.Sleep(Config.RequestTryInterval);
continue; continue;
} }
string? token = response["result"]?["token"]?.ToString(); string? token = response["result"]?["token"]?.ToString();
@ -66,13 +66,13 @@ public class MilitaryService
{ {
string url = $"{GetUrl()}/camera/setting/list"; string url = $"{GetUrl()}/camera/setting/list";
JObject response = new(); JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++) for (int i = 0; i < Config.RequestTryTime; i++)
{ {
response = WithToken(url).GetAsync().ReceiveJson<JObject>().Result; response = WithToken(url).GetAsync().ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean(); bool success = response["success"].ToBoolean();
if (!success) if (!success)
{ {
Thread.Sleep(Config.RequestRetryInterval); Thread.Sleep(Config.RequestTryInterval);
continue; continue;
} }
JToken records = response?["result"]?["records"] ?? new JObject(); JToken records = response?["result"]?["records"] ?? new JObject();
@ -89,9 +89,11 @@ public class MilitaryService
string ip = item?["ip"]?.ToString() ?? string.Empty; string ip = item?["ip"]?.ToString() ?? string.Empty;
string username = item?["user"]?.ToString() ?? string.Empty; string username = item?["user"]?.ToString() ?? string.Empty;
string password = item?["password"]?.ToString() ?? string.Empty; string password = item?["password"]?.ToString() ?? string.Empty;
string name = $"{item?["siteName"]?.ToString()}-{item?["cameraName"]?.ToString()}-{ip}";
if (VerifyUtil.IsEmpty(id) || !VerifyUtil.IsIp(ip) || VerifyUtil.IsEmpty(username) || VerifyUtil.IsEmpty(password)) continue; if (VerifyUtil.IsEmpty(id) || !VerifyUtil.IsIp(ip) || VerifyUtil.IsEmpty(username) || VerifyUtil.IsEmpty(password)) continue;
CameraInfo info = CameraInfo.New(manufactor, ip, username, password); CameraInfo info = CameraInfo.New(manufactor, ip, username, password);
info.Id = id; info.Id = id;
info.Name = name;
list.Add(info); list.Add(info);
} }
return list; return list;
@ -104,13 +106,13 @@ public class MilitaryService
{ {
string url = $"{GetUrl()}/msFencesInfo/list"; string url = $"{GetUrl()}/msFencesInfo/list";
JObject response = new(); JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++) for (int i = 0; i < Config.RequestTryTime; i++)
{ {
response = WithToken(url).GetAsync().ReceiveJson<JObject>().Result; response = WithToken(url).GetAsync().ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean(); bool success = response["success"].ToBoolean();
if (!success) if (!success)
{ {
Thread.Sleep(Config.RequestRetryInterval); Thread.Sleep(Config.RequestTryInterval);
continue; continue;
} }
return new List<object>(); return new List<object>();
@ -123,13 +125,13 @@ public class MilitaryService
{ {
string url = $"{GetUrl()}/military/MsCameraLinkage/list"; string url = $"{GetUrl()}/military/MsCameraLinkage/list";
JObject response = new(); JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++) for (int i = 0; i < Config.RequestTryTime; i++)
{ {
response = WithToken(url).GetAsync().ReceiveJson<JObject>().Result; response = WithToken(url).GetAsync().ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean(); bool success = response["success"].ToBoolean();
if (!success) if (!success)
{ {
Thread.Sleep(Config.RequestRetryInterval); Thread.Sleep(Config.RequestTryInterval);
continue; continue;
} }
JToken records = response?["result"]?["records"] ?? new JObject(); JToken records = response?["result"]?["records"] ?? new JObject();

67
JiLinApp.Docking/VibrateAlarm/Entity/ClientMessage.cs

@ -1,4 +1,5 @@
using System.Collections.Concurrent; using EC.Util.Common;
using System.Collections.Concurrent;
using System.Net.Sockets; using System.Net.Sockets;
namespace JiLinApp.Docking.VibrateAlarm; namespace JiLinApp.Docking.VibrateAlarm;
@ -11,57 +12,85 @@ public class ClientMessage
public TcpAlarmHost Host { get; set; } public TcpAlarmHost Host { get; set; }
public string Ip public int OnlineState { get; set; }//设备在线状态
public bool IsOnline
{ {
get get
{ {
if (Host != null) return Host.Ip; return Host != null && Host.Id >= 0 && OnlineState == 1;
//if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[0];
return "";
} }
} }
public string Port public ConcurrentDictionary<int, SensorState> SensorDict { get; } = new();
public int SensorTotal
{ {
get get
{ {
if (Host != null) return Host.Port; return SensorDict.Count;
//if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[1];
return "-1";
} }
} }
public int OnlineState { get; set; }//设备在线状态 public bool SensorsEmpty
{
get
{
return SensorDict == null || SensorDict.IsEmpty;
}
}
public bool IsOnline public List<byte> DataList { get; } = new();
public string ClientAddr
{ {
get get
{ {
return Host != null && Host.Id >= 0 && OnlineState == 1; return Client.ClientAddr();
} }
} }
public int SensorTotal public string ClientIp
{ {
get get
{ {
return SensorDict.Count; if (Host != null) return Host.Ip;
return Client.ClientIp();
} }
} }
public ConcurrentDictionary<int, SensorState> SensorDict { get; } = new(); public string ClientPort
{
get
{
if (Host != null) return Host.Port;
return Client.ClientPort();
}
}
public bool SensorsEmpty public string LocalAddr
{ {
get get
{ {
return SensorDict == null || SensorDict.IsEmpty; return Client.LocalAddr();
} }
} }
public ReaderWriterLockSlim SensorsLock { get; } = new(); public string LocalIp
{
get
{
return Client.LocalIp();
}
}
public List<byte> DataList { get; } = new(); public string LocalPort
{
get
{
return Client.LocalPort();
}
}
#endregion Fields #endregion Fields

151
JiLinApp.Docking/VibrateAlarm/Service/AsyncTcpServer.cs

@ -1,4 +1,5 @@
using System.Collections.Concurrent; using EC.Util.Common;
using System.Collections.Concurrent;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
@ -114,7 +115,7 @@ public class AsyncTcpServer : IDisposable
{ {
foreach (var client in Clients.Values) foreach (var client in Clients.Values)
{ {
client.TcpClient.Client.Disconnect(false); client.Client.Client.Disconnect(false);
} }
Clients.Clear(); Clients.Clear();
} }
@ -149,15 +150,18 @@ public class AsyncTcpServer : IDisposable
/// </summary> /// </summary>
public event EventHandler<TcpDatagramReceivedEventArgs<byte[]>>? DatagramReceived; public event EventHandler<TcpDatagramReceivedEventArgs<byte[]>>? DatagramReceived;
private void RaiseClientConnected(string clientKey, TcpClientState clientState) private void RaiseClientConnected(string clientAddr, TcpClientState clientState)
{ {
Clients.AddOrUpdate(clientKey, clientState, (n, o) => { return clientState; }); if (string.IsNullOrEmpty(clientAddr) || clientAddr.Equals(":")) return;
ClientConnected?.Invoke(this, new TcpClientConnectedEventArgs(clientState.TcpClient)); Clients.AddOrUpdate(clientAddr, clientState, (n, o) => { return clientState; });
ClientConnected?.Invoke(this, new TcpClientConnectedEventArgs(clientState.Client));
} }
private void RaiseClientDisconnected(string clientKey, TcpClient client) private void RaiseClientDisconnected(string clientAddr, TcpClient client)
{ {
if (Clients.TryRemove(clientKey, out _)) if (string.IsNullOrEmpty(clientAddr) || clientAddr.Equals(":")) return;
client.Client.Disconnect(false);
if (Clients.TryRemove(clientAddr, out _))
{ {
ClientDisconnected?.Invoke(this, new TcpClientDisconnectedEventArgs(client)); ClientDisconnected?.Invoke(this, new TcpClientDisconnectedEventArgs(client));
} }
@ -180,89 +184,97 @@ public class AsyncTcpServer : IDisposable
private void HandleTcpClientAccepted(IAsyncResult ar) private void HandleTcpClientAccepted(IAsyncResult ar)
{ {
if (!IsRunning()) return; if (!IsRunning()) return;
TcpListener? listener; if (ar.AsyncState is not TcpListener listener) return;
TcpClient? client; TcpClient? client;
try try
{ {
listener = ar.AsyncState as TcpListener; client = listener.EndAcceptTcpClient(ar);
client = listener?.EndAcceptTcpClient(ar); if (client == null || !client.Connected)
{
client?.Client.Disconnect(false);
return;
}
} }
catch (Exception) catch (Exception)
{ {
return; return;
} }
if (listener == null || client == null || !client.Connected) return;
// add client connection to cache
string clientAddr = client.ClientAddr();
byte[] buffer = new byte[client.ReceiveBufferSize]; byte[] buffer = new byte[client.ReceiveBufferSize];
TcpClientState clientState = new(client, buffer); TcpClientState clientState = new(client, buffer);
RaiseClientConnected(clientAddr, clientState);
// add client connection to cache
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
RaiseClientConnected(clientKey, clientState);
// begin to read data // begin to read data
ReadBuffer(clientState);
// keep listening to accept next connection
AcceptTcpClient(listener);
}
private void ReadBuffer(TcpClientState clientState)
{
try try
{ {
NetworkStream networkStream = clientState.NetworkStream; NetworkStream stream = clientState.GetStream;
ReadBuffer(clientState, networkStream); if (clientState.IsRead) return;
lock (clientState.IsReadLock)
{
if (clientState.IsRead) return;
clientState.IsRead = true;
stream.BeginRead(clientState.Buffer, 0, clientState.Buffer.Length, HandleDatagramReceived, clientState);
} }
catch (Exception) }
catch (IOException e)
{ {
RaiseClientDisconnected(clientKey, clientState.TcpClient); LogUnit.Error(e);
return; return;
} }
catch (Exception e)
// keep listening to accept next connection
AcceptTcpClient(listener);
}
private void ReadBuffer(TcpClientState clientState, NetworkStream networkStream)
{ {
networkStream.BeginRead(clientState.Buffer, 0, clientState.Buffer.Length, HandleDatagramReceived, clientState); LogUnit.Error(e);
string clientAddr = clientState.Client.ClientAddr();
RaiseClientDisconnected(clientAddr, clientState.Client);
}
} }
private void HandleDatagramReceived(IAsyncResult ar) private void HandleDatagramReceived(IAsyncResult ar)
{ {
if (!IsRunning()) return; if (!IsRunning()) return;
TcpClientState? internalClient = ar.AsyncState as TcpClientState; if (ar.AsyncState is not TcpClientState clientState) return;
if (internalClient == null) return;
string clientKey = internalClient.TcpClient.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
if (!internalClient.TcpClient.Connected)
{
// connection has been closed
RaiseClientDisconnected(clientKey, internalClient.TcpClient);
}
NetworkStream networkStream; int readNum;
int readBytesNum; string clientAddr = clientState.Client.ClientAddr();
try try
{ {
networkStream = internalClient.NetworkStream; NetworkStream networkStream = clientState.GetStream;
// if the remote host has shutdown its connection, // if the remote host has shutdown its connection, read will immediately return with zero bytes.
// read will immediately return with zero bytes. readNum = networkStream.EndRead(ar);
readBytesNum = networkStream.EndRead(ar); if (readNum == 0)
}
catch (Exception)
{ {
RaiseClientDisconnected(clientKey, internalClient.TcpClient); RaiseClientDisconnected(clientAddr, clientState.Client);
return; return;
} }
if (readBytesNum == 0) }
catch (Exception)
{ {
// connection has been closed RaiseClientDisconnected(clientAddr, clientState.Client);
RaiseClientDisconnected(clientKey, internalClient.TcpClient);
return; return;
} }
// received byte and trigger event notification // received byte and trigger event notification
byte[] receivedBytes = new byte[readBytesNum]; byte[] receivedBytes = new byte[readNum];
Buffer.BlockCopy(internalClient.Buffer, 0, receivedBytes, 0, readBytesNum); Buffer.BlockCopy(clientState.Buffer, 0, receivedBytes, 0, readNum);
RaiseDatagramReceived(internalClient, receivedBytes); RaiseDatagramReceived(clientState, receivedBytes);
lock (clientState.IsReadLock)
{
clientState.IsRead = false;
}
// continue listening for tcp datagram packets // continue listening for tcp datagram packets
ReadBuffer(internalClient, networkStream); ReadBuffer(clientState);
} }
#endregion Receive #endregion Receive
@ -277,20 +289,16 @@ public class AsyncTcpServer : IDisposable
public void Send(TcpClient client, byte[] datagram) public void Send(TcpClient client, byte[] datagram)
{ {
if (!IsRunning()) return; if (!IsRunning()) return;
if (client == null || !client.Connected || datagram == null) return; if (client == null || datagram == null) return;
try try
{ {
NetworkStream stream = client.GetStream(); NetworkStream stream = client.GetStream();
if (stream.CanWrite)
{
stream.Write(datagram, 0, datagram.Length); stream.Write(datagram, 0, datagram.Length);
} }
}
catch (Exception) catch (Exception)
{ {
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? ""; string clientAddr = client.ClientAddr();
if (clientKey == "") return; RaiseClientDisconnected(clientAddr, client);
if (client != null) RaiseClientDisconnected(clientKey, client);
} }
} }
@ -313,7 +321,7 @@ public class AsyncTcpServer : IDisposable
if (!IsRunning()) return; if (!IsRunning()) return;
foreach (var client in Clients.Values) foreach (var client in Clients.Values)
{ {
Send(client.TcpClient, datagram); Send(client.Client, datagram);
} }
} }
@ -335,18 +343,17 @@ public class AsyncTcpServer : IDisposable
public bool SendAsync(TcpClient client, byte[] datagram) public bool SendAsync(TcpClient client, byte[] datagram)
{ {
if (!IsRunning()) return false; if (!IsRunning()) return false;
if (client == null || !client.Connected || datagram == null) return false; if (client == null || datagram == null) return false;
try try
{ {
NetworkStream stream = client.GetStream(); NetworkStream stream = client.GetStream();
if (!stream.CanWrite) return false;
IAsyncResult result = stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, client); IAsyncResult result = stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, client);
return result.IsCompleted; return result.IsCompleted;
} }
catch (Exception) catch (Exception)
{ {
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? ""; string clientAddr = client.ClientAddr();
if (clientKey != "" && client != null) RaiseClientDisconnected(clientKey, client); RaiseClientDisconnected(clientAddr, client);
} }
return false; return false;
} }
@ -356,9 +363,9 @@ public class AsyncTcpServer : IDisposable
/// </summary> /// </summary>
/// <param name="client">客户端</param> /// <param name="client">客户端</param>
/// <param name="datagram">报文</param> /// <param name="datagram">报文</param>
public void SendAsync(TcpClient client, string datagram) public bool SendAsync(TcpClient client, string datagram)
{ {
SendAsync(client, Encoding.GetBytes(datagram)); return SendAsync(client, Encoding.GetBytes(datagram));
} }
/// <summary> /// <summary>
@ -370,7 +377,7 @@ public class AsyncTcpServer : IDisposable
if (!IsRunning()) return; if (!IsRunning()) return;
foreach (var client in Clients.Values) foreach (var client in Clients.Values)
{ {
SendAsync(client.TcpClient, datagram); SendAsync(client.Client, datagram);
} }
} }
@ -386,17 +393,15 @@ public class AsyncTcpServer : IDisposable
private void HandleDatagramWritten(IAsyncResult ar) private void HandleDatagramWritten(IAsyncResult ar)
{ {
TcpClient? client = null; if (ar.AsyncState is not TcpClient client) return;
try try
{ {
client = ar.AsyncState as TcpClient; client.GetStream().EndWrite(ar);
client?.GetStream().EndWrite(ar);
} }
catch (Exception) catch (Exception)
{ {
string clientKey = client?.Client.RemoteEndPoint?.ToString() ?? ""; string clientAddr = client.ClientAddr();
if (clientKey == "") return; RaiseClientDisconnected(clientAddr, client);
if (client != null) RaiseClientDisconnected(clientKey, client);
} }
} }

26
JiLinApp.Docking/VibrateAlarm/Service/TcpClientState.cs

@ -7,22 +7,21 @@ public class TcpClientState
/// <summary> /// <summary>
/// Constructor for a new Client /// Constructor for a new Client
/// </summary> /// </summary>
/// <param name="tcpClient">The TCP client</param> /// <param name="client">The TCP client</param>
/// <param name="buffer">The byte array buffer</param> /// <param name="buffer">The byte array buffer</param>
public TcpClientState(TcpClient tcpClient, byte[] buffer) public TcpClientState(TcpClient client, byte[] buffer)
{ {
if (tcpClient == null) throw new ArgumentNullException("tcpClient"); if (client == null) throw new ArgumentNullException("tcpClient");
if (buffer == null) throw new ArgumentNullException("buffer"); if (buffer == null) throw new ArgumentNullException("buffer");
Client = client;
TcpClient = tcpClient;
Buffer = buffer; Buffer = buffer;
temp = string.Empty; Temp = string.Empty;
} }
/// <summary> /// <summary>
/// Gets the TCP Client /// Gets the TCP Client
/// </summary> /// </summary>
public TcpClient TcpClient { get; private set; } public TcpClient Client { get; private set; }
/// <summary> /// <summary>
/// Gets the Buffer. /// Gets the Buffer.
@ -32,16 +31,23 @@ public class TcpClientState
/// <summary> /// <summary>
/// TCP接收到但未处理的数据 /// TCP接收到但未处理的数据
/// </summary> /// </summary>
public string temp { get; set; } public string Temp { get; set; }
/// <summary> /// <summary>
/// Gets the network stream /// Gets the network stream
/// </summary> /// </summary>
public NetworkStream NetworkStream public NetworkStream GetStream
{ {
get get
{ {
return TcpClient.GetStream(); NetworkStream stream = Client.GetStream();
stream.ReadTimeout = 5000;
stream.WriteTimeout = 5000;
return stream;
} }
} }
public bool IsRead { get; set; }
public object IsReadLock { get; } = new();
} }

4
JiLinApp.Docking/VibrateAlarm/Service/TcpDatagramReceivedEventArgs.cs

@ -9,7 +9,7 @@ public class TcpDatagramReceivedEventArgs<T> : EventArgs
/// <summary> /// <summary>
/// 客户端 /// 客户端
/// </summary> /// </summary>
public TcpClientState TcpClient { get; private set; } public TcpClientState ClientState { get; private set; }
/// <summary> /// <summary>
/// 报文 /// 报文
@ -23,7 +23,7 @@ public class TcpDatagramReceivedEventArgs<T> : EventArgs
/// <param name="datagram">报文</param> /// <param name="datagram">报文</param>
public TcpDatagramReceivedEventArgs(TcpClientState tcpClient, T datagram) public TcpDatagramReceivedEventArgs(TcpClientState tcpClient, T datagram)
{ {
TcpClient = tcpClient ?? throw new ArgumentNullException(nameof(tcpClient)); ClientState = tcpClient ?? throw new ArgumentNullException(nameof(tcpClient));
Datagram = datagram; Datagram = datagram;
} }
} }

492
JiLinApp.Docking/VibrateAlarm/Service/TcpManager.cs

@ -1,4 +1,5 @@
using System.Collections.Concurrent; using EC.Util.Common;
using System.Collections.Concurrent;
using System.Net; using System.Net;
using System.Timers; using System.Timers;
using Timer = System.Timers.Timer; using Timer = System.Timers.Timer;
@ -97,11 +98,11 @@ public class TcpManager
private void Server_ClientConnected(object? sender, TcpClientConnectedEventArgs e) private void Server_ClientConnected(object? sender, TcpClientConnectedEventArgs e)
{ {
string clientKey = e.TcpClient.Client.RemoteEndPoint?.ToString() ?? ""; string clientAddr = e.TcpClient.ClientAddr();
if (clientKey == "") return; if (clientAddr == ":") return;
string clientIp = clientKey.Split(':')[0]; string clientIp = clientAddr.Split(':')[0];
string clientPort = clientKey.Split(':')[1]; string clientPort = clientAddr.Split(':')[1];
Console.WriteLine("上线:{0}", clientIp); Console.WriteLine("主机上线:{0}", clientIp);
if (!TryGetDevice(clientIp, out ClientMessage clientMsg)) if (!TryGetDevice(clientIp, out ClientMessage clientMsg))
{ {
clientMsg = new() clientMsg = new()
@ -119,11 +120,11 @@ public class TcpManager
private void Server_ClientDisconnected(object? sender, TcpClientDisconnectedEventArgs e) private void Server_ClientDisconnected(object? sender, TcpClientDisconnectedEventArgs e)
{ {
string clientKey = e.TcpClient.Client.RemoteEndPoint?.ToString() ?? ""; string clientAddr = e.TcpClient.ClientAddr();
if (clientKey == "") return; if (clientAddr == ":") return;
string clientIp = clientKey.Split(':')[0]; string clientIp = clientAddr.Split(':')[0];
string clientPort = clientKey.Split(':')[1]; string clientPort = clientAddr.Split(':')[1];
Console.WriteLine("下线:{0}", clientIp); Console.WriteLine("主机下线:{0}", clientIp);
if (TryGetDevice(clientIp, out ClientMessage clientMsg)) if (TryGetDevice(clientIp, out ClientMessage clientMsg))
{ {
ProcessDeviceStateEvent(ref clientMsg, 0); ProcessDeviceStateEvent(ref clientMsg, 0);
@ -132,12 +133,16 @@ public class TcpManager
private void Server_DatagramReceived(object? sender, TcpDatagramReceivedEventArgs<byte[]> e) private void Server_DatagramReceived(object? sender, TcpDatagramReceivedEventArgs<byte[]> e)
{ {
string clientKey = e.TcpClient.TcpClient.Client.RemoteEndPoint?.ToString() ?? ""; string clientAddr = e.ClientState.Client.ClientAddr();
if (clientKey == "") return; if (clientAddr == ":") return;
string clientIp = clientKey.Split(':')[0]; string clientIp = clientAddr.Split(':')[0];
string clientPort = clientAddr.Split(':')[1];
if (TryGetDevice(clientIp, out ClientMessage clientMsg)) if (TryGetDevice(clientIp, out ClientMessage clientMsg))
{ {
if (clientMsg.Client == null || !clientMsg.Client.Connected) clientMsg.Client = e.ClientState.Client;
clientMsg.Host ??= new() { Id = -1, Ip = clientIp, Port = clientPort };
clientMsg.AddData(e.Datagram); clientMsg.AddData(e.Datagram);
ProcessDeviceStateEvent(ref clientMsg, 1);
AnalysisClientMessage(ref clientMsg); AnalysisClientMessage(ref clientMsg);
} }
} }
@ -148,96 +153,105 @@ public class TcpManager
private void AnalysisClientMessage(ref ClientMessage clientMsg) private void AnalysisClientMessage(ref ClientMessage clientMsg)
{ {
List<byte[]> msglist = clientMsg.GetMessageList(); List<byte[]> msgList = clientMsg.GetMessageList();
if (msglist == null || msglist.Count == 0) return; foreach (byte[] msg in msgList)
for (int i = 0; i < msglist.Count; i++)
{ {
byte[] msg = msglist[i];
bool vaild = msg.Length >= 19 && msg[0] == 0xAA && msg[1] == 0xAA; bool vaild = msg.Length >= 19 && msg[0] == 0xAA && msg[1] == 0xAA;
Console.WriteLine("Recv from {0}:{1} => {2}, {3}", clientMsg.Ip, clientMsg.Port, DataMessage.ToHexString(msg), vaild); Console.WriteLine("Recv from {0}:{1} => {2}, vaild:{3}", clientMsg.ClientIp, clientMsg.ClientPort, DataMessage.ToHexString(msg), vaild);
if (!vaild) continue; if (!vaild) continue;
DataMessage mm = new(); DataMessage mm = new();
mm.Decode(msglist[i]); mm.Decode(msg);
if (clientMsg.Host.Id != mm.DeviceId) clientMsg.Host.Id = mm.DeviceId;
switch (mm.FunctionNum) switch (mm.FunctionNum)
{ {
case 0x00: case 0x00:
Console.WriteLine("主机登录:{0}", clientMsg.Ip); Console.WriteLine("主机登录:{0}", clientMsg.ClientAddr);
if (clientMsg.Host == null || clientMsg.Host.Id != mm.DeviceId)
{
clientMsg.Host = new() { Id = mm.DeviceId, Ip = mm.SendIp, Port = mm.SendPort.ToString() };
UpdateDevice(clientMsg.Ip, clientMsg.Host);
}
ProcessDeviceStateEvent(ref clientMsg, 1);
ResponseHostLogin_10(clientMsg, mm); ResponseHostLogin_10(clientMsg, mm);
ClientMessage taskClientMsg = clientMsg; RequestHostAutoUploadState_24(clientMsg);
if (taskClientMsg.SensorsEmpty && taskClientMsg.SensorsLock.TryEnterWriteLock(1000)) RequestSensorList_07(clientMsg);
{
Task.Run(() =>
{
while (taskClientMsg.SensorsEmpty)
{
RequestSensorList_07(taskClientMsg);
Thread.Sleep(1000);
}
taskClientMsg.SensorsLock.ExitWriteLock();
});
}
break; break;
case 0x01: case 0x01:
Console.WriteLine("心跳:{0}", clientMsg.Ip); Console.WriteLine("主机心跳:{0}", clientMsg.ClientAddr);
if (clientMsg.Host == null || clientMsg.Host.Id != mm.DeviceId)
{
clientMsg.Host = new() { Id = mm.DeviceId, Ip = mm.SendIp, Port = mm.SendPort.ToString() };
UpdateDevice(clientMsg.Ip, clientMsg.Host);
}
ProcessDeviceStateEvent(ref clientMsg, 1);
break; break;
case 0x12: case 0x12:
Console.WriteLine("传感器地址设置响应:{0}", clientMsg.Ip); Console.WriteLine("传感器地址设置响应:{0}", clientMsg.ClientAddr);
SetDataRequest(mm, 0x02);
SetDataResponse(mm, 0x02);
break; break;
case 0x13: case 0x13:
Console.WriteLine("传感器模式设置响应:{0}", clientMsg.Ip); Console.WriteLine("传感器模式设置响应:{0}", clientMsg.ClientAddr);
SetDataRequest(mm, 0x03);
SetDataResponse(mm, 0x03);
break; break;
case 0x14: case 0x14:
Console.WriteLine("传感器轮询状态响应:{0}", clientMsg.Ip); Console.WriteLine("传感器轮询状态响应:{0}", clientMsg.ClientAddr);
int sensorAddr = mm.Data[0] + mm.Data[1] * 256; int sensorAddr = mm.Data[0] + mm.Data[1] * 256;
int state = mm.Data[2] + mm.Data[3] * 256; int state = mm.Data[2] + mm.Data[3] * 256;
int offline = state % 2; ProcessSensorStateEvent(ref clientMsg, mm, sensorAddr, state);
int alarm = state / 2 % 2;
ProcessSensorStateEvent(ref clientMsg, mm, sensorAddr, offline, alarm); SetDataResponse(mm, 0x04);
SetDataRequest(mm, 0x04);
break; break;
case 0x15: case 0x15:
Console.WriteLine("传感器复位响应:{0}", clientMsg.Ip); Console.WriteLine("传感器复位响应:{0}", clientMsg.ClientAddr);
SetDataRequest(mm, 0x05);
SetDataResponse(mm, 0x05);
break; break;
case 0x17: case 0x17:
Console.WriteLine("返回传感器列表:{0}", clientMsg.Ip); Console.WriteLine("主机返回传感器列表:{0}", clientMsg.ClientAddr);
if (clientMsg.SensorsEmpty)
{
for (int j = 2; j < mm.Data.Length; j++) for (int j = 2; j < mm.Data.Length; j++)
{ {
sensorAddr = Convert.ToByte((mm.Data[j] + mm.Data[++j] * 256)); sensorAddr = Convert.ToByte((mm.Data[j] + mm.Data[++j] * 256));
if (clientMsg.SensorDict.ContainsKey(sensorAddr)) continue;
SensorState sensor = new(mm.DeviceId, sensorAddr, 0, 0); SensorState sensor = new(mm.DeviceId, sensorAddr, 0, 0);
clientMsg.SensorDict[sensorAddr] = sensor; clientMsg.SensorDict[sensorAddr] = sensor;
} }
RequestSensorsStateActively_08(clientMsg); RequestSensorsState_04(clientMsg);
}
SetDataRequest(mm, 0x07); SetDataResponse(mm, 0x07);
break; break;
case 0x18: case 0x18:
Console.WriteLine("传感器主动状态响应:{0}", clientMsg.Ip); Console.WriteLine("传感器主动状态响应:{0}", clientMsg.ClientAddr);
sensorAddr = mm.Data[0] + mm.Data[1] * 256;
state = mm.Data[2] + mm.Data[3] * 256;
ProcessSensorStateEvent(ref clientMsg, mm, sensorAddr, state);
ResponseHostUploadState_08(clientMsg, mm);
break;
case 0x19:
Console.WriteLine("传感器关闭响应:{0}", clientMsg.ClientAddr);
SetDataResponse(mm, 0x09);
break;
case 0x30:
Console.WriteLine("传感器启动响应:{0}", clientMsg.ClientAddr);
SetDataResponse(mm, 0x20);
break;
SetDataRequest(mm, 0x08); case 0x31:
Console.WriteLine("传感器全部启动响应:{0}", clientMsg.ClientAddr);
SetDataResponse(mm, 0x21);
break;
case 0x34:
Console.WriteLine("主机启动自动上传响应:{0}", clientMsg.ClientAddr);
SetDataResponse(mm, 0x24);
break;
case 0x35:
Console.WriteLine("主机关闭自动上传响应:{0}", clientMsg.ClientAddr);
SetDataResponse(mm, 0x25);
break; break;
} }
} }
@ -252,8 +266,10 @@ public class TcpManager
} }
} }
private void ProcessSensorStateEvent(ref ClientMessage client, DataMessage mm, int sensorAddr, int offline, int alarm) private void ProcessSensorStateEvent(ref ClientMessage client, DataMessage mm, int sensorAddr, int state)
{ {
int offline = state % 2;
int alarm = state / 2 % 2;
if (!client.SensorDict.TryGetValue(sensorAddr, out SensorState? sensor)) if (!client.SensorDict.TryGetValue(sensorAddr, out SensorState? sensor))
{ {
sensor = new(mm.DeviceId, sensorAddr, offline, alarm); sensor = new(mm.DeviceId, sensorAddr, offline, alarm);
@ -269,7 +285,7 @@ public class TcpManager
if (alarm == 1) if (alarm == 1)
{ {
ReportAlarm(sensor.DeviceId, sensorAddr); ReportAlarm(sensor.DeviceId, sensorAddr);
//RequestSensorReset_05(clientMsg, sensorAddr); RequestSensorReset_05(client, sensorAddr);
} }
} }
@ -299,41 +315,24 @@ public class TcpManager
#region Send #region Send
public bool SendMessage(string ip, byte[] bytes) /// <summary>
{ /// 0x10:主机响应0x00登录
if (Server == null || !Server.IsRunning()) return false; /// </summary>
if (!TryGetDevice(ip, out ClientMessage clientMsg)) return false; /// <param name="client"></param>
string cmd = DataMessage.ToHexString(bytes); /// <param name="mm"></param>
DataMessage mm = new(); /// <returns></returns>
mm.Decode(bytes); public bool ResponseHostLogin_10(ClientMessage client, DataMessage mm)
bool flag = Server.SendAsync(clientMsg.Client, bytes);
Console.WriteLine("Send to {0}:{1} => {2}, {3}", ip, clientMsg.Port, cmd, flag);
return flag;
}
public bool SendRequest(ref DataRequest request)
{
if (request.Request == null) return false;
request.Request.FrameNum = FrameNumber;
FrameNumber++;
bool send = SendMessage(request.Request.ReceiveIp, request.Request.Encode());
return send;
}
public bool SendNoRequest(DataMessage msg)
{
msg.FrameNum = FrameNumber;
FrameNumber++;
bool send = SendMessage(msg.ReceiveIp, msg.Encode());
return send;
}
public bool SendResponse(DataMessage msg)
{ {
bool send = SendMessage(msg.ReceiveIp, msg.Encode()); if (!client.IsOnline) return false;
return send; DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x10, 0);
return SendResponse(msg, mm.FrameNum);
} }
/// <summary>
/// 0x01:心跳
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool SendHostHeart_01(ClientMessage client) public bool SendHostHeart_01(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
@ -342,6 +341,12 @@ public class TcpManager
return SendNoRequest(msg); return SendNoRequest(msg);
} }
/// <summary>
/// 0x02:设置传感器地址
/// </summary>
/// <param name="client"></param>
/// <param name="newSensorAddr"></param>
/// <returns></returns>
public bool RequestSensorChange_02(ClientMessage client, int newSensorAddr) public bool RequestSensorChange_02(ClientMessage client, int newSensorAddr)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
@ -351,9 +356,15 @@ public class TcpManager
{ {
Request = msg Request = msg
}; };
return SendRequest(ref request); return SendRequestTry(ref request);
} }
/// <summary>
/// 0x04:请求传感器状态
/// </summary>
/// <param name="client"></param>
/// <param name="sensorAddr"></param>
/// <returns></returns>
public bool RequestSensorState_04(ClientMessage client, int sensorAddr) public bool RequestSensorState_04(ClientMessage client, int sensorAddr)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
@ -364,13 +375,17 @@ public class TcpManager
{ {
Request = msg Request = msg
}; };
return SendRequest(ref request); return SendRequestTry(ref request);
} }
/// <summary>
/// 0x04:请求传感器状态
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool RequestSensorsState_04(ClientMessage client) public bool RequestSensorsState_04(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (client.SensorsEmpty) return false;
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x04, 2); DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x04, 2);
foreach (var item in client.SensorDict.Values) foreach (var item in client.SensorDict.Values)
{ {
@ -380,11 +395,17 @@ public class TcpManager
{ {
Request = msg Request = msg
}; };
SendRequest(ref request); SendRequestTry(ref request);
} }
return true; return true;
} }
/// <summary>
/// 0x05:复位传感器
/// </summary>
/// <param name="client"></param>
/// <param name="sensorAddr"></param>
/// <returns></returns>
public bool RequestSensorReset_05(ClientMessage client, int sensorAddr) public bool RequestSensorReset_05(ClientMessage client, int sensorAddr)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
@ -395,9 +416,14 @@ public class TcpManager
{ {
Request = msg Request = msg
}; };
return SendRequest(ref request); return SendRequestTry(ref request);
} }
/// <summary>
/// 0x07:请求传感器列表
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool RequestSensorList_07(ClientMessage client) public bool RequestSensorList_07(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
@ -406,27 +432,50 @@ public class TcpManager
{ {
Request = msg Request = msg
}; };
return SendRequest(ref request); return SendRequestMust(ref request);
} }
public bool RequestSensorStateActively_08(ClientMessage client, int sensorAddr) /// <summary>
/// 0x08:主机响应0x18主动上传状态
/// </summary>
/// <param name="client"></param>
/// <param name="mm"></param>
/// <returns></returns>
public bool ResponseHostUploadState_08(ClientMessage client, DataMessage mm)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (!client.SensorDict.TryGetValue(sensorAddr, out _)) return false;
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x08, 2); DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x08, 2);
msg.Data = new byte[] { mm.Data[0], mm.Data[1] };
return SendResponse(msg, mm.FrameNum);
}
/// <summary>
/// 0x09:关闭传感器
/// </summary>
/// <param name="client"></param>
/// <param name="sensorAddr"></param>
/// <returns></returns>
public bool RequestSensorTurnOff_09(ClientMessage client, int sensorAddr)
{
if (!client.IsOnline) return false;
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x09, 2);
msg.Data = new byte[] { (byte)(sensorAddr % 256), (byte)(sensorAddr / 256) }; msg.Data = new byte[] { (byte)(sensorAddr % 256), (byte)(sensorAddr / 256) };
DataRequest request = new() DataRequest request = new()
{ {
Request = msg Request = msg
}; };
return SendRequest(ref request); return SendRequestTry(ref request);
} }
public bool RequestSensorsStateActively_08(ClientMessage client) /// <summary>
/// 0x09:关闭传感器
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool RequestSensorsTurnOff_09(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (client.SensorsEmpty) return false; DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x09, 2);
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x08, 2);
foreach (var item in client.SensorDict.Values) foreach (var item in client.SensorDict.Values)
{ {
int sensorAddr = item.Addr; int sensorAddr = item.Addr;
@ -435,42 +484,38 @@ public class TcpManager
{ {
Request = msg Request = msg
}; };
SendRequest(ref request); SendRequestTry(ref request);
} }
return true; return true;
} }
public bool ResponseHostLogin_10(ClientMessage client, DataMessage mm) /// <summary>
{ /// 0x20:启动传感器
if (!client.IsOnline) return false; /// </summary>
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x10, 0); /// <param name="client"></param>
msg.FrameNum = mm.FrameNum; /// <param name="sensorAddr"></param>
return SendResponse(msg); /// <returns></returns>
} public bool RequestSensorTurnOn_20(ClientMessage client, int sensorAddr)
public bool RequestSensorTurnOff_09(ClientMessage client, int sensorAddr)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (client.SensorsEmpty) return false; DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x20, 2);
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x19, 2);
foreach (var item in client.SensorDict.Values)
{
int sensorAddr = item.Addr;
msg.Data = new byte[] { (byte)(sensorAddr % 256), (byte)(sensorAddr / 256) }; msg.Data = new byte[] { (byte)(sensorAddr % 256), (byte)(sensorAddr / 256) };
DataRequest request = new() DataRequest request = new()
{ {
Request = msg Request = msg
}; };
SendRequest(ref request); return SendRequestTry(ref request);
}
return true;
} }
public bool RequestSensorsTurnOff_09(ClientMessage client) /// <summary>
/// 0x20:启动传感器
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool RequestSensorsTurnOn_20(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (client.SensorsEmpty) return false; DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x20, 2);
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x19, 2);
foreach (var item in client.SensorDict.Values) foreach (var item in client.SensorDict.Values)
{ {
int sensorAddr = item.Addr; int sensorAddr = item.Addr;
@ -479,52 +524,57 @@ public class TcpManager
{ {
Request = msg Request = msg
}; };
SendRequest(ref request); SendRequestTry(ref request);
} }
return true; return true;
} }
public bool RequestSensorTurnOn_20(ClientMessage client, int sensorAddr) /// <summary>
/// 0x21:启动全部传感器
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool RequestSensorsTurnOn_21(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (client.SensorsEmpty) return false; DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x21, 0);
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x20, 2);
msg.Data = new byte[] { (byte)(sensorAddr % 256), (byte)(sensorAddr / 256) };
DataRequest request = new() DataRequest request = new()
{ {
Request = msg Request = msg
}; };
return SendRequest(ref request); return SendRequestTry(ref request);
} }
public bool RequestSensorsTurnOn_20(ClientMessage client) /// <summary>
/// 0x24:启动自动上传
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool RequestHostAutoUploadState_24(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (client.SensorsEmpty) return false; DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x24, 0);
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x20, 2);
foreach (var item in client.SensorDict.Values)
{
int sensorAddr = item.Addr;
msg.Data = new byte[] { (byte)(sensorAddr % 256), (byte)(sensorAddr / 256) };
DataRequest request = new() DataRequest request = new()
{ {
Request = msg Request = msg
}; };
SendRequest(ref request); return SendRequestMust(ref request);
}
return true;
} }
public bool RequestSensorsTurnOn_21(ClientMessage client) /// <summary>
/// 0x25:关闭自动上传
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public bool RequestSensorsTurnOn_25(ClientMessage client)
{ {
if (!client.IsOnline) return false; if (!client.IsOnline) return false;
if (client.SensorsEmpty) return false; DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x25, 0);
DataMessage msg = GetSendMessageHead(client.Host.Id, client, 0x21, 0);
DataRequest request = new() DataRequest request = new()
{ {
Request = msg Request = msg
}; };
return SendRequest(ref request); return SendRequestTry(ref request);
} }
#endregion Send #endregion Send
@ -577,13 +627,6 @@ public class TcpManager
return DeviceDict.Remove(clientIp, out _); return DeviceDict.Remove(clientIp, out _);
} }
private bool UpdateDevice(string clientIp, TcpAlarmHost host)
{
if (!DeviceDict.ContainsKey(clientIp)) return false;
DeviceDict[clientIp].Host = host;
return true;
}
public List<ClientMessage> GetDeviceList() public List<ClientMessage> GetDeviceList()
{ {
return DeviceDict.Values.ToList(); return DeviceDict.Values.ToList();
@ -593,36 +636,129 @@ public class TcpManager
#region Set #region Set
private byte FrameNumber { get; set; } = 0; private byte Frame { get; set; } = 0;
private DataMessage GetSendMessageHead(int deviceId, ClientMessage client, byte fun_num, byte datalen) private byte FrameInc
{ get { return (byte)(++Frame % byte.MaxValue); } }
private int SendTryTime { get; set; } = 5;
private int SendTryInterval { get; set; } = 200;
private int ReqWaitTime { get; set; } = 3 * 10;
private int ReqWaitInterval { get; set; } = 100;
private DataMessage GetSendMessageHead(int deviceId, ClientMessage client, byte funNum, byte dataLen)
{ {
DataMessage msg = new() DataMessage msg = new()
{ {
DeviceId = deviceId, DeviceId = deviceId,
SendIp = client.Host.Ip, SendIp = client.LocalIp,
//SendIp = client.Client.Client.LocalEndPoint.ToString().Split(':')[0], SendPort = client.LocalPort.ToInt(),
SendPort = Server.Port, ReceiveIp = client.ClientIp,
ReceiveIp = client.Ip, ReceivePort = client.ClientPort.ToInt(),
ReceivePort = int.Parse(client.Port), FunctionNum = funNum,
FunctionNum = fun_num, DataLen = dataLen
DataLen = datalen
}; };
return msg; return msg;
} }
public void SetDataRequest(DataMessage msg, byte functionNum) private bool SendMessage(string ip, byte[] bytes)
{ {
lock (this) if (Server == null || !Server.IsRunning()) return false;
if (!TryGetDevice(ip, out ClientMessage clientMsg)) return false;
string cmd = DataMessage.ToHexString(bytes);
bool send = false;
for (int i = 0; i < SendTryTime; i++)
{ {
//for (int i = 0; i < Reqlist.Count; i++) send = Server.SendAsync(clientMsg.Client, bytes);
//{ if (send) break;
// if (Reqlist[i].Request.FunctionNum == functionNum && Reqlist[i].Request.FrameNum == msg.FrameNum) Thread.Sleep(SendTryInterval);
// {
// Reqlist[i].Responce = msg;
// }
//}
} }
Console.WriteLine("Send to {0}:{1} => {2}, send:{3}", clientMsg.ClientIp, clientMsg.ClientPort, cmd, send);
return send;
}
private bool SendRequestTry(ref DataRequest request)
{
if (request.Request == null) return false;
request.Request.FrameNum = FrameInc;
bool send = SendMessage(request.Request.ReceiveIp, request.Request.Encode());
if (!send) return false;
bool respond = false;
SetDataRequest(request);
for (int i = 0; i < ReqWaitTime; i++)
{
respond = IsResponse(request);
if (respond) break;
Thread.Sleep(ReqWaitInterval);
}
RemoveDataRequest(request);
return respond;
}
private bool SendRequestMust(ref DataRequest request)
{
if (request.Request == null) return false;
request.Request.FrameNum = FrameInc;
bool send, respond = false;
do
{
send = SendMessage(request.Request.ReceiveIp, request.Request.Encode());
if (!send) continue;
SetDataRequest(request);
for (int i = 0; i < ReqWaitTime; i++)
{
respond = IsResponse(request);
if (respond) break;
Thread.Sleep(ReqWaitInterval);
}
} while (!send && !respond);
RemoveDataRequest(request);
return true;
}
private bool SendNoRequest(DataMessage request)
{
request.FrameNum = FrameInc;
bool send = SendMessage(request.ReceiveIp, request.Encode());
return send;
}
private bool SendResponse(DataMessage request, byte frameNum)
{
request.FrameNum = frameNum;
bool send = SendMessage(request.ReceiveIp, request.Encode());
return send;
}
private ConcurrentDictionary<string, DataRequest> DataRequestDict { get; } = new();
private void SetDataRequest(DataRequest request)
{
string key = $"{request.Request.FunctionNum}-{request.Request.FrameNum}";
DataRequestDict[key] = request;
}
private void SetDataResponse(DataMessage msg, byte funcNum)
{
string key = $"{funcNum}-{msg.FrameNum}";
DataRequest? item = DataRequestDict[key];
if (item != null) item.Responce = msg;
}
private void RemoveDataRequest(DataRequest request)
{
string key = $"{request.Request.FunctionNum}-{request.Request.FrameNum}";
DataRequestDict.Remove(key);
}
private bool IsResponse(DataRequest request)
{
string key = $"{request.Request.FunctionNum}-{request.Request.FrameNum}";
DataRequest? item = DataRequestDict[key];
return item != null && item.Responce != null;
} }
#endregion Set #endregion Set

4
JiLinApp/Components/CameraRealPlay.xaml.cs

@ -34,7 +34,7 @@ public partial class CameraRealPlay : Window
private void Init() private void Init()
{ {
// 初始化预置位 // 初始化预置位
for (int i = 1; i <= 8; i++) for (int i = 1; i <= 10; i++)
{ {
PresetId.Items.Add(new ComboBoxItem { Content = i }); PresetId.Items.Add(new ComboBoxItem { Content = i });
} }
@ -80,7 +80,7 @@ public partial class CameraRealPlay : Window
while (!IsPlaying()) while (!IsPlaying())
{ {
StartPlay(); StartPlay();
Thread.Sleep(100); Thread.Sleep(200);
} }
} }

22
JiLinApp/Pages/FenceServerManage/Main.xaml.cs

@ -119,18 +119,6 @@ public partial class Main : UserControl
defenceState = item.DefenceState defenceState = item.DefenceState
}); });
} }
//int[] dsArr = { 0, 1, 2, 4, 8, 9 };
//for (int i = 1; i <= 6; i++)
//{
// respDeviceList.Add(new
// {
// id = i,
// //groupId = item.GroupId,
// //userId = item.UserId,
// onlineState = i % 2,
// defenceState = dsArr[(i - 1) % 6]
// });
//}
AlarmService.SendDevices(DeviceType.Fence, respDeviceList); AlarmService.SendDevices(DeviceType.Fence, respDeviceList);
} }
@ -149,16 +137,6 @@ public partial class Main : UserControl
type = item.Type, type = item.Type,
}); });
} }
//for (int i = 1; i <= 7; i++)
//{
// respSensorList.Add(new
// {
// id = i,
// deviceId = deviceId,
// state = (i - 1) % 7,
// type = 0,
// });
//}
AlarmService.SendSensors(DeviceType.Fence, deviceId, respSensorList); AlarmService.SendSensors(DeviceType.Fence, deviceId, respSensorList);
} }

1
JiLinApp/Pages/PtzManage/Main.xaml

@ -81,6 +81,7 @@
<StackPanel> <StackPanel>
<ComboBox Name="CameraIp" materialDesign:HintAssist.Hint="相机Ip" Width="200" SelectedIndex="0" Style="{StaticResource MaterialDesignOutlinedComboBox}"> <ComboBox Name="CameraIp" materialDesign:HintAssist.Hint="相机Ip" Width="200" SelectedIndex="0" Style="{StaticResource MaterialDesignOutlinedComboBox}">
</ComboBox> </ComboBox>
<Button Name="ShowLiveVideoBtn" Content="实时视频" Width="120" Margin="0 10 0 0" Click="ShowLiveVideoBtn_Click" Style="{StaticResource MaterialDesignRaisedLightButton}" />
</StackPanel> </StackPanel>
</GroupBox> </GroupBox>
</Grid> </Grid>

54
JiLinApp/Pages/PtzManage/Main.xaml.cs

@ -83,7 +83,7 @@ public partial class Main : UserControl
CameraId.Items.Add(new ComboBoxItem { Content = i }); CameraId.Items.Add(new ComboBoxItem { Content = i });
} }
for (int i = 1; i <= 8; i++) for (int i = 1; i <= 10; i++)
{ {
PresetId.Items.Add(new ComboBoxItem { Content = i }); PresetId.Items.Add(new ComboBoxItem { Content = i });
} }
@ -256,6 +256,12 @@ public partial class Main : UserControl
} }
} }
private void ShowLiveVideoBtn_Click(object sender, RoutedEventArgs e)
{
string cameraIp = CameraIp.Text.Trim();
ShowLiveVideo(cameraIp);
}
private void ControlType_SelectionChanged(object sender, SelectionChangedEventArgs e) private void ControlType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
if (CameraId == null || CameraIp == null) return; if (CameraId == null || CameraIp == null) return;
@ -296,16 +302,19 @@ public partial class Main : UserControl
case PtzControlType.DCamera: case PtzControlType.DCamera:
CameraId.IsEnabled = true; CameraId.IsEnabled = true;
CameraIp.IsEnabled = false; CameraIp.IsEnabled = false;
ShowLiveVideoBtn.IsEnabled = false;
break; break;
case PtzControlType.CameraSdk: case PtzControlType.CameraSdk:
CameraId.IsEnabled = false; CameraId.IsEnabled = false;
CameraIp.IsEnabled = true; CameraIp.IsEnabled = true;
ShowLiveVideoBtn.IsEnabled = true;
break; break;
default: default:
CameraId.IsEnabled = false; CameraId.IsEnabled = false;
CameraIp.IsEnabled = false; CameraIp.IsEnabled = false;
ShowLiveVideoBtn.IsEnabled = false;
break; break;
} }
} }
@ -343,30 +352,22 @@ public partial class Main : UserControl
public void ShowLiveVideo(string cameraIp) public void ShowLiveVideo(string cameraIp)
{ {
CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk); CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK sdk);
if (cameraSdk == null) return; ShowLiveVideo(sdk);
RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay);
if (realPlay == null || realPlay.IsClosed)
{
realPlay = new(cameraSdk);
realPlay.Owner = Window.GetWindow(this);
RealPlayDict[cameraIp] = realPlay;
}
realPlay.Show();
realPlay.HideMinButton();
realPlay.StartPlay();
} }
public void ShowLiveVideo(ICameraSDK cameraSdk) public void ShowLiveVideo(ICameraSDK sdk)
{ {
if (cameraSdk == null) return; if (sdk == null) { LogUnit.Error(this, $"CameraSdk(cameraIp:{sdk.CameraInfo.Ip}) not found."); return; }
string cameraIp = cameraSdk.CameraInfo.Ip; if (!sdk.ConnectSuccess()) { LogUnit.Error(this, $"CameraSdk(cameraIp:{sdk.CameraInfo.Ip}) connect failure."); return; }
string cameraIp = sdk.CameraInfo.Ip;
RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay); RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay);
if (realPlay == null || realPlay.IsClosed) if (realPlay == null || realPlay.IsClosed)
{ {
realPlay = new(cameraSdk); realPlay = new(sdk);
realPlay.Owner = Window.GetWindow(this); realPlay.Owner = Window.GetWindow(this);
realPlay.HideMinButton(); realPlay.HideMinButton();
realPlay.Title += $"({sdk.CameraInfo.Name})";
RealPlayDict[cameraIp] = realPlay; RealPlayDict[cameraIp] = realPlay;
} }
realPlay.Show(); realPlay.Show();
@ -381,27 +382,31 @@ public partial class Main : UserControl
{ {
List<CameraInfo> cameraList = MilitaryService.GetCameraList(); List<CameraInfo> cameraList = MilitaryService.GetCameraList();
CameraLinkageList = MilitaryService.GetCameraLinkageList(); CameraLinkageList = MilitaryService.GetCameraLinkageList();
//List<CameraInfo> cameraList = new();
//CameraLinkageList = new();
TaskUtil.RunCatch(() => Dispatcher.Invoke(() => LoadCameraSdkDict(cameraList))); TaskUtil.RunCatch(() => Dispatcher.Invoke(() => LoadCameraSdkDict(cameraList)));
} }
private void LoadCameraSdkDict(List<CameraInfo> cameraList) private void LoadCameraSdkDict(List<CameraInfo> cameraList)
{ {
CameraSdkDict.Clear(); CameraSdkDict.Clear();
int tryTime = 5, tryInterval = 500;
for (int i = 0; i < cameraList.Count; i++) for (int i = 0; i < cameraList.Count; i++)
{ {
CameraInfo info = cameraList[i]; CameraInfo info = cameraList[i];
string ip = info.Ip; string ip = info.Ip;
if (CameraSdkDict.ContainsKey(ip)) continue; if (CameraSdkDict.ContainsKey(ip)) continue;
CameraSdkDict[ip] = null; ICameraSDK sdk = CameraFactory.BuildCameraSdk(info);
CameraSdkDict[ip] = sdk;
CameraIp.Items.Add(new ComboBoxItem { Content = ip }); CameraIp.Items.Add(new ComboBoxItem { Content = ip });
TaskUtil.RunCatch(() => TaskUtil.RunCatch(() =>
{ {
ICameraSDK sdk = CameraFactory.BuildCameraSdk(info); bool flag = false;
bool ret = sdk.Init(); for (int i = 0; i < tryTime; i++)
if (!ret) return; {
CameraSdkDict[ip] = sdk; flag = sdk.Init();
if (flag) break;
Thread.Sleep(tryInterval);
}
}); });
} }
} }
@ -429,6 +434,7 @@ public partial class Main : UserControl
{ {
foreach (var item in CameraSdkDict.Values) foreach (var item in CameraSdkDict.Values)
{ {
if (item == null) continue;
if (cameraId.Equals(item.CameraInfo.Id)) return item; if (cameraId.Equals(item.CameraInfo.Id)) return item;
} }
return null; return null;

9
JiLinApp/Pages/PtzManage/MainViewModel.cs

@ -1,4 +1,5 @@
using JiLinApp.Biz.TransmitAlarm; using EC.Util.Common;
using JiLinApp.Biz.TransmitAlarm;
using JiLinApp.Docking.FenceAlarm; using JiLinApp.Docking.FenceAlarm;
using JiLinApp.Docking.VibrateAlarm; using JiLinApp.Docking.VibrateAlarm;
using JiLinApp.Mvvm; using JiLinApp.Mvvm;
@ -33,13 +34,19 @@ public class MainViewModel : ViewModelBase
internal void VibrateTcpSendAlarm(TcpAlarmHostMessage msg) internal void VibrateTcpSendAlarm(TcpAlarmHostMessage msg)
{ {
AlarmMessage alarm = msg.ToAlarmMessage(); AlarmMessage alarm = msg.ToAlarmMessage();
TaskUtil.RunCatch(() =>
{
View.HandleAlarmInvoke(alarm); View.HandleAlarmInvoke(alarm);
});
} }
internal void FenceUdpSendAlarm(UdpAlarmHostMessage msg) internal void FenceUdpSendAlarm(UdpAlarmHostMessage msg)
{ {
AlarmMessage alarm = msg.ToAlarmMessage(); AlarmMessage alarm = msg.ToAlarmMessage();
TaskUtil.RunCatch(() =>
{
View.HandleAlarmInvoke(alarm); View.HandleAlarmInvoke(alarm);
});
} }
#endregion InvokeEvent #endregion InvokeEvent

6
JiLinApp/config/config.json

@ -22,11 +22,11 @@
] ]
}, },
"military": { "military": {
"url": "http://192.168.1.119:8080/military", "url": "http://192.168.1.181:8081/military",
"username": "admin", "username": "admin",
"password": "123456", "password": "123456",
"requestRetryTime": "5", "requestTryTime": "5",
"requestRetryInterval": "200" "requestTryInterval": "200"
}, },
"alarmPlatform": { "alarmPlatform": {
"realPlay": true, "realPlay": true,

Loading…
Cancel
Save