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
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
public static readonly ILog log = LogManager.GetLogger("DeviceCenter");
private NotificationManager notificationManager = new NotificationManager();
private ObservableCollection devices = new ObservableCollection();
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("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);
}
}
}
}
}
}