Browse Source

[feat] 调用 Military Api

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

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

@ -30,7 +30,7 @@ public class CameraException : Exception
public override string? ToString()
{
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(int manufactor, string ip, int port, string userName, string password)
public static CameraInfo New(CameraManufactor manufactor, string ip, int port, string username, string password)
{
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = userName, Password = password };
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = username, Password = password };
if (port <= 0) throw new Exception("Camera manufactor not support.");
return info;
}
public static CameraInfo New(int manufactor, string ip, string userName, string password)
public static CameraInfo New(CameraManufactor manufactor, string ip, string username, string password)
{
CameraInfo info = new() { Manufactor = manufactor, Ip = ip, UserName = userName, Password = password };
int port = (CameraManufactor)manufactor switch
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)
{
CameraManufactor cm = (CameraManufactor)manufactor;
CameraInfo info = new() { Manufactor = cm, Ip = ip, Port = port, UserName = username, Password = password };
if (port <= 0) throw new Exception("Camera manufactor not support.");
return info;
}
public static CameraInfo New(int manufactor, string ip, string username, string password)
{
CameraManufactor cm = (CameraManufactor)manufactor;
CameraInfo info = new() { Manufactor = cm, Ip = ip, UserName = username, Password = password };
int port = cm switch
{
CameraManufactor.HiK => (int)CameraPort.HiK,
CameraManufactor.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)
{

62
EC.Util/Common/DateUnit.cs

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

46
EC.Util/Common/FileUnit.cs

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

27
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(obj.GetType(), e);
}
logger.Error("Error", ex);
public static void Error(object obj, string msg)
{
logger.Error(obj.GetType(), new Exception(msg));
}
public static void Error(Type t, string logMessage)
public static void Error(Type type, Exception e)
{
logger.Error(type, e);
}
logger.Error(logMessage);
public static void Error(Type type, string msg)
{
logger.Error(type, new Exception(msg));
}
}

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

@ -1,9 +1,6 @@
using System;
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位身份证标准
}
}

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

42
EC.Util/Net/HttpServer.cs

@ -1,19 +1,13 @@

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

98
EC.Util/Net/NetUnit.cs

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

2
EC.Util/Zmq/ZmqUtil.cs

@ -1,6 +1,6 @@
namespace EC.Util.Zmq;
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";
}
}

91
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,15 +149,19 @@ 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)
{
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;

19
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"/>
</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>

40
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,15 +33,28 @@ 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)
{
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);
}
}
}
#endregion
@ -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>

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

10
JiLinApp/Pages/PtzManage/MainViewModel.cs

@ -1,5 +1,4 @@
using JiLinApp.Biz.TransmitAlarm;
using JiLinApp.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

30
JiLinApp/config/config.json

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

Loading…
Cancel
Save