Пример #1
0
        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);
        }
Пример #2
0
        /// <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 锁失败了");
                }
            }
        }
Пример #3
0
        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);
            }
        }
Пример #4
0
        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);
        }
Пример #5
0
        /// <summary>
        /// 序列化json  并保存到数据库
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private bool Save(string json)
        {
            C_To_S_Data <CSDataStandard.Transfer.RealRec> c_to_s_data = Utility.JsonHelper.JsonDeserialize <C_To_S_Data <CSDataStandard.Transfer.RealRec> >(json);

            lb_msg.Items.Add(string.Format("污水厂编号:{0}    接收数据行数:{1}", c_to_s_data.OrgId, c_to_s_data.Data.Count));

            try
            {
                SWSDataContext SWS = new SWSDataContext(getConByOrgId(c_to_s_data.OrgId));
                //循环从客户端接收到的数据
                foreach (CSDataStandard.Transfer.RealRec item in c_to_s_data.Data)
                {
                    //根据testid找出test记录信息
                    test _test = SWS.test.SingleOrDefault(c => c.testid == item.TestId);
                    if (_test != null)
                    {
                        //把数据转换成数值型
                        double top1 = 0, top2 = 0, btm1 = 0, btm2 = 0;
                        try
                        {
                            top1 = Convert.ToDouble(_test.toplimit1);
                            top2 = Convert.ToDouble(_test.toplimit2);
                            btm1 = Convert.ToDouble(_test.btmlimit1);
                            btm2 = Convert.ToDouble(_test.btmlimit2);
                        }
                        catch (Exception ex)
                        {
                            LogMg.AddError(ex);
                            //throw ex;
                        }

                        char status = '1';
                        //拿检测到的值和 提示上限 提示下限 警报上限 警报下限做比较
                        if (item.Value >= btm1 && item.Value <= top1)
                        {
                            status = '1';
                        }
                        else if ((item.Value > top1 && item.Value < top2) || (item.Value > btm2 && item.Value < btm1))
                        {
                            status = '2';
                        }
                        else
                        {
                            status = '3';
                        }
                        //修改test表
                        SWS.ExecuteCommand(string.Format("update test set testtime='{0}' , [value]={1} , status='{2}' , means='{3}' where testid={4}", item.TestTime, item.Value, status, "屏幕取词", item.TestId));
                        //插入数据到realrec
                        SWS.ExecuteCommand(string.Format("insert into realrec (testid,testtime,[value],status) values({0},'{1}',{2},'{3}')", item.TestId, item.TestTime, item.Value, status));
                    }
                }
            }
            catch (Exception ex)
            {
                LogMg.AddError(ex);
                DEBUG.ThrowException(ex);
                return(false);
            }

            return(true);
        }