Browse Source

[feat] 调用 Military Api

master
fajiao 1 year ago
parent
commit
10897922d8
  1. 2
      EC.Util/CameraSDK/Common/CameraException.cs
  2. 16
      EC.Util/CameraSDK/Common/CameraFactory.cs
  3. 59
      EC.Util/CameraSDK/Common/CameraStruct.cs
  4. 4
      EC.Util/CameraSDK/Common/ICameraSDK.cs
  5. 4
      EC.Util/CameraSDK/DaHua/DaHuaSDK.cs
  6. 8
      EC.Util/CameraSDK/HiK/HiKOriSDK.cs
  7. 4
      EC.Util/CameraSDK/HiK/HiKSDK.cs
  8. 4
      EC.Util/CameraSDK/YuShi/YuShiSDK.cs
  9. 62
      EC.Util/Common/DateUnit.cs
  10. 46
      EC.Util/Common/FileUnit.cs
  11. 27
      EC.Util/Common/LogUnit.cs
  12. 9
      EC.Util/Common/TaskUtil.cs
  13. 176
      EC.Util/Common/VerifyUtil.cs
  14. 16
      EC.Util/Net/APICallBack.cs
  15. 42
      EC.Util/Net/HttpServer.cs
  16. 98
      EC.Util/Net/NetUnit.cs
  17. 2
      EC.Util/Zmq/ZmqUtil.cs
  18. 2
      JiLinApp.Biz/TransmitAlarm/Common/Config.cs
  19. 2
      JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessage.cs
  20. 4
      JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessageHelper.cs
  21. 61
      JiLinApp.Biz/TransmitAlarm/Service/AlarmMqttService.cs
  22. 3
      JiLinApp.Biz/TransmitAlarm/Service/AlarmZmqService.cs
  23. 3
      JiLinApp.Docking/Alarm/AlarmCodeHelper.cs
  24. 8
      JiLinApp.Docking/FenceAlarm/Service/UdpServer.cs
  25. 4
      JiLinApp.Docking/JiLinApp.Docking.csproj
  26. 14
      JiLinApp.Docking/Military/Config.cs
  27. 18
      JiLinApp.Docking/Military/Entity/CameraLinkageInfo.cs
  28. 158
      JiLinApp.Docking/Military/MilitaryService.cs
  29. 2
      JiLinApp.Docking/Ptz/PtzCmd.cs
  30. 4
      JiLinApp.Docking/VibrateAlarm/Entity/ClientMessage.cs
  31. 91
      JiLinApp.Docking/VibrateAlarm/Service/AsyncTcpServer.cs
  32. 7
      JiLinApp.Docking/VibrateAlarm/Service/TcpManager.cs
  33. 5
      JiLinApp.sln
  34. 3
      JiLinApp/App.xaml.cs
  35. 19
      JiLinApp/Components/CameraRealPlay.xaml
  36. 40
      JiLinApp/Components/CameraRealPlay.xaml.cs
  37. 10
      JiLinApp/Core/Config.cs
  38. 17
      JiLinApp/Core/Global.cs
  39. 4
      JiLinApp/JiLinApp.csproj
  40. 3
      JiLinApp/Pages/PtzManage/Main.xaml
  41. 165
      JiLinApp/Pages/PtzManage/Main.xaml.cs
  42. 10
      JiLinApp/Pages/PtzManage/MainViewModel.cs
  43. 30
      JiLinApp/config/config.json

2
EC.Util/CameraSDK/Common/CameraException.cs

@ -30,7 +30,7 @@ public class CameraException : Exception
public override string? ToString() public override string? ToString()
{ {
StringBuilder builder = new(); StringBuilder builder = new();
builder.Append($"Ip:{CameraInfo?.Ip}, Manufactor:{CameraInfo?.GetManufactor}, Code:{Code}"); builder.Append($"Ip:{CameraInfo?.Ip}, Manufactor:{CameraInfo?.Manufactor}, Code:{Code}");
if (!string.IsNullOrEmpty(Msg)) builder.Append($", Msg:{Msg}"); if (!string.IsNullOrEmpty(Msg)) builder.Append($", Msg:{Msg}");
return builder.ToString(); return builder.ToString();
} }

16
EC.Util/CameraSDK/Common/CameraFactory.cs

@ -0,0 +1,16 @@
namespace EC.Util.CameraSDK;
public class CameraFactory
{
public static ICameraSDK BuildCameraSdk(CameraInfo info)
{
ICameraSDK sdk = (info.Manufactor) switch
{
CameraManufactor.HiK => new HiKSDK(info),
CameraManufactor.DaHua => new DaHuaSDK(info),
CameraManufactor.YuShi => new YuShiSDK(info),
_ => throw new NotSupportedException(),
};
return sdk;
}
}

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

@ -5,20 +5,17 @@
/// </summary> /// </summary>
public class CameraInfo public class CameraInfo
{ {
#region Attr #region Fields
/// <summary> /// <summary>
/// 相机厂商 /// id
/// </summary> /// </summary>
public int Manufactor { get; set; } public string Id { get; set; } = string.Empty;
public CameraManufactor GetManufactor /// <summary>
{ /// 相机厂商
get /// </summary>
{ public CameraManufactor Manufactor { get; set; }
return (CameraManufactor)Manufactor;
}
}
/// <summary> /// <summary>
/// ip 地址 /// ip 地址
@ -40,19 +37,43 @@ public class CameraInfo
/// </summary> /// </summary>
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
#endregion Attr #endregion Fields
public static CameraInfo New(int manufactor, string ip, int port, string userName, string password) public static CameraInfo New(CameraManufactor manufactor, string ip, int port, string username, string password)
{ {
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = userName, Password = password }; CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = username, Password = password };
if (port <= 0) throw new Exception("Camera manufactor not support."); if (port <= 0) throw new Exception("Camera manufactor not support.");
return info; return info;
} }
public static CameraInfo New(int manufactor, string ip, string userName, string password) public static CameraInfo New(CameraManufactor manufactor, string ip, string username, string password)
{ {
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, UserName = userName, Password = password }; CameraInfo info = new() { Manufactor = manufactor, Ip = ip, UserName = username, Password = password };
int port = (CameraManufactor)manufactor switch int port = manufactor switch
{
CameraManufactor.HiK => (int)CameraPort.HiK,
CameraManufactor.DaHua => (int)CameraPort.DaHua,
CameraManufactor.YuShi => (int)CameraPort.YuShi,
_ => -1,
};
if (port <= 0) throw new Exception("Camera manufactor not support.");
info.Port = port;
return info;
}
public static CameraInfo New(int manufactor, string ip, int port, string username, string password)
{
CameraManufactor cm = (CameraManufactor)manufactor;
CameraInfo info = new() { Manufactor = cm, Ip = ip, Port = port, UserName = username, Password = password };
if (port <= 0) throw new Exception("Camera manufactor not support.");
return info;
}
public static CameraInfo New(int manufactor, string ip, string username, string password)
{
CameraManufactor cm = (CameraManufactor)manufactor;
CameraInfo info = new() { Manufactor = cm, Ip = ip, UserName = username, Password = password };
int port = cm switch
{ {
CameraManufactor.HiK => (int)CameraPort.HiK, CameraManufactor.HiK => (int)CameraPort.HiK,
CameraManufactor.DaHua => (int)CameraPort.DaHua, CameraManufactor.DaHua => (int)CameraPort.DaHua,
@ -90,13 +111,15 @@ public enum CameraPort : int
/// </summary> /// </summary>
public class PtzInfo public class PtzInfo
{ {
#region Attr #region Fields
public double Pan { get; set; } public double Pan { get; set; }
public double Tilt { get; set; } public double Tilt { get; set; }
public double Zoom { get; set; } public double Zoom { get; set; }
#endregion Attr #endregion Fields
public PtzInfo(double pan, double tilt, double zoom) public PtzInfo(double pan, double tilt, double zoom)
{ {

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

@ -2,11 +2,11 @@
public abstract class ICameraSDK public abstract class ICameraSDK
{ {
#region Attr #region Fields
public CameraInfo CameraInfo { get; } public CameraInfo CameraInfo { get; }
#endregion Attr #endregion Fields
public ICameraSDK(CameraInfo cameraInfo) public ICameraSDK(CameraInfo cameraInfo)
{ {

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

@ -4,13 +4,13 @@ namespace EC.Util.CameraSDK;
public class DaHuaSDK : ICameraSDK public class DaHuaSDK : ICameraSDK
{ {
#region Attr #region Fields
private IntPtr LoginId { get; set; } = IntPtr.Zero; private IntPtr LoginId { get; set; } = IntPtr.Zero;
private IntPtr RealplayHandle { get; set; } = IntPtr.Zero; private IntPtr RealplayHandle { get; set; } = IntPtr.Zero;
#endregion Attr #endregion Fields
public DaHuaSDK(CameraInfo cameraInfo) : base(cameraInfo) public DaHuaSDK(CameraInfo cameraInfo) : base(cameraInfo)
{ {

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

@ -209,7 +209,7 @@ public static class HiKOriSDK
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct NET_DVR_PREVIEWINFO public struct NET_DVR_PREVIEWINFO
{ {
public Int32 lChannel; //通道号 public int lChannel; //通道号
public uint dwStreamType; // 码流类型,0-主码流,1-子码流,2-码流3,3-码流4 等以此类推 public uint dwStreamType; // 码流类型,0-主码流,1-子码流,2-码流3,3-码流4 等以此类推
public uint dwLinkMode; // 0:TCP方式,1:UDP方式,2:多播方式,3 - RTP方式,4-RTP/RTSP,5-RSTP/HTTP public uint dwLinkMode; // 0:TCP方式,1:UDP方式,2:多播方式,3 - RTP方式,4-RTP/RTSP,5-RSTP/HTTP
public IntPtr hPlayWnd; //播放窗口的句柄,为NULL表示不播放图象 public IntPtr hPlayWnd; //播放窗口的句柄,为NULL表示不播放图象
@ -304,10 +304,10 @@ public static class HiKOriSDK
**********************************************************/ **********************************************************/
public delegate void REALDATACALLBACK( public delegate void REALDATACALLBACK(
Int32 lRealHandle, int lRealHandle,
UInt32 dwDataType, uint dwDataType,
IntPtr pBuffer, IntPtr pBuffer,
UInt32 dwBufSize, uint dwBufSize,
IntPtr pUser IntPtr pUser
); );

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

@ -4,13 +4,13 @@ namespace EC.Util.CameraSDK;
public class HiKSDK : ICameraSDK public class HiKSDK : ICameraSDK
{ {
#region Attr #region Fields
private int LoginId { get; set; } = -1; private int LoginId { get; set; } = -1;
private int RealplayHandle { get; set; } = -1; private int RealplayHandle { get; set; } = -1;
#endregion Attr #endregion Fields
public HiKSDK(CameraInfo cameraInfo) : base(cameraInfo) public HiKSDK(CameraInfo cameraInfo) : base(cameraInfo)
{ {

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

@ -2,13 +2,13 @@
public class YuShiSDK : ICameraSDK public class YuShiSDK : ICameraSDK
{ {
#region Attr #region Fields
private IntPtr LoginId { get; set; } = IntPtr.Zero; private IntPtr LoginId { get; set; } = IntPtr.Zero;
private IntPtr RealplayHandle { get; set; } = IntPtr.Zero; private IntPtr RealplayHandle { get; set; } = IntPtr.Zero;
#endregion Attr #endregion Fields
public YuShiSDK(CameraInfo cameraInfo) : base(cameraInfo) public YuShiSDK(CameraInfo cameraInfo) : base(cameraInfo)
{ {

62
EC.Util/Common/DateUnit.cs

@ -1,9 +1,4 @@
using System; /*******************************************************/
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*******************************************************/
/*Project: /*Project:
Module : Module :
Description : Description :
@ -13,15 +8,13 @@ Update : 2015-12-31
TODO : */ TODO : */
/*******************************************************/ /*******************************************************/
namespace EC.Util.Common;
namespace System
{
/// <summary> /// <summary>
/// 日期时间操作单元 /// 日期时间操作单元
/// </summary> /// </summary>
public partial class DateUnit public partial class DateUnit
{ {
/// <summary> /// <summary>
/// 1970-1-1 /// 1970-1-1
/// </summary> /// </summary>
@ -37,6 +30,7 @@ namespace System
{ {
return DateTime.Now; return DateTime.Now;
} }
/// <summary> /// <summary>
/// 格式化后的当前日期 /// 格式化后的当前日期
/// </summary> /// </summary>
@ -44,6 +38,7 @@ namespace System
{ {
return FormatDate(DefDate()); return FormatDate(DefDate());
} }
/// <summary> /// <summary>
///格式化当前时间 ///格式化当前时间
/// </summary> /// </summary>
@ -59,6 +54,7 @@ namespace System
{ {
return DefDate().ToString("yyyy-MM-01"); return DefDate().ToString("yyyy-MM-01");
} }
/// <summary> /// <summary>
/// 字符串格式->格式化为当前日期 /// 字符串格式->格式化为当前日期
/// </summary> /// </summary>
@ -74,9 +70,8 @@ namespace System
} }
return FormatDate(nowDate); return FormatDate(nowDate);
} }
/// <summary> /// <summary>
/// 格式化为 日期格式yyyy-MM-dd /// 格式化为 日期格式yyyy-MM-dd
/// </summary> /// </summary>
@ -84,7 +79,6 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static string FormatDate(DateTime Indate) public static string FormatDate(DateTime Indate)
{ {
if (!Indate.Equals(null)) if (!Indate.Equals(null))
{ {
return Indate.ToString("yyyy-MM-dd"); return Indate.ToString("yyyy-MM-dd");
@ -93,8 +87,8 @@ namespace System
{ {
return DefFormatDate(); return DefFormatDate();
} }
} }
/// <summary> /// <summary>
/// 格式化为 日期时间格式yyyy-MM-dd HH:mm:ss /// 格式化为 日期时间格式yyyy-MM-dd HH:mm:ss
/// </summary> /// </summary>
@ -102,7 +96,6 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static string FormatDateTime(DateTime Indate) public static string FormatDateTime(DateTime Indate)
{ {
if (!Indate.Equals(null)) if (!Indate.Equals(null))
{ {
return Indate.ToString("yyyy-MM-dd HH:mm:ss"); return Indate.ToString("yyyy-MM-dd HH:mm:ss");
@ -111,8 +104,8 @@ namespace System
{ {
return DefFormatDate(); return DefFormatDate();
} }
} }
/// <summary> /// <summary>
/// 格式化时间 毫秒 /// 格式化时间 毫秒
/// </summary> /// </summary>
@ -120,7 +113,6 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static string FormatDateTimefff(DateTime Indate) public static string FormatDateTimefff(DateTime Indate)
{ {
if (!Indate.Equals(null)) if (!Indate.Equals(null))
{ {
return Indate.ToString("yyyy-MM-dd HH:mm:ss fff"); return Indate.ToString("yyyy-MM-dd HH:mm:ss fff");
@ -129,10 +121,8 @@ namespace System
{ {
return DefFormatDate(); return DefFormatDate();
} }
} }
#region 时间函数 #region 时间函数
/// <summary> /// <summary>
@ -151,12 +141,10 @@ namespace System
catch catch
{ {
result = false; result = false;
} }
return result; return result;
} }
/// <summary> /// <summary>
/// 将字符串转化成日期,如果输入的字符串不是日期时,则返回1970-1-1 /// 将字符串转化成日期,如果输入的字符串不是日期时,则返回1970-1-1
/// </summary> /// </summary>
@ -209,17 +197,14 @@ namespace System
{ {
if (!obj.Equals(null)) if (!obj.Equals(null))
{ {
return (DateTime)obj; return (DateTime)obj;
} }
else else
{ {
return DefDate(); return DefDate();
} }
} }
/// <summary> /// <summary>
/// 20070101-->2007-01-01 /// 20070101-->2007-01-01
/// </summary> /// </summary>
@ -241,12 +226,9 @@ namespace System
{ {
return DefFormatDate(); return DefFormatDate();
} }
} }
#endregion 时间函数
#endregion
#region 周计算 #region 周计算
@ -257,13 +239,10 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static string DayOfWeek(DateTime curDay) public static string DayOfWeek(DateTime curDay)
{ {
string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
string week = weekdays[Convert.ToInt32(curDay.DayOfWeek)]; string week = weekdays[Convert.ToInt32(curDay.DayOfWeek)];
return week; return week;
} }
/// <summary> /// <summary>
@ -273,7 +252,6 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static int WeekOfYear(DateTime curDay) public static int WeekOfYear(DateTime curDay)
{ {
int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "-" + "1-1").DayOfWeek); int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "-" + "1-1").DayOfWeek);
int days = curDay.DayOfYear; int days = curDay.DayOfYear;
@ -294,6 +272,7 @@ namespace System
} }
#region 返回某年某月最后一天 #region 返回某年某月最后一天
/// <summary> /// <summary>
/// 返回某年某月最后一天 /// 返回某年某月最后一天
/// </summary> /// </summary>
@ -306,13 +285,13 @@ namespace System
int Day = lastDay.Day; int Day = lastDay.Day;
return Day; return Day;
} }
#endregion
#endregion #endregion 返回某年某月最后一天
#endregion 周计算
#region 返回时间差 #region 返回时间差
/// <summary> /// <summary>
/// 返回时间差 秒 /// 返回时间差 秒
/// </summary> /// </summary>
@ -321,7 +300,6 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static double DateDiffSeconds(DateTime begDateTime, DateTime endDateTime) public static double DateDiffSeconds(DateTime begDateTime, DateTime endDateTime)
{ {
try try
{ {
TimeSpan ts = endDateTime - begDateTime; TimeSpan ts = endDateTime - begDateTime;
@ -332,6 +310,7 @@ namespace System
return 0; return 0;
} }
} }
/// <summary> /// <summary>
/// 返回时间差 分钟 /// 返回时间差 分钟
/// </summary> /// </summary>
@ -340,7 +319,6 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static double DateDiffMinutes(DateTime begDateTime, DateTime endDateTime) public static double DateDiffMinutes(DateTime begDateTime, DateTime endDateTime)
{ {
try try
{ {
TimeSpan ts = endDateTime - begDateTime; TimeSpan ts = endDateTime - begDateTime;
@ -351,9 +329,9 @@ namespace System
return 0; return 0;
} }
} }
public static double DateDiffHours(DateTime begDateTime, DateTime endDateTime) public static double DateDiffHours(DateTime begDateTime, DateTime endDateTime)
{ {
try try
{ {
TimeSpan ts = endDateTime - begDateTime; TimeSpan ts = endDateTime - begDateTime;
@ -364,9 +342,9 @@ namespace System
return 0; return 0;
} }
} }
public static double DateDifDays(DateTime begDateTime, DateTime endDateTime) public static double DateDifDays(DateTime begDateTime, DateTime endDateTime)
{ {
try try
{ {
TimeSpan ts = endDateTime - begDateTime; TimeSpan ts = endDateTime - begDateTime;
@ -377,7 +355,8 @@ namespace System
return 0; return 0;
} }
} }
#endregion
#endregion 返回时间差
/// <summary> /// <summary>
/// Unix时间戳 /// Unix时间戳
@ -390,6 +369,7 @@ namespace System
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t; return t;
} }
/// <summary> /// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式 /// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary> /// </summary>
@ -401,6 +381,7 @@ namespace System
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t; return t;
} }
/// <summary> /// <summary>
/// 时间戳转为C#格式时间 /// 时间戳转为C#格式时间
/// </summary> /// </summary>
@ -424,6 +405,7 @@ namespace System
DateTime dtStart = UnixTimeToDateTime(timeStamp); DateTime dtStart = UnixTimeToDateTime(timeStamp);
return FormatDate(dtStart); return FormatDate(dtStart);
} }
/// <summary> /// <summary>
/// Unix时间戳 时间格式化 为时间 /// Unix时间戳 时间格式化 为时间
/// </summary> /// </summary>
@ -434,6 +416,4 @@ namespace System
DateTime dtStart = UnixTimeToDateTime(timeStamp); DateTime dtStart = UnixTimeToDateTime(timeStamp);
return FormatDateTime(dtStart); return FormatDateTime(dtStart);
} }
}
} }

46
EC.Util/Common/FileUnit.cs

@ -1,10 +1,4 @@
using System; /*******************************************************/
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
/*******************************************************/
/*Project: /*Project:
Module : Module :
Description : Description :
@ -13,14 +7,16 @@ Create : Lxc
Update : 2014-12-31 Update : 2014-12-31
TODO : */ TODO : */
/*******************************************************/ /*******************************************************/
namespace System
{ namespace EC.Util.Common;
/// <summary> /// <summary>
/// 文件操作单元 /// 文件操作单元
/// </summary> /// </summary>
public partial class FileUnit public partial class FileUnit
{ {
static readonly string AppFilepatch = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; private static readonly string AppFilepatch = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
/// <summary> /// <summary>
/// 创建目录 /// 创建目录
/// </summary> /// </summary>
@ -42,12 +38,14 @@ namespace System
} }
return true; return true;
} }
//删除文件名 获取路径 //删除文件名 获取路径
public static string GetDirectory(string fullPath) public static string GetDirectory(string fullPath)
{ {
return Path.GetDirectoryName(fullPath); return Path.GetDirectoryName(fullPath);
//return allFileName.Substring(0, allFileName.LastIndexOf('\\')); //return allFileName.Substring(0, allFileName.LastIndexOf('\\'));
} }
/// <summary> /// <summary>
/// 得到文件名称 /// 得到文件名称
/// </summary> /// </summary>
@ -57,6 +55,7 @@ namespace System
{ {
return Path.GetFileName(fullPath); return Path.GetFileName(fullPath);
} }
/// <summary> /// <summary>
/// 得到扩展名 /// 得到扩展名
/// </summary> /// </summary>
@ -66,6 +65,7 @@ namespace System
{ {
return Path.GetExtension(fullPath); return Path.GetExtension(fullPath);
} }
/// <summary> /// <summary>
/// 得到名称没有扩展名 /// 得到名称没有扩展名
/// </summary> /// </summary>
@ -75,6 +75,7 @@ namespace System
{ {
return Path.GetFileNameWithoutExtension(fullPath); return Path.GetFileNameWithoutExtension(fullPath);
} }
/// <summary> /// <summary>
/// 复制文件 /// 复制文件
/// </summary> /// </summary>
@ -108,9 +109,8 @@ namespace System
{ {
return ex.Message; return ex.Message;
} }
} }
/// <summary> /// <summary>
/// 得到路径 没有扩展名 /// 得到路径 没有扩展名
/// </summary> /// </summary>
@ -123,6 +123,7 @@ namespace System
string disPatch = rtpDir + "\\" + disFileName;// +".docx"; string disPatch = rtpDir + "\\" + disFileName;// +".docx";
return disPatch; return disPatch;
} }
/// <summary> /// <summary>
/// 读取文本 /// 读取文本
/// </summary> /// </summary>
@ -130,7 +131,6 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static string ReadtxtFile(string filename) public static string ReadtxtFile(string filename)
{ {
try try
{ {
if (File.Exists(filename)) if (File.Exists(filename))
@ -143,14 +143,12 @@ namespace System
} }
} }
else LogUnit.Error(typeof(FileUnit), "no exists " + filename); else LogUnit.Error(typeof(FileUnit), "no exists " + filename);
} }
catch (Exception e) catch (Exception e)
{ {
LogUnit.Error(typeof(FileUnit), e.ToString()); LogUnit.Error(typeof(FileUnit), e.ToString());
} }
return ""; return "";
} }
/// <summary> /// <summary>
@ -195,12 +193,9 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static bool WritetxtFileLine(string filepatch, string filename, List<string> txtLines) public static bool WritetxtFileLine(string filepatch, string filename, List<string> txtLines)
{ {
List<string> filtxtLines = new List<string>(); List<string> filtxtLines = new List<string>();
try try
{ {
if (!Directory.Exists(filepatch)) if (!Directory.Exists(filepatch))
{ {
Directory.CreateDirectory(filepatch); Directory.CreateDirectory(filepatch);
@ -213,7 +208,6 @@ namespace System
} }
sw.Close(); sw.Close();
} }
} }
catch (Exception e) catch (Exception e)
{ {
@ -222,6 +216,7 @@ namespace System
} }
return true; return true;
} }
/// <summary> /// <summary>
/// 写入文本 /// 写入文本
/// </summary> /// </summary>
@ -231,11 +226,9 @@ namespace System
/// <returns></returns> /// <returns></returns>
public static bool WritetxtFile(string filepatch, string filename, string text) public static bool WritetxtFile(string filepatch, string filename, string text)
{ {
List<string> filtxtLines = new List<string>(); List<string> filtxtLines = new List<string>();
try try
{ {
if (!Directory.Exists(filepatch)) if (!Directory.Exists(filepatch))
{ {
Directory.CreateDirectory(filepatch); Directory.CreateDirectory(filepatch);
@ -243,12 +236,10 @@ namespace System
using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8)) using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8))
{ {
sw.Write(text); sw.Write(text);
sw.Close(); sw.Close();
} }
} }
catch (Exception e) catch (Exception e)
{ {
@ -260,7 +251,6 @@ namespace System
private static bool Log(string subfilepatch, string logmessage) private static bool Log(string subfilepatch, string logmessage)
{ {
try try
{ {
string logfilePath = AppFilepatch + "Log\\" + subfilepatch; string logfilePath = AppFilepatch + "Log\\" + subfilepatch;
@ -301,6 +291,7 @@ namespace System
string path = ""; string path = "";
Log(path, log); Log(path, log);
} }
public static void WebLog(string log) public static void WebLog(string log)
{ {
Log(log); Log(log);
@ -317,34 +308,36 @@ namespace System
string subpath = "ErrLog\\"; string subpath = "ErrLog\\";
Log(subpath, log); Log(subpath, log);
} }
public static void HisLog(string log) public static void HisLog(string log)
{ {
string subpath = "HisLog\\"; string subpath = "HisLog\\";
Log(subpath, log); Log(subpath, log);
} }
public static void Package(string log) public static void Package(string log)
{ {
string path = "Package\\"; string path = "Package\\";
Log(path, log); Log(path, log);
} }
public static void EPS(string log) public static void EPS(string log)
{ {
string path = "EPS\\"; string path = "EPS\\";
Log(path, log); Log(path, log);
} }
public static void AllLog(string log) public static void AllLog(string log)
{ {
string path = "AllLog\\"; string path = "AllLog\\";
Log(path, log); Log(path, log);
} }
public static bool Exists(string path) public static bool Exists(string path)
{ {
return File.Exists(path); return File.Exists(path);
} }
public static void DeleteFile(string path) public static void DeleteFile(string path)
{ {
try try
@ -364,4 +357,3 @@ namespace System
} }
} }
} }
}

27
EC.Util/Common/LogUnit.cs

@ -1,9 +1,7 @@
using log4net; using log4net;
using log4net.Config; using log4net.Config;
using System;
using System.IO;
namespace System; namespace EC.Util.Common;
public static class LogUnit public static class LogUnit
{ {
@ -49,19 +47,24 @@ public static class LogUnit
{ {
logger.Error(e); logger.Error(e);
} }
/// <summary>
/// 输出日志到Log4Net public static void Error(object obj, Exception e)
/// </summary>
/// <param name="t"></param>
/// <param name="ex"></param>
public static void Error(Type t, Exception ex)
{ {
logger.Error(obj.GetType(), e);
}
logger.Error("Error", ex); public static void Error(object obj, string msg)
{
logger.Error(obj.GetType(), new Exception(msg));
} }
public static void Error(Type t, string logMessage)
public static void Error(Type type, Exception e)
{ {
logger.Error(type, e);
}
logger.Error(logMessage); public static void Error(Type type, string msg)
{
logger.Error(type, new Exception(msg));
} }
} }

9
JiLinApp/Core/TaskUtil.cs → EC.Util/Common/TaskUtil.cs

@ -1,9 +1,6 @@
using System; namespace EC.Util.Common;
using System.Threading.Tasks;
namespace JiLinApp.Core; public class TaskUtil
public static class TaskUtil
{ {
public static Task Run(Action action) public static Task Run(Action action)
{ {
@ -25,7 +22,7 @@ public static class TaskUtil
} }
catch (Exception e) catch (Exception e)
{ {
LogUnit.Error(e); LogUnit.Error(typeof(TaskUtil), e);
} }
}); });
} }

176
EC.Util/Common/VerifyUtil.cs

@ -0,0 +1,176 @@
using System.Text.RegularExpressions;
namespace EC.Util.Common;
/// <summary>
/// 验证工具类
/// </summary>
public class VerifyUtil
{
/// <summary>
/// 验证是否为空
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsEmpty(string str)
{
return string.IsNullOrEmpty(str);
}
/// <summary>
/// 验证是否为邮件
/// </summary>
/// <param name="emailStr"></param>
/// <returns></returns>
public static bool IsEmail(string emailStr)
{
if (string.IsNullOrEmpty(emailStr)) return false;
string match = @"^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$";
Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return r.IsMatch(emailStr.Trim());
}
/// <summary>
/// 验证是否为数字
/// </summary>
/// <param name="numberStr"></param>
/// <returns></returns>
public static bool IsNumber(string numberStr)
{
if (string.IsNullOrEmpty(numberStr)) return false;
string match = @"^(0|[1-9][0-9]*)$";
Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return r.IsMatch(numberStr.Trim());
}
/// <summary>
/// 验证是否为浮点数
/// </summary>
/// <param name="decimalStr"></param>
/// <returns></returns>
public static bool IsDecimal(string decimalStr)
{
if (string.IsNullOrEmpty(decimalStr)) return false;
string match = @"^(-?\d+)(\.\d+)?$";
Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return r.IsMatch(decimalStr.Trim());
}
/// <summary>
/// 验证是否为手机号码
/// </summary>
/// <param name="mobileStr"></param>
/// <returns></returns>
public static bool IsMobile(string mobileStr)
{
if (string.IsNullOrEmpty(mobileStr)) return false;
string match = @"^[1]+[3,5,7,8]+\d{9}";
Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return r.IsMatch(mobileStr.Trim());
}
/// <summary>
/// 验证是否为电话号码
/// </summary>
/// <param name="telStr"></param>
/// <returns></returns>
public static bool IsTel(string telStr)
{
if (string.IsNullOrEmpty(telStr)) return false;
string match = @"^(\+86\s{1,1})?((\d{3,4}\-)\d{7,8})$";
Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return r.IsMatch(telStr.Trim());
}
/// <summary>
/// 验证是否为Ip地址
/// </summary>
/// <param name="ipStr"></param>
/// <returns></returns>
public static bool IsIp(string ipStr)
{
if (string.IsNullOrEmpty(ipStr)) return false;
string match = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";
Regex r = new(match);
return r.IsMatch(ipStr.Trim());
}
/// <summary>
/// 验证是否为身份证
/// </summary>
/// <param name="idcardStr">身份证号</param>
/// <returns></returns>
public static bool CheckIDCard(string idcardStr)
{
if (string.IsNullOrEmpty(idcardStr)) return false;
if (idcardStr.Length == 18) return CheckIDCard18(idcardStr);
else if (idcardStr.Length == 15) return CheckIDCard15(idcardStr);
return false;
}
/// <summary>
/// 18位身份证验证
/// </summary>
/// <param name="Id">身份证号</param>
/// <returns></returns>
private static bool CheckIDCard18(string Id)
{
long n = 0;
if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
char[] Ai = Id.Remove(17).ToCharArray();
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
}
int y = -1;
Math.DivRem(sum, 11, out y);
if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
{
return false;//校验码验证
}
return true;//符合GB11643-1999标准
}
/// <summary>
/// 15位身份证验证
/// </summary>
/// <param name="Id">身份证号</param>
/// <returns></returns>
private static bool CheckIDCard15(string Id)
{
long n = 0;
if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
}

16
EC.Util/Net/APICallBack.cs

@ -1,39 +1,39 @@
using System; namespace EC.Util.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EC.Util.Net
{
public class APICallBack public class APICallBack
{ {
public string reqCode { get; set; } public string reqCode { get; set; }
/// <summary> /// <summary>
/// 任务单号 /// 任务单号
/// </summary> /// </summary>
public string taskCode { get; set; } public string taskCode { get; set; }
/// <summary> /// <summary>
/// AGV状态指令 /// AGV状态指令
/// </summary> /// </summary>
public string method { get; set; } public string method { get; set; }
public string reqTime { get; set; } public string reqTime { get; set; }
public string wbCode { get; set; } public string wbCode { get; set; }
/// <summary> /// <summary>
/// AGV编号 /// AGV编号
/// </summary> /// </summary>
public string robotCode { get; set; } public string robotCode { get; set; }
/// <summary> /// <summary>
/// 请求AGV接口后返回的成功失败或其他消息 /// 请求AGV接口后返回的成功失败或其他消息
/// </summary> /// </summary>
public string message { get; set; } public string message { get; set; }
/// <summary> /// <summary>
/// 请求AGV接口后返回的任务单号 /// 请求AGV接口后返回的任务单号
/// </summary> /// </summary>
public string data { get; set; } public string data { get; set; }
/// <summary> /// <summary>
/// 请求AGV接口后返回的任务状态 /// 请求AGV接口后返回的任务状态
/// </summary> /// </summary>
public string code { get; set; } public string code { get; set; }
} }
}

42
EC.Util/Net/HttpServer.cs

@ -1,19 +1,13 @@
 using EC.Util.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net; using System.Net;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EC.Util.Net namespace EC.Util.Net;
{
public class HttpServer public class HttpServer
{ {
public event EventHandler<APICallBack> OnRecData; //定义一个委托类型的事件 public event EventHandler<APICallBack> OnRecData; //定义一个委托类型的事件
#region #region
public string Host { get; set; } public string Host { get; set; }
@ -24,7 +18,6 @@ namespace EC.Util.Net
private string directorySeparatorChar = Path.DirectorySeparatorChar.ToString(); private string directorySeparatorChar = Path.DirectorySeparatorChar.ToString();
public string ImageUploadPath { get; set; } public string ImageUploadPath { get; set; }
/// <summary> /// <summary>
/// 设置监听端口,重启服务生效 /// 设置监听端口,重启服务生效
/// </summary> /// </summary>
@ -54,6 +47,7 @@ namespace EC.Util.Net
this._webHomeDir = value; this._webHomeDir = value;
} }
} }
/// <summary> /// <summary>
/// 服务器是否在运行 /// 服务器是否在运行
/// </summary> /// </summary>
@ -61,12 +55,13 @@ namespace EC.Util.Net
{ {
get { return (listener == null) ? false : listener.IsListening; } get { return (listener == null) ? false : listener.IsListening; }
} }
#endregion #endregion
#region #region
public HttpServer(string host, string port, string webHomeDir, string imageUploadPath) public HttpServer(string host, string port, string webHomeDir, string imageUploadPath)
{ {
this.Host = host; this.Host = host;
this.port = port; this.port = port;
this._webHomeDir = webHomeDir; this._webHomeDir = webHomeDir;
@ -101,15 +96,13 @@ namespace EC.Util.Net
listenThread.Name = "signserver"; listenThread.Name = "signserver";
listenThread.Start(); listenThread.Start();
Log("开启接口监听服务:" + this.port); Log("开启接口监听服务:" + this.port);
} }
catch (Exception ex) catch (Exception ex)
{ {
LogUnit.Error(ex.Message); LogUnit.Error(ex.Message);
} }
} }
/// <summary> /// <summary>
/// 停止服务 /// 停止服务
/// </summary> /// </summary>
@ -122,7 +115,6 @@ namespace EC.Util.Net
//listener.Close(); //listener.Close();
//listener.Abort(); //listener.Abort();
listener.Stop(); listener.Stop();
} }
} }
catch (Exception ex) catch (Exception ex)
@ -134,7 +126,7 @@ namespace EC.Util.Net
/// <summary> /// <summary>
/// /接受客户端请求 /// /接受客户端请求
/// </summary> /// </summary>
void AcceptClient() private void AcceptClient()
{ {
//int maxThreadNum, portThreadNum; //int maxThreadNum, portThreadNum;
////线程池 ////线程池
@ -154,14 +146,14 @@ namespace EC.Util.Net
} }
catch catch
{ {
} }
} }
} }
#endregion #endregion
#region HandleRequest #region HandleRequest
//处理客户端请求 //处理客户端请求
private void HandleRequest(object ctx) private void HandleRequest(object ctx)
{ {
@ -178,8 +170,8 @@ namespace EC.Util.Net
rawUrl = rawUrl.Substring(0, paramStartIndex); rawUrl = rawUrl.Substring(0, paramStartIndex);
else if (paramStartIndex == 0) else if (paramStartIndex == 0)
rawUrl = ""; rawUrl = "";
if ( rawUrl.EndsWith("agvCallback") ) { if (rawUrl.EndsWith("agvCallback"))
{
APICallBack apiCallBack = new APICallBack(); APICallBack apiCallBack = new APICallBack();
apiCallBack.reqCode = context.Request.QueryString["reqCode"]; apiCallBack.reqCode = context.Request.QueryString["reqCode"];
@ -218,7 +210,6 @@ namespace EC.Util.Net
//var output = context.Response.OutputStream; //var output = context.Response.OutputStream;
//output.Write(buffer, 0, buffer.Length); //output.Write(buffer, 0, buffer.Length);
//output.Close(); //output.Close();
} }
else if (string.Compare(rawUrl, "/ImageUpload", true) == 0) else if (string.Compare(rawUrl, "/ImageUpload", true) == 0)
{ {
@ -298,9 +289,11 @@ namespace EC.Util.Net
LogUnit.Error(ex.Message); LogUnit.Error(ex.Message);
} }
} }
#endregion #endregion
#region GetContentType #region GetContentType
/// <summary> /// <summary>
/// 获取文件对应MIME类型 /// 获取文件对应MIME类型
/// </summary> /// </summary>
@ -328,9 +321,11 @@ namespace EC.Util.Net
else else
return "";//application/octet-stream return "";//application/octet-stream
} }
#endregion #endregion
#region WriteStreamToFile #region WriteStreamToFile
//const int ChunkSize = 1024 * 1024; //const int ChunkSize = 1024 * 1024;
private void WriteStreamToFile(BinaryReader br, string fileName, long length) private void WriteStreamToFile(BinaryReader br, string fileName, long length)
{ {
@ -353,10 +348,11 @@ namespace EC.Util.Net
} }
} }
} }
#endregion #endregion
public void Log(string msg, bool isErr = false) public void Log(string msg, bool isErr = false)
{ {
//(msg, isErr); //(msg, isErr);
} }
} }
}

98
EC.Util/Net/NetUnit.cs

@ -1,20 +1,16 @@
using System; using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace System namespace EC.Util.Net;
{
/// <summary> /// <summary>
/// 网络操作单元 /// 网络操作单元
/// </summary> /// </summary>
public partial class NetUnit public partial class NetUnit
{ {
#region 获取主机名称 #region 获取主机名称
/// <summary> /// <summary>
/// 获取本地机器名称 /// 获取本地机器名称
/// </summary> /// </summary>
@ -32,9 +28,11 @@ namespace System
return null; return null;
} }
} }
#endregion
#endregion 获取主机名称
#region 获取本地主机IP #region 获取本地主机IP
/// <summary> /// <summary>
/// 获取本地机器IP /// 获取本地机器IP
/// </summary> /// </summary>
@ -55,17 +53,17 @@ namespace System
{ {
return null; return null;
} }
} }
#endregion
#endregion 获取本地主机IP
#region 穿过代理服务器获得Ip地址,如果有多个IP,则第一个是用户的真实IP,其余全是代理的IP,用逗号隔开 #region 穿过代理服务器获得Ip地址,如果有多个IP,则第一个是用户的真实IP,其余全是代理的IP,用逗号隔开
//public static string getRealIp() //public static string getRealIp()
//{ //{
// string UserIP; // string UserIP;
// if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"]!=null) //得到穿过代理服务器的ip地址 // if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"]!=null) //得到穿过代理服务器的ip地址
// { // {
// UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
// } // }
// else // else
@ -74,10 +72,11 @@ namespace System
// } // }
// return UserIP; // return UserIP;
//} //}
#endregion
#endregion 穿过代理服务器获得Ip地址,如果有多个IP,则第一个是用户的真实IP,其余全是代理的IP,用逗号隔开
#region 获取主机MAC地址 #region 获取主机MAC地址
/// <summary> /// <summary>
/// 获取本机MAC地址 /// 获取本机MAC地址
/// </summary> /// </summary>
@ -102,18 +101,19 @@ namespace System
// return null; // return null;
//} //}
return null; return null;
} }
#endregion
#endregion 获取主机MAC地址
#region 获取本机IP #region 获取本机IP
public static string GetLocalIp() public static string GetLocalIp()
{ {
//Page.Request.UserHostName //Page.Request.UserHostName
return null; return null;
} }
#endregion
#endregion 获取本机IP
/// <summary> /// <summary>
/// C# 验证IP /// C# 验证IP
@ -131,6 +131,7 @@ namespace System
} }
else return true; else return true;
} }
public static string PingResult(string ip) public static string PingResult(string ip)
{ {
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
@ -143,11 +144,10 @@ namespace System
System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
return reply.Status.ToString(); return reply.Status.ToString();
} }
#region 获取指定WEB页面 #region 获取指定WEB页面
/// GET方法获取页面 /// GET方法获取页面
/// 函数名:GetWebUrl /// 函数名:GetWebUrl
/// 功能描述:WebClient 获取页面 /// 功能描述:WebClient 获取页面
@ -168,7 +168,6 @@ namespace System
//string pageHtml = Encoding.UTF8.GetString(pageData); //string pageHtml = Encoding.UTF8.GetString(pageData);
string pageHtml = Encoding.Default.GetString(pageData); string pageHtml = Encoding.Default.GetString(pageData);
return pageHtml; return pageHtml;
} }
catch (WebException webEx) catch (WebException webEx)
{ {
@ -178,12 +177,12 @@ namespace System
{ {
webClient = null; webClient = null;
} }
} }
#endregion
#endregion 获取指定WEB页面
#region PostUrl(String url, String paramList) #region PostUrl(String url, String paramList)
/// <summary> /// <summary>
/// POST方法获取页面 /// POST方法获取页面
/// </summary> /// </summary>
@ -196,7 +195,6 @@ namespace System
string strResult = ""; string strResult = "";
try try
{ {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST"; req.Method = "POST";
req.KeepAlive = true; req.KeepAlive = true;
@ -270,12 +268,10 @@ namespace System
return strResult; return strResult;
} }
#endregion #endregion PostUrl(String url, String paramList)
#region 下载指定WEB页面 #region 下载指定WEB页面
/// GET方法获取页面 /// GET方法获取页面
/// 函数名:GetFileUrl /// 函数名:GetFileUrl
/// 功能描述:WebClient 下载文件 /// 功能描述:WebClient 下载文件
@ -290,41 +286,32 @@ namespace System
{ {
try try
{ {
WebClient webClient = new WebClient(); WebClient webClient = new WebClient();
// webClient.Credentials = CredentialCache.DefaultCredentials; // webClient.Credentials = CredentialCache.DefaultCredentials;
webClient.DownloadFile(strurl, filename); webClient.DownloadFile(strurl, filename);
return true; return true;
} }
catch (WebException webex) catch (WebException webex)
{ {
return false;// "error_GetWebUrl:" + webEx.ToString(); return false;// "error_GetWebUrl:" + webEx.ToString();
} }
} }
#endregion
#endregion 下载指定WEB页面
#region 获取图片 #region 获取图片
public static Stream GetImage(String url) public static Stream GetImage(String url)
{ {
HttpWebResponse res = null; HttpWebResponse res = null;
try try
{ {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
res = (HttpWebResponse)req.GetResponse(); res = (HttpWebResponse)req.GetResponse();
Stream ReceiveStream = res.GetResponseStream(); Stream ReceiveStream = res.GetResponseStream();
return ReceiveStream; return ReceiveStream;
} }
catch catch
{ {
@ -346,7 +333,9 @@ namespace System
/// 日 期: /// 日 期:
/// 版 本: /// 版 本:
/// ///
#region GetImage(String url,string cookieheader) #region GetImage(String url,string cookieheader)
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
@ -359,7 +348,6 @@ namespace System
HttpWebResponse res = null; HttpWebResponse res = null;
try try
{ {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
@ -379,7 +367,6 @@ namespace System
// req.CookieContainer.SetCookies(new Uri(url),cookieheader); // req.CookieContainer.SetCookies(new Uri(url),cookieheader);
// } // }
//为请求加入cookies //为请求加入cookies
CookieContainer cookieCon = new CookieContainer(); CookieContainer cookieCon = new CookieContainer();
// req.CookieContainer = cookieCon; // req.CookieContainer = cookieCon;
@ -410,12 +397,9 @@ namespace System
//////////////////////////////////// ////////////////////////////////////
} }
res = (HttpWebResponse)req.GetResponse(); res = (HttpWebResponse)req.GetResponse();
Stream ReceiveStream = res.GetResponseStream(); Stream ReceiveStream = res.GetResponseStream();
byte[] mybytes = new byte[4096]; byte[] mybytes = new byte[4096];
int count = ReceiveStream.Read(mybytes, 0, 4096); int count = ReceiveStream.Read(mybytes, 0, 4096);
@ -424,8 +408,6 @@ namespace System
Array.Copy(mybytes, image, count); Array.Copy(mybytes, image, count);
if (res != null) if (res != null)
{ {
res.Close(); res.Close();
@ -437,9 +419,10 @@ namespace System
} }
} }
#endregion #endregion GetImage(String url,string cookieheader)
#region GetImage(String url,string cookieheader,out string outcookieheader,string Header_Referer) #region GetImage(String url,string cookieheader,out string outcookieheader,string Header_Referer)
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
@ -452,7 +435,6 @@ namespace System
HttpWebResponse res = null; HttpWebResponse res = null;
try try
{ {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
@ -506,8 +488,6 @@ namespace System
//////////////////////////////////// ////////////////////////////////////
} }
res = (HttpWebResponse)req.GetResponse(); res = (HttpWebResponse)req.GetResponse();
Stream ReceiveStream = res.GetResponseStream(); Stream ReceiveStream = res.GetResponseStream();
@ -526,7 +506,6 @@ namespace System
} }
} }
byte[] mybytes = new byte[4096]; byte[] mybytes = new byte[4096];
int count = ReceiveStream.Read(mybytes, 0, 4096); int count = ReceiveStream.Read(mybytes, 0, 4096);
@ -535,8 +514,6 @@ namespace System
Array.Copy(mybytes, image, count); Array.Copy(mybytes, image, count);
if (res != null) if (res != null)
{ {
res.Close(); res.Close();
@ -548,9 +525,10 @@ namespace System
} }
} }
#endregion #endregion GetImage(String url,string cookieheader,out string outcookieheader,string Header_Referer)
#region GetImage(String url,string cookieheader,string Header_Referer) #region GetImage(String url,string cookieheader,string Header_Referer)
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
@ -564,7 +542,6 @@ namespace System
HttpWebResponse res = null; HttpWebResponse res = null;
try try
{ {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
@ -618,12 +595,9 @@ namespace System
//////////////////////////////////// ////////////////////////////////////
} }
res = (HttpWebResponse)req.GetResponse(); res = (HttpWebResponse)req.GetResponse();
Stream ReceiveStream = res.GetResponseStream(); Stream ReceiveStream = res.GetResponseStream();
byte[] mybytes = new byte[4096]; byte[] mybytes = new byte[4096];
int count = ReceiveStream.Read(mybytes, 0, 4096); int count = ReceiveStream.Read(mybytes, 0, 4096);
@ -632,8 +606,6 @@ namespace System
Array.Copy(mybytes, image, count); Array.Copy(mybytes, image, count);
if (res != null) if (res != null)
{ {
res.Close(); res.Close();
@ -645,13 +617,7 @@ namespace System
} }
} }
#endregion #endregion GetImage(String url,string cookieheader,string Header_Referer)
#region GetImage(String url,string cookieheader,string Header_Referer,string Header_UserAgent,string http_type) #endregion 获取图片
#endregion
#endregion
}
} }

2
EC.Util/Zmq/ZmqUtil.cs

@ -1,6 +1,6 @@
namespace EC.Util.Zmq; namespace EC.Util.Zmq;
internal class ZmqUtil public class ZmqUtil
{ {
//#region Fields //#region Fields

2
JiLinApp.Biz/TransmitAlarm/Common/Config.cs

@ -11,6 +11,8 @@ public class AlarmPlatformConfig
public class MqttConfig public class MqttConfig
{ {
//public bool Local { get; set; }
public string Ip { get; set; } public string Ip { get; set; }
public int Port { get; set; } public int Port { get; set; }

2
JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessage.cs

@ -4,7 +4,7 @@ public class AlarmMessage
{ {
/** (必填)传感器设备编码*/ /** (必填)传感器设备编码*/
public string LabelCode { get; set; } public string LabelCode { get; set; }
public int ChannelId { get; set; } public string ChannelId { get; set; }
/** (必填)报警类型((1-视频报警,2-雷达报警;3-微振动警报,4-电子围网警报,9-其他报警))*/ /** (必填)报警类型((1-视频报警,2-雷达报警;3-微振动警报,4-电子围网警报,9-其他报警))*/
public int WarnType { get; set; } public int WarnType { get; set; }
/** (必填)报警级别(1-5)*/ /** (必填)报警级别(1-5)*/

4
JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessageHelper.cs

@ -12,7 +12,7 @@ public static class AlarmMessageHelper
AlarmMessage obj = new() AlarmMessage obj = new()
{ {
LabelCode = Convert.ToString(msg.DeviceID), LabelCode = Convert.ToString(msg.DeviceID),
ChannelId = Convert.ToInt32(msg.SensorAddr), ChannelId = msg.SensorAddr,
WarnType = 3, WarnType = 3,
WarnLevel = code.Level, WarnLevel = code.Level,
WarnContent = code.Content, WarnContent = code.Content,
@ -29,7 +29,7 @@ public static class AlarmMessageHelper
AlarmMessage obj = new() AlarmMessage obj = new()
{ {
LabelCode = Convert.ToString(msg.DeviceId), LabelCode = Convert.ToString(msg.DeviceId),
ChannelId = msg.SectorId, ChannelId = Convert.ToString(msg.SectorId),
WarnType = 4, WarnType = 4,
WarnLevel = code.Level, WarnLevel = code.Level,
WarnContent = code.Content, WarnContent = code.Content,

61
JiLinApp.Biz/TransmitAlarm/Service/AlarmMqttService.cs

@ -2,6 +2,8 @@
using MQTTnet; using MQTTnet;
using MQTTnet.Client; using MQTTnet.Client;
using MQTTnet.Exceptions; using MQTTnet.Exceptions;
using MQTTnet.Protocol;
using MQTTnet.Server;
using NewLife.Serialization; using NewLife.Serialization;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System.Text; using System.Text;
@ -14,8 +16,12 @@ public class AlarmMqttService : IAlarmService
private MqttConfig Config { get; } private MqttConfig Config { get; }
//private MqttServer? Server { get; }
private IMqttClient Client { get; } private IMqttClient Client { get; }
//private MqttServerOptions ServerOptions { get; }
private MqttClientOptions ClientOptions { get; } private MqttClientOptions ClientOptions { get; }
private MqttClientSubscribeOptions SubscribeOptions { get; } private MqttClientSubscribeOptions SubscribeOptions { get; }
@ -33,8 +39,7 @@ public class AlarmMqttService : IAlarmService
public AlarmMqttService(MqttConfig config) public AlarmMqttService(MqttConfig config)
{ {
MqttFactory factory = new(); MqttFactory factory = new();
IMqttClient client = factory.CreateMqttClient();
client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync;
ClientOptions = factory.CreateClientOptionsBuilder() ClientOptions = factory.CreateClientOptionsBuilder()
.WithTcpServer(config.Ip, config.Port) .WithTcpServer(config.Ip, config.Port)
.WithClientId(config.ClientId) .WithClientId(config.ClientId)
@ -46,6 +51,23 @@ public class AlarmMqttService : IAlarmService
.WithTopicFilter(f => f.WithTopic(config.SubCmdTopic)) .WithTopicFilter(f => f.WithTopic(config.SubCmdTopic))
.Build(); .Build();
//if (config.Local)
//{
// ServerOptions = factory.CreateServerOptionsBuilder()
// .WithDefaultEndpoint()
// .WithDefaultEndpointPort(config.Port)
// .Build();
// MqttServer server = factory.CreateMqttServer(ServerOptions);
// server.ValidatingConnectionAsync += Server_ValidatingConnectionAsync;
// server.ClientConnectedAsync += Server_ClientConnectedAsync;
// server.ClientDisconnectedAsync += Server_ClientDisconnectedAsync;
// server.ClientAcknowledgedPublishPacketAsync += Server_ClientAcknowledgedPublishPacketAsync;
// Server = server;
//}
IMqttClient client = factory.CreateMqttClient();
client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync;
Config = config; Config = config;
Client = client; Client = client;
} }
@ -110,7 +132,38 @@ public class AlarmMqttService : IAlarmService
#endregion Base #endregion Base
#region Receive #region Server Event
private Task Server_ValidatingConnectionAsync(ValidatingConnectionEventArgs arg)
{
if (arg.ClientId.Length == 0) arg.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
else if (arg.UserName != Config.UserName) arg.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
else if (arg.Password != Config.Password) arg.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return Task.CompletedTask;
}
private Task Server_ClientConnectedAsync(ClientConnectedEventArgs arg)
{
return Task.CompletedTask;
}
private Task Server_ClientDisconnectedAsync(ClientDisconnectedEventArgs arg)
{
return Task.CompletedTask;
}
private Task Server_ClientAcknowledgedPublishPacketAsync(ClientAcknowledgedPublishPacketEventArgs arg)
{
string clientId = arg.ClientId;
ushort packetIdentifier = arg.PublishPacket.PacketIdentifier;
string topic = arg.PublishPacket.Topic;
string msg = Encoding.UTF8.GetString(arg.PublishPacket.Payload);
return Task.CompletedTask;
}
#endregion Server Event
#region Client Event
private Task Client_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg) private Task Client_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{ {
@ -160,7 +213,7 @@ public class AlarmMqttService : IAlarmService
} }
} }
#endregion Receive #endregion Client Event
#region Send #region Send

3
JiLinApp.Biz/TransmitAlarm/Service/AlarmZmqService.cs

@ -3,8 +3,11 @@
public class AlarmZmqService : IAlarmService public class AlarmZmqService : IAlarmService
{ {
public event IAlarmService.HandleRecvEvent? OnFenceUdpSendDevices; public event IAlarmService.HandleRecvEvent? OnFenceUdpSendDevices;
public event IAlarmService.HandleRecvEvent? OnVibrateTcpSendDevices; public event IAlarmService.HandleRecvEvent? OnVibrateTcpSendDevices;
public event IAlarmService.HandleRecvEvent? OnFenceUdpSendSensors; public event IAlarmService.HandleRecvEvent? OnFenceUdpSendSensors;
public event IAlarmService.HandleRecvEvent? OnVibrateTcpSendSensors; public event IAlarmService.HandleRecvEvent? OnVibrateTcpSendSensors;
public void Start() public void Start()

3
JiLinApp.Docking/Alarm/AlarmCodeHelper.cs

@ -23,7 +23,8 @@ public class AlarmCodeHelper
} }
public static void Init() public static void Init()
{ } {
}
public static AlarmCode Get(string id) public static AlarmCode Get(string id)
{ {

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

@ -122,10 +122,12 @@ public class UdpServer
return flag; return flag;
} }
public bool SendMessage(IPEndPoint ipep, byte[] byteMsg) public bool SendMessage(IPEndPoint ipep, byte[] msg)
{ {
int result = SendUdp.Send(byteMsg, byteMsg.Length, ipep); int result = SendUdp.Send(msg, msg.Length, ipep);
return result >= byteMsg.Length; bool flag = result >= msg.Length;
Console.WriteLine("Send to {0}:{1} => {2}, {3}", ipep.Address.ToString(), ipep.Port, DataMessage.ToHexString(msg), flag);
return flag;
} }
#endregion Send #endregion Send

4
JiLinApp.Docking/JiLinApp.Docking.csproj

@ -7,7 +7,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="NewLife.Core" Version="10.2.2023.401" /> <PackageReference Include="Flurl" Version="3.0.7" />
<PackageReference Include="Flurl.Http" Version="3.2.4" />
<PackageReference Include="NewLife.Core" Version="10.3.2023.503" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

14
JiLinApp.Docking/Military/Config.cs

@ -0,0 +1,14 @@
namespace JiLinApp.Docking.Military;
public class MilitaryConfig
{
public string Url { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int RequestRetryTime { get; set; }
public int RequestRetryInterval { get; set; }
}

18
JiLinApp.Docking/Military/Entity/CameraLinkageInfo.cs

@ -0,0 +1,18 @@
namespace JiLinApp.Docking.Military;
public class CameraLinkageInfo
{
#region Fields
public string Id { get; set; }
public string DeviceId { get; set; }
public string SensorId { get; set; }
public string CameraId { get; set; }
public int[] PresetIds { get; set; }
#endregion Fields
}

158
JiLinApp.Docking/Military/MilitaryService.cs

@ -0,0 +1,158 @@
using EC.Util.CameraSDK;
using EC.Util.Common;
using Flurl.Http;
using Newtonsoft.Json.Linq;
namespace JiLinApp.Docking.Military;
public class MilitaryService
{
#region Fields
private MilitaryConfig Config { get; }
private string Token { get; set; }
#endregion Fields
public MilitaryService(MilitaryConfig config)
{
Config = config;
Token = Login();
}
#region Base
private string GetUrl()
{
return Config.Url;
}
#endregion Base
#region Cmd
public string Login()
{
string url = $"{GetUrl()}/sys/login";
object data = new
{
username = Config.UserName,
password = Config.Password,
};
JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++)
{
response = url.PostJsonAsync(data).ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean();
if (!success)
{
Thread.Sleep(Config.RequestRetryInterval);
continue;
}
string? token = response["result"]?["token"]?.ToString();
return token ?? string.Empty;
}
string? message = response["message"]?.ToString();
throw new Exception(message);
}
public List<CameraInfo> GetCameraList()
{
string url = $"{GetUrl()}/camera/setting/list";
JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++)
{
response = url.GetAsync().ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean();
if (!success)
{
Thread.Sleep(Config.RequestRetryInterval);
continue;
}
JToken records = response?["result"]?["records"] ?? new JObject();
List<CameraInfo> list = new();
foreach (var item in records)
{
CameraManufactor manufactor;
string factory = item?["factory_dictText"]?.ToString() ?? string.Empty;
if (factory.Contains("海康威视")) manufactor = CameraManufactor.HiK;
else if (factory.Contains("大华")) manufactor = CameraManufactor.DaHua;
else if (factory.Contains("宇视")) manufactor = CameraManufactor.YuShi;
else continue;
string id = item?["id"]?.ToString() ?? string.Empty;
string ip = item?["ip"]?.ToString() ?? string.Empty;
string username = item?["user"]?.ToString() ?? string.Empty;
string password = item?["password"]?.ToString() ?? string.Empty;
if (VerifyUtil.IsEmpty(id) || !VerifyUtil.IsIp(ip) || VerifyUtil.IsEmpty(username) || VerifyUtil.IsEmpty(password)) continue;
CameraInfo info = CameraInfo.New(manufactor, ip, username, password);
info.Id = id;
list.Add(info);
}
return list;
}
string? message = response["message"]?.ToString();
throw new Exception(message);
}
public List<object> GetFencesInfoList()
{
string url = $"{GetUrl()}/msFencesInfo/list";
JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++)
{
response = url.WithHeader("X-Access-Token", Token).GetAsync().ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean();
if (!success)
{
Thread.Sleep(Config.RequestRetryInterval);
continue;
}
return new List<object>();
}
string? message = response["message"]?.ToString();
throw new Exception(message);
}
public List<CameraLinkageInfo> GetCameraLinkageList()
{
string url = $"{GetUrl()}/military/MsCameraLinkage/list";
JObject response = new();
for (int i = 0; i < Config.RequestRetryTime; i++)
{
response = url.GetAsync().ReceiveJson<JObject>().Result;
bool success = response["success"].ToBoolean();
if (!success)
{
Thread.Sleep(Config.RequestRetryInterval);
continue;
}
JToken records = response?["result"]?["records"] ?? new JObject();
List<CameraLinkageInfo> list = new();
foreach (var item in records)
{
string id = item?["id"]?.ToString() ?? string.Empty;
//string deviceId = item?["deviceId"]?.ToString() ?? string.Empty;
string deviceId = "0";
string sensorId = item?["objCode"]?.ToString() ?? string.Empty;
string cameraId = item?["cameraId"]?.ToString() ?? string.Empty;
string placements = item?["placements"]?.ToString() ?? string.Empty;
int[] presetIds = Array.ConvertAll(placements.Split(","), int.Parse);
if (VerifyUtil.IsEmpty(id) || VerifyUtil.IsEmpty(sensorId) || VerifyUtil.IsEmpty(cameraId)) continue;
list.Add(new()
{
Id = id,
DeviceId = deviceId,
SensorId = sensorId,
CameraId = cameraId,
PresetIds = presetIds
});
}
return list;
}
string? message = response["message"]?.ToString();
throw new Exception(message);
}
#endregion Cmd
}

2
JiLinApp.Docking/Ptz/PtzCmd.cs

@ -140,7 +140,7 @@ public class PtzCameraCmd
public static void PtzMove(ICameraSDK sdk, PtzCmdType cmdType, int[] args) public static void PtzMove(ICameraSDK sdk, PtzCmdType cmdType, int[] args)
{ {
if (sdk == null || !sdk.ConnectSuccess() || args == null) return; if (sdk == null || !sdk.ConnectSuccess() || args == null) return;
switch (sdk.CameraInfo.GetManufactor) switch (sdk.CameraInfo.Manufactor)
{ {
case CameraManufactor.HiK: case CameraManufactor.HiK:
HikPtzMove(sdk, cmdType, args); HikPtzMove(sdk, cmdType, args);

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

@ -16,7 +16,7 @@ public class ClientMessage
get get
{ {
if (Host != null) return Host.Ip; if (Host != null) return Host.Ip;
if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[0]; //if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[0];
return ""; return "";
} }
} }
@ -26,7 +26,7 @@ public class ClientMessage
get get
{ {
if (Host != null) return Host.Port; if (Host != null) return Host.Port;
if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[1]; //if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[1];
return "-1"; return "-1";
} }
} }

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

@ -1,7 +1,6 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text; using System.Text;
namespace JiLinApp.Docking.VibrateAlarm; namespace JiLinApp.Docking.VibrateAlarm;
@ -39,8 +38,6 @@ public class AsyncTcpServer : IDisposable
#region Ctors #region Ctors
private byte[] InOptionValues { get; set; }
/// <summary> /// <summary>
/// 异步TCP服务器 /// 异步TCP服务器
/// </summary> /// </summary>
@ -64,11 +61,6 @@ public class AsyncTcpServer : IDisposable
/// <param name="port">监听的端口</param> /// <param name="port">监听的端口</param>
public AsyncTcpServer(IPAddress address, int port) public AsyncTcpServer(IPAddress address, int port)
{ {
uint dummy = 0;
InOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
BitConverter.GetBytes((uint)1).CopyTo(InOptionValues, 0);
BitConverter.GetBytes((uint)1000).CopyTo(InOptionValues, Marshal.SizeOf(dummy));
BitConverter.GetBytes((uint)1000).CopyTo(InOptionValues, Marshal.SizeOf(dummy) * 2);
Address = address; Address = address;
Port = port; Port = port;
Encoding = Encoding.Default; Encoding = Encoding.Default;
@ -157,15 +149,19 @@ public class AsyncTcpServer : IDisposable
/// </summary> /// </summary>
public event EventHandler<TcpDatagramReceivedEventArgs<byte[]>>? DatagramReceived; public event EventHandler<TcpDatagramReceivedEventArgs<byte[]>>? DatagramReceived;
private void RaiseClientConnected(TcpClient client) private void RaiseClientConnected(string clientKey, TcpClientState clientState)
{ {
ClientConnected?.Invoke(this, new TcpClientConnectedEventArgs(client)); Clients.AddOrUpdate(clientKey, clientState, (n, o) => { return clientState; });
ClientConnected?.Invoke(this, new TcpClientConnectedEventArgs(clientState.TcpClient));
} }
private void RaiseClientDisconnected(TcpClient client) private void RaiseClientDisconnected(string clientKey, TcpClient client)
{
if (Clients.TryRemove(clientKey, out _))
{ {
ClientDisconnected?.Invoke(this, new TcpClientDisconnectedEventArgs(client)); ClientDisconnected?.Invoke(this, new TcpClientDisconnectedEventArgs(client));
} }
}
private void RaiseDatagramReceived(TcpClientState sender, byte[] datagram) private void RaiseDatagramReceived(TcpClientState sender, byte[] datagram)
{ {
@ -181,11 +177,6 @@ public class AsyncTcpServer : IDisposable
listener.BeginAcceptTcpClient(HandleTcpClientAccepted, listener); listener.BeginAcceptTcpClient(HandleTcpClientAccepted, listener);
} }
private void ReadBuffer(TcpClientState internalClient, NetworkStream networkStream)
{
networkStream.BeginRead(internalClient.Buffer, 0, internalClient.Buffer.Length, HandleDatagramReceived, internalClient);
}
private void HandleTcpClientAccepted(IAsyncResult ar) private void HandleTcpClientAccepted(IAsyncResult ar)
{ {
if (!IsRunning()) return; if (!IsRunning()) return;
@ -195,7 +186,6 @@ public class AsyncTcpServer : IDisposable
{ {
listener = ar.AsyncState as TcpListener; listener = ar.AsyncState as TcpListener;
client = listener?.EndAcceptTcpClient(ar); client = listener?.EndAcceptTcpClient(ar);
client?.Client.IOControl(IOControlCode.KeepAliveValues, InOptionValues, null);
} }
catch (Exception) catch (Exception)
{ {
@ -204,24 +194,22 @@ public class AsyncTcpServer : IDisposable
if (listener == null || client == null || !client.Connected) return; if (listener == null || client == null || !client.Connected) return;
byte[] buffer = new byte[client.ReceiveBufferSize]; byte[] buffer = new byte[client.ReceiveBufferSize];
TcpClientState internalClient = new(client, buffer); TcpClientState clientState = new(client, buffer);
// add client connection to cache // add client connection to cache
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? ""; string clientKey = client.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return; if (clientKey == "") return;
Clients.AddOrUpdate(clientKey, internalClient, (n, o) => { return internalClient; }); RaiseClientConnected(clientKey, clientState);
RaiseClientConnected(client);
// begin to read data // begin to read data
try try
{ {
NetworkStream networkStream = internalClient.NetworkStream; NetworkStream networkStream = clientState.NetworkStream;
ReadBuffer(internalClient, networkStream); ReadBuffer(clientState, networkStream);
} }
catch (Exception) catch (Exception)
{ {
Clients.TryRemove(clientKey, out _); RaiseClientDisconnected(clientKey, clientState.TcpClient);
RaiseClientDisconnected(internalClient.TcpClient);
return; return;
} }
@ -229,6 +217,11 @@ public class AsyncTcpServer : IDisposable
AcceptTcpClient(listener); AcceptTcpClient(listener);
} }
private void ReadBuffer(TcpClientState clientState, NetworkStream networkStream)
{
networkStream.BeginRead(clientState.Buffer, 0, clientState.Buffer.Length, HandleDatagramReceived, clientState);
}
private void HandleDatagramReceived(IAsyncResult ar) private void HandleDatagramReceived(IAsyncResult ar)
{ {
if (!IsRunning()) return; if (!IsRunning()) return;
@ -239,8 +232,7 @@ public class AsyncTcpServer : IDisposable
if (!internalClient.TcpClient.Connected) if (!internalClient.TcpClient.Connected)
{ {
// connection has been closed // connection has been closed
Clients.TryRemove(clientKey, out _); RaiseClientDisconnected(clientKey, internalClient.TcpClient);
RaiseClientDisconnected(internalClient.TcpClient);
} }
NetworkStream networkStream; NetworkStream networkStream;
@ -254,13 +246,13 @@ public class AsyncTcpServer : IDisposable
} }
catch (Exception) catch (Exception)
{ {
RaiseClientDisconnected(clientKey, internalClient.TcpClient);
return; return;
} }
if (readBytesNum == 0) if (readBytesNum == 0)
{ {
// connection has been closed // connection has been closed
Clients.TryRemove(clientKey, out _); RaiseClientDisconnected(clientKey, internalClient.TcpClient);
RaiseClientDisconnected(internalClient.TcpClient);
return; return;
} }
@ -280,15 +272,15 @@ public class AsyncTcpServer : IDisposable
/// <summary> /// <summary>
/// 发送报文至指定的客户端 /// 发送报文至指定的客户端
/// </summary> /// </summary>
/// <param name="tcpClient">客户端</param> /// <param name="client">客户端</param>
/// <param name="datagram">报文</param> /// <param name="datagram">报文</param>
public void Send(TcpClient tcpClient, byte[] datagram) public void Send(TcpClient client, byte[] datagram)
{ {
if (!IsRunning()) return; if (!IsRunning()) return;
if (tcpClient == null || !tcpClient.Connected || datagram == null) return; if (client == null || !client.Connected || datagram == null) return;
try try
{ {
NetworkStream stream = tcpClient.GetStream(); NetworkStream stream = client.GetStream();
if (stream.CanWrite) if (stream.CanWrite)
{ {
stream.Write(datagram, 0, datagram.Length); stream.Write(datagram, 0, datagram.Length);
@ -296,17 +288,20 @@ public class AsyncTcpServer : IDisposable
} }
catch (Exception) catch (Exception)
{ {
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
if (client != null) RaiseClientDisconnected(clientKey, client);
} }
} }
/// <summary> /// <summary>
/// 发送报文至指定的客户端 /// 发送报文至指定的客户端
/// </summary> /// </summary>
/// <param name="tcpClient">客户端</param> /// <param name="client">客户端</param>
/// <param name="datagram">报文</param> /// <param name="datagram">报文</param>
public void Send(TcpClient tcpClient, string datagram) public void Send(TcpClient client, string datagram)
{ {
Send(tcpClient, Encoding.GetBytes(datagram)); Send(client, Encoding.GetBytes(datagram));
} }
/// <summary> /// <summary>
@ -335,33 +330,36 @@ public class AsyncTcpServer : IDisposable
/// <summary> /// <summary>
/// 发送报文至指定的客户端 /// 发送报文至指定的客户端
/// </summary> /// </summary>
/// <param name="tcpClient">客户端</param> /// <param name="client">客户端</param>
/// <param name="datagram">报文</param> /// <param name="datagram">报文</param>
public void SendAsync(TcpClient tcpClient, byte[] datagram) public void SendAsync(TcpClient client, byte[] datagram)
{ {
if (!IsRunning()) return; if (!IsRunning()) return;
if (tcpClient == null || !tcpClient.Connected || datagram == null) return; if (client == null || !client.Connected || datagram == null) return;
try try
{ {
NetworkStream stream = tcpClient.GetStream(); NetworkStream stream = client.GetStream();
if (stream.CanWrite) if (stream.CanWrite)
{ {
stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient); stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, client);
} }
} }
catch (Exception) catch (Exception)
{ {
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
if (client != null) RaiseClientDisconnected(clientKey, client);
} }
} }
/// <summary> /// <summary>
/// 发送报文至指定的客户端 /// 发送报文至指定的客户端
/// </summary> /// </summary>
/// <param name="tcpClient">客户端</param> /// <param name="client">客户端</param>
/// <param name="datagram">报文</param> /// <param name="datagram">报文</param>
public void SendAsync(TcpClient tcpClient, string datagram) public void SendAsync(TcpClient client, string datagram)
{ {
SendAsync(tcpClient, Encoding.GetBytes(datagram)); SendAsync(client, Encoding.GetBytes(datagram));
} }
/// <summary> /// <summary>
@ -389,12 +387,17 @@ public class AsyncTcpServer : IDisposable
private void HandleDatagramWritten(IAsyncResult ar) private void HandleDatagramWritten(IAsyncResult ar)
{ {
TcpClient? client = null;
try try
{ {
(ar.AsyncState as TcpClient)?.GetStream().EndWrite(ar); client = ar.AsyncState as TcpClient;
client?.GetStream().EndWrite(ar);
} }
catch (Exception) catch (Exception)
{ {
string clientKey = client?.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
if (client != null) RaiseClientDisconnected(clientKey, client);
} }
} }

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

@ -18,8 +18,6 @@ public class TcpManager
private Timer HeartTimer { get; } = new(); private Timer HeartTimer { get; } = new();
private Timer StateSpanTimer { get; } = new();
#region Event #region Event
public delegate void VibrateTcpDeviceStateEvent(ClientMessage device); public delegate void VibrateTcpDeviceStateEvent(ClientMessage device);
@ -476,8 +474,6 @@ public class TcpManager
#region Set #region Set
private List<DataRequest> Reqlist { get; } = new();
private byte FrameNumber { get; set; } = 0; private byte FrameNumber { get; set; } = 0;
private DataMessage GetSendMessageHead(int deviceId, ClientMessage client, byte fun_num, byte datalen) private DataMessage GetSendMessageHead(int deviceId, ClientMessage client, byte fun_num, byte datalen)
@ -485,7 +481,8 @@ public class TcpManager
DataMessage msg = new() DataMessage msg = new()
{ {
DeviceId = deviceId, DeviceId = deviceId,
SendIp = client.Client.Client.LocalEndPoint.ToString().Split(':')[0], SendIp = client.Host.Ip,
//SendIp = client.Client.Client.LocalEndPoint.ToString().Split(':')[0],
SendPort = Server.Port, SendPort = Server.Port,
ReceiveIp = client.Ip, ReceiveIp = client.Ip,
ReceivePort = int.Parse(client.Port), ReceivePort = int.Parse(client.Port),

5
JiLinApp.sln

@ -11,6 +11,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiLinApp.Docking", "JiLinAp
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiLinApp.Biz", "JiLinApp.Biz\JiLinApp.Biz.csproj", "{7CE63A50-C92C-4554-8E0C-F7BED355C1FD}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiLinApp.Biz", "JiLinApp.Biz\JiLinApp.Biz.csproj", "{7CE63A50-C92C-4554-8E0C-F7BED355C1FD}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{43972F12-0762-4EC2-AC09-900F53CC743D}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU

3
JiLinApp/App.xaml.cs

@ -1,4 +1,5 @@
using JiLinApp.Core; using EC.Util.Common;
using JiLinApp.Core;
using JiLinApp.Pages.Main; using JiLinApp.Pages.Main;
using Prism.Ioc; using Prism.Ioc;
using Prism.Modularity; using Prism.Modularity;

19
JiLinApp/Components/CameraRealPlay.xaml

@ -29,6 +29,9 @@
<RowDefinition Height="30" /> <RowDefinition Height="30" />
<RowDefinition Height="30" /> <RowDefinition Height="30" />
<RowDefinition Height="30" /> <RowDefinition Height="30" />
<RowDefinition Height="5" />
<RowDefinition Height="35" />
<RowDefinition Height="35" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="35" /> <ColumnDefinition Width="35" />
@ -90,7 +93,7 @@
</Button> </Button>
</StackPanel> </StackPanel>
<StackPanel Grid.Row="4" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel Grid.Row="4" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Style="{StaticResource MaterialDesignTextBlock}" Text="调焦" /> <TextBlock Style="{StaticResource MaterialDesignTextBlock}" Text="调焦" FontSize="11" />
</StackPanel> </StackPanel>
<StackPanel Grid.Row="4" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel Grid.Row="4" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="ZoomOutBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}"> <Button Name="ZoomOutBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}">
@ -104,7 +107,7 @@
</Button> </Button>
</StackPanel> </StackPanel>
<StackPanel Grid.Row="5" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel Grid.Row="5" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Style="{StaticResource MaterialDesignTextBlock}" Text="聚焦" /> <TextBlock Style="{StaticResource MaterialDesignTextBlock}" Text="聚焦" FontSize="11" />
</StackPanel> </StackPanel>
<StackPanel Grid.Row="5" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel Grid.Row="5" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="FocusFarBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}"> <Button Name="FocusFarBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}">
@ -118,13 +121,23 @@
</Button> </Button>
</StackPanel> </StackPanel>
<StackPanel Grid.Row="6" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel Grid.Row="6" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Style="{StaticResource MaterialDesignTextBlock}" Text="光焦" /> <TextBlock Style="{StaticResource MaterialDesignTextBlock}" Text="光焦" FontSize="11" />
</StackPanel> </StackPanel>
<StackPanel Grid.Row="6" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel Grid.Row="6" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="IrisCloseBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}"> <Button Name="IrisCloseBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}">
<materialDesign:PackIcon Kind="MinusThick"/> <materialDesign:PackIcon Kind="MinusThick"/>
</Button> </Button>
</StackPanel> </StackPanel>
<StackPanel Grid.Row="8" Grid.ColumnSpan="3" HorizontalAlignment="Center" VerticalAlignment="Center">
<ComboBox Name="PresetId" materialDesign:HintAssist.Hint="预置点" Width="90" Height="30" SelectedIndex="0" Style="{StaticResource MaterialDesignOutlinedComboBox}"
Padding="17 0 0 0" FontSize="11" Foreground="#90caf9" HorizontalContentAlignment="Center" BorderBrush="#90caf9" VerticalContentAlignment="Center">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="9" Grid.ColumnSpan="3" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="GotoBtn" Content="前往预置点" Width="90" Height="30" Click="GotoBtn_Click" Style="{StaticResource MaterialDesignOutlinedLightButton}"
Padding="0" FontSize="11" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
</StackPanel>
</Grid> </Grid>
</StackPanel> </StackPanel>
</Grid> </Grid>

40
JiLinApp/Components/CameraRealPlay.xaml.cs

@ -3,6 +3,7 @@ using JiLinApp.Docking.Ptz;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
@ -32,15 +33,28 @@ public partial class CameraRealPlay : Window
private void Init() private void Init()
{ {
// 初始化预置位
for (int i = 1; i <= 8; i++)
{
PresetId.Items.Add(new ComboBoxItem { Content = i });
}
// 绑定云台响应事件 // 绑定云台响应事件
List<Button> btnList = new(); List<Button> btnList = new();
WpfUtil.FindVisualChild(PtzPanel, ref btnList); WpfUtil.FindVisualChild(PtzPanel, ref btnList);
foreach (var btn in btnList) foreach (var btn in btnList)
{
if (btn.Name.StartsWith("goto", StringComparison.OrdinalIgnoreCase))
{
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(GotoBtn_Click), true);
}
else
{ {
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(PtzBtn_MouseDown), true); btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(PtzBtn_MouseDown), true);
btn.AddHandler(MouseUpEvent, new MouseButtonEventHandler(PtzBtn_MouseUp), true); btn.AddHandler(MouseUpEvent, new MouseButtonEventHandler(PtzBtn_MouseUp), true);
} }
} }
}
#endregion #endregion
@ -56,15 +70,21 @@ public partial class CameraRealPlay : Window
CameraSdk.StopPlay(); CameraSdk.StopPlay();
} }
public bool IsPlaying()
{
return CameraSdk.IsPlaying();
}
public void StartPlayFirmly() public void StartPlayFirmly()
{ {
while (!CameraSdk.IsPlaying()) while (!IsPlaying())
{ {
StartPlay(); StartPlay();
Thread.Sleep(100);
} }
} }
#endregion #endregion Base
#region ElementEvent #region ElementEvent
@ -84,7 +104,17 @@ public partial class CameraRealPlay : Window
PtzCameraCmd.PtzMove(CameraSdk, cmdType, new int[] { stop }); PtzCameraCmd.PtzMove(CameraSdk, cmdType, new int[] { stop });
} }
#endregion private void GotoBtn_Click(object sender, RoutedEventArgs e)
{
if (CameraSdk == null) return;
PtzCmdType cmdType = PtzCmdType.PresetGoto;
int presetId = int.Parse(PresetId.Text);
PtzCameraCmd.PtzMove(CameraSdk, cmdType, new int[] { presetId });
}
#endregion ElementEvent
#region Util
private const int GWL_STYLE = -16; private const int GWL_STYLE = -16;
private const int WS_MAXIMIZEBOX = 0x10000; private const int WS_MAXIMIZEBOX = 0x10000;
@ -109,8 +139,6 @@ public partial class CameraRealPlay : Window
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags); private static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
#region Util
public void HideMinButton() public void HideMinButton()
{ {
IntPtr hwnd = new WindowInteropHelper(this).Handle; IntPtr hwnd = new WindowInteropHelper(this).Handle;
@ -137,5 +165,5 @@ public partial class CameraRealPlay : Window
StopPlay(); StopPlay();
} }
#endregion #endregion Util
} }

10
JiLinApp/Core/Config.cs

@ -1,5 +1,5 @@
using EC.Util.CameraSDK; using JiLinApp.Biz.TransmitAlarm;
using JiLinApp.Biz.TransmitAlarm; using JiLinApp.Docking.Military;
using JiLinApp.Docking.Ptz; using JiLinApp.Docking.Ptz;
using System.Collections.Generic; using System.Collections.Generic;
@ -9,9 +9,7 @@ public class AppConfig
{ {
public BaseConfig Base { get; set; } public BaseConfig Base { get; set; }
public List<PtzControlTypeConfig> PtzCtrlTypes { get; set; } public MilitaryConfig Military { get; set; }
public List<CameraInfo> CameraList { get; set; }
public AlarmPlatformConfig AlarmPlatform { get; set; } public AlarmPlatformConfig AlarmPlatform { get; set; }
} }
@ -19,4 +17,6 @@ public class AppConfig
public class BaseConfig public class BaseConfig
{ {
public bool Console { get; set; } public bool Console { get; set; }
public List<PtzControlTypeConfig> PtzCtrlTypes { get; set; }
} }

17
JiLinApp/Core/Global.cs

@ -1,6 +1,7 @@
using EC.Util.Common; using EC.Util.Common;
using JiLinApp.Biz.TransmitAlarm; using JiLinApp.Biz.TransmitAlarm;
using JiLinApp.Docking.Alarm; using JiLinApp.Docking.Alarm;
using JiLinApp.Docking.Military;
using JiLinApp.Docking.Ptz; using JiLinApp.Docking.Ptz;
using NewLife.Configuration; using NewLife.Configuration;
using System; using System;
@ -16,6 +17,8 @@ public static class Global
public static AppConfig AppConfig { get; } public static AppConfig AppConfig { get; }
public static MilitaryService MilitaryService { get; }
public static IAlarmService AlarmService { get; } public static IAlarmService AlarmService { get; }
#endregion Fields #endregion Fields
@ -29,12 +32,20 @@ public static class Global
AppConfig = new AppConfig(); AppConfig = new AppConfig();
ConfigProvider.Bind(AppConfig); ConfigProvider.Bind(AppConfig);
// BaseConfig
BaseConfig baseConfig = AppConfig.Base;
// 控制台 // 控制台
if (AppConfig.Base.Console) SystemUtil.AllocConsole(); if (baseConfig.Console) SystemUtil.AllocConsole();
// ptzCtrlTypes // ptzCtrlTypes
PtzControlTypeConfigHelper.Init(AppConfig.PtzCtrlTypes); PtzControlTypeConfigHelper.Init(baseConfig.PtzCtrlTypes);
// MilitaryConfig
MilitaryConfig militaryConfig = AppConfig.Military;
MilitaryService = new MilitaryService(militaryConfig);
AlarmService = AlarmServiceFactory.CreateService(AppConfig.AlarmPlatform); // AlarmPlatformConfig
AlarmPlatformConfig alarmPlatformConfig = AppConfig.AlarmPlatform;
AlarmService = AlarmServiceFactory.CreateService(alarmPlatformConfig);
AlarmService?.Start(); AlarmService?.Start();
} }
catch (Exception) catch (Exception)

4
JiLinApp/JiLinApp.csproj

@ -16,7 +16,9 @@
<Compile Remove="Core\LogUnit.cs" /> <Compile Remove="Core\LogUnit.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="log4net" Version="2.0.15" /> <None Include="..\.editorconfig" Link=".editorconfig" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MaterialDesignColors" Version="2.1.2"> <PackageReference Include="MaterialDesignColors" Version="2.1.2">
<TreatAsUsed>true</TreatAsUsed> <TreatAsUsed>true</TreatAsUsed>
</PackageReference> </PackageReference>

3
JiLinApp/Pages/PtzManage/Main.xaml

@ -208,10 +208,9 @@
</Grid> </Grid>
<StackPanel Grid.Column="2"> <StackPanel Grid.Column="2">
<ComboBox Name="PresetId" materialDesign:HintAssist.Hint="预置点Id" Width="160" SelectedIndex="0" Style="{StaticResource MaterialDesignOutlinedComboBox}"> <ComboBox Name="PresetId" materialDesign:HintAssist.Hint="预置点" Width="160" SelectedIndex="0" Style="{StaticResource MaterialDesignOutlinedComboBox}">
</ComboBox> </ComboBox>
<Button Name="GotoBtn" Content="前往预置点" Width="120" Margin="0 10 0 0" Click="GotoBtn_Click" Style="{StaticResource MaterialDesignRaisedLightButton}" /> <Button Name="GotoBtn" Content="前往预置点" Width="120" Margin="0 10 0 0" Click="GotoBtn_Click" Style="{StaticResource MaterialDesignRaisedLightButton}" />
<Button Name="TestBtn" Content="测试" Width="120" Visibility="Visible" Margin="0 10 0 0" Click="TestBtn_Click" Style="{StaticResource MaterialDesignRaisedLightButton}" />
</StackPanel> </StackPanel>
</Grid> </Grid>
</GroupBox> </GroupBox>

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

@ -1,18 +1,18 @@
using EC.Util.CameraSDK; using EC.Util.CameraSDK;
using EC.Util.Common;
using EC.Util.Port; using EC.Util.Port;
using ImTools; using ImTools;
using JiLinApp.Biz.TransmitAlarm; using JiLinApp.Biz.TransmitAlarm;
using JiLinApp.Components; using JiLinApp.Components;
using JiLinApp.Core; using JiLinApp.Core;
using JiLinApp.Docking.Military;
using JiLinApp.Docking.Ptz; using JiLinApp.Docking.Ptz;
using NewLife.Reflection;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO.Ports; using System.IO.Ports;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
@ -27,15 +27,25 @@ public partial class Main : UserControl
{ {
#region Fields #region Fields
private AppConfig AppConfig { get; }
private MilitaryService MilitaryService { get; }
private YcSerialPort Port { get; set; } private YcSerialPort Port { get; set; }
private ConcurrentDictionary<string, ICameraSDK> CameraSdkMap { get; } = new(); private List<CameraLinkageInfo> CameraLinkageList { get; set; }
private ConcurrentDictionary<string, ICameraSDK> CameraSdkDict { get; } = new();
private ConcurrentDictionary<string, CameraRealPlay> RealPlayDict { get; } = new();
#endregion Fields #endregion Fields
public Main() public Main()
{ {
InitializeComponent(); InitializeComponent();
AppConfig = Global.AppConfig;
MilitaryService = Global.MilitaryService;
Init(); Init();
} }
@ -57,11 +67,11 @@ public partial class Main : UserControl
ComName.Items.Add(new ComboBoxItem { Content = port }); ComName.Items.Add(new ComboBoxItem { Content = port });
} }
// 解析海康相机 // 加载 Military 信息
TaskUtil.RunCatch(() => Dispatcher.Invoke(LoadCameraList)); LoadMilitaryInfo();
// 初始化云台控制类型 // 初始化云台控制类型
foreach (var cfg in Global.AppConfig.PtzCtrlTypes) foreach (var cfg in AppConfig.Base.PtzCtrlTypes)
{ {
ControlTypeName.Items.Add(new ComboBoxItem { Content = cfg.Name }); ControlTypeName.Items.Add(new ComboBoxItem { Content = cfg.Name });
} }
@ -72,7 +82,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 <= 6; i++) for (int i = 1; i <= 8; i++)
{ {
PresetId.Items.Add(new ComboBoxItem { Content = i }); PresetId.Items.Add(new ComboBoxItem { Content = i });
} }
@ -173,7 +183,7 @@ public partial class Main : UserControl
case PtzControlType.CameraSdk: case PtzControlType.CameraSdk:
string cameraIp = CameraIp.Text; string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk); CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) break; if (cameraSdk == null) break;
int stop = 0; int stop = 0;
PtzCameraCmd.PtzMove(cameraSdk, cmdType, new int[] { stop }); PtzCameraCmd.PtzMove(cameraSdk, cmdType, new int[] { stop });
@ -207,7 +217,7 @@ public partial class Main : UserControl
case PtzControlType.CameraSdk: case PtzControlType.CameraSdk:
string cameraIp = CameraIp.Text; string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk); CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) break; if (cameraSdk == null) break;
cmdType = PtzCmd.GetCmdType(((Button)sender).Name.Replace("Btn", "")); cmdType = PtzCmd.GetCmdType(((Button)sender).Name.Replace("Btn", ""));
int stop = 1; int stop = 1;
@ -236,7 +246,7 @@ public partial class Main : UserControl
case PtzControlType.CameraSdk: case PtzControlType.CameraSdk:
string cameraIp = CameraIp.Text; string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk); CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) break; if (cameraSdk == null) break;
PtzCameraCmd.PtzMove(cameraSdk, cmdType, new int[] { presetId }); PtzCameraCmd.PtzMove(cameraSdk, cmdType, new int[] { presetId });
break; break;
@ -245,21 +255,6 @@ public partial class Main : UserControl
} }
} }
private void TestBtn_Click(object sender, RoutedEventArgs e)
{
AlarmMessage alarm = new();
alarm.ChannelId = Convert.ToInt32(PresetId.Text);
if (PresetId.Text == "5")
{
PresetId.Text = "6";
}
else
{
PresetId.Text = "5";
}
GotoPresetInvoke(null);
}
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;
@ -318,95 +313,101 @@ public partial class Main : UserControl
#region InvokeEvent #region InvokeEvent
public void GotoPresetInvoke(AlarmMessage alarm) public void HandleAlarmInvoke(AlarmMessage alarm)
{
Dispatcher.Invoke(() =>
{ {
if (Global.AppConfig.AlarmPlatform.RealPlay) if (alarm == null) return;
{ bool realPlay = AppConfig.AlarmPlatform.RealPlay;
PtzControlType ctrlType = PtzControlTypeConfigHelper.GetControlType(ControlTypeName.Text); string deviceId = alarm.LabelCode;
if (ctrlType == PtzControlType.CameraSdk) ShowLiveVideo(); string sensorId = alarm.ChannelId;
CameraLinkageInfo cameraLinkage = GetCameraLinkage(sensorId);
if (cameraLinkage == null) { LogUnit.Error(this, $"CameraLinkageInfo(sensorId:{sensorId}) not found."); return; }
string cameraId = cameraLinkage.CameraId;
ICameraSDK cameraSdk = GetCameraSdk(cameraId);
if (cameraSdk == null) { LogUnit.Error(this, $"CameraSdk(cameraId:{cameraId}) not found."); return; }
if (realPlay) Dispatcher.Invoke(() => ShowLiveVideo(cameraSdk));
} }
if (alarm != null)
{ public void ShowLiveVideo(string cameraIp)
if (alarm.ChannelId <= 5)
{ {
PresetId.Text = "5"; CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
} if (cameraSdk == null) return;
else RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay);
if (realPlay == null || realPlay.IsClosed)
{ {
PresetId.Text = "6"; realPlay = new(cameraSdk);
} realPlay.Owner = Window.GetWindow(this);
// 切换至下一预置点 RealPlayDict[cameraIp] = realPlay;
//int index = PresetId.SelectedIndex;
//index = (index + 1) % PresetId.Items.Count;
//PresetId.SelectedIndex = index;
GotoBtn_Click(null, null);
} }
}); realPlay.Show();
realPlay.HideMinButton();
realPlay.StartPlay();
} }
private ConcurrentDictionary<string, CameraRealPlay> RealPlayDict { get; } = new(); public void ShowLiveVideo(ICameraSDK cameraSdk)
public void ShowLiveVideo()
{ {
string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) return; if (cameraSdk == null) return;
string cameraIp = cameraSdk.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(cameraSdk);
realPlay.Owner = Window.GetWindow(this); realPlay.Owner = Window.GetWindow(this);
realPlay.HideMinButton();
RealPlayDict[cameraIp] = realPlay; RealPlayDict[cameraIp] = realPlay;
} }
realPlay.Show(); realPlay.Show();
realPlay.HideMinButton(); if (!realPlay.IsPlaying()) realPlay.StartPlayFirmly();
realPlay.StartPlay();
//切换至下一相机
//int index = CameraIp.SelectedIndex;
//index = (index + 1) % CameraIp.Items.Count;
//CameraIp.SelectedIndex = index;
} }
#endregion InvokeEvent #endregion InvokeEvent
#region CameraSdkMap #region Military
private void LoadCameraList() private void LoadMilitaryInfo()
{ {
List<CameraInfo> cameraList = Global.AppConfig.CameraList; List<CameraInfo> cameraList = MilitaryService.GetCameraList();
foreach (var item in cameraList) CameraLinkageList = MilitaryService.GetCameraLinkageList();
{ TaskUtil.RunCatch(() => Dispatcher.Invoke(() => LoadCameraSdkDict(cameraList)));
string ip = item.Ip; }
if (CameraSdkMap.ContainsKey(ip)) continue;
CameraSdkMap[ip] = null; private void LoadCameraSdkDict(List<CameraInfo> cameraList)
CameraIp.Items.Add(new ComboBoxItem { Content = ip });
CameraInfo info = new();
info.Copy(item);
Task.Run(() =>
{ {
ICameraSDK sdk = (info.GetManufactor) switch CameraSdkDict.Clear();
for (int i = 0; i < cameraList.Count; i++)
{ {
CameraManufactor.HiK => new HiKSDK(info), CameraInfo info = cameraList[i];
CameraManufactor.DaHua => new DaHuaSDK(info), string ip = info.Ip;
CameraManufactor.YuShi => new YuShiSDK(info), if (CameraSdkDict.ContainsKey(ip)) continue;
_ => throw new NotSupportedException(), CameraSdkDict[ip] = null;
}; CameraIp.Items.Add(new ComboBoxItem { Content = ip });
try TaskUtil.RunCatch(() =>
{ {
ICameraSDK sdk = CameraFactory.BuildCameraSdk(info);
bool ret = sdk.Init(); bool ret = sdk.Init();
if (!ret) return; if (!ret) return;
CameraSdkMap[ip] = sdk; CameraSdkDict[ip] = sdk;
});
} }
catch (Exception ex) }
private CameraLinkageInfo GetCameraLinkage(string sensorId)
{
foreach (var item in CameraLinkageList)
{ {
MessageBox.Show(ex.Message); if (sensorId.Equals(item.SensorId)) return item;
} }
}); return null;
}
private ICameraSDK GetCameraSdk(string cameraId)
{
foreach (var item in CameraSdkDict.Values)
{
if (cameraId.Equals(item.CameraInfo.Id)) return item;
} }
return null;
} }
#endregion CameraSdkMap #endregion Military
} }

10
JiLinApp/Pages/PtzManage/MainViewModel.cs

@ -1,5 +1,4 @@
using JiLinApp.Biz.TransmitAlarm; using JiLinApp.Biz.TransmitAlarm;
using JiLinApp.Core;
using JiLinApp.Docking.FenceAlarm; using JiLinApp.Docking.FenceAlarm;
using JiLinApp.Docking.VibrateAlarm; using JiLinApp.Docking.VibrateAlarm;
using JiLinApp.Mvvm; using JiLinApp.Mvvm;
@ -15,15 +14,10 @@ public class MainViewModel : ViewModelBase
private Main View { get; set; } private Main View { get; set; }
private AppConfig AppConfig { get; }
#endregion Fields #endregion Fields
public MainViewModel(IRegionManager region, IEventAggregator ea) : base(region, ea) public MainViewModel(IRegionManager region, IEventAggregator ea) : base(region, ea)
{ {
// Bind global fields
AppConfig = Global.AppConfig;
// Bind invoke event // Bind invoke event
ea.GetEvent<VibrateTcpSendAlarmEvent>().Subscribe(VibrateTcpSendAlarm); ea.GetEvent<VibrateTcpSendAlarmEvent>().Subscribe(VibrateTcpSendAlarm);
ea.GetEvent<FenceUdpSendAlarmEvent>().Subscribe(FenceUdpSendAlarm); ea.GetEvent<FenceUdpSendAlarmEvent>().Subscribe(FenceUdpSendAlarm);
@ -39,13 +33,13 @@ public class MainViewModel : ViewModelBase
internal void VibrateTcpSendAlarm(TcpAlarmHostMessage msg) internal void VibrateTcpSendAlarm(TcpAlarmHostMessage msg)
{ {
AlarmMessage alarm = msg.ToAlarmMessage(); AlarmMessage alarm = msg.ToAlarmMessage();
View.GotoPresetInvoke(alarm); View.HandleAlarmInvoke(alarm);
} }
internal void FenceUdpSendAlarm(UdpAlarmHostMessage msg) internal void FenceUdpSendAlarm(UdpAlarmHostMessage msg)
{ {
AlarmMessage alarm = msg.ToAlarmMessage(); AlarmMessage alarm = msg.ToAlarmMessage();
View.GotoPresetInvoke(alarm); View.HandleAlarmInvoke(alarm);
} }
#endregion InvokeEvent #endregion InvokeEvent

30
JiLinApp/config/config.json

@ -1,7 +1,6 @@
{ {
"base": { "base": {
"console": true "console": true,
},
"ptzCtrlTypes": [ "ptzCtrlTypes": [
{ {
"type": "CameraSdk", "type": "CameraSdk",
@ -20,30 +19,15 @@
"Name": "协议D508" "Name": "协议D508"
} }
], ]
"cameraList": [
{
"manufactor": 1,
"ip": "192.168.1.65",
"port": "8000",
"username": "admin",
"password": "hk123456"
}, },
{ "military": {
"manufactor": 1, "url": "http://192.168.1.119:8080/military",
"ip": "192.168.1.65",
"port": "8000",
"username": "admin", "username": "admin",
"password": "hk123456" "password": "123456",
"requestRetryTime": "5",
"requestRetryInterval": "200"
}, },
{
"manufactor": 1,
"ip": "192.168.1.65",
"port": "8000",
"username": "admin",
"password": "hk123456"
}
],
"alarmPlatform": { "alarmPlatform": {
"realPlay": true, "realPlay": true,
"type": "mqtt", "type": "mqtt",

Loading…
Cancel
Save