Exemple #1
0
        private static void 添加DTU控制任务(SWSDataContext db)
        {
            try
            {
                //查询出一个小时内有指令的站点的id
                //List<int> stations = db.ExecuteQuery<int>("SELECT station_id FROM dbo.control_command where (state=0 OR state IS NULL) and communication_mode=2  and datediff(mi,add_datetime,GETDATE())<60 group by station_id ").ToList();
                List <int> stations = db.ExecuteQuery <int>("SELECT station_id FROM dbo.control_command where (state=0 OR state IS NULL) and (communication_mode=2 or tp='3')    group by station_id ").ToList();
                if (stations.Count == 0)
                {
                    return;
                }
                ///站点id和transfer_code的键值对
                List <Station_transferCode> StaTrans = db.ExecuteQuery <Station_transferCode>("SELECT  id as stationId,transfer_code FROM  dbo.country_station WHERE  transfer_code IS NOT NULL AND transfer_code<>''  AND transfer_code<>'null'").ToList();
                //循环站点   将站点添加到线程池
                foreach (int stationid in stations)
                {
                    try
                    {
                        Station_transferCode StaTran = StaTrans.SingleOrDefault(c => c.stationId == stationid);
                        //如果这个站点没有配置dtu    就跳过
                        if (StaTran == null)
                        {
                            continue;
                        }
                        //根据设备唯一编号 找出 DTUClientInfo
                        DTUClientInfo client = DTU_ClientManager.Clients.SingleOrDefault(c => c.TelOrGprsId == StaTran.transfer_code);
                        if (client == null)
                        {
                            continue;
                        }

                        //如果客户端在【任务队列】和【线程里】里已经存在了,就不继续添加
                        if (!HasExistClientInPool(client))
                        {
                            PoolA.AddTaskItem(new WaitCallback(ExecuteDtuOrder), client);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogMg.AddError(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                LogMg.AddError(ex);
            }
        }
Exemple #2
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);
        }
Exemple #3
0
 private static void 添加广岱控制任务(SWSDataContext db, String dbname, String gdServerCfg)
 {
     try
     {
         //查询出一个小时内有指令的站点的id
         List <int> stations = db.ExecuteQuery <int>("SELECT station_id FROM dbo.control_command where (state=0 OR state IS NULL) and communication_mode=4  group by station_id ").ToList();// tp is not NULL 暂时有拍照的数据
         if (stations.Count == 0)
         {
             return;
         }
         //循环站点   将站点添加到线程池
         foreach (int stationid in stations)
         {
             try
             {
                 //如果站点在【任务队列】和【线程里】里已经存在了,就不继续添加
                 if (!HasExistClientInPool(stationid))
                 {
                     Args arg = new Args()
                     {
                         dbName = dbname, station_id = stationid, gdServerCfg = gdServerCfg
                     };
                     PoolA.AddTaskItem(new WaitCallback(ExecuteGuangDaiOrder), arg);
                 }
             }
             catch (Exception ex)
             {
                 LogMg.AddError(ex);
             }
         }
     }
     catch (Exception ex)
     {
         LogMg.AddError(ex);
     }
 }
Exemple #4
0
        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());
                }
            }
        }
Exemple #5
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 锁失败了");
                }
            }
        }
Exemple #6
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);
            }
        }
        /// <summary>
        /// 读取配置
        /// </summary>
        public bool GenerateConfig()
        {
            try
            {
                List <GD_Station>            gd_stations = new List <GD_Station>(); //从数据库中找出来的站点信息列表
                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();
                List <SWS_DB.org>            db_orgs     = SWS_DB.org.Where(c => c.org_type == 2 || c.org_type == 3).ToList();
                log.Info("=========================================================================");
                foreach (SWS_DB.org _org in db_orgs)
                {
                    try
                    {
                        log.Info("_org.dbname: " + _org.dbname + "   org.orgid: " + _org.orgid);
                        SWSDataContext         country_db = new SWSDataContext(ConnectStringHelper.GetConnection(SysConfig.userProfile.DbAddress, _org.dbname, SysConfig.userProfile.DbUserName, SysConfig.userProfile.DbPassword));
                        List <country_station> stations   = country_db.ExecuteQuery <country_station>("select id,name from country_station where deleteflag=0 and jiankongyitiji_version=5").ToList();
                        //List<country_station> stations = country_db.country_station.Where(c => c.deleteflag == false && c.jiankongyitiji_version == 5).ToList();
                        foreach (country_station item in stations)
                        {
                            log.Info("station.name: " + item.name + "   station.id: " + item.id);
                            GD_Station GD_station = new GD_Station();
                            GD_station.tests     = new List <XML_Test>();
                            GD_station.dbName    = _org.dbname;
                            GD_station.OrgId     = _org.orgid;
                            GD_station.name      = item.name;
                            GD_station.stationId = item.id;
                            try
                            {
                                guangdai_station_link link = links.Single(c => c.station_id == item.id && c.db_name == _org.dbname && c.type == 1);
                                GD_station.wscId  = link.wsid;
                                GD_station.Unique = link.id;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                            //找出站点的检测指标
                            List <test> tests             = country_db.test.Where(c => c.station_id == item.id && c.means.Contains("自动获取") && c.delete_flag == false).ToList();
                            List <gong_kuang_config> gkcs = country_db.gong_kuang_config.Where(c => c.testid != 0 && c.config_type != "03" && c.config_type != "04").ToList();

                            foreach (test _test in tests)
                            {
                                try
                                {
                                    List <gong_kuang_config> gkc = gkcs.Where(c => c.testid == _test.testid).ToList();  //这个一般只有一行   但配置的时候可能会出现两行,
                                    if (gkc.Count > 0)
                                    {
                                        XML_Test gd_test = new XML_Test();
                                        gd_test.StationUnique  = GD_station.Unique;
                                        gd_test.RegisterNo     = ushort.Parse(gkc[0].read_register);
                                        gd_test.TestId         = _test.testid;
                                        gd_test.Multiple       = gkc[0].Multiple == null ? 1 : (double)gkc[0].Multiple; //如果没填,则默认为0
                                        gd_test.FunctionCode   = int.Parse(gkc[0].function_code);
                                        gd_test.ReceiveTimeout = (int)gkc[0].receive_timeout;
                                        gd_test.DataType       = gkc[0].data_type;
                                        gd_test.Address        = byte.Parse(gkc[0].address.ToString());
                                        if (!string.IsNullOrEmpty(gkc[0].decode_order))
                                        {
                                            gd_test.DecodeOrder = gkc[0].decode_order;
                                        }
                                        gd_test.Min       = gkc[0].dmin == null ? 0 : (double)gkc[0].dmin;           //如果没填,则默认为0
                                        gd_test.Max       = gkc[0].dmax == null ? 4294967296 : (double)gkc[0].dmax;  //如果没填,则默认为0
                                        gd_test.AddNumber = gkc[0].AddNumber == null ? 0 : (double)gkc[0].AddNumber; //如果没填,则默认为0
                                        gd_test.备注        = _test.name;
                                        GD_station.tests.Add(gd_test);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogMg.AddError(ex);
                                }
                            }
                            //if (GD_station.stationId == 629)
                            gd_stations.Add(GD_station);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogMg.AddError(ex);
                    }
                }
                log.Info("-----------------------------");
                for (int i = 0; i < gd_stations.Count; i++)
                {
                    GD_Station item    = gd_stations[i];
                    String     testids = "";
                    if (item.tests != null)
                    {
                        foreach (XML_Test test in item.tests)
                        {
                            testids += test.TestId;
                        }
                    }

                    log.Info("orgId: " + item.OrgId + "  dbName: " + item.dbName + "   wscId: " + item.wscId + "  stationId: " + item.stationId + " station.name" + item.name + "   testids: " + testids);
                }
                this.GD_Stations = gd_stations;


                return(true);
            }
            catch (Exception ex)
            {
                LogMg.AddError(ex);
                return(false);
            }
        }
        public bool GenerateFromDbToXML()
        {
            List <Clazz.Config.XML_Station> XML_stations = new List <Clazz.Config.XML_Station>(); //从数据库中找出来的站点信息列表
            List <Clazz.Config.XML_Test>    XML_Tests    = new List <Clazz.Config.XML_Test>();    //从数据库中找出来的test信息
            SWS_DBDataContext SWS_DB  = new SWS_DBDataContext(ConnectStringHelper.GetConnection(SysConfig.userProfile.DbAddress, SysConfig.userProfile.DbName, SysConfig.userProfile.DbUserName, SysConfig.userProfile.DbPassword));
            List <SWS_DB.org> db_orgs = SWS_DB.org.Where(c => c.org_type == 2 || c.org_type == 3).ToList();

            foreach (SWS_DB.org _org in db_orgs)
            {
                SWSDataContext country_db = new SWSDataContext(ConnectStringHelper.GetConnection(SysConfig.userProfile.DbAddress, _org.dbname, SysConfig.userProfile.DbUserName, SysConfig.userProfile.DbPassword));
                try
                {
                    //List<country_station> db_stations = country_db.country_station.Where(c => c.transfer_code != "" && c.transfer_code != "NULL" && c.Protocol != "" && c.deleteflag == false).ToList();
                    List <country_station> db_stations = country_db.ExecuteQuery <country_station>("select * from country_station where transfer_code <> '' and transfer_code <> 'NULL' and Protocol <> '' and deleteflag=0").ToList();
                    List <syscode>         syscodes    = country_db.syscode.Where(c => c.type == "0060").ToList();
                    foreach (country_station station in db_stations)
                    {
                        try
                        {
                            //将站点信息添加到列表
                            Clazz.Config.XML_Station xml_sta = new Clazz.Config.XML_Station();
                            xml_sta.Unique    = XML_stations.Count;
                            xml_sta.StationId = station.id;
                            xml_sta.Name      = station.name;
                            xml_sta.OrgId     = _org.orgid.ToString();
                            xml_sta.Tel       = station.transfer_code;
                            xml_sta.Protocol  = syscodes.Single(c => c.code == station.Protocol).name;

                            XML_stations.Add(xml_sta);

                            //找出站点的检测指标
                            List <test> tests             = country_db.test.Where(c => c.station_id == station.id && c.means.Contains("自动获取") && c.delete_flag == false).ToList();
                            List <gong_kuang_config> gkcs = country_db.gong_kuang_config.Where(c => c.testid != 0 && c.config_type != "03" && c.config_type != "04").ToList();

                            foreach (test _test in tests)
                            {
                                try
                                {
                                    List <gong_kuang_config> gkc = gkcs.Where(c => c.testid == _test.testid).ToList();  //这个一般只有一行   但配置的时候可能会出现两行,
                                    if (gkc.Count > 0)
                                    {
                                        Clazz.Config.XML_Test xml_t = new Clazz.Config.XML_Test();
                                        xml_t.StationUnique  = xml_sta.Unique;
                                        xml_t.StationId      = xml_sta.StationId;
                                        xml_t.RegisterNo     = ushort.Parse(gkc[0].read_register);
                                        xml_t.TestId         = _test.testid;
                                        xml_t.Multiple       = gkc[0].Multiple == null ? 1 : (double)gkc[0].Multiple; //如果没填,则默认为0
                                        xml_t.FunctionCode   = int.Parse(gkc[0].function_code);
                                        xml_t.ReceiveTimeout = (int)gkc[0].receive_timeout;
                                        xml_t.DataType       = gkc[0].data_type;
                                        xml_t.Address        = byte.Parse(gkc[0].address.ToString());
                                        if (!string.IsNullOrEmpty(gkc[0].decode_order))
                                        {
                                            xml_t.DecodeOrder = gkc[0].decode_order;
                                        }
                                        xml_t.Min       = gkc[0].dmin == null ? 0 : (double)gkc[0].dmin;           //如果没填,则默认为0
                                        xml_t.Max       = gkc[0].dmax == null ? 4294967296 : (double)gkc[0].dmax;  //如果没填,则默认为0
                                        xml_t.AddNumber = gkc[0].AddNumber == null ? 0 : (double)gkc[0].AddNumber; //如果没填,则默认为0
                                        xml_t.备注        = _test.name;
                                        XML_Tests.Add(xml_t);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogMg.AddError(ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogMg.AddError(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogMg.AddError(ex);
                }
            }
            SaveConfigToXML(XML_stations, XML_Tests);
            return(true);
        }