| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509 |
- using DeviceCenter.model;
- using DeviceCenter.utils;
- using DeviceCenter.views;
- using FluentScheduler;
- using log4net;
- using Microsoft.Win32;
- using Notifications.Wpf;
- using System;
- using System.Collections.ObjectModel;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Interop;
- namespace DeviceCenter
- {
- /// <summary>
- /// MainWindow.xaml 的交互逻辑
- /// </summary>
- public partial class MainWindow : Window
- {
- public static readonly ILog log = LogManager.GetLogger("DeviceCenter");
- private NotificationManager notificationManager = new NotificationManager();
- private ObservableCollection<Device> devices = new ObservableCollection<Device>();
- private Config config = Config.getInstance();
- private CHCNetSDK.MSGCallBack alarmCallback = null;
- private static CarCamSDK.FGetImageCB2 carPlateCallback;
- private int m_lGetCardCfgHandle = -1;
- private CHCNetSDK.RemoteConfigCallback g_fGetGatewayCardCallback = null;
- private System.Windows.Forms.NotifyIcon notifyIcon = null;
- private System.Windows.Forms.ContextMenu contextMenuExit;
- private System.Windows.Forms.MenuItem menuItem1;
- private System.Windows.Forms.MenuItem menuItem2;
- private System.ComponentModel.IContainer components;
- public MainWindow()
- {
- InitializeComponent();
- notifyIcon = new System.Windows.Forms.NotifyIcon();
- notifyIcon.Click += new EventHandler(notifyIcon_Click);
- notifyIcon.Icon = new Icon(AppDomain.CurrentDomain.BaseDirectory + "assets\\icon.ico");
- components = new System.ComponentModel.Container();
- contextMenuExit = new System.Windows.Forms.ContextMenu();
- menuItem1 = new System.Windows.Forms.MenuItem();
- menuItem2 = new System.Windows.Forms.MenuItem();
- // Initialize contextMenuExit
- this.contextMenuExit.MenuItems.AddRange(
- new System.Windows.Forms.MenuItem[] { this.menuItem1, menuItem2 });
- // Initialize menuItem1
- this.menuItem1.Index = 0;
- this.menuItem1.Text = "退出";
- this.menuItem1.Click += new EventHandler(this.menuItem1_Click);
- menuItem2.Index = 1;
- menuItem2.Text = "开机自启";
- menuItem2.Click += new EventHandler(this.menuItem2_Click);
- menuItem2.Checked = AppUtil.isAutoStart();
- notifyIcon.ContextMenu = this.contextMenuExit;
- initSdk();
- lv_device.ItemsSource = devices;
- //System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
- //dispatcherTimer.Tick += GetAllCard;
- //dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
- //dispatcherTimer.Start();
- //System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
- //timer.Tick += (s, e) =>
- //{
- // ((System.Windows.Threading.DispatcherTimer)s).Stop();
- // GetAllCard(null, null);
- //};
- //timer.Interval = new TimeSpan(0, 0, 5);
- //timer.Start();
- ScheduleJob();
- }
- private void ScheduleJob()
- {
- JobManager.Initialize();
- JobManager.AddJob(
- () =>
- {
- DateTime now = DateTime.Now.AddDays(-1);
- DateTime start = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
- DateTime end = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
- foreach (Device device in devices)
- {
- if (device.status == DeviceStatus.CONNECTED && device.type == DeviceType.ACS)
- {
- ((AcsDevice)device).getEvent(start, end);
- }
- }
- },
- s => s.ToRunEvery(1).Days().At(3, 0)
- );
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- notifyIcon.Visible = true;
- string imageDir = AppDomain.CurrentDomain.BaseDirectory + "Picture";
- if (!Directory.Exists(imageDir))
- {
- Directory.CreateDirectory(imageDir);
- }
- }
- private void notifyIcon_Click(object sender, EventArgs e)
- {
- Show();
- }
- private void menuItem1_Click(object Sender, EventArgs e)
- {
- ExitConfirm ex = new ExitConfirm();
- if (ex.ShowDialog() ?? false)
- {
- if (ex.password.Password == config.password)
- {
- notifyIcon.Dispose();
- Application.Current.Shutdown();
- }
- else
- {
- notificationManager.Show(new NotificationContent
- {
- Title = "Error",
- Message = "密码错误",
- Type = NotificationType.Error
- });
- }
- }
- }
- private void menuItem2_Click(object Sender, EventArgs e)
- {
- if (AppUtil.isAutoStart())
- {
- AppUtil.disableAutoStart();
- menuItem2.Checked = false;
- }
- else
- {
- AppUtil.enableAutoStart();
- menuItem2.Checked = true;
- }
- }
- private async void initSdk()
- {
- await Task.Run(() =>
- {
- long ts = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
- carPlateCallback = new CarCamSDK.FGetImageCB2(onGetCarPlate);
- CarCamSDK.Net_RegImageRecv2(carPlateCallback);
- //UsbSwitch.usb_relay_init();
- alarmCallback = new CHCNetSDK.MSGCallBack(onAlarm);
- if (CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V50(0, alarmCallback, IntPtr.Zero))
- {
- log.Info("NET_DVR_SetDVRMessageCallBack_V50 Succeed");
- notificationManager.Show(new NotificationContent
- {
- Title = "Success",
- Message = "NET_DVR_SetDVRMessageCallBack_V50 Succeed",
- Type = NotificationType.Success
- });
- }
- else
- {
- notificationManager.Show(new NotificationContent
- {
- Title = "Error",
- Message = "NET_DVR_SetDVRMessageCallBack_V50 Fail",
- Type = NotificationType.Error
- });
- }
- notificationManager.Show(new NotificationContent
- {
- Title = "Info",
- Message = "init finish, toke " + (new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds() - ts) + "ms",
- Type = NotificationType.Information
- });
- Application.Current.Dispatcher.Invoke((Action)(() =>
- {
- config.devices.ForEach(i =>
- {
- i.Init();
- devices.Add(i);
- });
- }));
- });
- }
- private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
- {
- e.Cancel = true;
- Hide();
- }
- private void btn_add_device_Click(object sender, RoutedEventArgs e)
- {
- AddDevice addDevice = new AddDevice();
- if (addDevice.ShowDialog() ?? false)
- {
- config.devices.Add(addDevice.device);
- config.save();
- devices.Add(addDevice.device);
- addDevice.device.Init();
- }
- }
- private void btn_del_device_Click(object sender, RoutedEventArgs e)
- {
- //NotificationUtil.show("连接设备失败", "请检查网络");
- if (lv_device.SelectedIndex == -1)
- {
- return;
- }
- Console.WriteLine(lv_device.SelectedItem);
- MessageBoxResult messageBoxResult = MessageBox.Show("确认删除?", "提示", MessageBoxButton.YesNo);
- if (messageBoxResult == MessageBoxResult.Yes)
- {
- int i = lv_device.SelectedIndex;
- if (devices[i].status != DeviceStatus.IDLE)
- {
- devices[i].dispose();
- }
- devices.RemoveAt(i);
- config.devices.RemoveAt(i);
- config.save();
- // lv_device.Items.Refresh();
- }
- }
- private void onAlarm(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
- {
- switch (lCommand)
- {
- case CHCNetSDK.COMM_ALARM_ACS:
- ProcessCommAlarmACS(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
- break;
- default:
- break;
- }
- }
- private void ProcessCommAlarmACS(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
- {
- foreach (Device device in devices)
- {
- if (device.type == DeviceType.ACS)
- {
- AcsDevice acsDevice = (AcsDevice)device;
- if (acsDevice.userId == pAlarmer.lUserID)
- {
- acsDevice.onAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
- }
- }
- }
- }
- private int onGetCarPlate(int tHandle, uint uiImageId, ref CarCamSDK.T_ImageUserInfo2 tImageInfo, ref CarCamSDK.T_PicInfo tPicInfo)
- {
- foreach (Device device in devices)
- {
- if (device.type == DeviceType.ACS)
- {
- CarCamDevice carCamDevice = (CarCamDevice)device;
- if (tHandle == carCamDevice.userId)
- {
- return carCamDevice.onGetCarPlate(tHandle, uiImageId, ref tImageInfo, ref tPicInfo);
- }
- }
- }
- return 0;
- }
- private void GetAllCard(object source, EventArgs e)
- {
- int m_userId = -1;
- AcsDevice device = null;
- try
- {
- device = (AcsDevice)devices.First(i => i.type == DeviceType.ACS && i.status == DeviceStatus.CONNECTED);
- }
- catch { }
- if (device == null)
- {
- log.Info("no connected device");
- return;
- }
- m_userId = device.userId;
- if (-1 != m_lGetCardCfgHandle)
- {
- if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lGetCardCfgHandle))
- {
- m_lGetCardCfgHandle = -1;
- }
- }
- CHCNetSDK.NET_DVR_CARD_CFG_COND struCond = new CHCNetSDK.NET_DVR_CARD_CFG_COND();
- struCond.dwSize = (uint)Marshal.SizeOf(struCond);
- struCond.wLocalControllerID = 0;
- struCond.dwCardNum = 0xffffffff;
- struCond.byCheckCardNo = 1;
- int dwSize = Marshal.SizeOf(struCond);
- IntPtr ptrStruCond = Marshal.AllocHGlobal(dwSize);
- Marshal.StructureToPtr(struCond, ptrStruCond, false);
- g_fGetGatewayCardCallback = new CHCNetSDK.RemoteConfigCallback(ProcessGetGatewayCardCallback);
- m_lGetCardCfgHandle = CHCNetSDK.NET_DVR_StartRemoteConfig(m_userId, CHCNetSDK.NET_DVR_GET_CARD_CFG_V50, ptrStruCond, dwSize, g_fGetGatewayCardCallback, new WindowInteropHelper(this).Handle);
- if (m_lGetCardCfgHandle == -1)
- {
- log.Info(string.Format("NET_DVR_GET_CARD_CFG_V50 FAIL, ERROR CODE {0}", CHCNetSDK.NET_DVR_GetLastError()));
- Marshal.FreeHGlobal(ptrStruCond);
- return;
- }
- else
- {
- log.Info("SUCC NET_DVR_GET_CARD_CFG_V50");
- }
- Marshal.FreeHGlobal(ptrStruCond);
- }
- private void ProcessGetGatewayCardCallback(uint dwType, IntPtr lpBuffer, uint dwBufLen, IntPtr pUserData)
- {
- if (pUserData == null)
- {
- return;
- }
- if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_DATA)
- {
- CHCNetSDK.NET_DVR_CARD_CFG_V50 struCardCfg = new CHCNetSDK.NET_DVR_CARD_CFG_V50();
- struCardCfg = (CHCNetSDK.NET_DVR_CARD_CFG_V50)Marshal.PtrToStructure(lpBuffer, typeof(CHCNetSDK.NET_DVR_CARD_CFG_V50));
- string strCardNo = System.Text.Encoding.UTF8.GetString(struCardCfg.byCardNo);
- IntPtr pCardInfo = Marshal.AllocHGlobal(Marshal.SizeOf(struCardCfg));
- Marshal.StructureToPtr(struCardCfg, pCardInfo, true);
- CHCNetSDK.PostMessage(pUserData, 1003, (Int64)pCardInfo, 0);
- string cardNo = Encoding.UTF8.GetString(struCardCfg.byCardNo);
- string isValid = 1 == struCardCfg.byCardValid ? "YES" : "NO";
- string cardPasswod = Encoding.UTF8.GetString(struCardCfg.byCardPassword);
- string cardType = (struCardCfg.byCardType == 0 || struCardCfg.byCardType > 7) ?
- AcsDemoPublic.strCardType[0] : AcsDemoPublic.strCardType[struCardCfg.byCardType];
- string leaderCard = 1 == struCardCfg.byLeaderCard ? "YES" : "NO";
- string name = Encoding.UTF8.GetString(struCardCfg.byName);
- log.Info($"cardNo:{cardNo} name:{name} departmentNo:{struCardCfg.wDepartmentNo}");
- //var request = new RestRequest("staffInfo/saveStaffInfo", DataFormat.Json);
- //request.AddParameter("name", name);
- //request.AddParameter("cardNo", cardNo);
- //restClient.Post(request);
- }
- else if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_STATUS)
- {
- uint dwStatus = (uint)Marshal.ReadInt32(lpBuffer);
- if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_SUCCESS)
- {
- log.Info("NET_DVR_GET_CARD_CFG_V50 Get finish");
- CHCNetSDK.PostMessage(pUserData, 1002, 0, 0);
- }
- else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_FAILED)
- {
- byte[] bRawData = new byte[40];//4字节状态 + 4字节错误码 + 32字节卡号
- Marshal.Copy(lpBuffer, bRawData, 0, 40);//将非托管内存指针数据复制到数组中
- byte[] errorb = new byte[4];//4字节错误码
- Array.Copy(bRawData, 4, errorb, 0, 4);
- int errorCode = BitConverter.ToInt32(errorb, 0);
- byte[] byCardNo = new byte[32];//32字节卡号
- Array.Copy(bRawData, 8, byCardNo, 0, 32);
- string strCardNo = Encoding.ASCII.GetString(byCardNo).TrimEnd('\0');
- log.Info(string.Format("NET_DVR_GET_CARD_CFG_V50 Get Failed,ErrorCode:{0},CardNo:{1}", errorCode, byCardNo));
- CHCNetSDK.PostMessage(pUserData, 1002, 0, 0);
- }
- }
- return;
- }
- public void getDepartments()
- {
- int m_userId = -1;
- AcsDevice device = null;
- try
- {
- device = (AcsDevice)devices.First(i => i.type == DeviceType.ACS && i.status == DeviceStatus.CONNECTED);
- }
- catch { }
- if (device == null)
- {
- log.Info("no connected device");
- return;
- }
- IntPtr lpRequestUrl = IntPtr.Zero;
- try
- {
- CHCNetSDK.NET_DVR_XML_CONFIG_INPUT input = new CHCNetSDK.NET_DVR_XML_CONFIG_INPUT();
- CHCNetSDK.NET_DVR_XML_CONFIG_INPUT output = new CHCNetSDK.NET_DVR_XML_CONFIG_INPUT();
- string url = "/ISAPI/AccessControl/DepartmentParam/capabilities";
- lpRequestUrl = Marshal.StringToHGlobalAnsi(url);
- input.lpRequestUrl = lpRequestUrl;
- IntPtr inputPtr = new IntPtr();
- IntPtr outputPtr = new IntPtr();
- Marshal.StructureToPtr(input, inputPtr, true);
- CHCNetSDK.NET_DVR_STDXMLConfig(m_userId, inputPtr, outputPtr);
- }
- catch (Exception e) { }
- finally
- {
- if (lpRequestUrl != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(lpRequestUrl);
- }
- }
- }
- private void btn_upload_staff_Click(object sender, RoutedEventArgs e)
- {
- OpenFileDialog openFileDialog = new OpenFileDialog();
- openFileDialog.Filter = "Excel (*.xlsx)|*.xlsx";
- if (openFileDialog.ShowDialog() == true)
- {
- Console.WriteLine(openFileDialog.FileName);
- Boolean canOpen = false;
- try
- {
- FileStream fileStream = File.OpenRead(openFileDialog.FileName);
- canOpen = true;
- fileStream.Close();
- }
- catch (IOException ee)
- {
- MessageBox.Show(ee.Message);
- }
- if (canOpen)
- {
- notificationManager.Show(new NotificationContent
- {
- Title = "OK",
- Message = "上传成功",
- Type = NotificationType.Success
- });
- http.upload<string>("staffInfo/import", openFileDialog.FileName);
- }
- }
- }
- private void ProcessAcsEvent(ref CHCNetSDK.NET_DVR_ACS_EVENT_CFG struCFG, ref bool flag)
- {
- int employNo = (int)struCFG.struAcsEventInfo.dwEmployeeNo;
- string cardNo = Encoding.UTF8.GetString(struCFG.struAcsEventInfo.byCardNo).TrimEnd('\0');
- 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}";
- log.Info($"receive acs event employNo:{employNo} cardNo:{cardNo} time:{time}");
- }
- private void Get_Event_Click(object sender, RoutedEventArgs e)
- {
- AskDate dialog = new AskDate();
- if (dialog.ShowDialog() ?? false)
- {
- foreach (Device device in devices)
- {
- if (device.status == DeviceStatus.CONNECTED && device.type == DeviceType.ACS)
- {
- ((AcsDevice)device).getEvent(dialog.start, dialog.end);
- }
- }
- }
- }
- }
- }
|