示例#1
0
        public static void Get_XAGL_WM2000YXGT_IndicatorDiagram_Mock(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                indicatorDiagram.WellId       = par.DeviceId;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.DateTime     = DateTime.Now;
                indicatorDiagram.Mock         = par.UseMockData;

                redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());
                redisClient.Set($"Group:OilWell:{par.DeviceName}-{par.DeviceId}:IndicatorDiagram", indicatorDiagram);
                redisClient.Set($"Single:OilWell:IndicatorDiagram:{par.DeviceName}-{par.DeviceId}", indicatorDiagram);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
        //处理功图包
        public static void ProcessWorkGraphPackage(byte[] data)
        {
            try
            {
                var iotDataOilWellIndicatorDiagram = new IotDataOilWellIndicatorDiagram
                {
                    DateTime = DateTime.Now,
                    Count    = (int?)BytesConvertHelper.ConvertByteArrayToInt8(data, 8),
                    Interval = BytesConvertHelper.ConvertByteArrayToInt16(data, 9) / 100.0,
                    D        = new List <double>(),
                    L        = new List <double>()
                };

                var count = (int)iotDataOilWellIndicatorDiagram.Count;

                var deviceId = (byte)1;
                var offset   = (ushort)((deviceId - 1) * 550);
                MyModbusServer.Server.SetHoldingRegister(deviceId, (ushort)(31550 + offset + 3), (ushort)count);
                MyModbusServer.Server.SetHoldingRegister(deviceId, (ushort)(31550 + offset + 4), (ushort)(iotDataOilWellIndicatorDiagram.Interval * 100));

                for (var i = 0; i < count; i++)
                {
                    iotDataOilWellIndicatorDiagram.L.Add(BytesConvertHelper.ConvertByteArrayToInt16(data, 11 + 2 * i));
                    MyModbusServer.Server.SetHoldingRegister(deviceId, (ushort)(31550 + offset + i), (ushort)(iotDataOilWellIndicatorDiagram.Interval * 100));
                }

                for (var i = 0; i < count; i++)
                {
                    iotDataOilWellIndicatorDiagram.D.Add(BytesConvertHelper.ConvertByteArrayToInt16(data, 11 + 2 * count + 2 * i));
                    MyModbusServer.Server.SetHoldingRegister(deviceId, (ushort)(31550 + offset + 262 + i), (ushort)(iotDataOilWellIndicatorDiagram.Interval * 100));
                }

                var connectionFactory = HostContext.TryResolve <IDbConnectionFactory>();
                var dbFac             = connectionFactory.OpenDbConnection();
                var list = dbFac.Select <IotOilWell>(x => x.ModbusAddress == data[0]);

                if (!list.IsEmpty())
                {
                    iotDataOilWellIndicatorDiagram.WellId = list[0].WellId;
                    DataWriter.WorkGraphDataQueue.Enqueue(iotDataOilWellIndicatorDiagram);
                }

                Logger.Info(iotDataOilWellIndicatorDiagram.Dump());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#3
0
        public static async Task Get_XAGL_WM2000YXGT_IndicatorDiagram(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;

                var flag = true;

                var jo1 = (JObject)JsonConvert.DeserializeObject(par.CommandParameter);
                if (jo1["0"] != null)
                {
                    indicatorDiagram.Displacement = Convert.ToDouble(jo1["0"].ToString());
                }

                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                indicatorDiagram.D = new List <double>();  //位移
                indicatorDiagram.L = new List <double>();  //载荷

                indicatorDiagram.DateTime = DateTime.Now;

                indicatorDiagram.WellId = par.DeviceId;


                #region  判断井状态

                lock (ClientInfo.locker)
                {
                    ClientInfo.RequestTime     = DateTime.Now;
                    ClientInfo.ExpectedType    = 0x03;
                    ClientInfo.ExpectedDataLen = 2;
                }

                var read = await client.ReadAsync($"s={par.ModbusAddress};x=3;4103", 1);

                if (read.IsSuccess)
                {
                    var value = client.ByteTransform.TransInt16(read.Content, 0);

                    if (value == 3)  //1:正转运行;3:变频停机
                    {
                        indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;
                        indicatorDiagram.AlarmCode   = 3;
                        indicatorDiagram.AlarmMsg    = "停井";
                    }
                }
                else
                {
                    flag = false;
                    indicatorDiagram.AlarmCode = -1;
                    indicatorDiagram.AlarmMsg  = "数据异常";

                    indicatorDiagram.Mock     = par.UseMockData;
                    logIotModbusPoll.DateTime = DateTime.Now;
                    logIotModbusPoll.State    = -1;
                    logIotModbusPoll.Result   = $"读取功图井状态数据异常![{read.Message}]";
                    $"GT:{par.DeviceName}-{par.DeviceId}{logIotModbusPoll.Result}".Info();

                    redisClient.AddItemToList("YCIOT:ERROR:Log_IOT_Modbus_Poll", logIotModbusPoll.ToJson().IndentJson());
                }
                #endregion


                const ushort step = 100;

                //ToDo:确认采样间隔和点数

                indicatorDiagram.Count = 300;

                if (flag && indicatorDiagram.Count <= 300 && indicatorDiagram.Count >= step)
                {
                    ushort regAddress = 38768;//读取载荷数据

                    for (ushort i = 0; i < indicatorDiagram.Count && flag; i += step)
                    {
                        var itemCount = (i + step > indicatorDiagram.Count) ? (ushort)(indicatorDiagram.Count - i) : step;
                        if (isDebug)
                        {
                            Logger.Info($"{i}:{itemCount}:{(ushort)(regAddress + i)}");
                        }

                        lock (ClientInfo.locker)
                        {
                            ClientInfo.RequestTime     = DateTime.Now;
                            ClientInfo.ExpectedType    = 0x03;
                            ClientInfo.ExpectedDataLen = itemCount * 2;
                        }

                        read = await client.ReadAsync($"s={par.ModbusAddress};x=3;{(regAddress + i)}", itemCount);

                        if (!read.IsSuccess)
                        {
                            read = await client.ReadAsync($"s={par.ModbusAddress};x=3;{(regAddress + i)}", itemCount);
                        }

                        if (read.IsSuccess)
                        {
                            for (var j = 0; j < itemCount; j++)
                            {
                                var value = client.ByteTransform.TransInt16(read.Content, j * 2);
                                if (value != 0)
                                {
                                    var Load = (value - 800) * 150 / 3200.0;
                                    indicatorDiagram.L.Add(Math.Round(Load, 2));
                                }
                                else
                                {
                                    indicatorDiagram.L.Add(value);
                                }
                            }
                        }
                        else
                        {
                            flag = false;

                            indicatorDiagram.AlarmCode = -1;
                            indicatorDiagram.AlarmMsg  = "数据异常";

                            indicatorDiagram.Mock     = par.UseMockData;
                            logIotModbusPoll.Type     = "Get_XAGL_WM2000YXGT_IndicatorDiagram";
                            logIotModbusPoll.DateTime = DateTime.Now;
                            logIotModbusPoll.State    = -1;
                            logIotModbusPoll.Result   = "从 " + (regAddress + i).ToString() + " 个开始,读取 " + itemCount.ToString() + $" 个有线功图载荷数据异常![{read.Message}]";

                            redisClient.AddItemToList("YCIOT:ERROR:Log_IOT_Modbus_Poll", logIotModbusPoll.ToJson().IndentJson());
                        }
                        Thread.Sleep(100);
                    }

                    regAddress = 37268;//读取位移数据
                    for (var i = 0; i < indicatorDiagram.Count && flag; i += step)
                    {
                        var itemCount = (i + step > indicatorDiagram.Count) ? (ushort)(indicatorDiagram.Count - i) : step;
                        if (isDebug)
                        {
                            Logger.Info($"{i}:{itemCount}:{(ushort)(regAddress + i)}");
                        }

                        lock (ClientInfo.locker)
                        {
                            ClientInfo.RequestTime     = DateTime.Now;
                            ClientInfo.ExpectedType    = 0x03;
                            ClientInfo.ExpectedDataLen = itemCount * 2;
                        }
                        read = await client.ReadAsync($"s={par.ModbusAddress};x=3;{(regAddress + i)}", itemCount);

                        if (!read.IsSuccess)
                        {
                            read = await client.ReadAsync($"s={par.ModbusAddress};x=3;{(regAddress + i)}", itemCount);
                        }

                        if (read.IsSuccess)
                        {
                            for (var j = 0; j < itemCount; j++)
                            {
                                var value = client.ByteTransform.TransInt16(read.Content, j * 2);

                                var d = (value - 800) * 100 / 3200.0 - 50;
                                indicatorDiagram.D.Add(Math.Round(d, 2));
                            }
                        }
                        else
                        {
                            flag = false;

                            indicatorDiagram.AlarmCode = -1;
                            indicatorDiagram.AlarmMsg  = "数据异常";

                            indicatorDiagram.Mock     = par.UseMockData;
                            logIotModbusPoll.Type     = "Get_XAGL_WM2000YXGT_IndicatorDiagram";
                            logIotModbusPoll.DateTime = DateTime.Now;
                            logIotModbusPoll.State    = -1;
                            logIotModbusPoll.Result   = "从 " + (regAddress + i).ToString() + " 个开始,读取 " +
                                                        itemCount.ToString() + $" 个有线功图位移数据异常![{read.Message}]";

                            redisClient.AddItemToList("YCIOT:ERROR:Log_IOT_Modbus_Poll",
                                                      logIotModbusPoll.ToJson().IndentJson());
                        }

                        Thread.Sleep(100);
                    }

                    var maxDis = indicatorDiagram.D.Max();
                    var minDis = indicatorDiagram.D.Min();

                    if (!indicatorDiagram.Displacement.HasValue)
                    {
                        indicatorDiagram.Displacement = maxDis;
                    }

                    for (var i = 0; i < indicatorDiagram.D.Count; i++)
                    {
                        if (Math.Abs(maxDis - minDis) > 0.1)
                        {
                            indicatorDiagram.D[i] = Math.Round(((indicatorDiagram.D[i] - minDis) / (maxDis - minDis) * (double)indicatorDiagram.Displacement), 2);
                        }
                    }

                    if (indicatorDiagram.D.Count > 0)
                    {
                        indicatorDiagram.MaxLoad = Math.Round(indicatorDiagram.L.Max(), 2);     //最大载荷
                        indicatorDiagram.MinLoad = Math.Round(indicatorDiagram.L.Min(), 2);     //最小载荷
                        indicatorDiagram.AvgLoad = Math.Round(indicatorDiagram.L.Average(), 2); //平均载荷
                        indicatorDiagram.D.Add(indicatorDiagram.D[0]);
                        indicatorDiagram.L.Add(indicatorDiagram.L[0]);
                    }
                }
                else
                {
                    flag = false;
                }

                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                if (flag == true)
                {
                    $"YXGT:{par.DeviceName}-{par.DeviceId}已获取到数据".Info();
                    indicatorDiagram.Mock = par.UseMockData;

                    redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());
                    redisClient.Set($"Group:OilWell:{par.DeviceName}-{par.DeviceId}:IndicatorDiagram", indicatorDiagram);
                    redisClient.Set($"Single:OilWell:IndicatorDiagram:{par.DeviceName}-{par.DeviceId}", indicatorDiagram);
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
示例#4
0
        public static async Task POST_LYQH_GJLShiShiCaiJI(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;

                var jo1 = (JObject)JsonConvert.DeserializeObject(par.CommandParameter);
                indicatorDiagram.Displacement = Convert.ToDouble(jo1["0"].ToString());

                var slotId = Convert.ToInt32(jo1["1"].ToString());

                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                var startAddress = (ushort)((slotId * 0x100) + 0x0030);

                var read = await client.WriteAsync($"s={par.ModbusAddress};{startAddress}", new byte[] { 00, 01, 20, 08, 27, 17, 21, 0 });

                var flag = true;
                if (read.IsSuccess)
                {
                }
                else
                {
                    flag = false;
                    FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", "实时采集异常!");
                }


                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                if (flag == true || par.UseMockData)
                {
                    indicatorDiagram.Mock = par.UseMockData;
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
示例#5
0
        public static async Task POST_LYQH_GJLSetting(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;


                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                var startAddress = (ushort)0x5140;

                /*
                 *  仪表类型:0x70
                 *  仪表编号:2020010002
                 *  modbus地址:240
                 *  modbus槽位:0
                 *  采集周期:1800
                 *  液位模式:0
                 *  校正K: 106
                 *  零偏B:0
                 *  井场安装编号:3
                 *  64位长地址:86 92 50 FE FF 14 2E 84
                 */

                byte[] macAddress = { 0x86, 0x92, 0x50, 0xFE, 0xFF, 0x14, 0x2E, 0x84 };

                var data = GetSettingData(2020010002, 240, 0, 1800, 0, 106, 0, 3, macAddress);

                //ushort[] data = { 0x70, 9088, 30748, 1, 1, 400, 0, 0x00, 1, 1, 1, 513, 1027, 1541, 2055 };

                var read = await client.WriteAsync($"s={par.ModbusAddress};{startAddress}", data);

                var flag = true;
                if (read.IsSuccess)
                {
                }
                else
                {
                    flag = false;
                    FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", "实时采集异常!");
                }


                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                if (flag == true || par.UseMockData)
                {
                    indicatorDiagram.Mock = par.UseMockData;
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
        private void btnExcelExportData_Click(object sender, RoutedEventArgs e)
        {
            var connectionFactory = App.ServiceProvider.GetRequiredService <IDbConnectionFactory>();

            using var dbFac = connectionFactory.OpenDbConnection();

            var appSettings = new AppSettings();
            var redisCon    = appSettings.GetString("TestRedis");

            using var redisClient = new RedisClient(redisCon);

            var       executablePathRoot = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            var       filePath           = System.IO.Path.Combine(executablePathRoot, "功图.xlsx");
            IWorkbook workbook           = null;
            ISheet    sheet = null;

            int s = 0;
            int f = 0;

            try
            {
                workbook = WorkbookFactory.Create(filePath);
                sheet    = workbook.GetSheetAt(0);//获取第1个工作薄

                var wellName = "";
                var display  = "";
                var load     = "";

                var total = 49;

                Dictionary <string, string> fields = new Dictionary <string, string>();

                for (var j = 1; j < total; j++)
                {
                    var row = sheet.GetRow(j);

                    int i = 0;
                    foreach (var cell in row.Cells)
                    {
                        var v = GetCellValue(cell);

                        //井号
                        if (i == 0)
                        {
                            wellName = v.ToString();
                        }
                        if (i == 1)
                        {
                            //位移
                            display = v.ToString();
                        }
                        if (i == 2)
                        {
                            //载荷
                            load = v.ToString();
                        }
                        i++;
                    }

                    //保存
                    var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                    {
                        AlarmCode = 0,
                        AlarmMsg  = "正常"
                    };

                    indicatorDiagram.Mock = true;

                    indicatorDiagram.D = new List <double>();  //位移
                    indicatorDiagram.L = new List <double>();  //载荷


                    var disList = display.Replace("[", "").Replace("]", "").Split(',');

                    foreach (var item in disList)
                    {
                        indicatorDiagram.D.Add(Convert.ToDouble(item));
                    }

                    var loads = load.Replace("[", "").Replace("]", "").Split(',');

                    foreach (var item in loads)
                    {
                        indicatorDiagram.L.Add(Convert.ToDouble(item));
                    }

                    indicatorDiagram.DateTime = DateTime.Now;

                    IotOilWell oilWell = null;

                    //根据文件名获取井Id
                    wellName = $"{wellName}井";

                    if (wellName != "")
                    {
                        oilWell = dbFac.Single <IotOilWell>(w => w.WellName == wellName);

                        if (oilWell != null)
                        {
                            indicatorDiagram.WellId = oilWell.WellId;
                        }
                    }

                    if (indicatorDiagram.L.Count > 0)
                    {
                        var maxLoad = Math.Round(indicatorDiagram.L.Max(), 2);     //最大载荷
                        var minLoad = Math.Round(indicatorDiagram.L.Min(), 2);     //最小载荷
                        var avgLoad = Math.Round(indicatorDiagram.L.Average(), 2); //平均载荷

                        //间隔 = 60(秒)/ 冲次 / 采样点数

                        int count = indicatorDiagram.D.Count;

                        //冲次2.5到3之间随机

                        var n = new Random().Next(1, 5);

                        var stroke = 2.5 + n * 0.1;

                        var interval = Math.Round(60 / stroke / count, 2);

                        indicatorDiagram.Displacement = Math.Round(indicatorDiagram.D.Max(), 2);
                        indicatorDiagram.Stroke       = stroke;
                        indicatorDiagram.Interval     = interval;

                        indicatorDiagram.MaxLoad = maxLoad;
                        indicatorDiagram.MinLoad = minLoad;
                        indicatorDiagram.AvgLoad = avgLoad;
                        indicatorDiagram.Count   = count;

                        indicatorDiagram.Id = indicatorDiagram.WellId;

                        if (indicatorDiagram.D.Last() != indicatorDiagram.D[0])
                        {
                            indicatorDiagram.D.Add(indicatorDiagram.D[0]);
                        }
                        if (indicatorDiagram.L.Last() != indicatorDiagram.L[0])
                        {
                            indicatorDiagram.L.Add(indicatorDiagram.L[0]);
                        }
                        Console.WriteLine($"当前井:{oilWell.WellName}-{oilWell.WellId}");
                        //写入数据库

                        if (indicatorDiagram.WellId > 0)
                        {
                            var recordMock = indicatorDiagram.ConvertTo <IotDataOilWellIndicatorDiagramMock>();

                            if (dbFac.Exists <IotDataOilWellIndicatorDiagramMock>(d => d.WellId == recordMock.WellId))
                            {
                                var aCount = dbFac.Update(recordMock);

                                if (aCount > 0)
                                {
                                    Console.WriteLine($"{oilWell.WellName}-{oilWell.WellId}功图数据更新成功");
                                }
                            }
                            else
                            {
                                var isSuccess = dbFac.Save(recordMock);

                                if (isSuccess)
                                {
                                    Console.WriteLine($"{oilWell.WellName}-{oilWell.WellId}功图数据保存成功");
                                }
                            }
                            s++;
                            redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());

                            if (oilWell != null)
                            {
                                redisClient.Set($"Group:OilWell:{oilWell.WellName}-{oilWell.WellId}:IndicatorDiagram", indicatorDiagram);
                                redisClient.Set($"Single:OilWell:IndicatorDiagram:{oilWell.WellName}-{oilWell.WellId}", indicatorDiagram);
                            }
                        }
                    }
                }

                Console.WriteLine($"总共{total - 1}条数据执行,成功{s}条,失败{f}条");
            }
            catch (Exception ex)
            {
                f++;
                Console.WriteLine("获取excel数据出错" + ex.Message);
                workbook?.Close();
            }
        }
示例#7
0
        public static async Task Get_XAGL_WM1000YXGT_IndicatorDiagram(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;

                var flag = true;
                var jo1  = (JObject)JsonConvert.DeserializeObject(par.CommandParameter);
                indicatorDiagram.Displacement = Convert.ToDouble(jo1["0"].ToString());

                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                indicatorDiagram.D = new List <double>();  //位移
                indicatorDiagram.L = new List <double>();  //载荷

                indicatorDiagram.DateTime = DateTime.Now;

                indicatorDiagram.WellId = par.DeviceId;
                lock (ClientInfo.locker)
                {
                    ClientInfo.RequestTime     = DateTime.Now;
                    ClientInfo.ExpectedType    = 0x03;
                    ClientInfo.ExpectedDataLen = 2;
                }
                var read = await client.ReadAsync($"s={par.ModbusAddress};x=3;4117", 1);

                if (read.IsSuccess)
                {
                    var value = client.ByteTransform.TransInt16(read.Content, 0);
                    if (value == 0)
                    {
                        indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;
                        indicatorDiagram.AlarmCode   = 3;
                        indicatorDiagram.AlarmMsg    = "停井";

                        redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram",
                                                  indicatorDiagram.ToJson().IndentJson());
                        redisClient.Set($"Group:OilWell:{par.DeviceName}-{par.DeviceId}:IndicatorDiagram", indicatorDiagram);
                        redisClient.Set($"Single:OilWell:IndicatorDiagram:{par.DeviceName}-{par.DeviceId}", indicatorDiagram);

                        if (!par.UserName.IsNullOrEmpty())
                        {
                            ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, 0,
                                                             indicatorDiagram.ToJson().IndentJson());
                        }

                        return;
                    }
                }
                else
                {
                    flag = false;

                    indicatorDiagram.AlarmCode = -1;
                    indicatorDiagram.AlarmMsg  = "数据异常";

                    logIotModbusPoll.Type     = "Get_XAGL_WM1000YXGT_IndicatorDiagram";
                    logIotModbusPoll.DateTime = DateTime.Now;
                    indicatorDiagram.Mock     = par.UseMockData;
                    logIotModbusPoll.State    = -1;
                    logIotModbusPoll.Result   = $"读取采样间隔数据异常!{read.Message}";

                    redisClient.AddItemToList("YCIOT:ERROR:Log_IOT_Modbus_Poll", logIotModbusPoll.ToJson().IndentJson());
                }

                if (flag)
                {
                    lock (ClientInfo.locker)
                    {
                        ClientInfo.RequestTime     = DateTime.Now;
                        ClientInfo.ExpectedType    = 0x03;
                        ClientInfo.ExpectedDataLen = 2;
                    }
                    read = await client.ReadAsync($"s={par.ModbusAddress};x=3;8097", 1);

                    if (read.IsSuccess)
                    {
                        var value = client.ByteTransform.TransInt16(read.Content, 0);
                        indicatorDiagram.Count    = 250;
                        indicatorDiagram.Interval = Math.Round(value * 0.01, 3);
                        indicatorDiagram.Stroke   = Math.Round((60.0 / ((int)indicatorDiagram.Count * (float)indicatorDiagram.Interval)), 2);
                    }
                    else
                    {
                        flag = false;

                        indicatorDiagram.AlarmCode = -1;
                        indicatorDiagram.AlarmMsg  = "数据异常";

                        indicatorDiagram.Mock     = par.UseMockData;
                        logIotModbusPoll.Type     = "Get_XAGL_WM1000YXGT_IndicatorDiagram";
                        logIotModbusPoll.DateTime = DateTime.Now;
                        logIotModbusPoll.State    = -1;
                        logIotModbusPoll.Result   = $"读取采样间隔数据异常![{read.Message}]";

                        redisClient.AddItemToList("YCIOT:ERROR:Log_IOT_Modbus_Poll", logIotModbusPoll.ToJson().IndentJson());
                    }
                }

                const ushort step = 100;
                if (flag && indicatorDiagram.Count <= 300 && indicatorDiagram.Count >= step)
                {
                    const ushort regAddress = 38268; //读取载荷数据

                    for (ushort i = 0; i < indicatorDiagram.Count && flag; i += step)
                    {
                        var itemCount = (i + step > indicatorDiagram.Count) ? (ushort)(indicatorDiagram.Count - i) : step;
                        if (isDebug)
                        {
                            Logger.Info($"{i}:{itemCount}:{(ushort)(regAddress + i)}");
                        }

                        lock (ClientInfo.locker)
                        {
                            ClientInfo.RequestTime     = DateTime.Now;
                            ClientInfo.ExpectedType    = 0x03;
                            ClientInfo.ExpectedDataLen = itemCount * 2;
                        }
                        read = await client.ReadAsync($"s={par.ModbusAddress};x=3;{(regAddress + i)}", itemCount);

                        if (read.IsSuccess)
                        {
                            for (var j = 0; j < itemCount; j++)
                            {
                                var value = client.ByteTransform.TransInt16(read.Content, j * 2);
                                if (value == 0)
                                {
                                    indicatorDiagram.L.Add(value);
                                }
                                else
                                {
                                    var L = (value - 800) * 150 / 3200.0;
                                    indicatorDiagram.L.Add(Math.Round(L, 2));
                                }
                            }
                        }
                        else
                        {
                            flag = false;

                            indicatorDiagram.AlarmCode = -1;
                            indicatorDiagram.AlarmMsg  = "数据异常";

                            indicatorDiagram.Mock     = par.UseMockData;
                            logIotModbusPoll.Type     = "Get_XAGL_WM1000YXGT_IndicatorDiagram";
                            logIotModbusPoll.DateTime = DateTime.Now;
                            logIotModbusPoll.State    = -1;
                            logIotModbusPoll.Result   = "从 " + (regAddress + i).ToString() + " 个开始,读取 " + itemCount.ToString() + $" 个有线功图载荷数据异常!{read.Message}";

                            redisClient.AddItemToList("YCIOT:ERROR:Log_IOT_Modbus_Poll", logIotModbusPoll.ToJson().IndentJson());
                        }

                        Thread.Sleep(100);
                    }

                    //读取冲程
                    indicatorDiagram.MaxLoad = Math.Round(indicatorDiagram.L.Max(), 2);     //最大载荷
                    indicatorDiagram.MinLoad = Math.Round(indicatorDiagram.L.Min(), 2);     //最小载荷
                    indicatorDiagram.AvgLoad = Math.Round(indicatorDiagram.L.Average(), 2); //平均载荷

                    if (indicatorDiagram.D.Count > 0)
                    {
                        indicatorDiagram.D.Add(indicatorDiagram.D[0]);
                    }
                    if (indicatorDiagram.L.Count > 0)
                    {
                        indicatorDiagram.L.Add(indicatorDiagram.L[0]);
                    }
                }
                else
                {
                    flag = false;
                }

                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                //用于将读取的结果写入Redis队列
                if (flag == true || par.UseMockData)
                {
                    indicatorDiagram.Mock = par.UseMockData;

                    if (indicatorDiagram.Count != null)
                    {
                        indicatorDiagram.D = DisplacementUtils.FitDisplacement((ushort)indicatorDiagram.Count, (double)indicatorDiagram.Displacement);
                    }

                    redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());
                    redisClient.Set($"Group:OilWell:{par.DeviceName}-{par.DeviceId}:IndicatorDiagram", indicatorDiagram);
                    redisClient.Set($"Single:OilWell:IndicatorDiagram:{par.DeviceName}-{par.DeviceId}", indicatorDiagram);
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
示例#8
0
        public static async Task Get_ZKAW_IndicatorDiagram(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;

                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                indicatorDiagram.D = new List <double>();     //位移
                indicatorDiagram.L = new List <double>();     //载荷

                indicatorDiagram.DateTime = DateTime.Now;
                indicatorDiagram.WellId   = par.DeviceId;

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var flag = true;

                var read = await client.ReadAsync($"s={modbusAddress};x=3;980", 4);    //功图实际点数

                if (read.IsSuccess)
                {
                    var value = client.ByteTransform.TransInt16(read.Content, 6);
                    indicatorDiagram.Count = value;            //采样点数
                    value = client.ByteTransform.TransInt16(read.Content, 0);
                    indicatorDiagram.Interval = value * 0.001; //采样间隔
                }
                else
                {
                    flag = false;

                    indicatorDiagram.AlarmCode = -1;
                    indicatorDiagram.AlarmMsg  = "数据异常";

                    indicatorDiagram.Mock   = par.UseMockData;
                    logIotModbusPoll.State  = -1;
                    logIotModbusPoll.Result = "读取采样间隔、采样点数数据异常!";

                    redisClient.AddItemToList("YCIOT:Log_IOT_Modbus_Poll", logIotModbusPoll.ToJson().IndentJson());
                }

                read = await client.ReadAsync($"s={modbusAddress};x=3;990", 2);    //冲次

                if (read.IsSuccess)
                {
                    var value = client.ByteTransform.TransInt16(read.Content, 0);
                    indicatorDiagram.Stroke = value;       //冲次
                    value = client.ByteTransform.TransInt16(read.Content, 2);
                    indicatorDiagram.Displacement = value; //冲程
                }
                else
                {
                    flag = false;

                    indicatorDiagram.AlarmCode = -1;
                    indicatorDiagram.AlarmMsg  = "数据异常";

                    indicatorDiagram.Mock   = par.UseMockData;
                    logIotModbusPoll.State  = -1;
                    logIotModbusPoll.Result = "读取冲次、冲程数据异常!";

                    redisClient.AddItemToList("YCIOT:Log_IOT_Modbus_Poll", logIotModbusPoll.ToJson().IndentJson());
                }

                const ushort step = 50;
                if (flag)
                {
                    //读取载荷数据
                    ushort regAddress = 1250;
                    for (ushort i = 0; i < indicatorDiagram.Count; i += step)
                    {
                        var itemCount = (i + step > indicatorDiagram.Count)
                                  ? (ushort)(indicatorDiagram.Count - i)
                                  : step;

                        Logger.Info($"{i}:{itemCount}:{(ushort)(regAddress + i)}");

                        read = await client.ReadAsync($"s={modbusAddress};x=3;{(ushort)(regAddress + i)}", itemCount);

                        if (!read.IsSuccess)
                        {
                            read = await client.ReadAsync($"s={modbusAddress};x=3;{(ushort)(regAddress + i)}", itemCount);
                        }

                        if (read.IsSuccess)
                        {
                            for (var j = 0; j < itemCount; j++)
                            {
                                var value = client.ByteTransform.TransInt16(read.Content, j * 2);
                                indicatorDiagram.L.Add(Math.Round(value * 0.01, 3));
                            }
                        }
                        else
                        {
                            flag = false;

                            indicatorDiagram.AlarmCode = -1;
                            indicatorDiagram.AlarmMsg  = "数据异常";

                            indicatorDiagram.Mock     = par.UseMockData;
                            logIotModbusPoll.DateTime = DateTime.Now;
                            logIotModbusPoll.State    = -1;
                            logIotModbusPoll.Result   = "从 " + (regAddress + i).ToString() + " 个开始,读取 " +
                                                        itemCount.ToString() + " 个有线功图载荷数据异常!";

                            redisClient.AddItemToList("YCIOT:Log_IOT_Modbus_Poll",
                                                      logIotModbusPoll.ToJson().IndentJson());
                        }

                        Thread.Sleep(20);
                    }
                }

                if (flag)
                {
                    //读取位移数据
                    var regAddress = 1000;
                    for (ushort i = 0; i < indicatorDiagram.Count; i += step)
                    {
                        var itemCount = (i + step > indicatorDiagram.Count)
                                  ? (ushort)(indicatorDiagram.Count - i)
                                  : step;

                        Logger.Info($"{i}:{itemCount}:{(ushort)(regAddress + i)}");

                        read = await client.ReadAsync($"s={modbusAddress};x=3;{(ushort)(regAddress + i)}", itemCount);

                        if (!read.IsSuccess)
                        {
                            read = await client.ReadAsync($"s={modbusAddress};x=3;{(ushort)(regAddress + i)}", itemCount);
                        }
                        if (read.IsSuccess)
                        {
                            for (var j = 0; j < itemCount; j++)
                            {
                                var value = client.ByteTransform.TransInt16(read.Content, j * 2);
                                indicatorDiagram.D.Add(Math.Round(value * 0.01, 3));
                            }
                        }
                        else
                        {
                            flag = false;

                            indicatorDiagram.AlarmCode = -1;
                            indicatorDiagram.AlarmMsg  = "数据异常";

                            indicatorDiagram.Mock     = par.UseMockData;
                            logIotModbusPoll.DateTime = DateTime.Now;
                            logIotModbusPoll.State    = -1;
                            logIotModbusPoll.Result   = "从 " + (regAddress + i).ToString() + " 个开始,读取 " +
                                                        itemCount.ToString() + " 个有线功图载荷数据异常!";

                            redisClient.AddItemToList("YCIOT:Log_IOT_Modbus_Poll",
                                                      logIotModbusPoll.ToJson().IndentJson());
                        }

                        Thread.Sleep(20);
                    }
                }

                if (flag)
                {
                    var maxLoad = indicatorDiagram.D.Max();
                    var minLoad = indicatorDiagram.D.Min();

                    for (var i = 0; i < indicatorDiagram.D.Count; i++)
                    {
                        indicatorDiagram.D[i] = Math.Round(((indicatorDiagram.D[i] - minLoad) / (maxLoad - minLoad) * (double)indicatorDiagram.Displacement), 2);
                    }

                    if (indicatorDiagram.D.Count > 0)
                    {
                        indicatorDiagram.Displacement = Math.Round(indicatorDiagram.D.Max(), 2);
                        indicatorDiagram.MaxLoad      = Math.Round(indicatorDiagram.L.Max(), 2);     //最大载荷
                        indicatorDiagram.MinLoad      = Math.Round(indicatorDiagram.L.Min(), 2);     //最小载荷
                        indicatorDiagram.AvgLoad      = Math.Round(indicatorDiagram.L.Average(), 2); //平均载荷
                    }
                }

                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                if (flag == true)
                {
                    redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());
                    redisClient.Set($"Group:OilWell:{par.DeviceName}-{par.DeviceId}:IndicatorDiagram", indicatorDiagram);
                    redisClient.Set($"Single:OilWell:IndicatorDiagram:{par.DeviceName}-{par.DeviceId}", indicatorDiagram);
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, 0, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
        /// <summary>
        /// 导出功图数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCSVExportData_Click(object sender, RoutedEventArgs e)
        {
            var connectionFactory = App.ServiceProvider.GetRequiredService <IDbConnectionFactory>();

            using var dbFac = connectionFactory.OpenDbConnection();

            var appSettings = new AppSettings();
            var redisCon    = appSettings.GetString("TestRedis");

            using var redisClient = new RedisClient(redisCon);

            var executablePathRoot = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            string targetFolder = "data";

            string dataDirPath = System.IO.Path.Combine(executablePathRoot, targetFolder);

            //获取文件夹下所有文件

            int s = 0;
            int f = 0;

            var files = Directory.GetFiles(dataDirPath);

            foreach (var file in files)
            {
                var filePath = file;

                string fileName = System.IO.Path.GetFileName(file).Replace(".csv", "");
                string wellName = "";

                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                indicatorDiagram.Mock = true;

                indicatorDiagram.D = new List <double>();  //位移
                indicatorDiagram.L = new List <double>();  //载荷

                indicatorDiagram.DateTime = DateTime.Now;

                IotOilWell oilWell = null;

                //根据文件名获取井Id
                var fileInfos = fileName.Split('-');

                if (fileInfos.Length > 1)
                {
                    wellName = $"{fileInfos[0]}-{fileInfos[1]}井";
                }
                if (fileInfos.Length == 1)
                {
                    wellName = $"{fileInfos[0]}井";
                }

                if (wellName != "")
                {
                    oilWell = dbFac.Single <IotOilWell>(w => w.WellName == wellName);

                    if (oilWell != null)
                    {
                        indicatorDiagram.WellId = oilWell.WellId;
                    }
                }

                try
                {
                    var dt = OpenCSV(filePath);

                    foreach (var item in dt)
                    {
                        if (item.Length > 1)
                        {
                            if (!string.IsNullOrEmpty(item[0]))
                            {
                                indicatorDiagram.D.Add(Math.Round(Convert.ToDouble(item[0]), 2));
                                indicatorDiagram.L.Add(Math.Round(Convert.ToDouble(item[1]), 2));
                            }
                        }
                    }
                    if (indicatorDiagram.L.Count > 0)
                    {
                        var maxLoad = Math.Round(indicatorDiagram.L.Max(), 2);     //最大载荷
                        var minLoad = Math.Round(indicatorDiagram.L.Min(), 2);     //最小载荷
                        var avgLoad = Math.Round(indicatorDiagram.L.Average(), 2); //平均载荷

                        //间隔 = 60(秒)/ 冲次 / 采样点数

                        int count = indicatorDiagram.D.Count;

                        //冲次2.5到3之间随机

                        var n = new Random().Next(1, 5);

                        var stroke = 2.5 + n * 0.1;

                        var interval = Math.Round(60 / stroke / count, 2);

                        indicatorDiagram.Displacement = Math.Round(indicatorDiagram.D.Max(), 2);
                        indicatorDiagram.Stroke       = stroke;
                        indicatorDiagram.Interval     = interval;

                        indicatorDiagram.MaxLoad = maxLoad;
                        indicatorDiagram.MinLoad = minLoad;
                        indicatorDiagram.AvgLoad = avgLoad;
                        indicatorDiagram.Count   = count;

                        indicatorDiagram.Id = indicatorDiagram.WellId;

                        if (indicatorDiagram.D.Last() != indicatorDiagram.D[0])
                        {
                            indicatorDiagram.D.Add(indicatorDiagram.D[0]);
                        }
                        if (indicatorDiagram.L.Last() != indicatorDiagram.L[0])
                        {
                            indicatorDiagram.L.Add(indicatorDiagram.L[0]);
                        }
                        Console.WriteLine($"当前井:{oilWell.WellName}-{oilWell.WellId}");
                        //写入数据库

                        if (indicatorDiagram.WellId > 0)
                        {
                            var recordMock = indicatorDiagram.ConvertTo <IotDataOilWellIndicatorDiagramMock>();

                            if (dbFac.Exists <IotDataOilWellIndicatorDiagramMock>(d => d.WellId == recordMock.WellId))
                            {
                                var aCount = dbFac.Update(recordMock);

                                if (aCount > 0)
                                {
                                    Console.WriteLine($"{oilWell.WellName}-{oilWell.WellId}功图数据更新成功");
                                }
                            }
                            else
                            {
                                var isSuccess = dbFac.Save(recordMock);

                                if (isSuccess)
                                {
                                    Console.WriteLine($"{oilWell.WellName}-{oilWell.WellId}功图数据保存成功");
                                }
                            }
                            s++;
                            redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());

                            if (oilWell != null)
                            {
                                redisClient.Set($"Group:OilWell:{oilWell.WellName}-{oilWell.WellId}:IndicatorDiagram", indicatorDiagram);
                                redisClient.Set($"Single:OilWell:IndicatorDiagram:{oilWell.WellName}-{oilWell.WellId}", indicatorDiagram);
                            }
                        }
                    }

                    Console.WriteLine($"总共{files.Length}条数据执行,成功{s}条,失败{f}条");
                }
                catch (Exception ex)
                {
                    f++;
                    Console.WriteLine("导出功图数据出错" + ex.Message);
                }
            }
        }
示例#10
0
文件: GT.cs 项目: windygu/MyAssistant
        public static async Task POST_LYQH_WG_IndicatorDiagramSetting(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;

                var jo1 = (JObject)JsonConvert.DeserializeObject(par.CommandParameter);

                var slotId = Convert.ToInt32(jo1["1"].ToString());

                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                var startAddress = (ushort)0x0000;

                //写入10个寄存器

                /*功图ID:20151 10017
                 * 采集周期:600
                 * 功图模式:0x10
                 * 功图点数:200
                 * 压缩标志:0
                 * MB地址:1
                 * 槽位:2
                 * 仪表类型:0x10
                 */

                //2015110017转成16进制0x781C 2381‬,0x781C一个寄存器,0x2381一个寄存器
                // 781C  2381   遵从CDAB   变为 2381   781C

                //9089   30748

                byte[] macAddress = { 0x47, 0x92, 0x50, 0xFE, 0xFF, 0x14, 0x2E, 0x84 };

                var data = GetSettingData(2020040107, 4, 1, 1800, 0x10, 200, macAddress);

                //ushort[] data = { 0x10, 9089, 30748, 1, 2, 600, 0, 0x10, 200, 0, 38453, 65104, 5375, 33838 };

                var read = await client.WriteAsync($"s={par.ModbusAddress};{startAddress}", data);

                var flag = true;
                if (read.IsSuccess)
                {
                }
                else
                {
                    flag = false;
                    FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "POST_LYQH_WG_IndicatorDiagramSetting", "功图设置异常!");
                }


                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                if (flag == true || par.UseMockData)
                {
                    indicatorDiagram.Mock = par.UseMockData;
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
示例#11
0
文件: GT.cs 项目: windygu/MyAssistant
        public static async Task <bool> SetIndicatorDiagram(RedisClient redisClient, ModbusRtuOverTcp client, int modbusAddress, IotDataOilWellIndicatorDiagram indicatorDiagram, LogIotModbusPoll logIotModbusPoll, ControlRequest par, int slotId, int tryReadTimes = 3)
        {
            var startAddress = (ushort)((slotId * 0x3000) + 256);

            //时间
            var isSuccess = await GetDateTime(client, modbusAddress, indicatorDiagram, startAddress, 3, tryReadTimes);

            if (!isSuccess)
            {
                FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", "读取采样时间数据异常!");
                return(false);
            }

            startAddress = (ushort)((slotId * 0x3000) + 260);
            //采样点数
            isSuccess = await GetCount(client, modbusAddress, indicatorDiagram, startAddress, 1, tryReadTimes);

            if (!isSuccess)
            {
                FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", "读取采样点数数据异常!");
                return(false);
            }

            startAddress = (ushort)((slotId * 0x3000) + 263);

            //读取冲次
            isSuccess = await GetStroke(client, modbusAddress, indicatorDiagram, startAddress, 1, tryReadTimes);

            if (!isSuccess)
            {
                FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", "读取冲次异常!");
                return(false);
            }

            ushort step = 100;

            if (indicatorDiagram.Count <= 250 && indicatorDiagram.Count >= step)
            {
                var regAddress = (ushort)((slotId * 0x3000) + 606);  //读取载荷数据

                for (ushort i = 0; i < indicatorDiagram.Count; i += step)
                {
                    var itemCount = (i + step > indicatorDiagram.Count) ? (ushort)(indicatorDiagram.Count - i) : step;

                    Logger.Info($"{i}:{itemCount}:{(ushort)(regAddress + i)}");

                    //读取载荷
                    isSuccess = await GetLData(client, modbusAddress, indicatorDiagram, (ushort)(regAddress + i), itemCount, tryReadTimes);

                    if (!isSuccess)
                    {
                        var message = "从 " + (regAddress + i).ToString() + " 个开始,读取 " + itemCount.ToString() + " 个载荷数据异常!";
                        FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", message);
                        return(false);
                    }
                    Thread.Sleep(100);
                }

                regAddress = (ushort)((slotId * 0x3000) + 356);  //读取位移数据

                for (var i = 0; i < indicatorDiagram.Count; i += step)
                {
                    var itemCount = (i + step > indicatorDiagram.Count) ? (ushort)(indicatorDiagram.Count - i) : step;

                    Logger.Info($"{i}:{itemCount}:{(ushort)(regAddress + i)}");

                    //读取位移
                    isSuccess = await GetDData(client, modbusAddress, indicatorDiagram, (ushort)(regAddress + i), itemCount, tryReadTimes);

                    if (!isSuccess)
                    {
                        var message = "从 " + (regAddress + i).ToString() + " 个开始,读取 " + itemCount.ToString() + " 个有线功图位移数据异常!";
                        FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", message);
                        return(false);
                    }
                    Thread.Sleep(100);
                }

                var maxDis = indicatorDiagram.D.Max();
                var minDis = indicatorDiagram.D.Min();

                for (var i = 0; i < indicatorDiagram.D.Count; i++)
                {
                    if (Math.Abs(maxDis - minDis) > 0.1)
                    {
                        indicatorDiagram.D[i] = Math.Round(((indicatorDiagram.D[i] - minDis) / (maxDis - minDis) * (double)indicatorDiagram.Displacement), 2);
                    }
                }

                if (indicatorDiagram.D.Count > 0)
                {
                    indicatorDiagram.MaxLoad = Math.Round(indicatorDiagram.L.Max(), 2);     //最大载荷
                    indicatorDiagram.MinLoad = Math.Round(indicatorDiagram.L.Min(), 2);     //最小载荷
                    indicatorDiagram.AvgLoad = Math.Round(indicatorDiagram.L.Average(), 2); //平均载荷
                    indicatorDiagram.D.Add(indicatorDiagram.D[0]);
                    indicatorDiagram.L.Add(indicatorDiagram.L[0]);
                }
            }
            else
            {
                return(false);
            }
            return(true);
        }
示例#12
0
文件: GT.cs 项目: windygu/MyAssistant
        public static async Task <bool> GetDateTime(ModbusRtuOverTcp client, int modbusAddress, IotDataOilWellIndicatorDiagram indicatorDiagram, ushort startAddress, ushort regCount, int tryReadTimes)
        {
            lock (ClientInfo.locker)
            {
                ClientInfo.RequestTime     = DateTime.Now;
                ClientInfo.ExpectedType    = 0x04;
                ClientInfo.ExpectedDataLen = regCount * 2;
            }
            var read = await client.ReadAsync($"s={modbusAddress};x=4;{startAddress}", regCount);

            if (read.IsSuccess)
            {
                var year  = client.ByteTransform.TransByte(read.Content, 0);
                var month = client.ByteTransform.TransByte(read.Content, 1);
                var date  = client.ByteTransform.TransByte(read.Content, 2);
                var h     = client.ByteTransform.TransByte(read.Content, 3);
                var m     = client.ByteTransform.TransByte(read.Content, 4);
                var s     = client.ByteTransform.TransByte(read.Content, 5);

                indicatorDiagram.DateTime = new DateTime(2000 + year, month, date, h, m, s);

                return(true);
            }
            else
            {
                tryReadTimes--;
                if (tryReadTimes > 0)
                {
                    return(await GetDateTime(client, modbusAddress, indicatorDiagram, startAddress, regCount, tryReadTimes));
                }
                return(false);
            }
        }
示例#13
0
文件: GT.cs 项目: windygu/MyAssistant
        public static async Task <bool> GetCount(ModbusRtuOverTcp client, int modbusAddress, IotDataOilWellIndicatorDiagram indicatorDiagram, ushort startAddress, ushort regCount, int tryReadTimes)
        {
            lock (ClientInfo.locker)
            {
                ClientInfo.RequestTime     = DateTime.Now;
                ClientInfo.ExpectedType    = 0x04;
                ClientInfo.ExpectedDataLen = regCount * 2;
            }
            var read = await client.ReadAsync($"s={modbusAddress};x=4;{startAddress}", regCount);

            if (read.IsSuccess)
            {
                var value = client.ByteTransform.TransInt16(read.Content, 0);
                indicatorDiagram.Count = value;
                return(true);
            }
            else
            {
                tryReadTimes--;

                if (tryReadTimes > 0)
                {
                    return(await GetCount(client, modbusAddress, indicatorDiagram, startAddress, regCount, tryReadTimes));
                }

                return(false);
            }
        }
示例#14
0
文件: GT.cs 项目: windygu/MyAssistant
        public static async Task Get_LYQH_WG_IndicatorDiagram(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;

                var jo1 = (JObject)JsonConvert.DeserializeObject(par.CommandParameter);
                indicatorDiagram.Displacement = Convert.ToDouble(jo1["0"].ToString());

                var slotId = Convert.ToInt32(jo1["1"].ToString());

                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                indicatorDiagram.D = new List <double>();  //位移
                indicatorDiagram.L = new List <double>();  //载荷

                indicatorDiagram.DateTime = DateTime.Now;
                indicatorDiagram.WellId   = par.DeviceId;

                var flag = await SetIndicatorDiagram(redisClient, client, modbusAddress, indicatorDiagram, logIotModbusPoll, par, slotId);

                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                if (flag == true || par.UseMockData)
                {
                    indicatorDiagram.Mock = par.UseMockData;

                    redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());
                    redisClient.Set($"Group:OilWell:{par.DeviceName}-{par.DeviceId}:IndicatorDiagram", indicatorDiagram);
                    redisClient.Set($"Single:OilWell:IndicatorDiagram:{par.DeviceName}-{par.DeviceId}", indicatorDiagram);
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
示例#15
0
        public static async Task POST_LYQH_DYMSetting(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    AlarmCode = 0,
                    AlarmMsg  = "正常"
                };

                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var modbusAddress = par.ModbusAddress;
                indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                indicatorDiagram.Mock         = false;


                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                var startAddress = (ushort)0x0C80;

                //写入10个寄存器

                /*
                 *  仪表类型:0x30
                 *  仪表编号:1801064
                 *  modbus地址:5
                 *  modbus槽位:1
                 *  采集周期:1800
                 *  预估深度:30000
                 *  预设声速:3400
                 *  接箍长度:9600
                 *  采样周期:400
                 *  电磁阀充电时间:10
                 *  采集模式:0x0
                 *  球阀动作时间:9
                 *  电磁阀动作时间:4
                 *  64位长地址:F2 98 50 FE FF 14 2E 84
                 */

                byte[] macAddress = { 0xF2, 0x98, 0x50, 0xFE, 0xFF, 0x14, 0x2E, 0x84 };
                var    data       = GetSettingData(1801064, 5, 1, 1800, 30000, 3400, 9600, 400, 10, 0x0, 9, 4, macAddress);
                //ushort[] data = { 0x30, 9088, 30748, 1, 1, 1800, 0, 30000, 3400, 9600, 400, 10, 0, 10, 20, 41130, 65140, 22527, 11 };

                var read = await client.WriteAsync($"s={par.ModbusAddress};{startAddress}", data);

                var flag = true;
                if (read.IsSuccess)
                {
                }
                else
                {
                    flag = false;
                    FailLog.Write(redisClient, par, indicatorDiagram, logIotModbusPoll, "Get_LYQH_WG_IndicatorDiagram", "实时采集异常!");
                }


                indicatorDiagram.NetworkNode = ClientInfo.ManyIpAddress;

                if (flag == true || par.UseMockData)
                {
                    indicatorDiagram.Mock = par.UseMockData;
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }
示例#16
0
        public static async Task Get_XAGL_WM3000WXGT_IndicatorDiagram(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            try
            {
                var logIotModbusPoll = par.ConvertTo <LogIotModbusPoll>();

                logIotModbusPoll.State  = 0;
                logIotModbusPoll.Result = "ok";

                var flag = true;

                var indicatorDiagram = new IotDataOilWellIndicatorDiagram()
                {
                    NetworkNode = ClientInfo.ManyIpAddress,
                    AlarmCode   = 0,
                    AlarmMsg    = "正常"
                };

                var jo1 = (JObject)JsonConvert.DeserializeObject(par.CommandParameter);

                double displacement = -1;

                if (jo1["0"] != null)
                {
                    double.TryParse(jo1["0"].ToString().Trim(), out displacement);
                }
                if (displacement > 0)
                {
                    indicatorDiagram.Displacement = displacement;
                }
                var modbusAddress = par.ModbusAddress;
                ClientInfo.CurrentModbusPoolAddress = modbusAddress;
                var commandParameter = par.CommandParameter.ToString();
                var slot             = Convert.ToInt32(jo1["1"].ToString());

                var  host        = par.RemoteHost;
                var  url         = "/getworkgraph/";
                bool IsHostAlive = false;

                if (host.StartsWith("192"))
                {
                    $"无线功图树莓派({host})不正确,或者没有接入无线功图".Error();
                }
                else
                {
                    IsHostAlive = TcpClientConnector.IsOnline(host, null, 1000);
                    if (IsHostAlive)
                    {
                        url = $"http://{host}{url}{slot}";

                        $"请求树莓派api:{url}".Info();

                        var indicatorDiagramJson = await url.GetJsonFromUrlAsync();

                        //$"树莓派api返回数据:{indicatorDiagramJson}".Info();

                        var oilWellIndicatorDiagram = indicatorDiagramJson.FromJson <OilWellIndicatorDiagram>();

                        indicatorDiagram.Stroke = oilWellIndicatorDiagram.chongCheng;
                        indicatorDiagram.L      = oilWellIndicatorDiagram.load;
                        indicatorDiagram.D      = oilWellIndicatorDiagram.displace;



                        var maxDis = indicatorDiagram.D.Max();
                        var minDis = indicatorDiagram.D.Min();

                        if (!indicatorDiagram.Displacement.HasValue)
                        {
                            indicatorDiagram.Displacement = maxDis;
                        }

                        for (var i = 0; i < indicatorDiagram.D.Count; i++)
                        {
                            if (Math.Abs(maxDis - minDis) > 0.1)
                            {
                                indicatorDiagram.D[i] = Math.Round(((indicatorDiagram.D[i] - minDis) / (maxDis - minDis) * (double)indicatorDiagram.Displacement), 2);
                            }
                        }

                        //补点
                        if (indicatorDiagram.L.Count > 0)
                        {
                            indicatorDiagram.L.Add(indicatorDiagram.L[0]);
                        }
                        if (indicatorDiagram.D.Count > 0)
                        {
                            indicatorDiagram.D.Add(indicatorDiagram.D[0]);
                        }

                        indicatorDiagram.MaxLoad = indicatorDiagram.L.Max();
                        indicatorDiagram.MinLoad = indicatorDiagram.L.Min();
                        indicatorDiagram.AvgLoad = indicatorDiagram.L.Average();


                        indicatorDiagram.DateTime = DateTime.Now;  //树莓派时间不准确,取服务器时间
                                                                   //to do 树莓派时间稳定了再换
                        indicatorDiagram.WellId   = oilWellIndicatorDiagram.wellId;
                        indicatorDiagram.Count    = oilWellIndicatorDiagram.count;
                        indicatorDiagram.Interval = oilWellIndicatorDiagram.interval;

                        indicatorDiagram.DeviceTypeId = par.DeviceTypeId;
                        indicatorDiagram.Mock         = par.UseMockData;
                        if (displacement > 0)
                        {
                            indicatorDiagram.Displacement = displacement;
                        }

                        indicatorDiagram.NetworkNode = host;

                        redisClient.AddItemToList("YCIOT:IOT_Data_OilWell_IndicatorDiagram", indicatorDiagram.ToJson().IndentJson());
                        redisClient.Set($"Group:OilWell:{par.DeviceName}-{par.DeviceId}:IndicatorDiagram", indicatorDiagram);
                        redisClient.Set($"Single:OilWell:IndicatorDiagram:{par.DeviceName}-{par.DeviceId}", indicatorDiagram);
                    }
                    else
                    {
                        $"无线功图树莓派({host})网络不通!".Error();
                    }
                }

                //用于通过ServerEvent给调用着返回消息
                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, flag ? 0 : -2, indicatorDiagram.ToJson().IndentJson());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }