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. 674
      EC.Util/Common/DateUnit.cs
  10. 560
      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. 72
      EC.Util/Net/APICallBack.cs
  15. 598
      EC.Util/Net/HttpServer.cs
  16. 1028
      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. 93
      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. 21
      JiLinApp/Components/CameraRealPlay.xaml
  36. 44
      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. 175
      JiLinApp/Pages/PtzManage/Main.xaml.cs
  42. 10
      JiLinApp/Pages/PtzManage/MainViewModel.cs
  43. 70
      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(CameraManufactor manufactor, string ip, int port, string username, string password)
{
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = username, Password = password };
if (port <= 0) throw new Exception("Camera manufactor not support.");
return info;
}
public static CameraInfo New(CameraManufactor manufactor, string ip, string username, string password)
{
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, UserName = username, Password = password };
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) public static CameraInfo New(int manufactor, string ip, int port, string username, string password)
{ {
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = userName, Password = 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."); 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(int manufactor, string ip, string username, string password)
{ {
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, UserName = userName, Password = password }; CameraManufactor cm = (CameraManufactor)manufactor;
int port = (CameraManufactor)manufactor switch 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)
{ {

674
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,427 +8,412 @@ Update : 2015-12-31
TODO : */ TODO : */
/*******************************************************/ /*******************************************************/
namespace EC.Util.Common;
namespace System /// <summary>
/// 日期时间操作单元
/// </summary>
public partial class DateUnit
{ {
/// <summary> /// <summary>
/// 日期时间操作单元 /// 1970-1-1
/// </summary> /// </summary>
public partial class DateUnit public static DateTime InitDate()
{ {
return new DateTime(1970, 1, 1);
}
/// <summary> /// <summary>
/// 1970-1-1 /// 默认当前日期
/// </summary> /// </summary>
public static DateTime InitDate() public static DateTime DefDate()
{ {
return new DateTime(1970, 1, 1); return DateTime.Now;
} }
/// <summary>
/// 格式化后的当前日期
/// </summary>
public static string DefFormatDate()
{
return FormatDate(DefDate());
}
/// <summary> /// <summary>
/// 默认当前日期 ///格式化当前时间
/// </summary> /// </summary>
public static DateTime DefDate() public static string DefFormatDateTime()
{
return FormatDateTime(DefDate());
}
/// <summary>
/// 格式化后的 当前月1号 日期格式yyyy-MM-01
/// </summary>
public static string DefMonthBegFormat()
{
return DefDate().ToString("yyyy-MM-01");
}
/// <summary>
/// 字符串格式->格式化为当前日期
/// </summary>
/// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDate(string Indate)
{
DateTime nowDate = DefDate();
if (Indate != null && Indate != "")
{ {
return DateTime.Now; nowDate = ToDate(Indate);
} }
/// <summary>
/// 格式化后的当前日期 return FormatDate(nowDate);
/// </summary> }
public static string DefFormatDate()
/// <summary>
/// 格式化为 日期格式yyyy-MM-dd
/// </summary>
/// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDate(DateTime Indate)
{
if (!Indate.Equals(null))
{ {
return FormatDate(DefDate()); return Indate.ToString("yyyy-MM-dd");
} }
/// <summary> else
///格式化当前时间
/// </summary>
public static string DefFormatDateTime()
{ {
return FormatDateTime(DefDate()); return DefFormatDate();
} }
}
/// <summary> /// <summary>
/// 格式化后的 当前月1号 日期格式yyyy-MM-01 /// 格式化为 日期时间格式yyyy-MM-dd HH:mm:ss
/// </summary> /// </summary>
public static string DefMonthBegFormat() /// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDateTime(DateTime Indate)
{
if (!Indate.Equals(null))
{ {
return DefDate().ToString("yyyy-MM-01"); return Indate.ToString("yyyy-MM-dd HH:mm:ss");
} }
/// <summary> else
/// 字符串格式->格式化为当前日期
/// </summary>
/// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDate(string Indate)
{ {
DateTime nowDate = DefDate(); return DefFormatDate();
if (Indate != null && Indate != "")
{
nowDate = ToDate(Indate);
}
return FormatDate(nowDate);
} }
/// <summary> }
/// 格式化为 日期格式yyyy-MM-dd
/// </summary>
/// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDate(DateTime Indate)
{
if (!Indate.Equals(null))
{
return Indate.ToString("yyyy-MM-dd");
}
else
{
return DefFormatDate();
}
/// <summary>
/// 格式化时间 毫秒
/// </summary>
/// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDateTimefff(DateTime Indate)
{
if (!Indate.Equals(null))
{
return Indate.ToString("yyyy-MM-dd HH:mm:ss fff");
} }
/// <summary> else
/// 格式化为 日期时间格式yyyy-MM-dd HH:mm:ss
/// </summary>
/// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDateTime(DateTime Indate)
{ {
return DefFormatDate();
}
}
if (!Indate.Equals(null)) #region 时间函数
{
return Indate.ToString("yyyy-MM-dd HH:mm:ss");
}
else
{
return DefFormatDate();
}
/// <summary>
/// 是不是时间格式
/// </summary>
/// <param name="datetm"></param>
/// <returns></returns>
public static bool IsDate(string datetm)
{
bool result = false;
try
{
DateTime dateTime = Convert.ToDateTime(datetm);
result = true;
} }
/// <summary> catch
/// 格式化时间 毫秒
/// </summary>
/// <param name="Indate"></param>
/// <returns></returns>
public static string FormatDateTimefff(DateTime Indate)
{ {
result = false;
}
return result;
}
if (!Indate.Equals(null)) /// <summary>
{ /// 将字符串转化成日期,如果输入的字符串不是日期时,则返回1970-1-1
return Indate.ToString("yyyy-MM-dd HH:mm:ss fff"); /// </summary>
} /// <param name="str"></param>
/// <returns></returns>
public static DateTime ToDate(string str)
{
if (str == null || str == "")
return DefDate();
else
{
DateTime dt = DefDate();
if (DateTime.TryParse(str, out dt) == false)
return DefDate();
else else
{ return dt;
return DefFormatDate();
}
} }
}
/// <summary>
#region 时间函数 /// 将对象转化成日期,如果输入的对象不是日期时,则返回1970-1-1
/// </summary>
/// <summary> /// <param name="obj"></param>
/// 是不是时间格式 /// <returns></returns>
/// </summary> public static DateTime ToDate(object obj)
/// <param name="datetm"></param> {
/// <returns></returns> DateTime Result = DefDate();
public static bool IsDate(string datetm) if (!obj.Equals(null))
{ {
bool result = false;
try try
{ {
DateTime dateTime = Convert.ToDateTime(datetm); Result = (DateTime)obj;
result = true;
} }
catch catch (Exception ex)
{ {
result = false; return DefDate();
} }
return result; //if (DateTime.TryParse(obj.ToString(), out Result) == false)
// return DefDate;
} }
return Result;
}
/// <summary>
/// <summary> /// 将对象转化成日期,如果输入的对象不是日期时,则返回1900-1-1
/// 将字符串转化成日期,如果输入的字符串不是日期时,则返回1970-1-1 /// </summary>
/// </summary> /// <param name="obj"></param>
/// <param name="str"></param> /// <returns></returns>
/// <returns></returns> public static DateTime ToDate(System.Nullable<System.DateTime> obj)
public static DateTime ToDate(string str) {
if (!obj.Equals(null))
{ {
if (str == null || str == "") return (DateTime)obj;
return DefDate();
else
{
DateTime dt = DefDate();
if (DateTime.TryParse(str, out dt) == false)
return DefDate();
else
return dt;
}
} }
else
/// <summary>
/// 将对象转化成日期,如果输入的对象不是日期时,则返回1970-1-1
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static DateTime ToDate(object obj)
{ {
DateTime Result = DefDate(); return DefDate();
if (!obj.Equals(null))
{
try
{
Result = (DateTime)obj;
}
catch (Exception ex)
{
return DefDate();
}
//if (DateTime.TryParse(obj.ToString(), out Result) == false)
// return DefDate;
}
return Result;
} }
}
/// <summary> /// <summary>
/// 将对象转化成日期,如果输入的对象不是日期时,则返回1900-1-1 /// 20070101-->2007-01-01
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="Str"></param>
/// <returns></returns> /// <returns></returns>
public static DateTime ToDate(System.Nullable<System.DateTime> obj) public static string StrTodate(string Str)
{
string stryear, strmon, strday;
try
{ {
if (!obj.Equals(null)) stryear = Str.Remove(4, 4);
{ Str = Str.Remove(0, 4);
strmon = Str.Remove(2, 2);
return (DateTime)obj; strday = Str.Remove(0, 2);
} stryear = stryear + "-" + strmon + "-" + strday;
else return stryear;
{
return DefDate();
}
} }
catch
/// <summary>
/// 20070101-->2007-01-01
/// </summary>
/// <param name="Str"></param>
/// <returns></returns>
public static string StrTodate(string Str)
{ {
string stryear, strmon, strday; return DefFormatDate();
try
{
stryear = Str.Remove(4, 4);
Str = Str.Remove(0, 4);
strmon = Str.Remove(2, 2);
strday = Str.Remove(0, 2);
stryear = stryear + "-" + strmon + "-" + strday;
return stryear;
}
catch
{
return DefFormatDate();
}
} }
}
#endregion 时间函数
#region 周计算
#endregion /// <summary>
/// 周几
#region 周计算 /// </summary>
/// <param name="curDay"></param>
/// <summary> /// <returns></returns>
/// 周几 public static string DayOfWeek(DateTime curDay)
/// </summary> {
/// <param name="curDay"></param> string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
/// <returns></returns> string week = weekdays[Convert.ToInt32(curDay.DayOfWeek)];
public static string DayOfWeek(DateTime curDay)
{
return week;
}
string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; /// <summary>
string week = weekdays[Convert.ToInt32(curDay.DayOfWeek)]; /// 第几周
/// </summary>
/// <param name="curDay"></param>
/// <returns></returns>
public static int WeekOfYear(DateTime curDay)
{
int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "-" + "1-1").DayOfWeek);
return week; int days = curDay.DayOfYear;
int daysOutOneWeek = days - (7 - firstdayofweek);
if (daysOutOneWeek <= 0)
{
return 1;
} }
else
/// <summary>
/// 第几周
/// </summary>
/// <param name="curDay"></param>
/// <returns></returns>
public static int WeekOfYear(DateTime curDay)
{ {
int weeks = daysOutOneWeek / 7;
if (daysOutOneWeek % 7 != 0)
weeks++;
int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "-" + "1-1").DayOfWeek); return weeks + 1;
int days = curDay.DayOfYear;
int daysOutOneWeek = days - (7 - firstdayofweek);
if (daysOutOneWeek <= 0)
{
return 1;
}
else
{
int weeks = daysOutOneWeek / 7;
if (daysOutOneWeek % 7 != 0)
weeks++;
return weeks + 1;
}
} }
}
#region 返回某年某月最后一天 #region 返回某年某月最后一天
/// <summary>
/// 返回某年某月最后一天
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns>日</returns>
public static int GetMonthLastDate(int year, int month)
{
DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
int Day = lastDay.Day;
return Day;
}
#endregion
/// <summary>
/// 返回某年某月最后一天
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns>日</returns>
public static int GetMonthLastDate(int year, int month)
{
DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
int Day = lastDay.Day;
return Day;
}
#endregion #endregion 返回某年某月最后一天
#endregion 周计算
#region 返回时间差 #region 返回时间差
/// <summary>
/// 返回时间差 秒
/// </summary>
/// <param name="begDateTime"></param>
/// <param name="endDateTime"></param>
/// <returns></returns>
public static double DateDiffSeconds(DateTime begDateTime, DateTime endDateTime)
{
try /// <summary>
{ /// 返回时间差 秒
TimeSpan ts = endDateTime - begDateTime; /// </summary>
return ts.TotalSeconds; /// <param name="begDateTime"></param>
} /// <param name="endDateTime"></param>
catch (Exception) /// <returns></returns>
{ public static double DateDiffSeconds(DateTime begDateTime, DateTime endDateTime)
return 0; {
} try
}
/// <summary>
/// 返回时间差 分钟
/// </summary>
/// <param name="begDateTime"></param>
/// <param name="endDateTime"></param>
/// <returns></returns>
public static double DateDiffMinutes(DateTime begDateTime, DateTime endDateTime)
{ {
TimeSpan ts = endDateTime - begDateTime;
try return ts.TotalSeconds;
{
TimeSpan ts = endDateTime - begDateTime;
return ts.TotalMinutes;
}
catch (Exception)
{
return 0;
}
} }
public static double DateDiffHours(DateTime begDateTime, DateTime endDateTime) catch (Exception)
{ {
return 0;
try
{
TimeSpan ts = endDateTime - begDateTime;
return ts.TotalHours;
}
catch (Exception)
{
return 0;
}
} }
public static double DateDifDays(DateTime begDateTime, DateTime endDateTime) }
{
try /// <summary>
{ /// 返回时间差 分钟
TimeSpan ts = endDateTime - begDateTime; /// </summary>
return ts.TotalDays; /// <param name="begDateTime"></param>
} /// <param name="endDateTime"></param>
catch (Exception) /// <returns></returns>
{ public static double DateDiffMinutes(DateTime begDateTime, DateTime endDateTime)
return 0; {
} try
{
TimeSpan ts = endDateTime - begDateTime;
return ts.TotalMinutes;
} }
#endregion catch (Exception)
/// <summary>
/// Unix时间戳
/// </summary>
/// <returns>毫秒</returns>
public static long UnixTime()
{ {
System.DateTime time = DateTime.Now; return 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
} }
/// <summary> }
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary> public static double DateDiffHours(DateTime begDateTime, DateTime endDateTime)
/// <param name="time">时间</param> {
/// <returns> 毫秒</returns> try
public static long DateTimeToUnixTime(System.DateTime time)
{ {
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); TimeSpan ts = endDateTime - begDateTime;
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 return ts.TotalHours;
return t;
} }
/// <summary> catch (Exception)
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime UnixTimeToDateTime(long timeStamp)
{ {
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); return 0;
long lTime = timeStamp * 10000;
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
} }
}
/// <summary> public static double DateDifDays(DateTime begDateTime, DateTime endDateTime)
/// Unix时间戳 时间格式化 为日期 {
/// </summary> try
/// <param name="timeStamp"></param>
/// <returns></returns>
public static string FormatDateUnixTime(long timeStamp)
{ {
DateTime dtStart = UnixTimeToDateTime(timeStamp); TimeSpan ts = endDateTime - begDateTime;
return FormatDate(dtStart); return ts.TotalDays;
} }
/// <summary> catch (Exception)
/// Unix时间戳 时间格式化 为时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static string FormatDateTimeUnixTime(long timeStamp)
{ {
DateTime dtStart = UnixTimeToDateTime(timeStamp); return 0;
return FormatDateTime(dtStart);
} }
}
#endregion 返回时间差
/// <summary>
/// Unix时间戳
/// </summary>
/// <returns>毫秒</returns>
public static long UnixTime()
{
System.DateTime time = DateTime.Now;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns> 毫秒</returns>
public static long DateTimeToUnixTime(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime UnixTimeToDateTime(long timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = timeStamp * 10000;
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
/// <summary>
/// Unix时间戳 时间格式化 为日期
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static string FormatDateUnixTime(long timeStamp)
{
DateTime dtStart = UnixTimeToDateTime(timeStamp);
return FormatDate(dtStart);
}
/// <summary>
/// Unix时间戳 时间格式化 为时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static string FormatDateTimeUnixTime(long timeStamp)
{
DateTime dtStart = UnixTimeToDateTime(timeStamp);
return FormatDateTime(dtStart);
} }
} }

560
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,355 +7,353 @@ Create : Lxc
Update : 2014-12-31 Update : 2014-12-31
TODO : */ TODO : */
/*******************************************************/ /*******************************************************/
namespace System
namespace EC.Util.Common;
/// <summary>
/// 文件操作单元
/// </summary>
public partial class FileUnit
{ {
private static readonly string AppFilepatch = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
/// <summary> /// <summary>
/// 文件操作单元 /// 创建目录
/// </summary> /// </summary>
public partial class FileUnit /// <param name="fullPath"></param>
/// <returns></returns>
public static bool CreateDir(string fullPath)
{ {
static readonly string AppFilepatch = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; if (!Directory.Exists(fullPath))
/// <summary>
/// 创建目录
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static bool CreateDir(string fullPath)
{ {
if (!Directory.Exists(fullPath)) try
{ {
try Directory.CreateDirectory(fullPath);
{ return true;
Directory.CreateDirectory(fullPath); }
return true; catch (Exception ex)
} {
catch (Exception ex) return false;
{
return false;
}
} }
return true;
}
//删除文件名 获取路径
public static string GetDirectory(string fullPath)
{
return Path.GetDirectoryName(fullPath);
//return allFileName.Substring(0, allFileName.LastIndexOf('\\'));
}
/// <summary>
/// 得到文件名称
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static string GetFileName(string fullPath)
{
return Path.GetFileName(fullPath);
}
/// <summary>
/// 得到扩展名
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static string GetFileExt(string fullPath)
{
return Path.GetExtension(fullPath);
}
/// <summary>
/// 得到名称没有扩展名
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static string GetFileNameNoExt(string fullPath)
{
return Path.GetFileNameWithoutExtension(fullPath);
} }
/// <summary> return true;
/// 复制文件 }
/// </summary>
/// <param name="sourceFileName"></param> //删除文件名 获取路径
/// <param name="destFileName"></param> public static string GetDirectory(string fullPath)
/// <returns></returns> {
public static string CopyFile(string sourceFileName, string destFileName) return Path.GetDirectoryName(fullPath);
//return allFileName.Substring(0, allFileName.LastIndexOf('\\'));
}
/// <summary>
/// 得到文件名称
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static string GetFileName(string fullPath)
{
return Path.GetFileName(fullPath);
}
/// <summary>
/// 得到扩展名
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static string GetFileExt(string fullPath)
{
return Path.GetExtension(fullPath);
}
/// <summary>
/// 得到名称没有扩展名
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static string GetFileNameNoExt(string fullPath)
{
return Path.GetFileNameWithoutExtension(fullPath);
}
/// <summary>
/// 复制文件
/// </summary>
/// <param name="sourceFileName"></param>
/// <param name="destFileName"></param>
/// <returns></returns>
public static string CopyFile(string sourceFileName, string destFileName)
{
try
{ {
try if (File.Exists(sourceFileName))
{ {
if (File.Exists(sourceFileName)) string destDirectory = GetDirectory(destFileName);// destFileName.Substring(0, destFileName.LastIndexOf('\\'));//删除文件名 获取路径
bool createDir = CreateDir(destDirectory);
if (createDir)
{ {
string destDirectory = GetDirectory(destFileName);// destFileName.Substring(0, destFileName.LastIndexOf('\\'));//删除文件名 获取路径 File.Copy(sourceFileName, destFileName);
bool createDir = CreateDir(destDirectory);
if (createDir)
{
File.Copy(sourceFileName, destFileName);
}
else
{
return "文件路径" + destFileName + "不正确!";
}
} }
else else
{ {
return "文件路径" + sourceFileName + "不存在!"; return "文件路径" + destFileName + "不正确!";
} }
return "";
} }
catch (Exception ex) else
{ {
return ex.Message; return "文件路径" + sourceFileName + "不存在!";
} }
return "";
} }
/// <summary> catch (Exception ex)
/// 得到路径 没有扩展名
/// </summary>
/// <param name="rptPath"></param>
/// <returns></returns>
public static string GetPathNoExt(string rptPath)
{ {
string rtpDir = GetDirectory(rptPath); return ex.Message;
string disFileName = GetFileNameNoExt(rptPath);
string disPatch = rtpDir + "\\" + disFileName;// +".docx";
return disPatch;
} }
/// <summary> }
/// 读取文本
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string ReadtxtFile(string filename)
{
try /// <summary>
/// 得到路径 没有扩展名
/// </summary>
/// <param name="rptPath"></param>
/// <returns></returns>
public static string GetPathNoExt(string rptPath)
{
string rtpDir = GetDirectory(rptPath);
string disFileName = GetFileNameNoExt(rptPath);
string disPatch = rtpDir + "\\" + disFileName;// +".docx";
return disPatch;
}
/// <summary>
/// 读取文本
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string ReadtxtFile(string filename)
{
try
{
if (File.Exists(filename))
{ {
if (File.Exists(filename)) // Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
{ {
// Create an instance of StreamReader to read from a file. return sr.ReadToEnd();
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
{
return sr.ReadToEnd();
}
} }
else LogUnit.Error(typeof(FileUnit),"no exists " + filename);
}
catch (Exception e)
{
LogUnit.Error(typeof(FileUnit), e.ToString());
} }
return ""; else LogUnit.Error(typeof(FileUnit), "no exists " + filename);
}
catch (Exception e)
{
LogUnit.Error(typeof(FileUnit), e.ToString());
} }
return "";
}
/// <summary> /// <summary>
/// 读取多行文本 /// 读取多行文本
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public static List<string> ReadtxtLinesFile(string filename) public static List<string> ReadtxtLinesFile(string filename)
{
List<string> filtxtLines = new List<string>();
try
{ {
List<string> filtxtLines = new List<string>(); if (File.Exists(filename))
try
{ {
if (File.Exists(filename)) // Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
{ {
// Create an instance of StreamReader to read from a file. String line;
// The using statement also closes the StreamReader. // Read and display lines from the file until the end of
using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8)) // the file is reached.
while ((line = sr.ReadLine()) != null)
{ {
String line; filtxtLines.Add(line);
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
filtxtLines.Add(line);
}
} }
} }
} }
catch (Exception e)
{
LogUnit.Error(typeof(FileUnit), e.ToString());
}
return filtxtLines;
} }
catch (Exception e)
/// <summary>
/// 读取多行文本
/// </summary>
/// <param name="filepatch"></param>
/// <param name="filename"></param>
/// <param name="txtLines"></param>
/// <returns></returns>
public static bool WritetxtFileLine(string filepatch,string filename, List<string> txtLines)
{ {
LogUnit.Error(typeof(FileUnit), e.ToString());
}
return filtxtLines;
}
List<string> filtxtLines = new List<string>(); /// <summary>
try /// 读取多行文本
/// </summary>
/// <param name="filepatch"></param>
/// <param name="filename"></param>
/// <param name="txtLines"></param>
/// <returns></returns>
public static bool WritetxtFileLine(string filepatch, string filename, List<string> txtLines)
{
List<string> filtxtLines = new List<string>();
try
{
if (!Directory.Exists(filepatch))
{ {
Directory.CreateDirectory(filepatch);
if (!Directory.Exists(filepatch))
{
Directory.CreateDirectory(filepatch);
}
using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8))
{
foreach (string str in txtLines)
{
sw.WriteLine(str);
}
sw.Close();
}
} }
catch (Exception e) using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8))
{ {
LogUnit.Error(typeof(FileUnit), e.ToString()); foreach (string str in txtLines)
return false; {
sw.WriteLine(str);
}
sw.Close();
} }
return true;
} }
/// <summary> catch (Exception e)
/// 写入文本
/// </summary>
/// <param name="filepatch"></param>
/// <param name="filename"></param>
/// <param name="text"></param>
/// <returns></returns>
public static bool WritetxtFile(string filepatch, string filename, string text)
{ {
LogUnit.Error(typeof(FileUnit), e.ToString());
return false;
}
return true;
}
List<string> filtxtLines = new List<string>(); /// <summary>
try /// 写入文本
/// </summary>
/// <param name="filepatch"></param>
/// <param name="filename"></param>
/// <param name="text"></param>
/// <returns></returns>
public static bool WritetxtFile(string filepatch, string filename, string text)
{
List<string> filtxtLines = new List<string>();
try
{
if (!Directory.Exists(filepatch))
{ {
Directory.CreateDirectory(filepatch);
if (!Directory.Exists(filepatch))
{
Directory.CreateDirectory(filepatch);
}
using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8))
{
sw.Write(text);
sw.Close();
}
} }
catch (Exception e)
using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8))
{ {
LogUnit.Error(typeof(FileUnit), e.ToString()); sw.Write(text);
return false;
sw.Close();
} }
return true;
} }
catch (Exception e)
private static bool Log(string subfilepatch,string logmessage)
{ {
LogUnit.Error(typeof(FileUnit), e.ToString());
return false;
}
return true;
}
try private static bool Log(string subfilepatch, string logmessage)
{
try
{
string logfilePath = AppFilepatch + "Log\\" + subfilepatch;
if (!Directory.Exists(logfilePath))
{ {
string logfilePath = AppFilepatch + "Log\\" + subfilepatch ; Directory.CreateDirectory(logfilePath);
if (!Directory.Exists(logfilePath))
{
Directory.CreateDirectory(logfilePath);
}
using (StreamWriter sw = new StreamWriter(logfilePath + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + " : " + logmessage);
sw.Close();
}
} }
catch (Exception e) using (StreamWriter sw = new StreamWriter(logfilePath + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, System.Text.Encoding.UTF8))
{ {
return false; sw.WriteLine(DateTime.Now.ToString() + " : " + logmessage);
sw.Close();
} }
return true;
} }
catch (Exception e)
//支付日志
public static void PayLog(string log)
{ {
string path = "PayLog\\"; return false;
Log(path, log);
} }
return true;
}
//订单日志 //支付日志
public static void OrderLog(string log) public static void PayLog(string log)
{ {
string path = "OrderLog\\"; string path = "PayLog\\";
Log(path, log); Log(path, log);
} }
//写入日志 //订单日志
public static void Log(string log) public static void OrderLog(string log)
{ {
string path = ""; string path = "OrderLog\\";
Log(path, log); Log(path, log);
} }
public static void WebLog(string log)
{
Log(log);
}
//public static void WebLog(string log) //写入日志
//{ public static void Log(string log)
// string path = HttpContext.Current.Server.MapPath(".")+"Web\\"; {
// Log(path, log); string path = "";
//} Log(path, log);
}
public static void ErrLog(string log) public static void WebLog(string log)
{ {
string subpath = "ErrLog\\"; Log(log);
Log(subpath, log); }
}
public static void HisLog(string log)
{
string subpath = "HisLog\\";
Log(subpath, log);
}
//public static void WebLog(string log)
//{
// string path = HttpContext.Current.Server.MapPath(".")+"Web\\";
// Log(path, log);
//}
public static void Package(string log) public static void ErrLog(string log)
{ {
string path = "Package\\"; string subpath = "ErrLog\\";
Log(path, log); Log(subpath, log);
} }
public static void HisLog(string log)
{
string subpath = "HisLog\\";
Log(subpath, log);
}
public static void EPS(string log) public static void Package(string log)
{ {
string path = "EPS\\"; string path = "Package\\";
Log(path, log); Log(path, log);
} }
public static void AllLog(string log)
{ public static void EPS(string log)
string path = "AllLog\\"; {
Log(path, log); string path = "EPS\\";
} Log(path, log);
public static bool Exists(string path) }
{
return File.Exists(path); public static void AllLog(string log)
} {
public static void DeleteFile(string path) string path = "AllLog\\";
Log(path, log);
}
public static bool Exists(string path)
{
return File.Exists(path);
}
public static void DeleteFile(string path)
{
try
{ {
try if (File.Exists(path))
{ {
if (File.Exists(path)) File.Delete(path);
{
File.Delete(path);
}
else
{
LogUnit.Error(typeof(FileUnit), "路径不存在" + path);
}
} }
catch (Exception ex) else
{ {
LogUnit.Error(typeof(FileUnit), ex.ToString()); LogUnit.Error(typeof(FileUnit), "路径不存在" + path);
} }
} }
catch (Exception ex)
{
LogUnit.Error(typeof(FileUnit), ex.ToString());
}
} }
} }

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位身份证标准
}
}

72
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 wbCode { get; set; } public string reqTime { get; set; }
/// <summary> public string wbCode { get; set; }
/// AGV编号
/// </summary> /// <summary>
public string robotCode { get; set; } /// AGV编号
/// <summary> /// </summary>
/// 请求AGV接口后返回的成功失败或其他消息 public string robotCode { get; set; }
/// </summary>
public string message { get; set; } /// <summary>
/// <summary> /// 请求AGV接口后返回的成功失败或其他消息
/// 请求AGV接口后返回的任务单号 /// </summary>
/// </summary> public string message { get; set; }
public string data { get; set; }
/// <summary> /// <summary>
/// 请求AGV接口后返回的任务状态 /// 请求AGV接口后返回的任务单号
/// </summary> /// </summary>
public string code { get; set; } public string data { get; set; }
}
/// <summary>
/// 请求AGV接口后返回的任务状态
/// </summary>
public string code { get; set; }
} }

598
EC.Util/Net/HttpServer.cs

@ -1,362 +1,358 @@
 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; } public string port { get; set; }
public string port { get; set; } private string _webHomeDir = "";
private string _webHomeDir = ""; private HttpListener listener;
private HttpListener listener; private Thread listenThread;
private Thread listenThread; 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>
/// 设置监听端口,重启服务生效 //public string Port
/// </summary> //{
//public string Port // get { return this.port; }
//{ // set
// get { return this.port; } // {
// set // int p;
// { // if (string.IsNullOrEmpty(value) || !int.TryParse(value, out p))
// int p; // {
// if (string.IsNullOrEmpty(value) || !int.TryParse(value, out p)) // throw new Exception("给http监听器赋值的端口号无效!");
// { // }
// throw new Exception("给http监听器赋值的端口号无效!"); // this.port = value;
// } // }
// this.port = value; //}
// } /// <summary>
//} /// http服务根目录
/// <summary> /// </summary>
/// http服务根目录 public string WebHomeDir
/// </summary> {
public string WebHomeDir get { return this._webHomeDir; }
{ set
get { return this._webHomeDir; }
set
{
if (!Directory.Exists(value))
throw new Exception("http服务器设置的根目录不存在!");
this._webHomeDir = value;
}
}
/// <summary>
/// 服务器是否在运行
/// </summary>
public bool IsRunning
{ {
get { return (listener == null) ? false : listener.IsListening; } if (!Directory.Exists(value))
throw new Exception("http服务器设置的根目录不存在!");
this._webHomeDir = value;
} }
#endregion }
/// <summary>
/// 服务器是否在运行
/// </summary>
public bool IsRunning
{
get { return (listener == null) ? false : listener.IsListening; }
}
#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.port = port;
this._webHomeDir = webHomeDir;
ImageUploadPath = imageUploadPath;
listener = new HttpListener();
}
public bool AddPrefixes(string uriPrefix)
{
string uri = "http://" + uriPrefix + ":" + this.port + "/";
if (listener.Prefixes.Contains(uri)) return false;
listener.Prefixes.Add(uri);
return true;
}
/// <summary>
/// 启动服务
/// </summary>
public void Start()
{
try
{ {
if (listener.IsListening)
return;
if (!string.IsNullOrEmpty(Host) && Host.Length > 0)
listener.Prefixes.Add("http://" + Host + ":" + this.port + "/"); //AGV/AGVAPI/agvCallback/
else if (listener.Prefixes == null || listener.Prefixes.Count == 0)
listener.Prefixes.Add("http://localhost:" + this.port + "/");
listener.Start();
this.Host = host; listenThread = new Thread(AcceptClient);
this.port = port; listenThread.Name = "signserver";
this._webHomeDir = webHomeDir; listenThread.Start();
ImageUploadPath = imageUploadPath; Log("开启接口监听服务:" + this.port);
listener = new HttpListener();
} }
catch (Exception ex)
public bool AddPrefixes(string uriPrefix)
{ {
string uri = "http://" + uriPrefix + ":" + this.port + "/"; LogUnit.Error(ex.Message);
if (listener.Prefixes.Contains(uri)) return false;
listener.Prefixes.Add(uri);
return true;
} }
}
/// <summary> /// <summary>
/// 启动服务 /// 停止服务
/// </summary> /// </summary>
public void Start() public void Stop()
{
try
{ {
try if (listener != null)
{
if (listener.IsListening)
return;
if (!string.IsNullOrEmpty(Host) && Host.Length > 0)
listener.Prefixes.Add("http://" + Host + ":" + this.port + "/"); //AGV/AGVAPI/agvCallback/
else if (listener.Prefixes == null || listener.Prefixes.Count == 0)
listener.Prefixes.Add("http://localhost:" + this.port + "/");
listener.Start();
listenThread = new Thread(AcceptClient);
listenThread.Name = "signserver";
listenThread.Start();
Log("开启接口监听服务:"+ this.port);
}
catch (Exception ex)
{ {
LogUnit.Error(ex.Message); //listener.Close();
//listener.Abort();
listener.Stop();
} }
}
catch (Exception ex)
{
LogUnit.Error(ex.Message);
}
}
/// <summary>
/// /接受客户端请求
/// </summary>
private void AcceptClient()
{
//int maxThreadNum, portThreadNum;
////线程池
//int minThreadNum;
//ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
//ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
//Console.WriteLine("最大线程数:{0}", maxThreadNum);
//Console.WriteLine("最小空闲线程数:{0}", minThreadNum);
} while (listener.IsListening)
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{ {
try try
{ {
if (listener != null) HttpListenerContext context = listener.GetContext();
{ //new Thread(HandleRequest).Start(context);
//listener.Close(); ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context);
//listener.Abort();
listener.Stop();
}
} }
catch (Exception ex) catch
{ {
LogUnit.Error(ex.Message);
} }
} }
}
/// <summary> #endregion
/// /接受客户端请求
/// </summary>
void AcceptClient()
{
//int maxThreadNum, portThreadNum;
////线程池
//int minThreadNum;
//ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
//ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
//Console.WriteLine("最大线程数:{0}", maxThreadNum);
//Console.WriteLine("最小空闲线程数:{0}", minThreadNum);
while (listener.IsListening)
{
try
{
HttpListenerContext context = listener.GetContext();
//new Thread(HandleRequest).Start(context);
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context);
}
catch
{
}
}
} #region HandleRequest
#endregion
#region HandleRequest //处理客户端请求
//处理客户端请求 private void HandleRequest(object ctx)
private void HandleRequest(object ctx) {
HttpListenerContext context = ctx as HttpListenerContext;
HttpListenerResponse response = context.Response;
HttpListenerRequest request = context.Request;
try
{ {
HttpListenerContext context = ctx as HttpListenerContext; context.Request.Headers.Add("Access-Control-Allow-Origin", "*");
HttpListenerResponse response = context.Response; context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
HttpListenerRequest request = context.Request; string rawUrl = System.Web.HttpUtility.UrlDecode(request.RawUrl);
try int paramStartIndex = rawUrl.IndexOf('?');
if (paramStartIndex > 0)
rawUrl = rawUrl.Substring(0, paramStartIndex);
else if (paramStartIndex == 0)
rawUrl = "";
if (rawUrl.EndsWith("agvCallback"))
{ {
context.Request.Headers.Add("Access-Control-Allow-Origin", "*"); APICallBack apiCallBack = new APICallBack();
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
string rawUrl = System.Web.HttpUtility.UrlDecode(request.RawUrl);
int paramStartIndex = rawUrl.IndexOf('?');
if (paramStartIndex > 0)
rawUrl = rawUrl.Substring(0, paramStartIndex);
else if (paramStartIndex == 0)
rawUrl = "";
if ( rawUrl.EndsWith("agvCallback") ) {
APICallBack apiCallBack = new APICallBack();
apiCallBack.reqCode = context.Request.QueryString["reqCode"];
apiCallBack.taskCode = context.Request.QueryString["taskCode"];
apiCallBack.method = context.Request.QueryString["method"];
apiCallBack.wbCode = context.Request.QueryString["wbCode"];
apiCallBack.robotCode = context.Request.QueryString["robotCode"];
//接收POST参数 2020-5-30
Stream stream = context.Request.InputStream;
System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
//整理应该是接收到的值
string body = reader.ReadToEnd();
//FileUnit.Log(body);
//if (JsonUtil.JSONToObject<APICallBack>(body)!=null)
//{
// apiCallBack = JsonUnit.JSONToObject<APICallBack>(body);
//}
response.ContentType = "text/html;charset=utf-8";
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{
OnRecData?.Invoke(this, apiCallBack);
string str = Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data = "调用成功", Message = "成功", ReqCode = apiCallBack.reqCode }); apiCallBack.reqCode = context.Request.QueryString["reqCode"];
writer.Write(str); apiCallBack.taskCode = context.Request.QueryString["taskCode"];
} apiCallBack.method = context.Request.QueryString["method"];
apiCallBack.wbCode = context.Request.QueryString["wbCode"];
apiCallBack.robotCode = context.Request.QueryString["robotCode"];
////Response //接收POST参数 2020-5-30
//context.Response.StatusCode = 200; Stream stream = context.Request.InputStream;
//context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
//context.Response.ContentType = "application/json"; //整理应该是接收到的值
//context.Response.ContentEncoding = Encoding.UTF8; string body = reader.ReadToEnd();
//byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data= "调用成功", Message = "成功" , ReqCode ="",})); //FileUnit.Log(body);
//context.Response.ContentLength64 = buffer.Length; //if (JsonUtil.JSONToObject<APICallBack>(body)!=null)
//var output = context.Response.OutputStream; //{
//output.Write(buffer, 0, buffer.Length); // apiCallBack = JsonUnit.JSONToObject<APICallBack>(body);
//output.Close(); //}
} response.ContentType = "text/html;charset=utf-8";
else if (string.Compare(rawUrl, "/ImageUpload", true) == 0) using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{ {
#region 上传图片 OnRecData?.Invoke(this, apiCallBack);
string fileName = context.Request.QueryString["name"];
string filePath = ImageUploadPath + "\\" + DateTime.Now.ToString("yyMMdd_HHmmss_ffff")
+ Path.GetExtension(fileName).ToLower();
using (var stream = request.InputStream)
{
using (var br = new BinaryReader(stream))
{
WriteStreamToFile(br, filePath, request.ContentLength64);
}
}
response.ContentType = "text/html;charset=utf-8";
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) string str = Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data = "调用成功", Message = "成功", ReqCode = apiCallBack.reqCode });
{ writer.Write(str);
writer.WriteLine("接收完成!");
}
#endregion
} }
else
////Response
//context.Response.StatusCode = 200;
//context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
//context.Response.ContentType = "application/json";
//context.Response.ContentEncoding = Encoding.UTF8;
//byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data= "调用成功", Message = "成功" , ReqCode ="",}));
//context.Response.ContentLength64 = buffer.Length;
//var output = context.Response.OutputStream;
//output.Write(buffer, 0, buffer.Length);
//output.Close();
}
else if (string.Compare(rawUrl, "/ImageUpload", true) == 0)
{
#region 上传图片
string fileName = context.Request.QueryString["name"];
string filePath = ImageUploadPath + "\\" + DateTime.Now.ToString("yyMMdd_HHmmss_ffff")
+ Path.GetExtension(fileName).ToLower();
using (var stream = request.InputStream)
{ {
#region 网页请求 using (var br = new BinaryReader(stream))
string InputStream = "";
using (var streamReader = new StreamReader(request.InputStream))
{
InputStream = streamReader.ReadToEnd();
}
string filePath = "";
if (string.IsNullOrEmpty(rawUrl) || rawUrl.Length == 0 || rawUrl == "/")
filePath = WebHomeDir + directorySeparatorChar + "Index.html";
else
filePath = WebHomeDir + rawUrl.Replace("/", directorySeparatorChar);
if (!File.Exists(filePath))
{ {
response.ContentLength64 = 0; WriteStreamToFile(br, filePath, request.ContentLength64);
response.StatusCode = 404;
response.Abort();
} }
else
{
response.StatusCode = 200;
string exeName = Path.GetExtension(filePath);
response.ContentType = GetContentType(exeName);
FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
int byteLength = (int)fileStream.Length;
byte[] fileBytes = new byte[byteLength];
fileStream.Read(fileBytes, 0, byteLength);
fileStream.Close();
fileStream.Dispose();
response.ContentLength64 = byteLength;
response.OutputStream.Write(fileBytes, 0, byteLength);
response.OutputStream.Close();
}
#endregion
} }
} response.ContentType = "text/html;charset=utf-8";
catch (Exception ex)
{
LogUnit.Error(ex.Message);
response.StatusCode = 200;
response.ContentType = "text/plain";
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{ {
writer.WriteLine("接收完成!"); writer.WriteLine("接收完成!");
} }
#endregion
} }
try else
{ {
response.Close(); #region 网页请求
string InputStream = "";
using (var streamReader = new StreamReader(request.InputStream))
{
InputStream = streamReader.ReadToEnd();
}
string filePath = "";
if (string.IsNullOrEmpty(rawUrl) || rawUrl.Length == 0 || rawUrl == "/")
filePath = WebHomeDir + directorySeparatorChar + "Index.html";
else
filePath = WebHomeDir + rawUrl.Replace("/", directorySeparatorChar);
if (!File.Exists(filePath))
{
response.ContentLength64 = 0;
response.StatusCode = 404;
response.Abort();
}
else
{
response.StatusCode = 200;
string exeName = Path.GetExtension(filePath);
response.ContentType = GetContentType(exeName);
FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
int byteLength = (int)fileStream.Length;
byte[] fileBytes = new byte[byteLength];
fileStream.Read(fileBytes, 0, byteLength);
fileStream.Close();
fileStream.Dispose();
response.ContentLength64 = byteLength;
response.OutputStream.Write(fileBytes, 0, byteLength);
response.OutputStream.Close();
}
#endregion
} }
catch (Exception ex) }
catch (Exception ex)
{
LogUnit.Error(ex.Message);
response.StatusCode = 200;
response.ContentType = "text/plain";
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{ {
LogUnit.Error(ex.Message); writer.WriteLine("接收完成!");
} }
} }
#endregion try
#region GetContentType
/// <summary>
/// 获取文件对应MIME类型
/// </summary>
/// <param name="fileExtention">文件扩展名,如.jpg</param>
/// <returns></returns>
protected string GetContentType(string fileExtention)
{ {
if (string.Compare(fileExtention, ".html", true) == 0 response.Close();
|| string.Compare(fileExtention, ".htm", true) == 0)
return "text/html;charset=utf-8";
else if (string.Compare(fileExtention, ".js", true) == 0)
return "application/javascript";
else if (string.Compare(fileExtention, ".css", true) == 0)
return "text/css";
else if (string.Compare(fileExtention, ".png", true) == 0)
return "image/png";
else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0)
return "image/jpeg";
else if (string.Compare(fileExtention, ".gif", true) == 0)
return "image/gif";
else if (string.Compare(fileExtention, ".swf", true) == 0)
return "application/x-shockwave-flash";
else if (string.Compare(fileExtention, ".pdf", true) == 0)
return "application/pdf";
else
return "";//application/octet-stream
} }
#endregion catch (Exception ex)
{
LogUnit.Error(ex.Message);
}
}
#endregion
#region GetContentType
/// <summary>
/// 获取文件对应MIME类型
/// </summary>
/// <param name="fileExtention">文件扩展名,如.jpg</param>
/// <returns></returns>
protected string GetContentType(string fileExtention)
{
if (string.Compare(fileExtention, ".html", true) == 0
|| string.Compare(fileExtention, ".htm", true) == 0)
return "text/html;charset=utf-8";
else if (string.Compare(fileExtention, ".js", true) == 0)
return "application/javascript";
else if (string.Compare(fileExtention, ".css", true) == 0)
return "text/css";
else if (string.Compare(fileExtention, ".png", true) == 0)
return "image/png";
else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0)
return "image/jpeg";
else if (string.Compare(fileExtention, ".gif", true) == 0)
return "image/gif";
else if (string.Compare(fileExtention, ".swf", true) == 0)
return "application/x-shockwave-flash";
else if (string.Compare(fileExtention, ".pdf", true) == 0)
return "application/pdf";
else
return "";//application/octet-stream
}
#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) {
byte[] fileContents = new byte[] { };
var bytes = new byte[length];
int i = 0;
while ((i = br.Read(bytes, 0, (int)length)) != 0)
{ {
byte[] fileContents = new byte[] { }; byte[] arr = new byte[fileContents.LongLength + i];
var bytes = new byte[length]; fileContents.CopyTo(arr, 0);
int i = 0; Array.Copy(bytes, 0, arr, fileContents.Length, i);
while ((i = br.Read(bytes, 0, (int)length)) != 0) fileContents = arr;
{ }
byte[] arr = new byte[fileContents.LongLength + i];
fileContents.CopyTo(arr, 0);
Array.Copy(bytes, 0, arr, fileContents.Length, i);
fileContents = arr;
}
using (var fs = new FileStream(fileName, FileMode.Create)) using (var fs = new FileStream(fileName, FileMode.Create))
{
using (var bw = new BinaryWriter(fs))
{ {
using (var bw = new BinaryWriter(fs)) bw.Write(fileContents);
{
bw.Write(fileContents);
}
} }
} }
#endregion }
public void Log(string msg, bool isErr = false)
{ #endregion
//(msg, isErr);
} public void Log(string msg, bool isErr = false)
{
//(msg, isErr);
} }
} }

1028
EC.Util/Net/NetUnit.cs

File diff suppressed because it is too large

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";
} }
} }

93
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,14 +149,18 @@ 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)
{ {
ClientDisconnected?.Invoke(this, new TcpClientDisconnectedEventArgs(client)); if (Clients.TryRemove(clientKey, out _))
{
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;

21
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>

44
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,13 +33,26 @@ 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)
{ {
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(PtzBtn_MouseDown), true); if (btn.Name.StartsWith("goto", StringComparison.OrdinalIgnoreCase))
btn.AddHandler(MouseUpEvent, new MouseButtonEventHandler(PtzBtn_MouseUp), true); {
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(GotoBtn_Click), true);
}
else
{
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(PtzBtn_MouseDown), true);
btn.AddHandler(MouseUpEvent, new MouseButtonEventHandler(PtzBtn_MouseUp), true);
}
} }
} }
@ -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>

175
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,40 +313,24 @@ public partial class Main : UserControl
#region InvokeEvent #region InvokeEvent
public void GotoPresetInvoke(AlarmMessage alarm) public void HandleAlarmInvoke(AlarmMessage alarm)
{ {
Dispatcher.Invoke(() => if (alarm == null) return;
{ bool realPlay = AppConfig.AlarmPlatform.RealPlay;
if (Global.AppConfig.AlarmPlatform.RealPlay) string deviceId = alarm.LabelCode;
{ string sensorId = alarm.ChannelId;
PtzControlType ctrlType = PtzControlTypeConfigHelper.GetControlType(ControlTypeName.Text); CameraLinkageInfo cameraLinkage = GetCameraLinkage(sensorId);
if (ctrlType == PtzControlType.CameraSdk) ShowLiveVideo(); if (cameraLinkage == null) { LogUnit.Error(this, $"CameraLinkageInfo(sensorId:{sensorId}) not found."); return; }
} string cameraId = cameraLinkage.CameraId;
if (alarm != null) ICameraSDK cameraSdk = GetCameraSdk(cameraId);
{ if (cameraSdk == null) { LogUnit.Error(this, $"CameraSdk(cameraId:{cameraId}) not found."); return; }
if (alarm.ChannelId <= 5) if (realPlay) Dispatcher.Invoke(() => ShowLiveVideo(cameraSdk));
{
PresetId.Text = "5";
}
else
{
PresetId.Text = "6";
}
// 切换至下一预置点
//int index = PresetId.SelectedIndex;
//index = (index + 1) % PresetId.Items.Count;
//PresetId.SelectedIndex = index;
GotoBtn_Click(null, null);
}
});
}
private ConcurrentDictionary<string, CameraRealPlay> RealPlayDict { get; } = new(); }
public void ShowLiveVideo() public void ShowLiveVideo(string cameraIp)
{ {
string cameraIp = CameraIp.Text; CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) return; if (cameraSdk == null) return;
RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay); RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay);
if (realPlay == null || realPlay.IsClosed) if (realPlay == null || realPlay.IsClosed)
@ -363,50 +342,72 @@ public partial class Main : UserControl
realPlay.Show(); realPlay.Show();
realPlay.HideMinButton(); realPlay.HideMinButton();
realPlay.StartPlay(); realPlay.StartPlay();
}
//切换至下一相机 public void ShowLiveVideo(ICameraSDK cameraSdk)
//int index = CameraIp.SelectedIndex; {
//index = (index + 1) % CameraIp.Items.Count; if (cameraSdk == null) return;
//CameraIp.SelectedIndex = index; string cameraIp = cameraSdk.CameraInfo.Ip;
RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay);
if (realPlay == null || realPlay.IsClosed)
{
realPlay = new(cameraSdk);
realPlay.Owner = Window.GetWindow(this);
realPlay.HideMinButton();
RealPlayDict[cameraIp] = realPlay;
}
realPlay.Show();
if (!realPlay.IsPlaying()) realPlay.StartPlayFirmly();
} }
#endregion InvokeEvent #endregion InvokeEvent
#region CameraSdkMap #region Military
private void LoadMilitaryInfo()
{
List<CameraInfo> cameraList = MilitaryService.GetCameraList();
CameraLinkageList = MilitaryService.GetCameraLinkageList();
TaskUtil.RunCatch(() => Dispatcher.Invoke(() => LoadCameraSdkDict(cameraList)));
}
private void LoadCameraList() private void LoadCameraSdkDict(List<CameraInfo> cameraList)
{ {
List<CameraInfo> cameraList = Global.AppConfig.CameraList; CameraSdkDict.Clear();
foreach (var item in cameraList) for (int i = 0; i < cameraList.Count; i++)
{ {
string ip = item.Ip; CameraInfo info = cameraList[i];
if (CameraSdkMap.ContainsKey(ip)) continue; string ip = info.Ip;
CameraSdkMap[ip] = null; if (CameraSdkDict.ContainsKey(ip)) continue;
CameraSdkDict[ip] = null;
CameraIp.Items.Add(new ComboBoxItem { Content = ip }); CameraIp.Items.Add(new ComboBoxItem { Content = ip });
CameraInfo info = new(); TaskUtil.RunCatch(() =>
info.Copy(item);
Task.Run(() =>
{ {
ICameraSDK sdk = (info.GetManufactor) switch ICameraSDK sdk = CameraFactory.BuildCameraSdk(info);
{ bool ret = sdk.Init();
CameraManufactor.HiK => new HiKSDK(info), if (!ret) return;
CameraManufactor.DaHua => new DaHuaSDK(info), CameraSdkDict[ip] = sdk;
CameraManufactor.YuShi => new YuShiSDK(info),
_ => throw new NotSupportedException(),
};
try
{
bool ret = sdk.Init();
if (!ret) return;
CameraSdkMap[ip] = sdk;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}); });
} }
} }
#endregion CameraSdkMap private CameraLinkageInfo GetCameraLinkage(string sensorId)
{
foreach (var item in CameraLinkageList)
{
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 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

70
JiLinApp/config/config.json

@ -1,49 +1,33 @@
{ {
"base": { "base": {
"console": true "console": true,
}, "ptzCtrlTypes": [
"ptzCtrlTypes": [ {
{ "type": "CameraSdk",
"type": "CameraSdk", "Name": "协议HDY"
"Name": "协议HDY" },
}, {
{ "type": "PelcoD",
"type": "PelcoD", "Name": "协议Pd"
"Name": "协议Pd" },
}, {
{ "type": "PelcoP",
"type": "PelcoP", "Name": "协议Pp"
"Name": "协议Pp" },
}, {
{ "type": "DCamera",
"type": "DCamera", "Name": "协议D508"
"Name": "协议D508" }
}
], ]
"cameraList": [ },
{ "military": {
"manufactor": 1, "url": "http://192.168.1.119:8080/military",
"ip": "192.168.1.65", "username": "admin",
"port": "8000", "password": "123456",
"username": "admin", "requestRetryTime": "5",
"password": "hk123456" "requestRetryInterval": "200"
}, },
{
"manufactor": 1,
"ip": "192.168.1.65",
"port": "8000",
"username": "admin",
"password": "hk123456"
},
{
"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