//创建新表 private static string creatNewTable(string childName) { MySQLDB.InitDb(); MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; strSQL = "CREATE TABLE " + childName + "(id INT AUTO_INCREMENT, CardID VARCHAR(45), DataDate VARCHAR(45), DoorID VARCHAR(45), PRIMARY KEY (`id`));"; //建立新表 /*parmss = new MySqlParameter[] * { * new MySqlParameter("?sensorChildTable", MySqlDbType.VarChar) * }; * parmss[0].Value = childName;*/ try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); } }
//处理接收队列 private void CheckRecDataQueue(object state) { checkRecDataQueueResetEvent.Reset(); //Reset()将事件状态设置为非终止状态,导致线程阻止。 while (IsServerOpen) { try { foreach (DataItem dataItem in htClient.Values) { dataItem.HandleData(); dataItem.SendData(); if (CheckTimeout(dataItem.HeartTime, maxTimeOut) && dataItem.status == true) { dataItem.status = false; //更新数据库信息 DbClass.UpdateSensorInfo(dataItem.strID, "status", dataItem.status.ToString()); } } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); } Thread.Sleep(checkRecDataQueueTimeInterval); //当前数据处理线程休眠一段时间 } checkRecDataQueueResetEvent.Set(); }
//清除ID对应的记录 public static string deleteHistory(string strID) { MySQLDB.InitDb(); MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; string childName = "thistorychild" + strID; strSQL = "DELETE FROM " + childName; //删除全部记录 try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); } }
//更新所有设备在线信息为false public static string UpdateSensorInfo() { MySQLDB.InitDb(); string strResult = ""; MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; strSQL = "Update tdevice SET status = 'False'"; try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); } }
public void Stop() { if (CloseServer() == true) { UtilClass.writeLog("停止成功"); } else { UtilClass.writeLog("停止失败"); } }
/// <summary> /// 读取命令,返回二维数组,并重置字段为-1 /// </summary> public static string[,] readCmd() { MySQLDB.InitDb(); string[,] ret; //从数据库中查找当前ID是否存在 try { DataSet ds1 = new DataSet("tcommand"); string strSQL1 = "SELECT * FROM tcommand where (cmdName!='-1' AND cmdName!='ok' AND cmdName!='fail')"; ds1 = MySQLDB.SelectDataSet(strSQL1, null); if (ds1 != null) { // 有数据集 int count = ds1.Tables[0].Rows.Count; if (count > 0) { ret = new string[count, 4]; for (int i = 0; i < count; i++) { ret[i, 0] = ds1.Tables[0].Rows[i]["deviceID"].ToString(); ret[i, 1] = ds1.Tables[0].Rows[i]["cmdName"].ToString(); ret[i, 2] = ds1.Tables[0].Rows[i]["operation"].ToString(); ret[i, 3] = ds1.Tables[0].Rows[i]["data"].ToString(); } //重置字段为-1,add3-5 //3-24只修改对应ID的cmdName,不能全部修改,否则会把反馈信息“ok”覆盖掉! for (int i = 0; i < count; i++) { string strSQL2 = "UPDATE tcommand SET cmdName = '-1' WHERE deviceID=" + "\"" + ret[i, 0].ToString() + "\""; ds1 = MySQLDB.SelectDataSet(strSQL2, null); } return(ret); } else { return(null); } } else { return(null); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return(null); } }
/// <summary> /// 异步发送数据 /// </summary> /// <param name="ar">IAsyncResult</param> private void OnSend(IAsyncResult ar) { try { Socket client = (Socket)ar.AsyncState; client.EndSendTo(ar); } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); } }
public static byte[] makeCommand(string cmdFlag, string rw, string data, byte[] mcuID) { try { if (cmdFlag == null || rw == null || data == null || mcuID == null || cmdFlag == "-1" || rw == "-1" || data == "-1") { return(null); } byte len = (byte)(data.Length / 2); byte[] buf = new byte[len + 13]; byte[] byteData = UtilClass.hexStrToByte(data); int i; byte crcRet; buf[0] = 0xA5; buf[1] = 0xA5; if (!htCmdNum.ContainsKey(cmdFlag) || !htCmdNum.ContainsKey(rw)) { return(null); } buf[2] = Convert.ToByte(htCmdNum[cmdFlag]); buf[3] = mcuID[0]; buf[4] = mcuID[1]; buf[5] = mcuID[2]; buf[6] = mcuID[3]; buf[7] = Convert.ToByte(htCmdNum[rw]); buf[8] = (byte)(len >> 8); buf[9] = (byte)(len & 0xFF); for (i = 0; i < len; i++) { buf[10 + i] = byteData[i]; } crcRet = Get_Crc8(buf, 10 + len); buf[10 + len + 0] = crcRet; buf[10 + len + 1] = 0x5A; buf[10 + len + 2] = 0x5A; return(buf); } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return(null); } }
/// <summary> /// 发送命令 /// </summary> /// <param name="cmd"></param> private void SendCmd(byte[] cmd) { try { #if DEBUG UtilClass.writeLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "硬件" + strID + "发送数据:" + UtilClass.byteToHexStr(cmd)); #endif socket.BeginSendTo(cmd, 0, cmd.Length, SocketFlags.None, remote, new AsyncCallback(OnSend), socket); } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); } }
/// <summary> /// 服务开始,进行初始化 /// </summary> public void Start() { serviceInit(); CmdClass.cmdInit(); if (OpenServer() == true) { //初始化设备状态为false DbClass.UpdateSensorInfo(); UtilClass.writeLog("启动成功"); } else { UtilClass.writeLog("启动失败"); } }
/// <summary> /// 接收数据 /// </summary> /// <param name="ar"></param> private void OnReceive(IAsyncResult ar) { int len = -1; string strID; byte[] id = new byte[4]; try { EndPoint remote = (EndPoint)(ar.AsyncState); len = ServerSocket.EndReceiveFrom(ar, ref remote); //报文格式过滤 if (buffer[0] == 0xA5 && buffer[1] == 0xA5 && buffer[len - 2] == 0x5A && buffer[len - 1] == 0x5A) { Array.Copy(buffer, 3, id, 0, 4); strID = UtilClass.byteToHexStr(id); //判断哈希表中是否存在当前ID,不存在则创建,存在则把数据加入队列 if (htClient.ContainsKey(strID) == false) { DataItem dataItem = new DataItem(); dataItem.Init(ServerSocket, id, strID, updateDataLength, broadcastRemote, maxHistoryPackage); //初始化dataItem htClient.Add(strID, dataItem); //把设备信息存入数据库,创建记录表 DbClass.addsensorinfo(strID, dataItem.HeartTime.ToString("yyyy-MM-dd HH:mm:ss"), dataItem.status.ToString()); DbClass.creatHistoryChildtable(strID); } else { DataItem dataItem = (DataItem)htClient[strID]; //取出address对应的dataitem byte[] recData = new byte[len]; Array.Copy(buffer, recData, len); dataItem.recDataQueue.Enqueue(recData); //Enqueue 将对象添加到 Queue<T> 的结尾处 } } //继续接收数据 ServerSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remote, new AsyncCallback(OnReceive), remote); } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); } }
/// <summary> /// 开启socket服务 /// </summary> /// <returns></returns> private bool OpenServer() { try { IPEndPoint myclient = new IPEndPoint(IPAddress.Any, 0); EndPoint myRemote = (EndPoint)(myclient); //得到本机IP,设置TCP端口号 IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), ServerPort); ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //配置广播发送socket ServerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); //绑定网络地址 ServerSocket.Bind(ipEndPoint); ServerSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref myRemote, new AsyncCallback(OnReceive), myRemote); //接收数据包处理线程 if (!ThreadPool.QueueUserWorkItem(CheckRecDataQueue)) { return(false); } //add3-7 合并发送数据包处理线程到接收线程中 if (!ThreadPool.QueueUserWorkItem(CheckDataBaseQueue)) { return(false); } IsServerOpen = true; return(true); } catch (Exception e) { Console.WriteLine(e); UtilClass.writeLog(e.ToString()); return(false); } }
//批量插入记录 public static string insertHistory(string strID, string[,] dataStrings, int dataNum) { MySQLDB.InitDb(); string strResult = ""; MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; string childName = "thistorychild" + strID; strSQL = "INSERT INTO " + childName + "(CardID, DataDate, DoorID) VALUES "; for (int i = 0; i < dataNum; i++) { strSQL += "(" + "'" + dataStrings[i, 0] + "'" + "," + "'" + dataStrings[i, 1] + "'" + "," + "'" + dataStrings[i, 2] + "'" + ")"; if (i < dataNum - 1) { strSQL += ","; } } try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); } }
//更新设备信息 public static string UpdateCmd(string sensorintdeviceID, string updateItem, string updateNum) { MySQLDB.InitDb(); string strResult = ""; MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; strSQL = "Update tcommand SET " + updateItem + " =?sensorupdateItem WHERE deviceID=?sensorintdeviceID"; parmss = new MySqlParameter[] { new MySqlParameter("?sensorintdeviceID", MySqlDbType.VarChar), new MySqlParameter("?sensorupdateItem", MySqlDbType.VarChar) }; parmss[0].Value = sensorintdeviceID; parmss[1].Value = updateNum; try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); } }
/// <summary> /// 关闭socket /// </summary> public bool CloseServer() { try { IsServerOpen = false; checkRecDataQueueResetEvent.WaitOne(); //checkSendDataQueueResetEvent.WaitOne(); checkDataBaseQueueResetEvent.WaitOne(); ServerSocket.Dispose(); htClient.Clear(); GC.SuppressFinalize(this); return(true); } catch (Exception e) { Console.WriteLine(e); UtilClass.writeLog(e.ToString()); return(false); } }
public void Continued() { UtilClass.writeLog("继续运行"); }
public static string addsensorinfo(string sensorintdeviceID, string sensorloginTime, string sensorStatus) { MySQLDB.InitDb(); string sensorid = "0"; //从数据库中查找当前ID是否存在 try { DataSet ds1 = new DataSet("tdevice"); string strSQL1 = "SELECT deviceID FROM tdevice where deviceID=" + "\"" + sensorintdeviceID + "\""; ds1 = MySQLDB.SelectDataSet(strSQL1, null); if (ds1 != null) { if (ds1.Tables[0].Rows.Count > 0) // 有数据集 { sensorid = ds1.Tables[0].Rows[0][0].ToString(); } } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); //数据库异常 } //************************************************************ if (sensorid == "0") //若不存在,则添加 { DataSet ds = new DataSet("tdevice"); string strResult = ""; MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; strSQL = " insert into tdevice (deviceID, lastLoginTime, status) values" + "(?sensorintdeviceID,?sensorloginTime,?sensorStatus);"; parmss = new MySqlParameter[] { new MySqlParameter("?sensorintdeviceID", MySqlDbType.VarChar), new MySqlParameter("?sensorloginTime", MySqlDbType.VarChar), new MySqlParameter("?sensorStatus", MySqlDbType.VarChar) }; parmss[0].Value = sensorintdeviceID; parmss[1].Value = sensorloginTime; parmss[2].Value = sensorStatus; try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { //add 3-19,根据龚的要求,新上线设备后,要一起添加id号到命令表 strSQL = " insert into tcommand (deviceID) values" + "(?sensorintdeviceID);"; parmss = new MySqlParameter[] { new MySqlParameter("?sensorintdeviceID", MySqlDbType.VarChar) }; parmss[0].Value = sensorintdeviceID; IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess == false) { return("fail"); } return("ok"); } else { return("fail"); } } catch (Exception ex) { return("fail"); //数据库异常 } } else //若ID存在,就更新update { DataSet ds = new DataSet("dssensorinfo"); string strResult = ""; MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; strSQL = "Update tdevice SET lastLoginTime=?sensorloginTime, status=?sensorStatus WHERE deviceID=?sensorintdeviceID"; parmss = new MySqlParameter[] { new MySqlParameter("?sensorintdeviceID", MySqlDbType.VarChar), new MySqlParameter("?sensorloginTime", MySqlDbType.VarChar), new MySqlParameter("?sensorStatus", MySqlDbType.VarChar) }; parmss[0].Value = sensorintdeviceID; parmss[1].Value = sensorloginTime; parmss[2].Value = sensorStatus; try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); //数据库异常 } } }
//创建历史记录子表 public static string creatHistoryChildtable(string sensorintdeviceID) { MySQLDB.InitDb(); string sensorid = "0"; //从数据库中查找当前ID是否存在 try { DataSet ds1 = new DataSet("thistory"); string strSQL1 = " SELECT deviceID FROM thistory WHERE deviceID=" + "\"" + sensorintdeviceID + "\""; ds1 = MySQLDB.SelectDataSet(strSQL1, null); if (ds1 != null) { if (ds1.Tables[0].Rows.Count > 0) // 有数据集 { sensorid = ds1.Tables[0].Rows[0][0].ToString(); } } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); //数据库异常 } //************************************************************ if (sensorid == "0") //若不存在,则添加,创建子表并新增数据 { //DataSet ds = new DataSet("dssensorad"); //string strResult = ""; MySqlParameter[] parmss = null; string strSQL = ""; //string strSQL2 = ""; bool IsDelSuccess = false; //先在母表中插入ID和字表名 string childName = "thistorychild" + sensorintdeviceID; strSQL = "insert into thistory (deviceID, ChildTable) values (?sensorintdeviceID , ?sensorChildTable);"; parmss = new MySqlParameter[] { new MySqlParameter("?sensorintdeviceID", MySqlDbType.VarChar), new MySqlParameter("?sensorChildTable", MySqlDbType.VarChar) }; parmss[0].Value = sensorintdeviceID; parmss[1].Value = childName; try { IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { creatNewTable(childName); //创建子表 return("ok"); } else { return("fail"); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); } } else { return("ok"); } }
//读取数据库命令线程 public void CheckDataBaseQueue(object state) { //add 3-17 粗心掉了一句 checkDataBaseQueueResetEvent.Reset(); //Reset()将事件状态设置为非终止状态,导致线程阻止。 while (IsServerOpen) { try { /*1.先读取tcommand表中所有deviceID的cmdName字段 * 2.“-1”表示无命令,其余值表示命令名称“name” * 3.根据name来读取对应ID的operation和data * 4.构造命令 * 5.把命令加入发送队列 * 6.如果是升级文件的路径,则需要读取文件内容并存入dataitem,设置标志位 * 7.如果是设置卡号,需要在dataitem设置大数组,加标志位并分多包发送。 * */ /* * ret[i, 0] = ds1.Tables[0].Rows[i]["deviceID"].ToString(); * ret[i, 1] = ds1.Tables[0].Rows[i]["cmdName"].ToString(); * ret[i, 2] = ds1.Tables[0].Rows[i]["operation"].ToString(); * ret[i, 3] = ds1.Tables[0].Rows[i]["data"].ToString(); */ string[,] cmdStrings = DbClass.readCmd(); if (cmdStrings != null)//先判定是否为空 { //add 3-14,强制处理一次数据,缩减时间,避免等待 byte[] Cmd = new byte[13]; Cmd[0] = 0xA5; Cmd[1] = 0xA5; Cmd[2] = 0x00; Cmd[3] = 0x00; Cmd[4] = 0x00; Cmd[5] = 0x00; Cmd[6] = 0x00; Cmd[7] = 0x00; Cmd[8] = 0x00; Cmd[9] = 0x00; Cmd[10 + 0] = 0xFF; Cmd[10 + 1] = 0x5A; Cmd[10 + 2] = 0x5A; for (int i = 0; i < cmdStrings.Length / 4; i++) { if (htClient.ContainsKey(cmdStrings[i, 0])) { DataItem dataItem = (DataItem)htClient[cmdStrings[i, 0]]; //有一些指令需要多包发送和读取 if (cmdStrings[i, 1] == "history") { //先清空表的记录,再采集新纪录 DbClass.deleteHistory(dataItem.strID); dataItem.tHistory.IsNeedHistory = true; //add 3-14,强制处理一次数据,缩减时间,避免等待 dataItem.recDataQueue.Enqueue(Cmd); //Enqueue 将对象添加到 Queue<T> 的结尾处 } else if (cmdStrings[i, 1] == "update") { using (FileStream fsSource = new FileStream(cmdStrings[i, 3], FileMode.Open, FileAccess.Read)) { // Read the source file into a byte array. for (int j = 0; j < updateDataLength; j++) //先用0xFF填充 { dataItem.updateData[j] = 0xFF; } int numBytesToRead = (int)fsSource.Length; if (numBytesToRead > 0) { // Read may return anything from 0 to numBytesToRead. fsSource.Read(dataItem.updateData, 0, numBytesToRead); } } //设置升级属性 dataItem.tUpdate.IsNeedUpdate = true; } else if (cmdStrings[i, 1] == "generalCardID") { if (cmdStrings[i, 2] == "write") { dataItem.tGeneralCardId.rw = 1; dataItem.generalCardID = UtilClass.hexStrToByte(cmdStrings[i, 3]); dataItem.tGeneralCardId.IsNeedSet = true; } else if (cmdStrings[i, 2] == "read") { dataItem.tGeneralCardId.rw = 0; dataItem.tGeneralCardId.IsNeedSet = true; } //add 3-14,强制处理一次数据,缩减时间,避免等待 dataItem.recDataQueue.Enqueue(Cmd); //Enqueue 将对象添加到 Queue<T> 的结尾处 } else if (cmdStrings[i, 1] == "fingerID") { if (cmdStrings[i, 2] == "write") { dataItem.tFingerId.rw = 1; dataItem.fingerID = UtilClass.hexStrToByte(cmdStrings[i, 3]); dataItem.tFingerId.IsNeedSet = true; } else if (cmdStrings[i, 2] == "read") { dataItem.tFingerId.rw = 0; dataItem.tFingerId.IsNeedSet = true; } } else//普通指令可以直接构造并发送 { byte[] cmd = CmdClass.makeCommand(cmdStrings[i, 1], cmdStrings[i, 2], cmdStrings[i, 3], dataItem.byteID); if (cmd != null) { dataItem.sendDataQueue.Enqueue(cmd); } } } }//end of for } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); } Thread.Sleep(checkDataBaseQueueTimeInterval); } checkDataBaseQueueResetEvent.Set(); }
public void Paused() { UtilClass.writeLog("已暂停"); }
public void Shutdown() { UtilClass.writeLog("已卸载"); }
public static string addOneHistory(string cardID, string sensorDate, string sensorTime, string[] timeTable, string[] typeTable) { #region 变量 //预设时间点 timeTable = new string[4]; timeTable[0] = "08:00:00"; timeTable[1] = "08:15:00"; timeTable[2] = "17:15:00"; timeTable[3] = "17:30:00"; typeTable = new string[5]; typeTable[0] = "上班"; typeTable[1] = "迟到"; typeTable[2] = "旷工"; typeTable[3] = "早退"; typeTable[4] = "下班"; string type = ""; MySQLDB.InitDb(); string sensorid = "0"; string strResult = ""; MySqlParameter[] parmss = null; string strSQL = ""; bool IsDelSuccess = false; #endregion //从数据库中查找当前ID是否存在 try { DataSet ds1 = new DataSet("historyrecord"); if (sensorTime.CompareTo("12:00:00") <= 0) { strSQL = "SELECT date_time FROM historyrecord where (card_id=" + "\"" + cardID + "\" AND data_date=" + sensorDate + ")"; ds1 = MySQLDB.SelectDataSet(strSQL, null); if (ds1 != null) // 有数据集 { if (ds1.Tables[0].Rows.Count == 0) //判断数据库有没有数据,小于就直接插入,有就不管,肯定小于当前时间 { if (sensorTime.CompareTo(timeTable[0]) < 0) { type = typeTable[0]; } else if (sensorTime.CompareTo(timeTable[0]) > 0 && sensorTime.CompareTo(timeTable[1]) < 0) { type = typeTable[1]; } else if (sensorTime.CompareTo(timeTable[1]) > 0 && sensorTime.CompareTo(timeTable[2]) < 0) { type = typeTable[2]; } strSQL = " insert into historyrecord (card_id, data_date, date_time, type) values" + "(?cardID,?sensorDate,?sensorTime,?type);"; parmss = new MySqlParameter[] { new MySqlParameter("?cardID", MySqlDbType.VarChar), new MySqlParameter("?sensorDate", MySqlDbType.VarChar), new MySqlParameter("?sensorTime", MySqlDbType.VarChar), new MySqlParameter("?type", MySqlDbType.VarChar) }; parmss[0].Value = cardID; parmss[1].Value = sensorDate; parmss[2].Value = sensorTime; parmss[3].Value = type; IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } } //end if if (ds1 != null) } else //大于12点 { strSQL = "SELECT id FROM historyrecord where (card_id=" + "\"" + cardID + "\"" + "AND data_date=" + "\"" + sensorDate + "\"" + " AND date_time>'12:00:00'" + ") "; ds1 = MySQLDB.SelectDataSet(strSQL, null); if (ds1 != null) // 有数据集 { if (ds1.Tables[0].Rows.Count == 0) //判断数据库有没有数据,小于就直接插入,有就要更新 { if (sensorTime.CompareTo(timeTable[1]) > 0 && sensorTime.CompareTo(timeTable[2]) < 0) { type = typeTable[2]; } else if (sensorTime.CompareTo(timeTable[2]) > 0 && sensorTime.CompareTo(timeTable[3]) < 0) { type = typeTable[3]; } else if (sensorTime.CompareTo(timeTable[3]) > 0) { type = typeTable[4]; } strSQL = " insert into historyrecord (card_id, data_date, date_time, type) values" + "(?cardID,?sensorDate,?sensorTime,?type);"; parmss = new MySqlParameter[] { new MySqlParameter("?cardID", MySqlDbType.VarChar), new MySqlParameter("?sensorDate", MySqlDbType.VarChar), new MySqlParameter("?sensorTime", MySqlDbType.VarChar), new MySqlParameter("?type", MySqlDbType.VarChar) }; parmss[0].Value = cardID; parmss[1].Value = sensorDate; parmss[2].Value = sensorTime; parmss[3].Value = type; IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } else//进行更新操作 { if (sensorTime.CompareTo(timeTable[1]) > 0 && sensorTime.CompareTo(timeTable[2]) < 0) { type = typeTable[2]; } else if (sensorTime.CompareTo(timeTable[2]) > 0 && sensorTime.CompareTo(timeTable[3]) < 0) { type = typeTable[3]; } else if (sensorTime.CompareTo(timeTable[3]) > 0) { type = typeTable[4]; } strSQL = " update historyrecord SET date_time=?sensorTime, type=?type WHERE (card_id=" + "\"" + cardID + "\" AND data_date=" + "\"" + sensorDate + "\"" + ")"; parmss = new MySqlParameter[] { new MySqlParameter("?cardID", MySqlDbType.VarChar), new MySqlParameter("?sensorDate", MySqlDbType.VarChar), new MySqlParameter("?sensorTime", MySqlDbType.VarChar), new MySqlParameter("?type", MySqlDbType.VarChar) }; parmss[0].Value = cardID; parmss[1].Value = sensorDate; parmss[2].Value = sensorTime; parmss[3].Value = type; IsDelSuccess = MySQLDB.ExecuteNonQry(strSQL, parmss); if (IsDelSuccess != false) { return("ok"); } else { return("fail"); } } } //end if if (ds1 != null) } return("fail"); } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); return("fail"); //数据库异常 } }
//处理数据和写入数据库 public void AnalyzeData(byte[] datagramBytes) { try { switch (datagramBytes[2]) { #region 心跳包和刷卡记录 //心跳包(也用于搜索设备) case 0x00: status = true; HeartTime = DateTime.Now; DbClass.UpdateSensorInfo(strID, "lastLoginTime", HeartTime.ToString("yyyy-MM-dd HH:mm:ss")); DbClass.UpdateSensorInfo(strID, "status", status.ToString()); break; //刷卡记录 case 0x23: if (tHistory.IsNeedHistory == true) { if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); break; } tHistory.currentNum++; //当前读取包数加1 //写入数据库,历史记录的包太多,除以8,避免超出byte范围 if (tHistory.currentNum % 8 == 0) { DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[tHistory.currentNum / 8]); } if (tHistory.currentNum == maxHistoryPackage) //读到尾部了 { tHistory.IsNeedHistory = false; tHistory.currentNum = 0; } //解析数据 string[,] dadaStrings = new string[1024, 3]; int dataNum = 0; for (int i = 0; i < 1024; i += 8) { if (datagramBytes[10 + i + 3] != 0xFF) //年份不可能为0xFF,否则是没有数据 { //卡号 dadaStrings[dataNum, 0] = UtilClass.hex2String[datagramBytes[10 + i]] + UtilClass.hex2String[datagramBytes[10 + i + 1]] + UtilClass.hex2String[datagramBytes[10 + i + 2]]; //时间 /*dadaStrings[dataNum, 1] = UtilClass.hex2String[datagramBytes[10 + i + 3]] + //年 * UtilClass.hex2String * [datagramBytes[10 + i + 4] & 0x0F] + //低四位表示月 * UtilClass.hex2String[datagramBytes[10 + i + 5]] + //日 * UtilClass.hex2String[datagramBytes[10 + i + 6]] + //时 * UtilClass.hex2String[datagramBytes[10 + i + 7]]; //分*/ DateTime dt = new DateTime(datagramBytes[10 + i + 3] + 2000, datagramBytes[10 + i + 4] & 0x0F, datagramBytes[10 + i + 5], datagramBytes[10 + i + 6], datagramBytes[10 + i + 7], 0, 0); dadaStrings[dataNum, 1] = dt.ToString("yyyy-MM-dd HH:mm:ss"); //门号, 高四位表示门号 if ((datagramBytes[10 + i + 4] >> 4) == 0x00) { dadaStrings[dataNum, 2] = "A"; } else if ((datagramBytes[10 + i + 4] >> 4) == 0x01) { dadaStrings[dataNum, 2] = "B"; } dataNum++; //有效记录数 //写入数据库 DbClass.insertHistory(strID, dadaStrings, dataNum); DbClass.UpdateCmd(strID, "cmdName", "ok"); } else //停止读取,复位结构体成员 { tHistory.IsNeedHistory = false; tHistory.currentNum = 0; //跳出for循环 break; } } //end of for } break; #endregion #region 设备升级相关命令 //升级 case 0x1E: if (tUpdate.IsNeedUpdate == true) { if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[tUpdate.currentNum]); tUpdate.currentNum++; } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } //最多256个包(256K) if (tUpdate.currentNum == 256) { tUpdate.IsNeedUpdate = false; tUpdate.currentNum = 0; //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } } break; //重启(并升级) case 0x21: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } break; //读取版本号 case 0x24: //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); break; #endregion #region 开关门时长,本地ip和时间 //DS1302时间 case 0x02: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]] + UtilClass.hex2String[datagramBytes[13]] + UtilClass.hex2String[datagramBytes[14]]); DbClass.UpdateCmd(strID, "cmdName", "ok"); //命令执行成功 } break; //local ip case 0x03: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]] + UtilClass.hex2String[datagramBytes[13]]); DbClass.UpdateCmd(strID, "cmdName", "ok"); //命令执行成功 } break; //开门时长(取值为1-255,不能为0) case 0x07: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); DbClass.UpdateCmd(strID, "cmdName", "ok"); //命令执行成功 } break; //关门时长,若为0,表示不检测反馈 case 0x08: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; #endregion #region 关系命令 //读头A关系 case 0x09: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //读头B关系 case 0x0A: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //按键A关系 case 0x0B: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //按键B关系 case 0x0C: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; #endregion #region 8个开门方式的配置开关,0-关,1-开,互锁、首卡、多重卡不能同时开启 //互锁 case 0x0D: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //首卡 case 0x0E: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //多重卡 case 0x0F: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //超级卡 case 0x10: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //超级密码 case 0x11: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //胁迫卡 case 0x12: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //胁迫码 case 0x13: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; //指纹模块 case 0x14: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]]); } break; #endregion #region 多种开门方式的卡号配置 //首卡 case 0x15: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]]); } break; //超级卡 case 0x16: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]]); } break; //超级密码 case 0x17: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]]); } break; //胁迫卡,3张 case 0x18: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]] + UtilClass.hex2String[datagramBytes[13]] + UtilClass.hex2String[datagramBytes[14]] + UtilClass.hex2String[datagramBytes[15]] + UtilClass.hex2String[datagramBytes[16]] + UtilClass.hex2String[datagramBytes[17]] + UtilClass.hex2String[datagramBytes[18]]); } break; //胁迫码 case 0x19: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]]); } break; //按键密码 case 0x1A: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]]); } break; //多重卡,10张 case 0x1B: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } else if (datagramBytes[7] == 0x00) { byte[] tenCard = new byte[30]; Array.Copy(datagramBytes, 10, tenCard, 0, 30); //写入数据库 DbClass.UpdateCmd(strID, "data", UtilClass.byteToHexStr(tenCard)); } break; #endregion #region 普通卡和指纹的配置 case 0x1D: //普通卡,第9个字节表示第几包 if (tGeneralCardId.IsNeedSet == true) { if (datagramBytes[7] == 0x00) { Array.Copy(datagramBytes, 10, generalCardID, tGeneralCardId.currentNum * 300, 300); tGeneralCardId.currentNum++; } if (datagramBytes[10] == 0x55) { tGeneralCardId.currentNum++; } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } //最多5个包(1500字节,500个卡号) if (tGeneralCardId.currentNum == 5) { tGeneralCardId.IsNeedSet = false; tGeneralCardId.currentNum = 0; //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); if (tGeneralCardId.rw == 0) { DbClass.UpdateCmd(strID, "data", UtilClass.byteToHexStr(generalCardID)); } } } break; case 0x1C: //指纹号,第9个字节表示第几包 if (tFingerId.IsNeedSet == true) { if (datagramBytes[7] == 0x00) { Array.Copy(datagramBytes, 10, fingerID, tFingerId.currentNum * 300, 300); tFingerId.currentNum++; } if (datagramBytes[10] == 0x55) { tFingerId.currentNum++; } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } //最多5个包(1500字节,500个卡号) if (tFingerId.currentNum == 5) { tFingerId.IsNeedSet = false; tFingerId.currentNum = 0; //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); if (tFingerId.rw == 0) { DbClass.UpdateCmd(strID, "data", UtilClass.byteToHexStr(fingerID)); } } } break; #endregion #region 重置参数、远程开门、报警消息、当前刷卡号 case 0x06: string door = "-1"; string cardID = UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]]; DbClass.UpdateSensorInfo(strID, "cardID_now", cardID); //门号, 高四位表示门号 if (datagramBytes[7] == 0x00) { door = "A"; } else if (datagramBytes[7] == 0x01) { door = "B"; } DbClass.UpdateSensorInfo(strID, "door_now", door); //add 4-10 根据龚的要求,添加数据到考勤表,并做判断 DbClass.addOneHistory(cardID, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("HH:mm:ss"), null, null); break; case 0x22: DbClass.UpdateSensorInfo(strID, "cardID_now", UtilClass.hex2String[datagramBytes[10]] + UtilClass.hex2String[datagramBytes[11]] + UtilClass.hex2String[datagramBytes[12]]); DbClass.UpdateSensorInfo(strID, "door_now", "22"); break; case 0x1F: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } break; //远程开门,低a高b case 0x20: if (datagramBytes[10] == 0x55) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "ok"); } else if (datagramBytes[10] == 0xAA) { //写入数据库 DbClass.UpdateCmd(strID, "cmdName", "fail"); } break; #endregion default: break; } if (tHistory.IsNeedHistory == true) { SendCmd(SetHisCmd(tHistory.currentNum)); } if (tUpdate.IsNeedUpdate == true) { SendCmd(SetUpdateCmd(tUpdate.currentNum)); } if (tGeneralCardId.IsNeedSet == true) { SendCmd(SetGeneralCardID(tGeneralCardId.currentNum, tGeneralCardId.rw)); } if (tFingerId.IsNeedSet == true) { SendCmd(SetFingerID(tFingerId.currentNum, tFingerId.rw)); } } catch (Exception ex) { Console.WriteLine(ex); UtilClass.writeLog(ex.ToString()); } #if DEBUG UtilClass.writeLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "硬件" + strID + "收到数据:" + UtilClass.byteToHexStr(datagramBytes)); #endif }