MainWindow.xaml.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. using DeviceCenter.model;
  2. using DeviceCenter.utils;
  3. using DeviceCenter.views;
  4. using FluentScheduler;
  5. using log4net;
  6. using Microsoft.Win32;
  7. using Notifications.Wpf;
  8. using System;
  9. using System.Collections.ObjectModel;
  10. using System.Drawing;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Runtime.InteropServices;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using System.Windows;
  17. using System.Windows.Interop;
  18. namespace DeviceCenter
  19. {
  20. /// <summary>
  21. /// MainWindow.xaml 的交互逻辑
  22. /// </summary>
  23. public partial class MainWindow : Window
  24. {
  25. public static readonly ILog log = LogManager.GetLogger("DeviceCenter");
  26. private NotificationManager notificationManager = new NotificationManager();
  27. private ObservableCollection<Device> devices = new ObservableCollection<Device>();
  28. private Config config = Config.getInstance();
  29. private CHCNetSDK.MSGCallBack alarmCallback = null;
  30. private static CarCamSDK.FGetImageCB2 carPlateCallback;
  31. private int m_lGetCardCfgHandle = -1;
  32. private CHCNetSDK.RemoteConfigCallback g_fGetGatewayCardCallback = null;
  33. private System.Windows.Forms.NotifyIcon notifyIcon = null;
  34. private System.Windows.Forms.ContextMenu contextMenuExit;
  35. private System.Windows.Forms.MenuItem menuItem1;
  36. private System.Windows.Forms.MenuItem menuItem2;
  37. private System.ComponentModel.IContainer components;
  38. public MainWindow()
  39. {
  40. InitializeComponent();
  41. notifyIcon = new System.Windows.Forms.NotifyIcon();
  42. notifyIcon.Click += new EventHandler(notifyIcon_Click);
  43. notifyIcon.Icon = new Icon(AppDomain.CurrentDomain.BaseDirectory + "assets\\icon.ico");
  44. components = new System.ComponentModel.Container();
  45. contextMenuExit = new System.Windows.Forms.ContextMenu();
  46. menuItem1 = new System.Windows.Forms.MenuItem();
  47. menuItem2 = new System.Windows.Forms.MenuItem();
  48. // Initialize contextMenuExit
  49. this.contextMenuExit.MenuItems.AddRange(
  50. new System.Windows.Forms.MenuItem[] { this.menuItem1, menuItem2 });
  51. // Initialize menuItem1
  52. this.menuItem1.Index = 0;
  53. this.menuItem1.Text = "退出";
  54. this.menuItem1.Click += new EventHandler(this.menuItem1_Click);
  55. menuItem2.Index = 1;
  56. menuItem2.Text = "开机自启";
  57. menuItem2.Click += new EventHandler(this.menuItem2_Click);
  58. menuItem2.Checked = AppUtil.isAutoStart();
  59. notifyIcon.ContextMenu = this.contextMenuExit;
  60. initSdk();
  61. lv_device.ItemsSource = devices;
  62. //System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
  63. //dispatcherTimer.Tick += GetAllCard;
  64. //dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
  65. //dispatcherTimer.Start();
  66. //System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
  67. //timer.Tick += (s, e) =>
  68. //{
  69. // ((System.Windows.Threading.DispatcherTimer)s).Stop();
  70. // GetAllCard(null, null);
  71. //};
  72. //timer.Interval = new TimeSpan(0, 0, 5);
  73. //timer.Start();
  74. ScheduleJob();
  75. }
  76. private void ScheduleJob()
  77. {
  78. JobManager.Initialize();
  79. JobManager.AddJob(
  80. () =>
  81. {
  82. DateTime now = DateTime.Now.AddDays(-1);
  83. DateTime start = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
  84. DateTime end = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
  85. foreach (Device device in devices)
  86. {
  87. if (device.status == DeviceStatus.CONNECTED && device.type == DeviceType.ACS)
  88. {
  89. ((AcsDevice)device).getEvent(start, end);
  90. }
  91. }
  92. },
  93. s => s.ToRunEvery(1).Days().At(3, 0)
  94. );
  95. }
  96. private void Window_Loaded(object sender, RoutedEventArgs e)
  97. {
  98. notifyIcon.Visible = true;
  99. string imageDir = AppDomain.CurrentDomain.BaseDirectory + "Picture";
  100. if (!Directory.Exists(imageDir))
  101. {
  102. Directory.CreateDirectory(imageDir);
  103. }
  104. }
  105. private void notifyIcon_Click(object sender, EventArgs e)
  106. {
  107. Show();
  108. }
  109. private void menuItem1_Click(object Sender, EventArgs e)
  110. {
  111. ExitConfirm ex = new ExitConfirm();
  112. if (ex.ShowDialog() ?? false)
  113. {
  114. if (ex.password.Password == config.password)
  115. {
  116. notifyIcon.Dispose();
  117. Application.Current.Shutdown();
  118. }
  119. else
  120. {
  121. notificationManager.Show(new NotificationContent
  122. {
  123. Title = "Error",
  124. Message = "密码错误",
  125. Type = NotificationType.Error
  126. });
  127. }
  128. }
  129. }
  130. private void menuItem2_Click(object Sender, EventArgs e)
  131. {
  132. if (AppUtil.isAutoStart())
  133. {
  134. AppUtil.disableAutoStart();
  135. menuItem2.Checked = false;
  136. }
  137. else
  138. {
  139. AppUtil.enableAutoStart();
  140. menuItem2.Checked = true;
  141. }
  142. }
  143. private async void initSdk()
  144. {
  145. await Task.Run(() =>
  146. {
  147. long ts = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
  148. carPlateCallback = new CarCamSDK.FGetImageCB2(onGetCarPlate);
  149. CarCamSDK.Net_RegImageRecv2(carPlateCallback);
  150. //UsbSwitch.usb_relay_init();
  151. alarmCallback = new CHCNetSDK.MSGCallBack(onAlarm);
  152. if (CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V50(0, alarmCallback, IntPtr.Zero))
  153. {
  154. log.Info("NET_DVR_SetDVRMessageCallBack_V50 Succeed");
  155. notificationManager.Show(new NotificationContent
  156. {
  157. Title = "Success",
  158. Message = "NET_DVR_SetDVRMessageCallBack_V50 Succeed",
  159. Type = NotificationType.Success
  160. });
  161. }
  162. else
  163. {
  164. notificationManager.Show(new NotificationContent
  165. {
  166. Title = "Error",
  167. Message = "NET_DVR_SetDVRMessageCallBack_V50 Fail",
  168. Type = NotificationType.Error
  169. });
  170. }
  171. notificationManager.Show(new NotificationContent
  172. {
  173. Title = "Info",
  174. Message = "init finish, toke " + (new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds() - ts) + "ms",
  175. Type = NotificationType.Information
  176. });
  177. Application.Current.Dispatcher.Invoke((Action)(() =>
  178. {
  179. config.devices.ForEach(i =>
  180. {
  181. i.Init();
  182. devices.Add(i);
  183. });
  184. }));
  185. });
  186. }
  187. private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  188. {
  189. e.Cancel = true;
  190. Hide();
  191. }
  192. private void btn_add_device_Click(object sender, RoutedEventArgs e)
  193. {
  194. AddDevice addDevice = new AddDevice();
  195. if (addDevice.ShowDialog() ?? false)
  196. {
  197. config.devices.Add(addDevice.device);
  198. config.save();
  199. devices.Add(addDevice.device);
  200. addDevice.device.Init();
  201. }
  202. }
  203. private void btn_del_device_Click(object sender, RoutedEventArgs e)
  204. {
  205. //NotificationUtil.show("连接设备失败", "请检查网络");
  206. if (lv_device.SelectedIndex == -1)
  207. {
  208. return;
  209. }
  210. Console.WriteLine(lv_device.SelectedItem);
  211. MessageBoxResult messageBoxResult = MessageBox.Show("确认删除?", "提示", MessageBoxButton.YesNo);
  212. if (messageBoxResult == MessageBoxResult.Yes)
  213. {
  214. int i = lv_device.SelectedIndex;
  215. if (devices[i].status != DeviceStatus.IDLE)
  216. {
  217. devices[i].dispose();
  218. }
  219. devices.RemoveAt(i);
  220. config.devices.RemoveAt(i);
  221. config.save();
  222. // lv_device.Items.Refresh();
  223. }
  224. }
  225. private void onAlarm(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
  226. {
  227. switch (lCommand)
  228. {
  229. case CHCNetSDK.COMM_ALARM_ACS:
  230. ProcessCommAlarmACS(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
  231. break;
  232. default:
  233. break;
  234. }
  235. }
  236. private void ProcessCommAlarmACS(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
  237. {
  238. foreach (Device device in devices)
  239. {
  240. if (device.type == DeviceType.ACS)
  241. {
  242. AcsDevice acsDevice = (AcsDevice)device;
  243. if (acsDevice.userId == pAlarmer.lUserID)
  244. {
  245. acsDevice.onAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
  246. }
  247. }
  248. }
  249. }
  250. private int onGetCarPlate(int tHandle, uint uiImageId, ref CarCamSDK.T_ImageUserInfo2 tImageInfo, ref CarCamSDK.T_PicInfo tPicInfo)
  251. {
  252. foreach (Device device in devices)
  253. {
  254. if (device.type == DeviceType.ACS)
  255. {
  256. CarCamDevice carCamDevice = (CarCamDevice)device;
  257. if (tHandle == carCamDevice.userId)
  258. {
  259. return carCamDevice.onGetCarPlate(tHandle, uiImageId, ref tImageInfo, ref tPicInfo);
  260. }
  261. }
  262. }
  263. return 0;
  264. }
  265. private void GetAllCard(object source, EventArgs e)
  266. {
  267. int m_userId = -1;
  268. AcsDevice device = null;
  269. try
  270. {
  271. device = (AcsDevice)devices.First(i => i.type == DeviceType.ACS && i.status == DeviceStatus.CONNECTED);
  272. }
  273. catch { }
  274. if (device == null)
  275. {
  276. log.Info("no connected device");
  277. return;
  278. }
  279. m_userId = device.userId;
  280. if (-1 != m_lGetCardCfgHandle)
  281. {
  282. if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lGetCardCfgHandle))
  283. {
  284. m_lGetCardCfgHandle = -1;
  285. }
  286. }
  287. CHCNetSDK.NET_DVR_CARD_CFG_COND struCond = new CHCNetSDK.NET_DVR_CARD_CFG_COND();
  288. struCond.dwSize = (uint)Marshal.SizeOf(struCond);
  289. struCond.wLocalControllerID = 0;
  290. struCond.dwCardNum = 0xffffffff;
  291. struCond.byCheckCardNo = 1;
  292. int dwSize = Marshal.SizeOf(struCond);
  293. IntPtr ptrStruCond = Marshal.AllocHGlobal(dwSize);
  294. Marshal.StructureToPtr(struCond, ptrStruCond, false);
  295. g_fGetGatewayCardCallback = new CHCNetSDK.RemoteConfigCallback(ProcessGetGatewayCardCallback);
  296. m_lGetCardCfgHandle = CHCNetSDK.NET_DVR_StartRemoteConfig(m_userId, CHCNetSDK.NET_DVR_GET_CARD_CFG_V50, ptrStruCond, dwSize, g_fGetGatewayCardCallback, new WindowInteropHelper(this).Handle);
  297. if (m_lGetCardCfgHandle == -1)
  298. {
  299. log.Info(string.Format("NET_DVR_GET_CARD_CFG_V50 FAIL, ERROR CODE {0}", CHCNetSDK.NET_DVR_GetLastError()));
  300. Marshal.FreeHGlobal(ptrStruCond);
  301. return;
  302. }
  303. else
  304. {
  305. log.Info("SUCC NET_DVR_GET_CARD_CFG_V50");
  306. }
  307. Marshal.FreeHGlobal(ptrStruCond);
  308. }
  309. private void ProcessGetGatewayCardCallback(uint dwType, IntPtr lpBuffer, uint dwBufLen, IntPtr pUserData)
  310. {
  311. if (pUserData == null)
  312. {
  313. return;
  314. }
  315. if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_DATA)
  316. {
  317. CHCNetSDK.NET_DVR_CARD_CFG_V50 struCardCfg = new CHCNetSDK.NET_DVR_CARD_CFG_V50();
  318. struCardCfg = (CHCNetSDK.NET_DVR_CARD_CFG_V50)Marshal.PtrToStructure(lpBuffer, typeof(CHCNetSDK.NET_DVR_CARD_CFG_V50));
  319. string strCardNo = System.Text.Encoding.UTF8.GetString(struCardCfg.byCardNo);
  320. IntPtr pCardInfo = Marshal.AllocHGlobal(Marshal.SizeOf(struCardCfg));
  321. Marshal.StructureToPtr(struCardCfg, pCardInfo, true);
  322. CHCNetSDK.PostMessage(pUserData, 1003, (Int64)pCardInfo, 0);
  323. string cardNo = Encoding.UTF8.GetString(struCardCfg.byCardNo);
  324. string isValid = 1 == struCardCfg.byCardValid ? "YES" : "NO";
  325. string cardPasswod = Encoding.UTF8.GetString(struCardCfg.byCardPassword);
  326. string cardType = (struCardCfg.byCardType == 0 || struCardCfg.byCardType > 7) ?
  327. AcsDemoPublic.strCardType[0] : AcsDemoPublic.strCardType[struCardCfg.byCardType];
  328. string leaderCard = 1 == struCardCfg.byLeaderCard ? "YES" : "NO";
  329. string name = Encoding.UTF8.GetString(struCardCfg.byName);
  330. log.Info($"cardNo:{cardNo} name:{name} departmentNo:{struCardCfg.wDepartmentNo}");
  331. //var request = new RestRequest("staffInfo/saveStaffInfo", DataFormat.Json);
  332. //request.AddParameter("name", name);
  333. //request.AddParameter("cardNo", cardNo);
  334. //restClient.Post(request);
  335. }
  336. else if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_STATUS)
  337. {
  338. uint dwStatus = (uint)Marshal.ReadInt32(lpBuffer);
  339. if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_SUCCESS)
  340. {
  341. log.Info("NET_DVR_GET_CARD_CFG_V50 Get finish");
  342. CHCNetSDK.PostMessage(pUserData, 1002, 0, 0);
  343. }
  344. else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_FAILED)
  345. {
  346. byte[] bRawData = new byte[40];//4字节状态 + 4字节错误码 + 32字节卡号
  347. Marshal.Copy(lpBuffer, bRawData, 0, 40);//将非托管内存指针数据复制到数组中
  348. byte[] errorb = new byte[4];//4字节错误码
  349. Array.Copy(bRawData, 4, errorb, 0, 4);
  350. int errorCode = BitConverter.ToInt32(errorb, 0);
  351. byte[] byCardNo = new byte[32];//32字节卡号
  352. Array.Copy(bRawData, 8, byCardNo, 0, 32);
  353. string strCardNo = Encoding.ASCII.GetString(byCardNo).TrimEnd('\0');
  354. log.Info(string.Format("NET_DVR_GET_CARD_CFG_V50 Get Failed,ErrorCode:{0},CardNo:{1}", errorCode, byCardNo));
  355. CHCNetSDK.PostMessage(pUserData, 1002, 0, 0);
  356. }
  357. }
  358. return;
  359. }
  360. public void getDepartments()
  361. {
  362. int m_userId = -1;
  363. AcsDevice device = null;
  364. try
  365. {
  366. device = (AcsDevice)devices.First(i => i.type == DeviceType.ACS && i.status == DeviceStatus.CONNECTED);
  367. }
  368. catch { }
  369. if (device == null)
  370. {
  371. log.Info("no connected device");
  372. return;
  373. }
  374. IntPtr lpRequestUrl = IntPtr.Zero;
  375. try
  376. {
  377. CHCNetSDK.NET_DVR_XML_CONFIG_INPUT input = new CHCNetSDK.NET_DVR_XML_CONFIG_INPUT();
  378. CHCNetSDK.NET_DVR_XML_CONFIG_INPUT output = new CHCNetSDK.NET_DVR_XML_CONFIG_INPUT();
  379. string url = "/ISAPI/AccessControl/DepartmentParam/capabilities";
  380. lpRequestUrl = Marshal.StringToHGlobalAnsi(url);
  381. input.lpRequestUrl = lpRequestUrl;
  382. IntPtr inputPtr = new IntPtr();
  383. IntPtr outputPtr = new IntPtr();
  384. Marshal.StructureToPtr(input, inputPtr, true);
  385. CHCNetSDK.NET_DVR_STDXMLConfig(m_userId, inputPtr, outputPtr);
  386. }
  387. catch (Exception e) { }
  388. finally
  389. {
  390. if (lpRequestUrl != IntPtr.Zero)
  391. {
  392. Marshal.FreeHGlobal(lpRequestUrl);
  393. }
  394. }
  395. }
  396. private void btn_upload_staff_Click(object sender, RoutedEventArgs e)
  397. {
  398. OpenFileDialog openFileDialog = new OpenFileDialog();
  399. openFileDialog.Filter = "Excel (*.xlsx)|*.xlsx";
  400. if (openFileDialog.ShowDialog() == true)
  401. {
  402. Console.WriteLine(openFileDialog.FileName);
  403. Boolean canOpen = false;
  404. try
  405. {
  406. FileStream fileStream = File.OpenRead(openFileDialog.FileName);
  407. canOpen = true;
  408. fileStream.Close();
  409. }
  410. catch (IOException ee)
  411. {
  412. MessageBox.Show(ee.Message);
  413. }
  414. if (canOpen)
  415. {
  416. notificationManager.Show(new NotificationContent
  417. {
  418. Title = "OK",
  419. Message = "上传成功",
  420. Type = NotificationType.Success
  421. });
  422. http.upload<string>("staffInfo/import", openFileDialog.FileName);
  423. }
  424. }
  425. }
  426. private void ProcessAcsEvent(ref CHCNetSDK.NET_DVR_ACS_EVENT_CFG struCFG, ref bool flag)
  427. {
  428. int employNo = (int)struCFG.struAcsEventInfo.dwEmployeeNo;
  429. string cardNo = Encoding.UTF8.GetString(struCFG.struAcsEventInfo.byCardNo).TrimEnd('\0');
  430. string time = $"{struCFG.struTime.dwYear:D4}-{struCFG.struTime.dwMonth:D2}-{struCFG.struTime.dwDay:D2} {struCFG.struTime.dwHour:D2}:{struCFG.struTime.dwMinute:D2}:{struCFG.struTime.dwSecond:D2}";
  431. log.Info($"receive acs event employNo:{employNo} cardNo:{cardNo} time:{time}");
  432. }
  433. private void Get_Event_Click(object sender, RoutedEventArgs e)
  434. {
  435. AskDate dialog = new AskDate();
  436. if (dialog.ShowDialog() ?? false)
  437. {
  438. foreach (Device device in devices)
  439. {
  440. if (device.status == DeviceStatus.CONNECTED && device.type == DeviceType.ACS)
  441. {
  442. ((AcsDevice)device).getEvent(dialog.start, dialog.end);
  443. }
  444. }
  445. }
  446. }
  447. }
  448. }