/// <summary> /// 处理考勤数据 /// </summary> /// <param name="bytes"></param> private void handlerAttMsg(byte[] bytes) { try { LogMg.AddDebug("udp协议接收的考勤数据============= " + ToHexString(bytes)); int stationNo = 0; int pid = 0; int state = 0; DateTime date = DateTime.Now; parseDataAtt(bytes, ref stationNo, ref pid, ref state, ref date); //找出编号对应的站点 SWS_DB.guangdai_station_link link = V88StationLink.SingleOrDefault(c => Int32.Parse(c.wsid) == stationNo); if (link == null) { return; } SWSDataContext sws = new SWSDataContext(ConnectStringHelper.GetConnection(SysConfig.userProfile.DbAddress, link.db_name, SysConfig.userProfile.DbUserName, SysConfig.userProfile.DbPassword)); updateStationLine(sws, (int)link.station_id); users user = findUserByPid(sws, pid); if (user == null) { return; } country_attendance att = sws.country_attendance.Where(c => c.RFID == pid.ToString() && c.station_id == link.station_id && c.edate != null && DateTime.Now.AddHours(-1).CompareTo(c.edate) < 0).OrderByDescending(c => c.id).FirstOrDefault(); if (att == null) { att = new country_attendance(); if (user == null) { att.userid = 0; } else { att.userid = user.userid; } att.station_id = link.station_id; att.sdate = date; att.edate = date; att.type = "01"; att.remark = "V88设备的考勤数据"; att.RFID = pid.ToString(); sws.country_attendance.InsertOnSubmit(att); sws.SubmitChanges(); } else { att.edate = date; sws.SubmitChanges(); } } catch (Exception ex) { LogMg.AddError(ex); } }
public void Save(Socket socket, string json) { C_To_S_Data <object> obj = Utility.JsonHelper.JsonDeserialize <C_To_S_Data <object> >(json); Clazz.Config.XML_Org _org = SysConfig.orgConfig.GetOrgByOrgId(obj.OrgId); if (_org == null) { //将信息写入到日志文件中 orgid为***的污水厂不存在 LogMg.AddError("OrgId:\"{0}\"不存在"); //isSuccess = false; } else { try { SWSDataContext SWS = new SWSDataContext(ServerSocketHelper.GetConnection(_org.DBName)); //建立一个分厂数据源提供程序实例 country_station station = SWS.country_station.SingleOrDefault(c => c.id == obj.StationId); if (station == null) { LogMg.AddError("StationId: " + obj.StationId + " 不存在"); } else { station.ip = obj.Data[0].ToString(); //保存客户端IP地址 SWS.SubmitChanges(); } } catch (Exception ex) { LogMg.AddError(ex); } } }
/// <summary> /// 保存客户端的IP地址 /// </summary> /// <param name="socket"></param> /// <param name="c_to_s_data"></param> public void SaveClientIp(Socket socket, C_To_S_Data <CSDataStandard.Transfer.RealRec> c_to_s_data) { IPEndPoint ipEndPoint = (IPEndPoint)socket.RemoteEndPoint; string ip = ipEndPoint.Address.ToString(); Clazz.Config.XML_Org _org = SysConfig.orgConfig.GetOrgByOrgId(c_to_s_data.OrgId); if (_org == null) { //将信息写入到日志文件中 orgid为***的污水厂不存在 LogMg.AddError(String.Format("OrgId:{0} 不存在", c_to_s_data.OrgId)); //isSuccess = false; } else { try { SWSDataContext SWS = new SWSDataContext(ServerSocketHelper.GetConnection(_org.DBName)); //建立一个分厂数据源提供程序实例 country_station station = SWS.country_station.SingleOrDefault(c => c.id == c_to_s_data.StationId); if (station == null) { LogMg.AddError("StationId: " + c_to_s_data.StationId + " 不存在"); } else { station.ip = ip; //保存客户端IP地址 SWS.SubmitChanges(); } } catch (Exception ex) { LogMg.AddError(ex); } } }
/// <summary> /// 拍照方法 /// </summary> /// <param name="db">数据库对象</param> /// <param name="stationid">站点id</param> /// <param name="client">客户端</param> private static void takePhoto(SWSDataContext db, int stationid, Clazz.DTUClientInfo client) { ///根据站点id去指定的数据库中找拍照指令,如果存在拍照的指令,则调用【_485_JBT_Camera】类的拍照方法。 try { List <control_command> jbt_commands = db.control_command.Where(c => c.gong_kuang_id == 0 && c.state == 0 && c.tp == "3" && c.station_id == stationid).OrderBy(c => c.add_datetime).ToList(); foreach (control_command command in jbt_commands) { if (command.COUNT == null) { command.COUNT = 0; } try { bool flag = false; command.state = 1; //标志为已发送 byte[] imageBytes = new byte[1]; //takePhoto方法内部会再次分配图像数组大小 while (flag == false && command.COUNT < SysConfig.userProfile.ExecuteFailureCount) { flag = _485_JBT_Camera.TakePhoto(client, 5000, ref imageBytes); command.COUNT++; LogMg.AddDebug("拍照失败" + (int)command.COUNT + "次"); } if (flag == true) //如果拍照成功 { SavePicture(db, stationid, imageBytes); //保存照片到数据库 command.execute_result = 1; //标记为执行成功 command.execute_comment = "拍照成功"; } else { command.execute_result = 0; //标记为执行失败 command.execute_comment = "拍照失败"; } } catch (Exception ex) { LogMg.AddError(ex); command.execute_result = 0; command.execute_comment = "拍照失败"; } finally { command.complete_datetime = DateTime.Now; db.SubmitChanges(); } } } catch (Exception ex) { LogMg.AddError(ex); } }
private void Save(SWSDataContext db, realrec _realrec) { try { db.realrec.InsertOnSubmit(_realrec); db.SubmitChanges(); } catch (Exception ex) { LogMg.AddError(ex); } }
private void sendData(SWSDataContext db, Socket socket, string stationName, int stationId) { //发送设备控制信息到客户端 C_To_S_Data <CSDataStandard.Transfer.DeviceControl> sendObj = new C_To_S_Data <CSDataStandard.Transfer.DeviceControl>(); sendObj.Flag = HandleFlag.DeviceControl; sendObj.Data = new List <CSDataStandard.Transfer.DeviceControl>(); // List<device_control> listDeviceControl = db.device_control.Where(c => c.state == "0" && c.station_id == stationId).ToList(); //0表示未发送 //把那时不需要发送到客户端的记录的发送状态都置为2 db.ExecuteCommand("UPDATE dbo.device_control SET state=2 WHERE station_id=" + stationId + " AND state=0 AND id NOT IN (SELECT MAX(id) AS datetime FROM dbo.device_control WHERE station_id=" + stationId + " AND state=0 GROUP BY testid,gong_kuang_id)"); //找出需要发送的几行数据 List <device_control> listDeviceControl = db.ExecuteQuery <device_control>("SELECT * FROM dbo.device_control WHERE id IN (SELECT MAX(id) AS datetime FROM dbo.device_control WHERE station_id=" + stationId + " AND state=0 GROUP BY testid,gong_kuang_id)").ToList(); //device_control device_control = listDeviceControl.OrderByDescending(c => c.datetime).FirstOrDefault(); foreach (device_control device_control in listDeviceControl) { try { gong_kuang_config gongKuang = db.gong_kuang_config.SingleOrDefault(c => c.id == device_control.gong_kuang_id); CSDataStandard.Transfer.DeviceControl transferDeviceControl = new CSDataStandard.Transfer.DeviceControl(); transferDeviceControl.Value = device_control.control_code; //控制的值 transferDeviceControl.Address = (int)gongKuang.address; transferDeviceControl.Register = gongKuang.write_register; transferDeviceControl.DeviceControlId = device_control.id; //设备控制表的id //transferDeviceControl.DeviceNumber = device_control.device_number; //transferDeviceControl.Datetime = Convert.ToDateTime(device_control.datetime); //transferDeviceControl.ControlCode = device_control.control_code; sendObj.Data.Add(transferDeviceControl); } catch (Exception ex) { LogMg.AddError(ex); } } //更改设备控制表中的数据为已发送状态 foreach (device_control item in listDeviceControl) { item.state = "1"; } db.SubmitChanges(); //保存 //把对象转换为json字符串 string sendJson = Utility.JsonHelper.JsonSerializer <C_To_S_Data <CSDataStandard.Transfer.DeviceControl> >(sendObj); Byte[] msgSend = Encoding.Unicode.GetBytes(sendJson); socket.Send(msgSend, msgSend.Length, SocketFlags.None); //显示到UI界面 // string msg = string.Format("发送{0}行数据到【{1}】客户端", sendObj.Data.Count, stationName); // lb_msg.BeginInvoke(new Action<string>(printMsg), msg); }
public static void updateStationLine(SWSDataContext sws, int stationId) { try { test test = sws.test.SingleOrDefault(c => c.station_id == stationId && c.test_code == 22); test.value = "0"; sws.SubmitChanges(); } catch (Exception e) { LogMg.AddError(e); } }
/// <summary> /// 保存数据到数据库 /// </summary> /// <param name="testid"></param> /// <param name="value"></param> private static void SaveToDatabase(SWSDataContext db, int testid, double value) { LogMg.AddDebug(string.Format("testid={0} value={1}", testid, value)); // SWSDataContext db = new SWSDataContext(Util.ServerSocketHelper.GetConnection(dbname)); test test = db.test.SingleOrDefault(c => c.testid == testid); //查询出检测点 if (test != null) { if (test.means.Trim() == "屏幕取词" || test.means.Trim() == "自动获取") { realrec realrec = new realrec(); realrec.testid = testid; realrec.value = (decimal)value; realrec.testtime = DateTime.Now; realrec.remark = "from 201 Server AutoCollectionThread"; db.realrec.InsertOnSubmit(realrec); db.SubmitChanges(); //提交 } } }
/// <summary> /// 保存图片到数据库 /// </summary> /// <param name="db"></param> /// <param name="stationId"></param> /// <param name="imageBytes"></param> /// <returns></returns> private static bool SavePicture(SWSDataContext db, int stationId, byte[] imageBytes) { try { picture_info pic = new picture_info(); pic.station_id = stationId.ToString(); pic.title = "在线抓拍"; pic.contents = "在线抓拍"; pic.username = ""; pic.images = imageBytes; pic.updatetime = DateTime.Now; pic.source = "03"; pic.type = "01"; db.picture_info.InsertOnSubmit(pic); db.SubmitChanges(); return(true); } catch (Exception ex) { LogMg.AddError(ex); return(false); } }
/// <summary> /// 保存客户端发来的设备控制信息 ,把状态字段更新到数据库 /// </summary> /// <param name="db"></param> /// <param name="receiveObj"></param> private void saveData(SWSDataContext db, C_To_S_Data <CSDataStandard.Transfer.DeviceControl> receiveObj, string stationName) { try { //接收客户端数据 foreach (CSDataStandard.Transfer.DeviceControl item in receiveObj.Data) { device_control device_control = db.device_control.Where(c => c.id == item.DeviceControlId).SingleOrDefault(); if (device_control != null) { device_control.execute_result = item.ExecuteResult; } } db.SubmitChanges(); //输出消息 // string msg = string.Format("保存【{0}】客户端发送来的{1}行设备控制执行结果", stationName, receiveObj.Data.Count); // lb_msg.BeginInvoke(new Action<string>(printMsg), msg); } catch (Exception ex) { LogMg.AddError(ex); } }
/// <summary> /// 更新站点在线信息 /// </summary> /// <param name="db"></param> /// <param name="p"></param> public static void updateStationOnlineInfo(SWSDataContext db, int stationId) { try { country_station station = db.country_station.SingleOrDefault(c => c.id == stationId); if (station != null) { station_online_info online_info = db.station_online_info.SingleOrDefault(c => c.stationid == stationId); if (online_info != null) { online_info.name = station.name; online_info.register_time = DateTime.Now; online_info.last_visit_time = DateTime.Now; online_info.stationid = stationId; } else { online_info = new station_online_info(); online_info.name = station.name; online_info.register_time = DateTime.Now; online_info.last_visit_time = DateTime.Now; online_info.stationid = stationId; db.station_online_info.InsertOnSubmit(online_info); } List <station_online_info> deletes = db.station_online_info.Where(c => c.stationid == online_info.stationid && c.id != online_info.id).ToList(); if (deletes.Count > 0) { db.station_online_info.DeleteAllOnSubmit(deletes); } db.SubmitChanges(); } } catch (Exception ex) { LogMg.AddError("保存广岱客户端在线信息失败,\r\n" + ex.ToString()); } }
private static void TakePhotoTp5(SWSDataContext db, GuangDaiService.CorePlatformWebServiceClient ws, int stationId, string wscid) { // List<control_command> commands = db.control_command.Where(c => c.station_id == stationId && c.tp.Trim() == "5" && c.state == 0).ToList(); List <control_command> commands = db.ExecuteQuery <control_command>("SELECT * FROM dbo.control_command WHERE station_id=" + stationId + " AND state=0 AND tp='5'").ToList(); foreach (control_command command in commands) { if (command.COUNT == null) { command.COUNT = 0; } try { gong_kuang_config gongkuang = db.gong_kuang_config.SingleOrDefault(c => c.id == command.gong_kuang_id); if (gongkuang == null) //如果找不到command对应和gongkuangid,则把这条command标记为执行失败。 { LogMg.AddError("找不到控制命令所对应的工况配置信息"); command.execute_result = 0; //标记为执行失败 command.state = 1; // 就当已经执行过 command.execute_comment = "执行失败,找不到控制命令所对应的工况配置信息"; command.complete_datetime = DateTime.Now; db.SubmitChanges(); continue; } byte address = (byte)gongkuang.address; GuangDaiService.config config = ws.doConfig(wscid, Convert.ToInt32(gongkuang.write_register), (int)command.read_or_write, Convert.ToInt32(command.value), ""); LogMg.AddDebug(String.Format(" ws.doConfig({0},{1}, {2}, {3}, {4}) 返回结果是 result={5} value={6} message={7} ", wscid, gongkuang.write_register, command.read_or_write, "-1", "", config.result, config.value, config.message)); command.state = 1; //标志为已发送 if (config.result == true) { command.execute_result = 1; //标记为执行成功 command.execute_comment = "执行写操作成功"; gongkuang.write_value = command.value; gongkuang.execute_comment = "执行写操作成功"; } else { command.execute_result = 0; //标记为执行失败 command.execute_comment = "执行广岱拍照操作失败"; gongkuang.execute_comment = "执行广岱拍照操作失败"; } gongkuang.execute_datetime = DateTime.Now; command.complete_datetime = DateTime.Now; } catch (Exception ex) { command.execute_result = 0; //标记为执行失败 command.execute_comment = "执行广岱拍照操作失败,服务程序出现了异常"; // MessageQueue.Enqueue_DataInfo(string.Format("接收时间:【{0}】,站点:{1}, 执行工况配置失败.程序出现异常,请查看日志. ", DateTime.Now, station.name)); LogMg.AddError(ex); } finally { command.complete_datetime = DateTime.Now; } try { db.SubmitChanges(); } catch (Exception ex) { LogMg.AddError(ex.ToString()); } } }
/// <summary> /// 执行DTU控制任务 /// </summary> /// <param name="state"></param> private static void ExecuteDtuOrder(object state) { //1.锁住客户端对象 //2.找出客户端对应的数据库,并找出需要执行的控制指令。 //3.循环发送指令到客户端,再接收返回的数据,存入数据库。 //4.释放客户端对象 DTUClientInfo client = (DTUClientInfo)state; using (MyLock mylock = new MyLock(client, 20000, false)) { if (mylock.IsTimeout == false) { //LogManager.AddDebug("ControlCommandThread线程:" + Thread.CurrentThread.ManagedThreadId + " 开始锁了 是否超时" + mylock.IsTimeout); //找出这个站点对应的数据库, 并获取数据库连接 SqlConnection connection = GetDbConnectionByTel(client.TelOrGprsId); if (connection == null) //找不到对应的数据库连接 { LogMg.AddDebug(string.Format("根据Tel={0}的设备唯一id,在sysconfig.xml中找不到对应的数据库连接", client.TelOrGprsId.ToString())); return; } SWSDataContext db = new SWSDataContext(connection); takePhoto(db, client.StationId, client); //把那些不需要执行了的数据 state=1 就当这行指令已经执行过了 List <int> giveUpCommands = db.ExecuteQuery <int>("SELECT id FROM dbo.control_command WHERE station_id=" + client.StationId + " AND (state=0 OR state IS NULL) AND id NOT IN (SELECT MAX(id) FROM dbo.control_command WHERE station_id=" + client.StationId + " AND (state=0 OR state IS NULL) GROUP BY gong_kuang_id,read_or_write) ").ToList(); if (giveUpCommands.Count > 0) { db.ExecuteCommand("UPDATE dbo.control_command SET state=1 WHERE id in(" + string.Join(", ", giveUpCommands) + ")"); } //db.ExecuteCommand("UPDATE dbo.control_command SET state=1 WHERE station_id=" + client.StationId + " AND (state=0 OR state IS NULL) AND id NOT IN (SELECT MAX(id) FROM dbo.control_command WHERE station_id=" + client.StationId + " AND (state=0 OR state IS NULL) GROUP BY gong_kuang_id,read_or_write) "); //获取需要执行的指令 List <control_command> commands = db.ExecuteQuery <control_command>("SELECT * FROM dbo.control_command WHERE id IN(SELECT MAX(id) FROM dbo.control_command WHERE station_id=" + client.StationId + " AND communication_mode=2 AND (state=0 OR state IS NULL) GROUP BY gong_kuang_id,read_or_write) ORDER BY add_datetime").ToList(); List <gong_kuang_config> gongKuangs = db.gong_kuang_config.Where(c => c.station_id == client.StationId).ToList(); foreach (control_command command in commands) //循环发送指令 { if (command.COUNT == null) { command.COUNT = 0; } try { gong_kuang_config gongkuang = gongKuangs.SingleOrDefault(c => c.id == command.gong_kuang_id); if (gongkuang == null) //如果找不到command对应和gongkuangid,则把这条command标记为执行失败。 { LogMg.AddError("找不到控制命令所对应的工况配置信息"); command.execute_result = 0; //标记为执行失败 command.state = 1; // 就当已经执行过 command.execute_comment = "执行失败,找不到控制命令所对应的工况配置信息"; command.complete_datetime = DateTime.Now; db.SubmitChanges(); continue; } byte address = (byte)gongkuang.address; ClearSocketCache(client.socket);//清除缓冲区 LogMg.AddDebug("hashcode=" + client.socket.GetHashCode()); ModbusReturn modbusReturn = new ModbusReturn(); if (command.read_or_write == 0) //读读读读读读读读读读读 { while (modbusReturn.success == false && command.COUNT < SysConfig.userProfile.ExecuteFailureCount) { modbusReturn.clear(); modbus.readdata(client.Protocol, client.socket, "", address, ushort.Parse(gongkuang.read_register), int.Parse(gongkuang.function_code), gongkuang.data_type, gongkuang.decode_order, (int)gongkuang.receive_timeout, modbusReturn); //LogManager.AddDebug(String.Format("执行读命令 GPRSID:{0} gongkuangid:{1} address{2} 读寄存器编号:{3} 读取的值{4} 方法的返回bool值:{5}", client.TelOrGprsId, gongkuang.id, address, gongkuang.read_register, value.ToString(), flag)); command.COUNT++; } command.state = 1; //标志为已发送 if (modbusReturn.success == true) { DTU_ClientManager.UpdateLastVisitTime(client, DateTime.Now); command.execute_result = 1; //标记为执行成功 command.value = Convert.ToString(modbusReturn.value); gongkuang.read_value = Convert.ToString(modbusReturn.value); gongkuang.execute_comment = "执行读取操作成功"; if (gongkuang.config_type == "05") { try { test test = db.test.Single(c => c.testid == gongkuang.testid); test.value = Convert.ToString(modbusReturn.value * gongkuang.Multiple + gongkuang.AddNumber); } catch (Exception ex) { LogMg.AddError(ex); LogMg.AddDebug("找不到工况对应的检测点,gongkuangid=" + gongkuang.id + " testid=" + gongkuang.testid); } } } else { command.execute_result = 0; //标记为执行失败 gongkuang.execute_comment = "执行读取操作失败"; } command.execute_comment = modbusReturn.ToString(); } else //写写写写写写写写写写写写写写写 { while (modbusReturn.success == false && command.COUNT < SysConfig.userProfile.ExecuteFailureCount) { modbusReturn.clear(); modbus.writedata(client.Protocol, client.socket, "", address, ushort.Parse(gongkuang.write_register), gongkuang.data_type, (int)gongkuang.receive_timeout, short.Parse(command.value), modbusReturn); //LogManager.AddDebug(String.Format("执行写命令 GPRSID:{0} address{1} 写寄存器编号:{2} 写入的值{3} 方法的返回bool值:{4}", client.TelOrGprsId, address, gongkuang.write_register, command.value, flag)); command.COUNT++; } command.state = 1; //标志为已发送 if (modbusReturn.success == true) { DTU_ClientManager.UpdateLastVisitTime(client, DateTime.Now); command.execute_result = 1; //标记为执行成功 gongkuang.write_value = command.value; gongkuang.execute_comment = "执行写操作成功"; } else { command.execute_result = 0; //标记为执行失败 gongkuang.execute_comment = "执行写操作失败"; } command.execute_comment = modbusReturn.ToString(); } gongkuang.execute_datetime = DateTime.Now; command.complete_datetime = DateTime.Now; } catch (Exception ex) { command.execute_result = 0; //标记为执行失败 command.execute_comment = "执行命令失败,服务程序出现了异常"; // MessageQueue.Enqueue_DataInfo(string.Format("接收时间:【{0}】,站点:{1}, 执行工况配置失败.程序出现异常,请查看日志. ", DateTime.Now, station.name)); LogMg.AddError(ex); } finally { command.complete_datetime = DateTime.Now; } db.SubmitChanges(); } //LogManager.AddDebug("ControlCommandThread线程:" + Thread.CurrentThread.ManagedThreadId + " 释放锁了 "); } else { LogMg.AddDebug("ControlCommandThread 锁失败了"); } } }
private static void ExecuteGuangDai透传Order(object state) { try { Args arg = (Args)state; SWSDataContext db = new SWSDataContext(ConnectStringHelper.GetConnection(SysConfig.userProfile.DbAddress, arg.dbName, SysConfig.userProfile.DbUserName, SysConfig.userProfile.DbPassword)); GuangDaiService.CorePlatformWebServiceClient ws = new GuangDaiService.CorePlatformWebServiceClient(arg.gdServerCfg); SWS_DBDataContext SWS_DB = new SWS_DBDataContext(ConnectStringHelper.GetConnection(SysConfig.userProfile.DbAddress, SysConfig.userProfile.DbName, SysConfig.userProfile.DbUserName, SysConfig.userProfile.DbPassword)); List <guangdai_station_link> links = SWS_DB.guangdai_station_link.ToList(); String wscid = getWscId(arg, db, links); if (String.IsNullOrEmpty(wscid)) { LogMg.AddDebug("站点id=" + arg.station_id + " 找不到对应的wscId"); return; } //把那些不需要执行了的数据 state=1 就当这行指令已经执行过了 List <int> giveUpCommands = db.ExecuteQuery <int>("SELECT id FROM dbo.control_command WHERE station_id=" + arg.station_id + " AND (state=0 OR state IS NULL) AND id NOT IN (SELECT MAX(id) FROM dbo.control_command WHERE station_id=" + arg.station_id + " AND (state=0 OR state IS NULL) GROUP BY gong_kuang_id,read_or_write) ").ToList(); if (giveUpCommands.Count > 0) { db.ExecuteCommand("UPDATE dbo.control_command SET state=1 WHERE id in(" + string.Join(", ", giveUpCommands) + ")"); } //db.ExecuteCommand("UPDATE dbo.control_command SET state=1 WHERE station_id=" + arg.station_id + " AND (state=0 OR state IS NULL) AND id NOT IN (SELECT MAX(id) FROM dbo.control_command WHERE station_id=" + arg.station_id + " AND (state=0 OR state IS NULL) GROUP BY gong_kuang_id,read_or_write) "); //获取需要执行的指令 List <control_command> commands = db.ExecuteQuery <control_command>("SELECT * FROM dbo.control_command WHERE id IN(SELECT MAX(id) as id FROM dbo.control_command WHERE station_id=" + arg.station_id + " AND communication_mode in (5,6) AND tp is Null AND (state=0 OR state IS NULL) GROUP BY gong_kuang_id,read_or_write) ORDER BY add_datetime").ToList(); TakePhotoTp5(db, ws, arg.station_id, wscid); for (int i = 0; i < commands.Count; i++) { control_command command = commands[i]; if (command.COUNT == null) { command.COUNT = 0; } try { gong_kuang_config gongkuang = db.gong_kuang_config.SingleOrDefault(c => c.id == command.gong_kuang_id); if (gongkuang == null) //如果找不到command对应和gongkuangid,则把这条command标记为执行失败。 { LogMg.AddError("找不到控制命令所对应的工况配置信息"); command.execute_result = 0; //标记为执行失败 command.state = 1; // 就当已经执行过 command.execute_comment = "执行失败,找不到控制命令所对应的工况配置信息"; command.complete_datetime = DateTime.Now; db.SubmitChanges(); continue; } ModbusReturn modbusReturn = new ModbusReturn(); byte address = (byte)gongkuang.address; if (command.read_or_write == 0) //读读读读读读读读读读读 { GuangDaiCommunicationModbus.readdata(ws, wscid, address, ushort.Parse(gongkuang.read_register), int.Parse(gongkuang.function_code), gongkuang.data_type, gongkuang.decode_order, modbusReturn); command.state = 1; //标志为已发送 if (modbusReturn.success == true) { command.execute_result = 1; //标记为执行成功 command.value = Convert.ToString(modbusReturn.value); gongkuang.read_value = Convert.ToString(modbusReturn.value); gongkuang.execute_comment = "执行读取操作成功"; if (gongkuang.config_type == "05") { try { test test = db.test.Single(c => c.testid == gongkuang.testid); double multiple = gongkuang.Multiple == null ? 1 : (double)gongkuang.Multiple; double addNumber = gongkuang.AddNumber == null ? 0 : (double)gongkuang.AddNumber; test.value = Convert.ToString(modbusReturn.value * multiple + addNumber); } catch (Exception ex) { LogMg.AddError(ex); LogMg.AddDebug("找不到工况对应的检测点,gongkuangid=" + gongkuang.id + " testid=" + gongkuang.testid); } } } else { command.execute_result = 0; //标记为执行失败 gongkuang.execute_comment = "执行读取操作失败"; } command.execute_comment = modbusReturn.ToString(); } if (command.read_or_write == 1) //写写写写写写写写写写写写写写写 { GuangDaiCommunicationModbus.writedata(ws, wscid, address, ushort.Parse(gongkuang.read_register), int.Parse(gongkuang.function_code), gongkuang.data_type, gongkuang.decode_order, short.Parse(command.value), modbusReturn); // GuangDaiService.config config = ws.doConfig(wscid, Convert.ToInt32(gongkuang.write_register), (int)command.read_or_write, Convert.ToInt32(command.value), ""); // LogManager.AddDebug(String.Format("ws.transmitTransparently({0},{1}, {2}, {3}, {4}) 返回结果是 {5} ", wscid, gongkuang.write_register, command.read_or_write, "-1", "", flag)); command.state = 1; //标志为已发送 if (modbusReturn.success == true) { command.execute_result = 1; //标记为执行成功 gongkuang.write_value = command.value; gongkuang.execute_comment = "执行写操作成功"; } else { command.execute_result = 0; //标记为执行失败 gongkuang.execute_comment = "执行写操作失败"; } command.execute_comment = modbusReturn.ToString(); } gongkuang.execute_datetime = DateTime.Now; command.complete_datetime = DateTime.Now; } catch (Exception ex) { command.execute_result = 0; //标记为执行失败 command.execute_comment = "执行命令失败,服务程序出现了异常"; // MessageQueue.Enqueue_DataInfo(string.Format("接收时间:【{0}】,站点:{1}, 执行工况配置失败.程序出现异常,请查看日志. ", DateTime.Now, station.name)); LogMg.AddError(ex); } finally { command.complete_datetime = DateTime.Now; } try { db.SubmitChanges(); } catch (Exception ex) { LogMg.AddError(ex.ToString()); } } } catch (Exception ex) { Args arg = (Args)state; LogMg.AddError("异常数据库是:" + arg.dbName + " 站点id=" + arg.station_id); LogMg.AddError(ex); } }
private bool Save(string json, Socket RSocket) { bool isSuccess = true; string stationName = ""; //站点名称 C_To_S_Data <CSDataStandard.Transfer.RealRec> c_to_s_data = Utility.JsonHelper.JsonDeserialize <C_To_S_Data <CSDataStandard.Transfer.RealRec> >(json); Clazz.Config.XML_Org _org = SysConfig.orgConfig.GetOrgByOrgId(c_to_s_data.OrgId); if (_org == null) { //将信息写入到日志文件中 orgid为***的污水厂不存在 LogMg.AddError("OrgId:\"{0}\"不存在"); isSuccess = false; } else { try { SWSDataContext SWS = new SWSDataContext(Util.ServerSocketHelper.GetConnection(_org.DBName)); //建立一个分厂数据源提供程序实例 //查找站点名称 country_station _station = SWS.country_station.SingleOrDefault(c => c.id == c_to_s_data.StationId); if (_station != null) { stationName = _station.name; //站点名称 } //遍历数据 并把数据添加到数据库中 List <testrec> list = new List <testrec>(); List <test> listTest = new List <test>(); foreach (CSDataStandard.Transfer.RealRec item in c_to_s_data.Data) { //判断检测当前数据在数据库中是否已经存在 if (SWS.realrec.SingleOrDefault(c => c.testid == item.TestId && c.testtime == item.TestTime) == null) { testrec _testrec = new testrec(); _testrec.testid = item.TestId; _testrec.testtime = item.TestTime; _testrec.value = (decimal)item.Value; list.Add(_testrec); } //修改test表 SWS.ExecuteCommand(string.Format("update test set [value]={0} where testid={1}", item.Value, item.TestId)); } SWS.testrec.InsertAllOnSubmit(list); SWS.SubmitChanges(); isSuccess = true; } catch (Exception ex) { isSuccess = false; //把错误信息输出到日志文件中 LogMg.AddError(ex.ToString()); DEBUG.ThrowException(ex); } } lock (lb_msg) { if (lb_msg.Items.Count > 200) { lb_msg.Items.Clear(); } this.lb_msg.Items.Add(string.Format("时间:{0} 客户端:{1} 数据行数{2} 保存{3}", DateTime.Now.ToString(), stationName, c_to_s_data.Data.Count, isSuccess ? "成功" : "失败")); } return(isSuccess); }
private void handlerV88Msg(string data) { LogMg.AddDebug("udp协议接收的数据============= " + data); List <String> datas = CaiBao(data); DateTime date = DateTime.Now; List <Dictionary <string, string> > listDir = parseDataV88(datas, ref date); foreach (Dictionary <string, string> item in listDir) { try { //找出设备编号 String stationNo = getStationNo(item); if (String.IsNullOrEmpty(stationNo)) { continue; } //找出编号对应的站点 SWS_DB.guangdai_station_link link = V88StationLink.SingleOrDefault(c => c.wsid == stationNo); if (link == null) { continue; } SWSDataContext sws = new SWSDataContext(ConnectStringHelper.GetConnection(SysConfig.userProfile.DbAddress, link.db_name, SysConfig.userProfile.DbUserName, SysConfig.userProfile.DbPassword)); updateStationLine(sws, (int)link.station_id); foreach (string key in item.Keys) { //数据 KeyValuePair <string, string> data1 = item.Single(c => c.Key == key); try { KeyValuePair <string, int>?keyAndValue = getRegisterByKey(key); if (keyAndValue == null) { continue; } List <gong_kuang_config> gks = sws.gong_kuang_config.Where(c => c.station_id == link.station_id && c.read_register == ((KeyValuePair <string, int>)keyAndValue).Value.ToString()).ToList(); foreach (gong_kuang_config gk in gks) { if (gk == null || gk.testid == null || gk.testid == 0) { continue; } AutoCollectionThread.updateStationOnlineInfo(sws, (int)link.station_id); //保存数据 double multiple = gk.Multiple == null ? 1 : (double)gk.Multiple; double addNumber = gk.AddNumber == null ? 0 : (double)gk.AddNumber; String strValue = data1.Value; if (key.StartsWith("k") || key.StartsWith("K")) { if (strValue == "1") { strValue = "0"; } else { strValue = "1"; } } double value = Double.Parse(strValue) * multiple + addNumber; gk.read_value = value.ToString(); realrec rec = new realrec(); rec.testid = gk.testid; rec.value = (decimal)value; rec.testtime = date; rec.remark = "V88协议的设备数据"; sws.realrec.InsertOnSubmit(rec); } } catch (Exception ex) { LogMg.AddError(ex); } } sws.SubmitChanges(); } catch (Exception ex) { LogMg.AddError(ex); } } }
/// <summary> /// 将json字符串转换成对象, 再把对象保存到数据库中 /// </summary> /// <param name="json"></param> /// <returns></returns> private bool Save(string json, Socket socket) { bool isSuccess = true; string stationName = ""; //分厂名称 C_To_S_Data <CSDataStandard.Transfer.RealRec> c_to_s_data = Utility.JsonHelper.JsonDeserialize <C_To_S_Data <CSDataStandard.Transfer.RealRec> >(json); Clazz.Config.XML_Org _org = SysConfig.orgConfig.GetOrgByOrgId(c_to_s_data.OrgId); if (_org == null) { //将信息写入到日志文件中 orgid为***的污水厂不存在 LogMg.AddError(string.Format("OrgId:{0}不存在", c_to_s_data.OrgId)); isSuccess = false; } else { try { SWSDataContext SWS = new SWSDataContext(Util.ServerSocketHelper.GetConnection(_org.DBName)); //建立一个分厂数据源提供程序实例 //查找站点名称 country_station _station = SWS.country_station.SingleOrDefault(c => c.id == c_to_s_data.StationId); //更新站点的IP _station.ip = ((System.Net.IPEndPoint)socket.RemoteEndPoint).Address.ToString(); if (_station != null) { stationName = _station.name; //站点名称 } //遍历数据 并把数据添加到数据库中 List <realrec> listrealrec = new List <realrec>(); List <testrec> listtestrec = new List <testrec>(); foreach (CSDataStandard.Transfer.RealRec item in c_to_s_data.Data) { test test = SWS.test.SingleOrDefault(c => c.testid == item.TestId); if (test == null) { LogMg.AddError(string.Format("testid为 {0} 的检测点不存在", item.TestId)); //记录日志 isSuccess = false; } else { if (test.means.Trim() == "屏幕取词" || test.means.Trim() == "自动获取") { realrec _realrec = new realrec(); _realrec.testid = item.TestId; _realrec.testtime = item.TestTime; _realrec.value = (decimal)item.Value; listrealrec.Add(_realrec); } if (test.means.Trim() == "检测录入") { testrec _testrec = SWS.testrec.SingleOrDefault(c => c.testid == item.TestId && c.testtime == item.TestTime); //判断检测当前数据在数据库中是否已经存在 if (_testrec == null) { _testrec = new testrec(); _testrec.testid = item.TestId; _testrec.testtime = item.TestTime; _testrec.value = (decimal)item.Value; listtestrec.Add(_testrec); } else { _testrec.testid = item.TestId; _testrec.testtime = item.TestTime; _testrec.value = (decimal)item.Value; } } } } SWS.realrec.InsertAllOnSubmit(listrealrec); SWS.testrec.InsertAllOnSubmit(listtestrec); SWS.SubmitChanges(); isSuccess = true; } catch (Exception ex) { isSuccess = false; //把错误信息输出到日志文件中 LogMg.AddError(ex.ToString()); DEBUG.ThrowException(ex); } } //lock (lb_msg) //{ // if (lb_msg.Items.Count > 200) // lb_msg.Items.Clear(); // this.lb_msg.Items.Add(string.Format("时间:{0} 客户端:{1} 数据行数{2} 保存{3}", DateTime.Now.ToString(), stationName, c_to_s_data.Data.Count, isSuccess ? "成功" : "失败")); // } SaveClientIp(socket, c_to_s_data); return(isSuccess); }
/// <summary> /// 保存客户端的连接信息到数据库 /// </summary> private void SaveOnlineInfo() { while (true) { try { foreach (XML_Org org in SysConfig.orgConfig.Orgs) { try { SWSDataContext db = new SWSDataContext(Util.ServerSocketHelper.GetConnection(org.DBName)); //采用有屏版电控柜的客户端遍历 List <Clazz.Config.ClientConfig.XML_Station> list_station = SysConfig.clientConfig.AllStation.Where(c => c.OrgId == org.OrgId).ToList(); for (int i = 0; i < list_station.Count; i++) { ClientInfo client_info = ServerSocketHelper.ClientSockets.SingleOrDefault(c => c.TransferCode == list_station[i].TransferCode); if (client_info != null) { station_online_info online_info = db.station_online_info.SingleOrDefault(c => c.transfer_code == list_station[i].TransferCode); if (online_info != null) { online_info.name = client_info.Name; online_info.register_time = client_info.RegisterTime; online_info.last_visit_time = client_info.LastVisitTime; online_info.stationid = client_info.StationId; } else { online_info = new station_online_info(); online_info.transfer_code = client_info.TransferCode; online_info.name = client_info.Name; online_info.register_time = client_info.RegisterTime; online_info.last_visit_time = client_info.LastVisitTime; online_info.stationid = client_info.StationId; db.station_online_info.InsertOnSubmit(online_info); } List <station_online_info> deletes = db.station_online_info.Where(c => c.stationid == online_info.stationid && c.id != online_info.id).ToList(); if (deletes.Count > 0) { db.station_online_info.DeleteAllOnSubmit(deletes); } } } //采用DTU电控柜的客户端遍历 List <XML_Station> list_DTU_Station = SysConfig.DTU_StationConfig.Stations.Where(c => c.OrgId == org.OrgId).ToList(); for (int i = 0; i < list_DTU_Station.Count; i++) { DTUClientInfo DTU_clientinfo = DTU_ClientManager.Clients.SingleOrDefault(c => c.TelOrGprsId == list_DTU_Station[i].Tel); if (DTU_clientinfo != null) { station_online_info online_info = db.station_online_info.SingleOrDefault(c => c.dtu_tel == DTU_clientinfo.TelOrGprsId); if (online_info != null) { online_info.stationid = DTU_clientinfo.StationId; online_info.name = DTU_clientinfo.Name; online_info.register_time = DTU_clientinfo.RegisterTime; online_info.last_visit_time = DTU_clientinfo.LastVisitTime; } else { online_info = new station_online_info(); online_info.stationid = DTU_clientinfo.StationId; online_info.name = DTU_clientinfo.Name; online_info.register_time = DTU_clientinfo.RegisterTime; online_info.last_visit_time = DTU_clientinfo.LastVisitTime; online_info.dtu_tel = DTU_clientinfo.TelOrGprsId; db.station_online_info.InsertOnSubmit(online_info); } List <station_online_info> deletes = db.station_online_info.Where(c => c.stationid == online_info.stationid && c.id != online_info.id).ToList(); if (deletes.Count > 0) { db.station_online_info.DeleteAllOnSubmit(deletes); } } } db.SubmitChanges(); } catch (Exception ex) { LogMg.AddError("保存客户端在线数据时失败,\r\n" + ex.ToString()); } } } catch (Exception ex) { LogMg.AddError(ex); } Thread.Sleep(60000); } }