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. 680
      EC.Util/Common/DateUnit.cs
  10. 572
      EC.Util/Common/FileUnit.cs
  11. 29
      EC.Util/Common/LogUnit.cs
  12. 9
      EC.Util/Common/TaskUtil.cs
  13. 176
      EC.Util/Common/VerifyUtil.cs
  14. 74
      EC.Util/Net/APICallBack.cs
  15. 606
      EC.Util/Net/HttpServer.cs
  16. 1036
      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()
{
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}");
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>
public class CameraInfo
{
#region Attr
#region Fields
/// <summary>
/// 相机厂商
/// id
/// </summary>
public int Manufactor { get; set; }
public string Id { get; set; } = string.Empty;
public CameraManufactor GetManufactor
{
get
{
return (CameraManufactor)Manufactor;
}
}
/// <summary>
/// 相机厂商
/// </summary>
public CameraManufactor Manufactor { get; set; }
/// <summary>
/// ip 地址
@ -40,19 +37,43 @@ public class CameraInfo
/// </summary>
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.");
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 };
int port = (CameraManufactor)manufactor switch
CameraManufactor cm = (CameraManufactor)manufactor;
CameraInfo info = new() { Manufactor = cm, Ip = ip, UserName = username, Password = password };
int port = cm switch
{
CameraManufactor.HiK => (int)CameraPort.HiK,
CameraManufactor.DaHua => (int)CameraPort.DaHua,
@ -90,13 +111,15 @@ public enum CameraPort : int
/// </summary>
public class PtzInfo
{
#region Attr
#region Fields
public double Pan { get; set; }
public double Tilt { get; set; }
public double Zoom { get; set; }
#endregion Attr
#endregion Fields
public PtzInfo(double pan, double tilt, double zoom)
{

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

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

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

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

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

@ -209,7 +209,7 @@ public static class HiKOriSDK
[StructLayout(LayoutKind.Sequential)]
public struct NET_DVR_PREVIEWINFO
{
public Int32 lChannel; //通道号
public int lChannel; //通道号
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 IntPtr hPlayWnd; //播放窗口的句柄,为NULL表示不播放图象
@ -304,10 +304,10 @@ public static class HiKOriSDK
**********************************************************/
public delegate void REALDATACALLBACK(
Int32 lRealHandle,
UInt32 dwDataType,
int lRealHandle,
uint dwDataType,
IntPtr pBuffer,
UInt32 dwBufSize,
uint dwBufSize,
IntPtr pUser
);

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

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

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

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

680
EC.Util/Common/DateUnit.cs

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

572
EC.Util/Common/FileUnit.cs

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

29
EC.Util/Common/LogUnit.cs

@ -1,9 +1,7 @@
using log4net;
using log4net.Config;
using System;
using System.IO;
namespace System;
namespace EC.Util.Common;
public static class LogUnit
{
@ -49,19 +47,24 @@ public static class LogUnit
{
logger.Error(e);
}
/// <summary>
/// 输出日志到Log4Net
/// </summary>
/// <param name="t"></param>
/// <param name="ex"></param>
public static void Error(Type t, Exception ex)
public static void Error(object obj, Exception e)
{
logger.Error("Error", ex);
logger.Error(obj.GetType(), e);
}
public static void Error(Type t, string logMessage)
public static void Error(object obj, string msg)
{
logger.Error(obj.GetType(), new Exception(msg));
}
logger.Error(logMessage);
public static void Error(Type type, Exception e)
{
logger.Error(type, e);
}
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;
using System.Threading.Tasks;
namespace EC.Util.Common;
namespace JiLinApp.Core;
public static class TaskUtil
public class TaskUtil
{
public static Task Run(Action action)
{
@ -25,7 +22,7 @@ public static class TaskUtil
}
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位身份证标准
}
}

74
EC.Util/Net/APICallBack.cs

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

606
EC.Util/Net/HttpServer.cs

@ -1,362 +1,358 @@

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EC.Util.Common;
using System.Net;
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; //定义一个委托类型的事件
#region
public string Host { get; set; }
public string port { get; set; }
private string _webHomeDir = "";
private HttpListener listener;
private Thread listenThread;
private string directorySeparatorChar = Path.DirectorySeparatorChar.ToString();
public string ImageUploadPath { get; set; }
/// <summary>
/// 设置监听端口,重启服务生效
/// </summary>
//public string Port
//{
// get { return this.port; }
// set
// {
// int p;
// if (string.IsNullOrEmpty(value) || !int.TryParse(value, out p))
// {
// throw new Exception("给http监听器赋值的端口号无效!");
// }
// this.port = value;
// }
//}
/// <summary>
/// http服务根目录
/// </summary>
public string WebHomeDir
{
public event EventHandler<APICallBack> OnRecData; //定义一个委托类型的事件
#region
public string Host { get; set; }
public string port { get; set; }
private string _webHomeDir = "";
private HttpListener listener;
private Thread listenThread;
private string directorySeparatorChar = Path.DirectorySeparatorChar.ToString();
public string ImageUploadPath { get; set; }
/// <summary>
/// 设置监听端口,重启服务生效
/// </summary>
//public string Port
//{
// get { return this.port; }
// set
// {
// int p;
// if (string.IsNullOrEmpty(value) || !int.TryParse(value, out p))
// {
// throw new Exception("给http监听器赋值的端口号无效!");
// }
// this.port = value;
// }
//}
/// <summary>
/// http服务根目录
/// </summary>
public string WebHomeDir
{
get { return this._webHomeDir; }
set
{
if (!Directory.Exists(value))
throw new Exception("http服务器设置的根目录不存在!");
this._webHomeDir = value;
}
}
/// <summary>
/// 服务器是否在运行
/// </summary>
public bool IsRunning
get { return this._webHomeDir; }
set
{
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
{
this.Host = host;
this.port = port;
this._webHomeDir = webHomeDir;
ImageUploadPath = imageUploadPath;
listener = new HttpListener();
}
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();
public bool AddPrefixes(string uriPrefix)
listenThread = new Thread(AcceptClient);
listenThread.Name = "signserver";
listenThread.Start();
Log("开启接口监听服务:" + this.port);
}
catch (Exception ex)
{
string uri = "http://" + uriPrefix + ":" + this.port + "/";
if (listener.Prefixes.Contains(uri)) return false;
listener.Prefixes.Add(uri);
return true;
LogUnit.Error(ex.Message);
}
}
/// <summary>
/// 启动服务
/// </summary>
public void Start()
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
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();
listenThread = new Thread(AcceptClient);
listenThread.Name = "signserver";
listenThread.Start();
Log("开启接口监听服务:"+ this.port);
}
catch (Exception ex)
if (listener != null)
{
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);
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
while (listener.IsListening)
{
try
{
if (listener != null)
{
//listener.Close();
//listener.Abort();
listener.Stop();
}
HttpListenerContext context = listener.GetContext();
//new Thread(HandleRequest).Start(context);
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context);
}
catch (Exception ex)
catch
{
LogUnit.Error(ex.Message);
}
}
}
/// <summary>
/// /接受客户端请求
/// </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
{
#endregion
}
}
#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;
HttpListenerResponse response = context.Response;
HttpListenerRequest request = context.Request;
try
context.Request.Headers.Add("Access-Control-Allow-Origin", "*");
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"))
{
context.Request.Headers.Add("Access-Control-Allow-Origin", "*");
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 });
writer.Write(str);
}
APICallBack apiCallBack = new APICallBack();
////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)
{
using (var br = new BinaryReader(stream))
{
WriteStreamToFile(br, filePath, request.ContentLength64);
}
}
response.ContentType = "text/html;charset=utf-8";
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"];
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{
writer.WriteLine("接收完成!");
}
//接收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);
//}
#endregion
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 });
writer.Write(str);
}
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 网页请求
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
using (var br = new BinaryReader(stream))
{
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();
WriteStreamToFile(br, filePath, request.ContentLength64);
}
#endregion
}
}
catch (Exception ex)
{
LogUnit.Error(ex.Message);
response.StatusCode = 200;
response.ContentType = "text/plain";
response.ContentType = "text/html;charset=utf-8";
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{
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
#region GetContentType
/// <summary>
/// 获取文件对应MIME类型
/// </summary>
/// <param name="fileExtention">文件扩展名,如.jpg</param>
/// <returns></returns>
protected string GetContentType(string fileExtention)
try
{
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
response.Close();
}
#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;
private void WriteStreamToFile(BinaryReader br, string fileName, long length)
//const int ChunkSize = 1024 * 1024;
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[] { };
var bytes = new byte[length];
int i = 0;
while ((i = br.Read(bytes, 0, (int)length)) != 0)
{
byte[] arr = new byte[fileContents.LongLength + i];
fileContents.CopyTo(arr, 0);
Array.Copy(bytes, 0, arr, fileContents.Length, i);
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)
{
//(msg, isErr);
}
}
}
#endregion
public void Log(string msg, bool isErr = false)
{
//(msg, isErr);
}
}

1036
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;
internal class ZmqUtil
public class ZmqUtil
{
//#region Fields

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

@ -11,6 +11,8 @@ public class AlarmPlatformConfig
public class MqttConfig
{
//public bool Local { get; set; }
public string Ip { 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 int ChannelId { get; set; }
public string ChannelId { get; set; }
/** (必填)报警类型((1-视频报警,2-雷达报警;3-微振动警报,4-电子围网警报,9-其他报警))*/
public int WarnType { get; set; }
/** (必填)报警级别(1-5)*/

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

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

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

@ -2,6 +2,8 @@
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Exceptions;
using MQTTnet.Protocol;
using MQTTnet.Server;
using NewLife.Serialization;
using Newtonsoft.Json.Linq;
using System.Text;
@ -14,8 +16,12 @@ public class AlarmMqttService : IAlarmService
private MqttConfig Config { get; }
//private MqttServer? Server { get; }
private IMqttClient Client { get; }
//private MqttServerOptions ServerOptions { get; }
private MqttClientOptions ClientOptions { get; }
private MqttClientSubscribeOptions SubscribeOptions { get; }
@ -33,8 +39,7 @@ public class AlarmMqttService : IAlarmService
public AlarmMqttService(MqttConfig config)
{
MqttFactory factory = new();
IMqttClient client = factory.CreateMqttClient();
client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync;
ClientOptions = factory.CreateClientOptionsBuilder()
.WithTcpServer(config.Ip, config.Port)
.WithClientId(config.ClientId)
@ -46,6 +51,23 @@ public class AlarmMqttService : IAlarmService
.WithTopicFilter(f => f.WithTopic(config.SubCmdTopic))
.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;
Client = client;
}
@ -110,7 +132,38 @@ public class AlarmMqttService : IAlarmService
#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)
{
@ -160,7 +213,7 @@ public class AlarmMqttService : IAlarmService
}
}
#endregion Receive
#endregion Client Event
#region Send

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

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

3
JiLinApp.Docking/Alarm/AlarmCodeHelper.cs

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

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

@ -122,10 +122,12 @@ public class UdpServer
return flag;
}
public bool SendMessage(IPEndPoint ipep, byte[] byteMsg)
public bool SendMessage(IPEndPoint ipep, byte[] msg)
{
int result = SendUdp.Send(byteMsg, byteMsg.Length, ipep);
return result >= byteMsg.Length;
int result = SendUdp.Send(msg, msg.Length, ipep);
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

4
JiLinApp.Docking/JiLinApp.Docking.csproj

@ -7,7 +7,9 @@
</PropertyGroup>
<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>

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)
{
if (sdk == null || !sdk.ConnectSuccess() || args == null) return;
switch (sdk.CameraInfo.GetManufactor)
switch (sdk.CameraInfo.Manufactor)
{
case CameraManufactor.HiK:
HikPtzMove(sdk, cmdType, args);

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

@ -16,7 +16,7 @@ public class ClientMessage
get
{
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 "";
}
}
@ -26,7 +26,7 @@ public class ClientMessage
get
{
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";
}
}

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

@ -1,7 +1,6 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
namespace JiLinApp.Docking.VibrateAlarm;
@ -39,8 +38,6 @@ public class AsyncTcpServer : IDisposable
#region Ctors
private byte[] InOptionValues { get; set; }
/// <summary>
/// 异步TCP服务器
/// </summary>
@ -64,11 +61,6 @@ public class AsyncTcpServer : IDisposable
/// <param name="port">监听的端口</param>
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;
Port = port;
Encoding = Encoding.Default;
@ -157,14 +149,18 @@ public class AsyncTcpServer : IDisposable
/// </summary>
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)
@ -181,11 +177,6 @@ public class AsyncTcpServer : IDisposable
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)
{
if (!IsRunning()) return;
@ -195,7 +186,6 @@ public class AsyncTcpServer : IDisposable
{
listener = ar.AsyncState as TcpListener;
client = listener?.EndAcceptTcpClient(ar);
client?.Client.IOControl(IOControlCode.KeepAliveValues, InOptionValues, null);
}
catch (Exception)
{
@ -204,24 +194,22 @@ public class AsyncTcpServer : IDisposable
if (listener == null || client == null || !client.Connected) return;
byte[] buffer = new byte[client.ReceiveBufferSize];
TcpClientState internalClient = new(client, buffer);
TcpClientState clientState = new(client, buffer);
// add client connection to cache
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
Clients.AddOrUpdate(clientKey, internalClient, (n, o) => { return internalClient; });
RaiseClientConnected(client);
RaiseClientConnected(clientKey, clientState);
// begin to read data
try
{
NetworkStream networkStream = internalClient.NetworkStream;
ReadBuffer(internalClient, networkStream);
NetworkStream networkStream = clientState.NetworkStream;
ReadBuffer(clientState, networkStream);
}
catch (Exception)
{
Clients.TryRemove(clientKey, out _);
RaiseClientDisconnected(internalClient.TcpClient);
RaiseClientDisconnected(clientKey, clientState.TcpClient);
return;
}
@ -229,6 +217,11 @@ public class AsyncTcpServer : IDisposable
AcceptTcpClient(listener);
}
private void ReadBuffer(TcpClientState clientState, NetworkStream networkStream)
{
networkStream.BeginRead(clientState.Buffer, 0, clientState.Buffer.Length, HandleDatagramReceived, clientState);
}
private void HandleDatagramReceived(IAsyncResult ar)
{
if (!IsRunning()) return;
@ -239,8 +232,7 @@ public class AsyncTcpServer : IDisposable
if (!internalClient.TcpClient.Connected)
{
// connection has been closed
Clients.TryRemove(clientKey, out _);
RaiseClientDisconnected(internalClient.TcpClient);
RaiseClientDisconnected(clientKey, internalClient.TcpClient);
}
NetworkStream networkStream;
@ -254,13 +246,13 @@ public class AsyncTcpServer : IDisposable
}
catch (Exception)
{
RaiseClientDisconnected(clientKey, internalClient.TcpClient);
return;
}
if (readBytesNum == 0)
{
// connection has been closed
Clients.TryRemove(clientKey, out _);
RaiseClientDisconnected(internalClient.TcpClient);
RaiseClientDisconnected(clientKey, internalClient.TcpClient);
return;
}
@ -280,15 +272,15 @@ public class AsyncTcpServer : IDisposable
/// <summary>
/// 发送报文至指定的客户端
/// </summary>
/// <param name="tcpClient">客户端</param>
/// <param name="client">客户端</param>
/// <param name="datagram">报文</param>
public void Send(TcpClient tcpClient, byte[] datagram)
public void Send(TcpClient client, byte[] datagram)
{
if (!IsRunning()) return;
if (tcpClient == null || !tcpClient.Connected || datagram == null) return;
if (client == null || !client.Connected || datagram == null) return;
try
{
NetworkStream stream = tcpClient.GetStream();
NetworkStream stream = client.GetStream();
if (stream.CanWrite)
{
stream.Write(datagram, 0, datagram.Length);
@ -296,17 +288,20 @@ public class AsyncTcpServer : IDisposable
}
catch (Exception)
{
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
if (client != null) RaiseClientDisconnected(clientKey, client);
}
}
/// <summary>
/// 发送报文至指定的客户端
/// </summary>
/// <param name="tcpClient">客户端</param>
/// <param name="client">客户端</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>
@ -335,33 +330,36 @@ public class AsyncTcpServer : IDisposable
/// <summary>
/// 发送报文至指定的客户端
/// </summary>
/// <param name="tcpClient">客户端</param>
/// <param name="client">客户端</param>
/// <param name="datagram">报文</param>
public void SendAsync(TcpClient tcpClient, byte[] datagram)
public void SendAsync(TcpClient client, byte[] datagram)
{
if (!IsRunning()) return;
if (tcpClient == null || !tcpClient.Connected || datagram == null) return;
if (client == null || !client.Connected || datagram == null) return;
try
{
NetworkStream stream = tcpClient.GetStream();
NetworkStream stream = client.GetStream();
if (stream.CanWrite)
{
stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient);
stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, client);
}
}
catch (Exception)
{
string clientKey = client.Client.RemoteEndPoint?.ToString() ?? "";
if (clientKey == "") return;
if (client != null) RaiseClientDisconnected(clientKey, client);
}
}
/// <summary>
/// 发送报文至指定的客户端
/// </summary>
/// <param name="tcpClient">客户端</param>
/// <param name="client">客户端</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>
@ -389,12 +387,17 @@ public class AsyncTcpServer : IDisposable
private void HandleDatagramWritten(IAsyncResult ar)
{
TcpClient? client = null;
try
{
(ar.AsyncState as TcpClient)?.GetStream().EndWrite(ar);
client = ar.AsyncState as TcpClient;
client?.GetStream().EndWrite(ar);
}
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 StateSpanTimer { get; } = new();
#region Event
public delegate void VibrateTcpDeviceStateEvent(ClientMessage device);
@ -476,8 +474,6 @@ public class TcpManager
#region Set
private List<DataRequest> Reqlist { get; } = new();
private byte FrameNumber { get; set; } = 0;
private DataMessage GetSendMessageHead(int deviceId, ClientMessage client, byte fun_num, byte datalen)
@ -485,7 +481,8 @@ public class TcpManager
DataMessage msg = new()
{
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,
ReceiveIp = client.Ip,
ReceivePort = int.Parse(client.Port),

5
JiLinApp.sln

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

21
JiLinApp/Components/CameraRealPlay.xaml

@ -29,6 +29,9 @@
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="5" />
<RowDefinition Height="35" />
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="35" />
@ -90,7 +93,7 @@
</Button>
</StackPanel>
<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 Grid.Row="4" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="ZoomOutBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}">
@ -104,7 +107,7 @@
</Button>
</StackPanel>
<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 Grid.Row="5" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="FocusFarBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}">
@ -118,13 +121,23 @@
</Button>
</StackPanel>
<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 Grid.Row="6" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="IrisCloseBtn" Width="25" Height="25" Padding="0" Style="{StaticResource MaterialDesignOutlinedLightButton}">
<materialDesign:PackIcon Kind="MinusThick" />
<materialDesign:PackIcon Kind="MinusThick"/>
</Button>
</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>
</StackPanel>
</Grid>

44
JiLinApp/Components/CameraRealPlay.xaml.cs

@ -3,6 +3,7 @@ using JiLinApp.Docking.Ptz;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
@ -32,13 +33,26 @@ public partial class CameraRealPlay : Window
private void Init()
{
// 初始化预置位
for (int i = 1; i <= 8; i++)
{
PresetId.Items.Add(new ComboBoxItem { Content = i });
}
// 绑定云台响应事件
List<Button> btnList = new();
WpfUtil.FindVisualChild(PtzPanel, ref btnList);
foreach (var btn in btnList)
{
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(PtzBtn_MouseDown), true);
btn.AddHandler(MouseUpEvent, new MouseButtonEventHandler(PtzBtn_MouseUp), true);
if (btn.Name.StartsWith("goto", StringComparison.OrdinalIgnoreCase))
{
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(GotoBtn_Click), true);
}
else
{
btn.AddHandler(MouseDownEvent, new MouseButtonEventHandler(PtzBtn_MouseDown), true);
btn.AddHandler(MouseUpEvent, new MouseButtonEventHandler(PtzBtn_MouseUp), true);
}
}
}
@ -56,15 +70,21 @@ public partial class CameraRealPlay : Window
CameraSdk.StopPlay();
}
public bool IsPlaying()
{
return CameraSdk.IsPlaying();
}
public void StartPlayFirmly()
{
while (!CameraSdk.IsPlaying())
while (!IsPlaying())
{
StartPlay();
Thread.Sleep(100);
}
}
#endregion
#endregion Base
#region ElementEvent
@ -84,7 +104,17 @@ public partial class CameraRealPlay : Window
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 WS_MAXIMIZEBOX = 0x10000;
@ -109,8 +139,6 @@ public partial class CameraRealPlay : Window
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
#region Util
public void HideMinButton()
{
IntPtr hwnd = new WindowInteropHelper(this).Handle;
@ -137,5 +165,5 @@ public partial class CameraRealPlay : Window
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 System.Collections.Generic;
@ -9,9 +9,7 @@ public class AppConfig
{
public BaseConfig Base { get; set; }
public List<PtzControlTypeConfig> PtzCtrlTypes { get; set; }
public List<CameraInfo> CameraList { get; set; }
public MilitaryConfig Military { get; set; }
public AlarmPlatformConfig AlarmPlatform { get; set; }
}
@ -19,4 +17,6 @@ public class AppConfig
public class BaseConfig
{
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 JiLinApp.Biz.TransmitAlarm;
using JiLinApp.Docking.Alarm;
using JiLinApp.Docking.Military;
using JiLinApp.Docking.Ptz;
using NewLife.Configuration;
using System;
@ -16,6 +17,8 @@ public static class Global
public static AppConfig AppConfig { get; }
public static MilitaryService MilitaryService { get; }
public static IAlarmService AlarmService { get; }
#endregion Fields
@ -29,12 +32,20 @@ public static class Global
AppConfig = new AppConfig();
ConfigProvider.Bind(AppConfig);
// BaseConfig
BaseConfig baseConfig = AppConfig.Base;
// 控制台
if (AppConfig.Base.Console) SystemUtil.AllocConsole();
if (baseConfig.Console) SystemUtil.AllocConsole();
// 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();
}
catch (Exception)

4
JiLinApp/JiLinApp.csproj

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

3
JiLinApp/Pages/PtzManage/Main.xaml

@ -208,10 +208,9 @@
</Grid>
<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>
<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>
</Grid>
</GroupBox>

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

@ -1,18 +1,18 @@
using EC.Util.CameraSDK;
using EC.Util.Common;
using EC.Util.Port;
using ImTools;
using JiLinApp.Biz.TransmitAlarm;
using JiLinApp.Components;
using JiLinApp.Core;
using JiLinApp.Docking.Military;
using JiLinApp.Docking.Ptz;
using NewLife.Reflection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
@ -27,15 +27,25 @@ public partial class Main : UserControl
{
#region Fields
private AppConfig AppConfig { get; }
private MilitaryService MilitaryService { get; }
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
public Main()
{
InitializeComponent();
AppConfig = Global.AppConfig;
MilitaryService = Global.MilitaryService;
Init();
}
@ -57,11 +67,11 @@ public partial class Main : UserControl
ComName.Items.Add(new ComboBoxItem { Content = port });
}
// 解析海康相机
TaskUtil.RunCatch(() => Dispatcher.Invoke(LoadCameraList));
// 加载 Military 信息
LoadMilitaryInfo();
// 初始化云台控制类型
foreach (var cfg in Global.AppConfig.PtzCtrlTypes)
foreach (var cfg in AppConfig.Base.PtzCtrlTypes)
{
ControlTypeName.Items.Add(new ComboBoxItem { Content = cfg.Name });
}
@ -72,7 +82,7 @@ public partial class Main : UserControl
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 });
}
@ -173,7 +183,7 @@ public partial class Main : UserControl
case PtzControlType.CameraSdk:
string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) break;
int stop = 0;
PtzCameraCmd.PtzMove(cameraSdk, cmdType, new int[] { stop });
@ -207,7 +217,7 @@ public partial class Main : UserControl
case PtzControlType.CameraSdk:
string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) break;
cmdType = PtzCmd.GetCmdType(((Button)sender).Name.Replace("Btn", ""));
int stop = 1;
@ -236,7 +246,7 @@ public partial class Main : UserControl
case PtzControlType.CameraSdk:
string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) break;
PtzCameraCmd.PtzMove(cameraSdk, cmdType, new int[] { presetId });
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)
{
if (CameraId == null || CameraIp == null) return;
@ -318,40 +313,24 @@ public partial class Main : UserControl
#region InvokeEvent
public void GotoPresetInvoke(AlarmMessage alarm)
public void HandleAlarmInvoke(AlarmMessage alarm)
{
Dispatcher.Invoke(() =>
{
if (Global.AppConfig.AlarmPlatform.RealPlay)
{
PtzControlType ctrlType = PtzControlTypeConfigHelper.GetControlType(ControlTypeName.Text);
if (ctrlType == PtzControlType.CameraSdk) ShowLiveVideo();
}
if (alarm != null)
{
if (alarm.ChannelId <= 5)
{
PresetId.Text = "5";
}
else
{
PresetId.Text = "6";
}
// 切换至下一预置点
//int index = PresetId.SelectedIndex;
//index = (index + 1) % PresetId.Items.Count;
//PresetId.SelectedIndex = index;
GotoBtn_Click(null, null);
}
});
}
if (alarm == null) return;
bool realPlay = AppConfig.AlarmPlatform.RealPlay;
string deviceId = alarm.LabelCode;
string sensorId = alarm.ChannelId;
CameraLinkageInfo cameraLinkage = GetCameraLinkage(sensorId);
if (cameraLinkage == null) { LogUnit.Error(this, $"CameraLinkageInfo(sensorId:{sensorId}) not found."); return; }
string cameraId = cameraLinkage.CameraId;
ICameraSDK cameraSdk = GetCameraSdk(cameraId);
if (cameraSdk == null) { LogUnit.Error(this, $"CameraSdk(cameraId:{cameraId}) not found."); return; }
if (realPlay) Dispatcher.Invoke(() => ShowLiveVideo(cameraSdk));
private ConcurrentDictionary<string, CameraRealPlay> RealPlayDict { get; } = new();
}
public void ShowLiveVideo()
public void ShowLiveVideo(string cameraIp)
{
string cameraIp = CameraIp.Text;
CameraSdkMap.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
CameraSdkDict.TryGetValue(cameraIp, out ICameraSDK cameraSdk);
if (cameraSdk == null) return;
RealPlayDict.TryGetValue(cameraIp, out CameraRealPlay realPlay);
if (realPlay == null || realPlay.IsClosed)
@ -363,50 +342,72 @@ public partial class Main : UserControl
realPlay.Show();
realPlay.HideMinButton();
realPlay.StartPlay();
}
//切换至下一相机
//int index = CameraIp.SelectedIndex;
//index = (index + 1) % CameraIp.Items.Count;
//CameraIp.SelectedIndex = index;
public void ShowLiveVideo(ICameraSDK cameraSdk)
{
if (cameraSdk == null) return;
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
#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;
foreach (var item in cameraList)
CameraSdkDict.Clear();
for (int i = 0; i < cameraList.Count; i++)
{
string ip = item.Ip;
if (CameraSdkMap.ContainsKey(ip)) continue;
CameraSdkMap[ip] = null;
CameraInfo info = cameraList[i];
string ip = info.Ip;
if (CameraSdkDict.ContainsKey(ip)) continue;
CameraSdkDict[ip] = null;
CameraIp.Items.Add(new ComboBoxItem { Content = ip });
CameraInfo info = new();
info.Copy(item);
Task.Run(() =>
TaskUtil.RunCatch(() =>
{
ICameraSDK sdk = (info.GetManufactor) switch
{
CameraManufactor.HiK => new HiKSDK(info),
CameraManufactor.DaHua => new DaHuaSDK(info),
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);
}
ICameraSDK sdk = CameraFactory.BuildCameraSdk(info);
bool ret = sdk.Init();
if (!ret) return;
CameraSdkDict[ip] = sdk;
});
}
}
#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.Core;
using JiLinApp.Docking.FenceAlarm;
using JiLinApp.Docking.VibrateAlarm;
using JiLinApp.Mvvm;
@ -15,15 +14,10 @@ public class MainViewModel : ViewModelBase
private Main View { get; set; }
private AppConfig AppConfig { get; }
#endregion Fields
public MainViewModel(IRegionManager region, IEventAggregator ea) : base(region, ea)
{
// Bind global fields
AppConfig = Global.AppConfig;
// Bind invoke event
ea.GetEvent<VibrateTcpSendAlarmEvent>().Subscribe(VibrateTcpSendAlarm);
ea.GetEvent<FenceUdpSendAlarmEvent>().Subscribe(FenceUdpSendAlarm);
@ -39,13 +33,13 @@ public class MainViewModel : ViewModelBase
internal void VibrateTcpSendAlarm(TcpAlarmHostMessage msg)
{
AlarmMessage alarm = msg.ToAlarmMessage();
View.GotoPresetInvoke(alarm);
View.HandleAlarmInvoke(alarm);
}
internal void FenceUdpSendAlarm(UdpAlarmHostMessage msg)
{
AlarmMessage alarm = msg.ToAlarmMessage();
View.GotoPresetInvoke(alarm);
View.HandleAlarmInvoke(alarm);
}
#endregion InvokeEvent

70
JiLinApp/config/config.json

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

Loading…
Cancel
Save