Example #1
0
        /// <summary>
        /// 请求获取数据的命令,并且返回请求结果数据的字节数组
        /// </summary>
        /// <param name="device"></param>
        /// <param name="realData"></param>
        /// <param name="error"></param>
        /// <param name="fragment">当前请求的modbus地址分段</param>
        /// <returns></returns>
        public Task <List <byte> > RequestData(RealData read)
        {
            List <byte> allbytes = new List <byte>();

            var task = Task.Run <List <byte> >(() =>
            {
                try
                {
                    if (serialPort != null && serialPort.IsOpen)
                    {
                        //分段读取数据,如果是读取整个寄存器的话,一次只能最多读取123个,
                        //如果是读取线圈的话最大只能读取1999个,因此要分段进行数据的读取
                        //增加了一个写入后返回消息
                        master.Transport.WriteMessage = new Action <byte[]>((s) =>
                        {
                            if (LogOutput != null)
                            {
                                LogOutput(ModbusConvert.ByteToHexStr(s));
                            }
                        });
                        master.Transport.CheckFrame = true;
                        ModbusFragment fragment     = read.Fragment;
                        switch (fragment.Code)
                        {
                        case "01":        // 01和05是一个码 可写可读
                            {
                                //返回的线圈状态,由于线圈是按位操作,转换也是按位转换
                                Task <bool[]> result = master.ReadCoilsAsync(byte.Parse(read.Address), fragment.StartRegister, fragment.RegisterNum);

                                byte[] bytes = ModbusConvert.BoolToByte(result.Result);

                                allbytes.AddRange(bytes);
                            }
                            break;

                        case "02":        //只读属性
                            {
                                //返回的线圈状态
                                Task <bool[]> result = master.ReadInputsAsync(byte.Parse(read.Address), fragment.StartRegister, fragment.RegisterNum);
                                byte[] bytes         = ModbusConvert.BoolToByte(result.Result);

                                allbytes.AddRange(bytes);
                            }
                            break;

                        case "03":        //HR保持寄存器,可写可读
                            {
                                //返回的数据全部是ushort 需要将ushort 转换为byte在进行传递
                                Task <ushort[]> result = master.ReadHoldingRegistersAsync(byte.Parse(read.Address), fragment.StartRegister, fragment.RegisterNum);
                                byte[] bytes           = ModbusConvert.Ushorts2Bytes(result.Result);
                                allbytes.AddRange(bytes);
                            }
                            break;

                        case "04":        //只读属性
                            {
                                //返回的数据全部是ushort 需要将ushort 转换为byte在进行传递
                                Task <ushort[]> result = master.ReadInputRegistersAsync(byte.Parse(read.Address), fragment.StartRegister, fragment.RegisterNum);
                                byte[] bytes           = ModbusConvert.Ushorts2Bytes(result.Result);

                                allbytes.AddRange(bytes);
                            }
                            break;
                        }
                    }
                    return(allbytes);
                }
                catch
                {
                    return(allbytes);
                }
            });

            return(task);
        }
Example #2
0
        /// <summary>
        /// 写入操作,针对的数据类型只有 字符串量 计算值 关系数据库值
        /// </summary>
        /// <param name="server"></param>
        /// <param name="comm"></param>
        /// <param name="device"></param>
        /// <param name="para">要写入参数</param>
        /// <param name="value">要写入的值</param>
        /// <returns></returns>
        public Task <bool> ResponseData(string SlaveId, string Address, ModbusFragment para, string value)
        {
            var task = Task.Run <bool>(() => {
                if (para == null)
                {
                    return(false);
                }

                //设备地址不能为空
                if (Address == "")
                {
                    return(false);
                }
                try
                {
                    //获取参数中的
                    if (serialPort != null && serialPort.IsOpen && master != null)
                    {
                        ushort offset = para.StartRegister;
                        switch (para.Code)
                        {
                        case "01":
                            {
                                ///写入单个线圈
                                if (ushort.Parse(value) > 0)
                                {
                                    master.WriteSingleCoil(byte.Parse(Address), offset, true);
                                }
                                else
                                {
                                    master.WriteSingleCoil(byte.Parse(Address), offset, false);
                                }
                            }
                            break;

                        case "02":    //此类型只能查询,不能写入
                            {
                            }
                            break;

                        case "03":
                            {
                                switch (para.DataType)
                                {
                                case "float":        //单精度浮点型
                                    {
                                        ushort[] buff    = new ushort[2];
                                        float WriteValue = float.Parse(value);
                                        ModbusConvert.SetReal(buff, 0, WriteValue);
                                        master.WriteMultipleRegisters(byte.Parse(Address), offset, buff);
                                    }
                                    break;

                                case "double":        //双精度浮点数64位
                                    {
                                        ushort[] buff     = new ushort[4];
                                        double WriteValue = double.Parse(value);
                                        ModbusConvert.SetDouble(buff, 0, WriteValue);
                                        master.WriteMultipleRegisters(byte.Parse(Address), offset, buff);
                                    }
                                    break;

                                case "string":        //字符型
                                    {
                                        ushort[] buff     = new ushort[para.charsize];
                                        string WriteValue = value;
                                        if (value.Length > para.charsize)
                                        {
                                            WriteValue = value.Substring(0, para.charsize);
                                        }
                                        if (value.Length < para.charsize)
                                        {
                                            WriteValue = value.PadRight(para.charsize, ' ');
                                        }
                                        ModbusConvert.SetString(buff, 0, WriteValue);
                                        master.WriteMultipleRegisters(byte.Parse(Address), offset, buff);
                                    }
                                    break;

                                case "byte":        //无符号整数8位:
                                    {
                                        ushort[] buff   = new ushort[1];
                                        byte WriteValue = byte.Parse(value);
                                        ModbusConvert.SetByte(buff, 0, WriteValue, true);
                                        master.WriteSingleRegister(byte.Parse(Address), offset, buff[0]);
                                    }
                                    break;

                                case "sbyte":        //有符号整数8位:
                                    {
                                        ushort[] buff    = new ushort[1];
                                        sbyte WriteValue = sbyte.Parse(value);
                                        ModbusConvert.SetSByte(buff, 0, WriteValue, true);
                                        master.WriteSingleRegister(byte.Parse(Address), offset, buff[0]);
                                    }
                                    break;

                                case "uint16":        //无符号整数16位:
                                    {
                                        ushort WriteValue = ushort.Parse(value);
                                        ushort[] buff     = new ushort[1];
                                        ModbusConvert.SetUShort(buff, 0, WriteValue);
                                        master.WriteSingleRegister(byte.Parse(Address), offset, buff[0]);
                                    }
                                    break;

                                case "int16":        //有符号整数16位:
                                    {
                                        Int16 WriteValue = Int16.Parse(value);
                                        ushort[] buff    = new ushort[1];
                                        ModbusConvert.SetShort(buff, 0, WriteValue);
                                        master.WriteSingleRegister(byte.Parse(Address), offset, buff[0]);
                                    }
                                    break;

                                case "uint32":        //无符号整数32位:
                                    {
                                        uint WriteValue = uint.Parse(value);
                                        ushort[] buff   = new ushort[2];
                                        ModbusConvert.SetUInt(buff, 0, WriteValue);
                                        master.WriteMultipleRegisters(byte.Parse(Address), offset, buff);
                                    }
                                    break;

                                case "int32":        //有符号整数32位:
                                    {
                                        int WriteValue = int.Parse(value);
                                        ushort[] buff  = new ushort[2];
                                        ModbusConvert.SetInt(buff, 0, WriteValue);
                                        master.WriteMultipleRegisters(byte.Parse(Address), offset, buff);
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
                catch
                {
                    return(false);
                }
                return(true);
            });

            return(task);
        }
Example #3
0
        public static void InitMonitorManager(MainForm mainForm)
        {
            try
            {
                MainForm = mainForm;
                //实时数据缓存池
                ReceiveCachec           = new ReceiveCachec();
                ReceiveCachec.OnGeted  += ReceiveCachec_OnGeted;
                ReceiveCachec.OnPushed += ReceiveCachec_OnPushed;
                ReceiveCachec.MaxNumber = 1000;
                //报警缓存池
                ReceiveAlarmCachec           = new ReceiveCachec();
                ReceiveAlarmCachec.OnGeted  += ReceiveAlarmCachec_OnGeted;
                ReceiveAlarmCachec.OnPushed += ReceiveAlarmCachec_OnPushed;
                ReceiveAlarmCachec.MaxNumber = 1000;

                ///报警状态
                ReceiveAlarmStatusCachec           = new ReceiveCachec();
                ReceiveAlarmStatusCachec.OnGeted  += ReceiveAlarmStatusCachec_OnGeted;
                ReceiveAlarmStatusCachec.OnPushed += ReceiveAlarmStatusCachec_OnPushed;
                ReceiveAlarmStatusCachec.MaxNumber = 1000;


                Config = new GasMonitorConfig();
                GasMonitorManager.Chanels = Config.Channels;
                //加载系统配置表单信息

                systenSetFrm.InitForms();
                realDataFrm.InitForms();
                realSeriesFrm.InitForms();
                alarmSetFrm.InitForms();
                //初始化主界面左边树结构
                MainForm.InitForms();
                SerialConfig serialConfig = new SerialConfig()
                {
                    BaudRate = int.Parse(Config.SerialPort.BaudRate),
                    CollectFaultsInternal = int.Parse(Config.SerialPort.CollectFaultsInternal),
                    CollectFaultsNumber   = int.Parse(Config.SerialPort.CollectFaultsNumber),
                    ContinueCollect       = string.IsNullOrEmpty(Config.SerialPort.ContinueCollect) || Config.SerialPort.ContinueCollect.Trim() == "0" ? false : true,
                    DataBits             = int.Parse(Config.SerialPort.DataBits),
                    ModbusType           = "RTU",
                    OffsetInterval       = int.Parse(Config.SerialPort.OffsetInterval),
                    PackMaxSize          = int.Parse(Config.SerialPort.PackMaxSize),
                    ReadTimeout          = int.Parse(Config.SerialPort.ReadTimeout),
                    WriteTimeout         = int.Parse(Config.SerialPort.WriteTimeout),
                    SerialCheck          = (Parity)Enum.Parse(typeof(Parity), Config.SerialPort.CheckBit),
                    SerialPort           = Config.SerialPort.Port,
                    UpdateCycle          = Config.SerialPort.UpdateCycle,
                    RTSEnable            = string.IsNullOrEmpty(Config.SerialPort.RTSEnable) || Config.SerialPort.RTSEnable.Trim() == "0" ? false : true,
                    RSTSendPreKeeyTime   = int.Parse(Config.SerialPort.RSTSendPreKeeyTime),
                    RTSSendAfterKeeyTime = int.Parse(Config.SerialPort.RSTSendPreKeeyTime),
                    Chanels     = Chanels,
                    StopBits    = StopBits.One,
                    ModbusParas = Config.ModbusPara
                };
                switch (Config.SerialPort.StopBit.Trim())
                {
                case "0":
                    serialConfig.StopBits = StopBits.None;
                    break;

                case "1":
                    serialConfig.StopBits = StopBits.One;
                    break;

                case "2":
                    serialConfig.StopBits = StopBits.Two;
                    break;

                case "1.5":
                    serialConfig.StopBits = StopBits.OnePointFive;
                    break;

                default:
                    serialConfig.StopBits = StopBits.One;
                    break;
                }
                ModbusSlave           = new Modbus_Serial(serialConfig);
                ModbusSlave.LogOutput = new Action <string>((s) =>
                {
                    if (logFrm != null && !logFrm.IsDisposed)
                    {
                        logFrm.AddLog(s);
                    }
                });
                //接收到数据,在此处进行解析
                ModbusSlave.ReadDataSuccessed = new Action <List <RealData> >((s) =>
                {
                    try
                    {
                        if (s == null || s.Count <= 0)
                        {
                            return;
                        }
                        string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + DateTime.Now.Millisecond.ToString();
                        string str      = "";
                        foreach (RealData d in s)
                        {
                            if (d.ReadSendByte == null || d.ReadSendByte.Length <= 0)
                            {
                                continue;
                            }
                            str += ModbusConvert.ByteToHexStr(d.ReadSendByte) + " ,";
                            try
                            {
                                ReceiveItem realData    = new ReceiveItem();
                                ReceiveItem alarmData   = new ReceiveItem();
                                ReceiveItem alarmstatus = new ReceiveItem();
                                realData.Id             = d.SlaveId;
                                realData.Name           = d.ParaName;
                                realData.Address        = d.Address;
                                realData.DateTime       = datetime;
                                realData.Value          = "-9999";
                                alarmData.Id            = d.SlaveId;
                                alarmData.Name          = d.ParaName;
                                alarmData.Address       = d.Address;
                                alarmData.DateTime      = datetime;
                                alarmData.Value         = "0.00";
                                alarmstatus.Id          = d.SlaveId;
                                alarmstatus.Name        = d.ParaName;
                                alarmstatus.Address     = d.Address;
                                alarmstatus.DateTime    = datetime;
                                alarmstatus.Value       = "0.00";
                                //获取放大倍数
                                byte[] blxs = new byte[2];
                                Array.Copy(d.ReadSendByte, 12, blxs, 0, 2);
                                float blxsvalue = ModbusConvert.GetUShort(ModbusConvert.Bytes2Ushorts(blxs), 0);
                                blxsvalue       = Convert.ToSingle(Math.Pow(10, blxsvalue));

                                //获取单位
                                byte[] unitb = new byte[2];
                                Array.Copy(d.ReadSendByte, 14, unitb, 0, 2);
                                realData.Unit = (new GasUnit(ModbusConvert.GetUShort(ModbusConvert.Bytes2Ushorts(unitb), 0))).Unit;

                                //获取气体值
                                realData.Address  = d.Address;
                                realData.DateTime = datetime;
                                byte[] vub        = new byte[4];
                                Array.Copy(d.ReadSendByte, 0, vub, 0, 4);
                                realData.Value = (ModbusConvert.GetUInt(ModbusConvert.Bytes2Ushorts(vub), 0) / blxsvalue).ToString("0.00");



                                //获取报警状态
                                alarmstatus.Address  = d.Address;
                                alarmstatus.DateTime = datetime;
                                byte[] alarmstatusb  = new byte[2];
                                Array.Copy(d.ReadSendByte, 4, alarmstatusb, 0, 2);
                                alarmstatus.Value = ModbusConvert.GetUShort(ModbusConvert.Bytes2Ushorts(alarmstatusb), 0).ToString();
                                //获取报警值

                                if (alarmstatus.Value == "0")//无报警
                                {
                                    alarmData.Address  = d.Address;
                                    alarmData.DateTime = datetime;
                                    alarmData.Value    = "0";
                                }
                                else if (alarmstatus.Value == "1")//低报警
                                {
                                    alarmData.Address  = d.Address;
                                    alarmData.DateTime = datetime;
                                    byte[] alarmb      = new byte[4];
                                    Array.Copy(d.ReadSendByte, 16, alarmb, 0, 4);
                                    alarmData.Value = (ModbusConvert.GetUInt(ModbusConvert.Bytes2Ushorts(alarmb), 0) / blxsvalue).ToString("0.00");
                                }
                                else if (alarmstatus.Value == "2")//高报警
                                {
                                    alarmData.Address  = d.Address;
                                    alarmData.DateTime = datetime;
                                    byte[] alarmb      = new byte[4];
                                    Array.Copy(d.ReadSendByte, 20, alarmb, 0, 4);
                                    alarmData.Value = (ModbusConvert.GetUInt(ModbusConvert.Bytes2Ushorts(alarmb), 0) / blxsvalue).ToString("0.00");
                                }
                                alarmData.Id       = realData.Id;
                                alarmData.Unit     = realData.Unit;
                                alarmData.Name     = d.ParaName;
                                alarmData.Address  = d.Address;
                                alarmData.DateTime = datetime;

                                if (realData != null && realData.Value != "-9999")
                                {
                                    realDataFrm.SetChannelStatus();
                                    realDataFrm.SetReadData(realData, alarmData, alarmstatus);
                                    realSeriesFrm.SetReadSeries(realData, alarmData, alarmstatus);
                                    GasMonitorManager.ReceiveCachec.PushItem(realData);
                                    GasMonitorManager.ReceiveAlarmCachec.PushItem(alarmData);
                                    GasMonitorManager.ReceiveAlarmStatusCachec.PushItem(alarmstatus);
                                }
                            }
                            catch
                            {
                                continue;
                            }
                        }
                        logFrm.AddLog(str);
                    }
                    catch (Exception emx)
                    {
                        logFrm.AddLog(emx.Message);
                    }
                });

                GasMonitorManager.Start();
            }
            catch (Exception emx)
            {
                logFrm.AddLog(emx.Message + " ERROR=01");
            }
        }