public void Analysis(byte[] plcData, ushort length) { try { switch (this.Protocol) { case ProtocolType.ModbusRTU: { byte[] validData = plcData.Take(length).ToArray(); // 有效数据 if (!ModbusRTU.CheckData(validData, out string err)) { TraceManager.AppendDebug(this.ID + "数据异常:" + err); return; } if (validData.Length == 509) // 249 以前的版本 { AnalysisAllModRTU(validData); } else { AnalysisResponseForModRTU(validData); } } break; } } catch (Exception e) { TraceManager.AppendErrMsg(this.ID + "解析数据时出错:" + e.Message); } }
public static void Start() { if (IsRuning) { return; } queue = new BlockingCollection <GPRS_DATA_RECORD>(); task = new Task(() => { foreach (GPRS_DATA_RECORD item in queue.GetConsumingEnumerable()) { try { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); //开始监视代码运行时间 Excute(item); //停止监视 watch.Stop(); TimeSpan timespan = watch.Elapsed; //获取当前实例测量得出的总时间 // MessageBox.Show(string.Format("打开窗口代码执行时间:{0}(毫秒)", timespan.TotalMilliseconds.ToString())); //总毫秒数 // Excute(item); } catch (Exception e) { TraceManager.AppendErrMsg("DTU解析器出错:" + e.Message); } } }, TaskCreationOptions.LongRunning); task.Start(); IsRuning = true; }
public static void Stop() { if (!IsRuning) { return; } if (DTUResolver1.IsRuning) { DTUResolver1.Stop(); if (DTUResolver1.IsRuning) { TraceManager.AppendErrMsg("DTU解析器1关闭出错"); } } if (DTUResolver2.IsRuning) { DTUResolver2.Stop(); if (DTUResolver1.IsRuning) { TraceManager.AppendErrMsg("DTU解析器2关闭出错"); } } if (DTUResolver3.IsRuning) { DTUResolver3.Stop(); if (DTUResolver3.IsRuning) { TraceManager.AppendErrMsg("DTU解析器3关闭出错"); } } IsRuning = false; }
public static void Start() { if (IsRuning) { return; } ReadingFlag = true; task = new Task(() => { try { SpinWait spinWait = new SpinWait(); while (ReadingFlag) { ReadOnce(); spinWait.SpinOnce(); } } catch (Exception e) { TraceManager.AppendErrMsg("DTU读取工作者异常--" + e.Message); } }, TaskCreationOptions.LongRunning); task.Start(); IsRuning = true; }
public static void Stop() { if (!IsRuning) { return; } // 先完成添加 queue.CompleteAdding(); DateTime time1 = DateTime.Now; while (queue.Count > 0) { Thread.Sleep(1); // 最多等待10秒避免关不掉 if (DateTime.Now - time1 > TimeSpan.FromSeconds(10)) { TraceManager.AppendErrMsg("DTU解析器关闭超时丢弃了" + queue.Count.ToString() + "条任务"); break; } } while (queue.Count > 0) { // 等了十秒还没听,队列全部元素废弃 queue.Take(); } queue = null; Task.WaitAll(task); task.Dispose(); task = null; IsRuning = false; }
public static void Start(out string errMsg) { errMsg = ""; if (IsRuning) { return; } LoadConfig(); // 打开宏电官方库 HDDTUAPI.SetCustomIP(HDDTUAPI.inet_addr(ip)); HDDTUAPI.SetWorkMode(serverMode); //开发包函数,设置服务模式:2-消息,0-阻塞,1-非阻塞 HDDTUAPI.SelectProtocol((socketType == "TCP") ? 1 : 0); //开发包函数,设置服务类型:0-UDP,1-TCP StringBuilder mess = new StringBuilder(1000); if (HDDTUAPI.start_net_service(IntPtr.Zero, 0, port, mess) != 0) //开发包函数,非消息模式启动服务 { errMsg = mess.ToString().Trim(); Stop(); return; } // 宏电API的状态维护 StartMaintainHDAPI(); if (!IsRuningMaintainHDAPI) { TraceManager.AppendErrMsg("HDAPI维护服务启动失败" + errMsg); Stop(); return; } IsRuning = true; }
public static void Start() { if (IsRuning) { return; } LoadConfig(); // 数据库DTU缓存表状态清理 if (!MakeAllDTUOffline(out string errMsg)) { TraceManager.AppendErrMsg("DTU状态更新失败" + errMsg); Stop(); return; } // 启用DTU缓存队列 StartDTUCache(); if (!IsRuningMaintainDTUCache) { TraceManager.AppendErrMsg("DTU数据同步服务启动失败" + errMsg); Stop(); return; } // DTU 缓存器启动成功 IsRuning = true; }
public static void Stop() { // 宏电API的状态维护 if (IsRuningMaintainHDAPI) { StopMaintainHDAPI(); if (IsRuningMaintainHDAPI) { TraceManager.AppendErrMsg("HDAPI维护服务停止失败"); } } //宏电官方库 try { StringBuilder mess = new StringBuilder(1000); int socketShutFlag = HDDTUAPI.stop_net_service(mess); if (socketShutFlag != 0) { TraceManager.AppendErrMsg("DTU通信服务关闭失败:" + mess); } } catch { } IsRuning = false; }
private void SaveDataToDB() { //if ((DateTime.Now - Config.LastTime).TotalDays <= 1) // return; string sql = this.GetSavePointsSQL() + this.GetSaveAlarmsSQL(); if (string.IsNullOrEmpty(sql)) { TraceManager.AppendErrMsg(this.ID + "未查询到相关点表业务信息"); return; } DBUtil.ExecuteNonQuery(sql, out string err); string str = this.Name == null ? this.ID : this.Name + "--" + this.pumpAreaName; if (!string.IsNullOrEmpty(err)) { TraceManager.AppendErrMsg(str + "保存PLC数据到数据库失败"); } //else // TraceManager.AppendInfo(str + "--保存PLC数据到数据库成功"); //string err = ""; //DBUtil.ExecuteNonQuery(this.GetSavePointsSQL(), out err); //if (!string.IsNullOrEmpty(err)) // TraceManager.AppendErrMsg(this.ID + "保存PLC点表数据到数据库失败" + err); //DBUtil.ExecuteNonQuery(this.GetSaveSensorsSQL(), out err); //if (!string.IsNullOrEmpty(err)) // TraceManager.AppendErrMsg(this.ID + "保存PLC-SACDA数据到数据库失败" + err); //DBUtil.ExecuteNonQuery(this.GetSaveAlarmsSQL(), out err); //if (!string.IsNullOrEmpty(err)) // TraceManager.AppendErrMsg(this.ID + "保存PLC报警数据到数据库失败" + err); }
private void GetValue(byte[] plcData) { foreach (Point point in this.Points) { point.ReadValForModRTU(plcData); if (point.State == ValueState.Fail) { point.Value = 0; TraceManager.AppendErrMsg(this.ID + "下的" + point.PLCAddress + "解析出错:" + point.Mess); } } //foreach (Sensor sensor in this.Sensors) //{ // Point[] curPoints = this.Points.Where(p => p.ID == sensor.PointID).ToArray(); // if (curPoints == null || curPoints.Length != 1) // continue; // Point point = curPoints[0]; // sensor.Value = point.Value; // sensor.State = point.State; // sensor.Mess = point.Mess; // sensor.LastTime = point.LastTime; // sensor.FDate=Convert.ToDateTime(sensor.LastTime).ToString("yyyy-MM-dd"); ; //} }
// 解析所有 private void AnalysisAllModRTU(byte[] validData) { byte[] headBytes = validData.Take(7).ToArray(); if (ByteUtil.BytesToText(headBytes, headBytes.Length).Trim() != "02 10 00 00 00 78 F0") { return; } // PLC定时推送120个寄存器和数据长度240的数组 //减去前面7个字节数据描述,最后两个字节的CRC byte[] plcData = validData.Skip(7).Take(validData.Length - 9).ToArray(); ushort plcAddress = ByteUtil.GetUshortValue(plcData, 0); this.GetPumpAreaName(plcAddress); // 加载点表信息 if (!GetDBInfos(out string errMsg)) { TraceManager.AppendErrMsg("查询DTU挂接点表集合失败:" + errMsg); return; } // 解析加载点表值 GetValue(plcData); // 存储到数据库 SaveDataToDB(); // 清楚对象中点表等缓存,避免内存过大 this.CLearDBInfos(); }
public static void Start() { if (IsRuning) { return; } DTUResolver1.Start(); if (!DTUResolver1.IsRuning) { TraceManager.AppendErrMsg("DTU解析器1打开出错"); Stop(); return; } DTUResolver2.Start(); if (!DTUResolver2.IsRuning) { TraceManager.AppendErrMsg("DTU解析器2打开出错"); Stop(); return; } DTUResolver3.Start(); if (!DTUResolver3.IsRuning) { TraceManager.AppendErrMsg("DTU解析器3打开出错"); Stop(); return; } IsRuning = true; }
private static void StartDTUCache() { if (IsRuningMaintainDTUCache) { return; } dtusCache = new ConcurrentDictionary <string, DTUInfo>(); dtuCacheUpdateTimer = new System.Timers.Timer(); dtuCacheUpdateTimer.Interval = dtuListUpdateTime * 1000; dtuCacheUpdateTimer.Elapsed += (o, e) => { try { if (dtusCache == null) { return; } DBWorker.Append(DBCommand.CreateDtuCacheUpdate(GetDtuInfos())); } catch { TraceManager.AppendErrMsg("DTU缓存队列同步数据库失败"); } }; dtuCacheUpdateTimer.Enabled = true; IsRuningMaintainDTUCache = true; }
private void RegisterDTU(DTUInfo dtu) { string setOnlineSQL = string.Format(@" update DTUBase set [是否使用] ={0}, [是否在线] ={1}, [登录时间] = '{2}', [最后注册时间] ='{3}', [终端IP地址] ='{4}', [终端端口] ={5}, [网关IP地址] ='{6}', [网关端口] ={7} where [终端登录号码] = '{8}'", dtu.IsUsed, dtu.IsActive, dtu.ActiveTime, dtu.LastRegisterTime, dtu.TerminalIP, dtu.TerminalPort, dtu.GatewayIP, dtu.GatewayPort, dtu.ID); int rows = DBUtil.ExecuteNonQuery(setOnlineSQL, out string err); if (!string.IsNullOrEmpty(err)) { TraceManager.AppendErrMsg(dtu.ID + "数据链路同步到数据库失败"); return; } if (rows == 0) { TraceManager.AppendInfo(dtu.ID + "数据库没有该条链路信息"); return; } if (rows > 0) { string sqlQuery = string.Format(@"SELECT TOP 1 [ID] ,[名称] ,[描述] ,[DTU厂家] ,[DTU型号] ,[DTU工作方式] ,[通信协议] FROM DTUBase where 终端登录号码='{0}'; ", dtu.ID); DataTable dt = DBUtil.ExecuteDataTable(sqlQuery, out err); if (!string.IsNullOrEmpty(err)) { TraceManager.AppendErrMsg(dtu.ID + "数据库同步链路的业务信息失败"); return; } DataRow dr = dt.Rows[0];// 只查询一行,在条件里面可以不用担心出错 dtu.DBID = DataUtil.ToInt(dr["ID"]); dtu.Name = DataUtil.ToString(dr["名称"]); dtu.Description = DataUtil.ToString(dr["描述"]); dtu.FactoryName = DataUtil.ToString(dr["DTU厂家"]); dtu.Model = DataUtil.ToString(dr["DTU型号"]); dtu.WorkType = DataUtil.ToString(dr["DTU工作方式"]); dtu.Protocol = DTUInfo.GetProtocol(DataUtil.ToString(dr["通信协议"])); DTUCacheManager.OperDTUCache(DTUCacheManager.OPeratingType.Add, dtu, null); } }
//根据字节数据拿到请求对象 public static Request FromBytes(byte[] bytes) { try { switch (bytes[1]) { case 0x03: { Request request = new Request(); request.PlcAddress = bytes[0]; request.Type = RequestType.Read; request.RegisterBeginAddress = ByteUtil.ToUshort(bytes, 2); request.RegisterCount = ByteUtil.ToUshort(bytes, 4); request.CRC = BitConverter.ToUInt16(bytes, 6); // CRC 无需反转高低位 return(request); } case 0x06: { Request request = new Request(); request.PlcAddress = bytes[0]; request.Type = RequestType.Write; request.RegisterBeginAddress = ByteUtil.ToUshort(bytes, 2); request.RegisterValue = ByteUtil.ToUshort(bytes, 4); request.CRC = BitConverter.ToUInt16(bytes, 6); // CRC 无需反转高低位 return(request); } case 0x10: { Request request = new Request(); request.PlcAddress = bytes[0]; request.Type = RequestType.WriteMulti; request.RegisterBeginAddress = ByteUtil.ToUshort(bytes, 2); request.RegisterCount = ByteUtil.ToUshort(bytes, 4); request.DataLength = bytes[6]; request.Values = ByteUtil.ToUshorts(bytes, 7, request.DataLength); request.CRC = BitConverter.ToUInt16(bytes, bytes.Length - 2); // CRC 无需反转高低位 return(request); //写多指测试 // ModbusRTURequest r = ModbusRTURequest.FromBytes(new byte[] { 0x01, 0x10, 0x00, 0x01, 0x00, 0x02, 0x04, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00 }); } } } catch (Exception e) { TraceManager.AppendErrMsg("根据字节数组转modbus请求对象失败:" + e.Message); return(null); } return(null); }
private void DtuOffline(string dtuID) { string errMsg = ""; string updateSQL = string.Format(@"update DTUBase set [是否在线]=0 where 终端登录号码 ='{0}'", dtuID); int effectRows = DBUtil.ExecuteNonQuery(updateSQL, out errMsg); if (!string.IsNullOrEmpty(errMsg)) { TraceManager.AppendErrMsg("DTU下线执行出错" + errMsg); return; } //if (effectRows > 0) // TraceManager.AppendInfo(dtuID + "【下线】更新成功"); }
public static void Append(GPRS_DATA_RECORD data) { if (!IsRuning) { return; } if (queue.IsAddingCompleted) { return; } if (queue.Count > 4096) { TraceManager.AppendErrMsg("DTU数据解析队列到达上限无法插入"); return; } queue.Add(data); }
public static void Stop() { if (!IsRuning) { return; } DTUReader.Stop(); if (DTUReader.IsRuning) { TraceManager.AppendErrMsg("DTU读取器关闭失败"); } DTUResolverManager.Stop(); if (DTUResolverManager.IsRuning) { TraceManager.AppendErrMsg("DTU解析器关闭失败"); } IsRuning = false; }
public static void Stop() { if (!IsRuning) { return; } if (IsRuningMaintainDTUCache) { StopDTUCache(); if (IsRuningMaintainDTUCache) { TraceManager.AppendErrMsg("DTU数据同步服务停止失败"); } } if (!MakeAllDTUOffline(out string errMsg)) { TraceManager.AppendErrMsg("DTU状态更新失败" + errMsg); return; } IsRuning = false; }
public static void Start() { if (IsRuning) { return; } commandQueue = new BlockingCollection <DBCommand>(); task = new Task(() => { foreach (DBCommand command in commandQueue.GetConsumingEnumerable()) { try { command.Execute(); } catch (Exception e) { TraceManager.AppendErrMsg("数据库工作服务执行异常" + e.Message); } } }, TaskCreationOptions.LongRunning); task.Start(); IsRuning = true; }
public void Execute() { try { switch (Type) { case DBCommandType.DtuRegister: RegisterDTU(DTUInfo); break; case DBCommandType.DtuOffline: DtuOffline(DTUID); break; case DBCommandType.DtuListUpdate: DtuListUpdate(DtuList); break; } } catch (Exception e) { TraceManager.AppendErrMsg("工作队列执行出错:" + e.Message); } }
public static void Start() { if (IsRuning) { return; } //先打开解析器,再打开读取器 DTUResolverManager.Start(); if (!DTUResolverManager.IsRuning) { Stop(); TraceManager.AppendErrMsg("DTU解析器打开失败"); return; } DTUReader.Start(); if (!DTUReader.IsRuning) { Stop(); TraceManager.AppendErrMsg("DTU读取器打开失败"); return; } IsRuning = true; }
public void Start(out string errMsg) { errMsg = ""; if (IsRuning) { return; } try { TraceManager.Start(TriggerTrace); // 环境检查 if (!EnvChecker.Check(out errMsg)) { return; } TraceManager.AppendDebug("环境检查通过"); //数据库工作服务打开 if (DBWorker.IsRuning) { DBWorker.Stop(); } DBWorker.Start(); if (DBWorker.IsRuning) { TraceManager.AppendDebug("数据库工作器已经打开"); } else { errMsg = "数据库工作器打开失败"; TraceManager.AppendErrMsg(errMsg); Stop(); return; } // 打开DTU缓存管理器 if (DTUCacheManager.IsRuning) { DTUCacheManager.Stop(); } DTUCacheManager.Start(); if (DTUCacheManager.IsRuning) { TraceManager.AppendDebug("DTU缓存管理器已经打开"); } else { errMsg = "DTU缓存管理器打开失败"; TraceManager.AppendErrMsg(errMsg); Stop(); return; } // DTU通信器 if (HDDTUService.IsRuning) { HDDTUService.Stop(); } HDDTUService.Start(out string err); if (HDDTUService.IsRuning) { TraceManager.AppendDebug("DTU监听器已经打开"); } else { errMsg = "DTU控制器打开失败:" + err; TraceManager.AppendErrMsg(errMsg); Stop(); return; } // DTU控制器 if (DTUController.IsRuning) { DTUController.Stop(); } DTUController.Start(); if (DTUController.IsRuning) { TraceManager.AppendDebug("DTU控制器已经打开"); } else { errMsg = "DTU控制器打开失败"; TraceManager.AppendErrMsg(errMsg); Stop(); return; } // DTU监听器 if (DTUListener.IsRuning) { DTUListener.Stop(); } DTUListener.Start(); if (DTUListener.IsRuning) { TraceManager.AppendDebug("DTU监听器已经打开"); } else { errMsg = "DTU监听器打开失败"; TraceManager.AppendErrMsg(errMsg); Stop(); return; } } catch (Exception e) { errMsg = e.Message; Stop(); return; } IsRuning = true; }
// 增删改调度及事件触发 public static bool OperDTUCache(OPeratingType type, object target, DTUInfo souceDTU) { try { switch (type) { case OPeratingType.Add: { DTUInfo dtu = target as DTUInfo; Add(dtu); TriggerAdd(dtu); TraceManager.AppendInfo(dtu.ID + "上线"); return(true); } case OPeratingType.UpdateSocketInfo: { DTUInfo targetDTU = target as DTUInfo; UpdateSocketInfo(targetDTU, souceDTU); TriggerUpdateSocInfo(targetDTU); return(true); } case OPeratingType.UpdateBSInfoMulti: { DTUInfo[] dtus = target as DTUInfo[]; if (UpdateBSInfo(dtus)) { TriggerUpdateMulti(dtus); return(true); } else { TraceManager.AppendErrMsg("DTU缓存更新业务对象失败"); return(false); } } case OPeratingType.Delete: { string dtuID = target as String; if (RemoveDtuCache(dtuID)) { TriggerDelOne(dtuID); TraceManager.AppendInfo(dtuID + "下线"); return(true); } else { TraceManager.AppendErrMsg("DTU缓存移除对象失败"); return(false); } } default: return(false); } } catch (Exception e) { TraceManager.AppendErrMsg("DTU缓存字典操作出错:" + e.Message); return(false); } }
private void DtuListUpdate(DTUInfo[] dtuInfos) { if (dtuInfos == null || dtuInfos.Length == 0) { return; } string dtuIDs = "'第一个补个位'"; string setOnlineSQL = ""; foreach (DTUInfo dtu in dtuInfos) { if (dtu.IsActive == 1) { setOnlineSQL += string.Format(@" update DTUBase set [是否使用] ={0}, [是否在线] ={1}, [登录时间] = '{2}', [最后注册时间] ='{3}', [终端IP地址] ='{4}', [终端端口] ={5}, [网关IP地址] ='{6}', [网关端口] ={7} where [终端登录号码] = '{8}'", dtu.IsUsed, dtu.IsActive, dtu.ActiveTime, dtu.LastRegisterTime, dtu.TerminalIP, dtu.TerminalPort, dtu.GatewayIP, dtu.GatewayPort, dtu.ID); dtuIDs += "'" + dtu.ID + "'"; } } string setAllOfflineSQL = string.Format(@"UPDATE DTUBase SET 是否在线 =0;"); // 注意先复位先更新 DBUtil.ExecuteNonQuery(setOnlineSQL, out string errMsg); if (!string.IsNullOrEmpty(errMsg)) { TraceManager.AppendErrMsg("DTU列表更新到数据库失败:" + errMsg); return; } DataTable dt = new DataTable(); string querySQL = @"select * from DTUBase where 终端登录号码 in (" + dtuIDs + ");"; // string querySQL = @"select * from DTUBase;"; dt = DBUtil.ExecuteDataTable(querySQL, out errMsg); if (!string.IsNullOrEmpty(errMsg)) { TraceManager.AppendErrMsg("DTU列表从数据库加载时出错" + errMsg); return; } List <DTUInfo> dbDtus = new List <DTUInfo>(); foreach (DataRow dr in dt.Rows) { DTUInfo dtu = new DTUInfo(); dtu.DBID = DataUtil.ToInt(dr["ID"]); dtu.ID = DataUtil.ToString(dr["终端登录号码"]); dtu.Name = DataUtil.ToString(dr["名称"]); dtu.Description = DataUtil.ToString(dr["描述"]); dtu.FactoryName = DataUtil.ToString(dr["DTU厂家"]); dtu.Model = DataUtil.ToString(dr["DTU型号"]); dtu.WorkType = DataUtil.ToString(dr["DTU工作方式"]); dtu.Protocol = DTUInfo.GetProtocol(DataUtil.ToString(dr["通信协议"])); dtu.IsUsed = DataUtil.ToInt(dr["是否使用"]); dtu.IsActive = DataUtil.ToInt(dr["是否在线"]); dtu.ActiveTime = DataUtil.ToDateString(dr["登录时间"]); dtu.LastRegisterTime = DataUtil.ToDateString(dr["最后注册时间"]); dtu.TerminalIP = DataUtil.ToString(dr["终端IP地址"]); dtu.TerminalPort = DataUtil.ToInt(dr["终端端口"]); dtu.GatewayIP = DataUtil.ToString(dr["网关IP地址"]); dtu.GatewayPort = DataUtil.ToInt(dr["网关端口"]); dbDtus.Add(dtu); } // 同步到内存 if (dbDtus.Count > 0) { DTUCacheManager.OperDTUCache(DTUCacheManager.OPeratingType.UpdateBSInfoMulti, dbDtus.ToArray(), null); } }
public void Stop() { try { // DTU监听器 if (DTUListener.IsRuning) { DTUListener.Stop(); if (!DTUListener.IsRuning) { TraceManager.AppendDebug("DTU监听器已经关闭"); } else { TraceManager.AppendErrMsg("DTU监听器关闭失败"); } } // DTU控制器 if (DTUController.IsRuning) { DTUController.Stop(); if (!DTUController.IsRuning) { TraceManager.AppendDebug("DTU控制器已经关闭"); } else { TraceManager.AppendErrMsg("DTU控制器关闭失败"); } } // DTU通信器 if (HDDTUService.IsRuning) { HDDTUService.Stop(); if (!HDDTUService.IsRuning) { TraceManager.AppendDebug("DTU通信器已经关闭"); } else { TraceManager.AppendErrMsg("DTU控制器关闭失败"); } } // DTU缓存管理器 if (DTUCacheManager.IsRuning) { DTUCacheManager.Stop(); if (!DTUCacheManager.IsRuning) { TraceManager.AppendDebug("DTU缓存管理器已经关闭"); } else { TraceManager.AppendErrMsg("DTU缓存管理器关闭失败"); } } //数据库工作器 if (DBWorker.IsRuning) { DBWorker.Stop(); if (!DBWorker.IsRuning) { TraceManager.AppendDebug("数据库工作器已经关闭"); } else { TraceManager.AppendErrMsg("数据库工作器关闭失败"); } } // 日志管理器 if (TraceManager.IsRuning) { TraceManager.Stop(); } } catch { } IsRuning = false; }