예제 #1
0
        public void Connection()
        {
            busRtuClient?.Close();
            busRtuClient = new ModbusRtu(Station);
            busRtuClient.AddressStartWithZero = true;

            busRtuClient.IsStringReverse = false;
            try
            {
                busRtuClient.SerialPortInni(sp =>
                {
                    sp.PortName = serialPort.PortName;
                    sp.BaudRate = serialPort.BaudRate;
                    sp.DataBits = serialPort.DataBits;
                    sp.StopBits = serialPort.StopBits;
                    sp.Parity   = serialPort.Parity;
                });
                busRtuClient.Open();
                IsConnected = true;
            }
            catch (TimeoutException ex)
            {
                EventscadaException?.Invoke(this.GetType().Name, ex.Message);
            }
        }
예제 #2
0
        public CameraController(VM_MSConfig msConfig)
        {
            Config = msConfig;

            busRtuClient?.Close();
            busRtuClient = new ModbusRtu(Config.Station);
            busRtuClient.AddressStartWithZero = Config.DDFlag;
            busRtuClient.IsStringReverse      = Config.ComFlag;
            try
            {
                busRtuClient.SerialPortInni(sp =>
                {
                    sp.PortName = Config.Com;
                    sp.BaudRate = Config.BaudRate;
                    sp.DataBits = Config.DataBits;
                    sp.StopBits = Config.StopBits == 0 ? System.IO.Ports.StopBits.None : (Config.StopBits == 1 ? System.IO.Ports.StopBits.One : System.IO.Ports.StopBits.Two);
                    sp.Parity   = Config.Parity == 0 ? System.IO.Ports.Parity.None : (Config.Parity == 1 ? System.IO.Ports.Parity.Odd : System.IO.Ports.Parity.Even);
                });
                busRtuClient.Open();
                LogHelper.WriteInfoLog("busRtuClient Open  Succeed!");
            }
            catch (Exception ex)
            {
                LogHelper.WriteInfoLog(ex.Message);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!int.TryParse(textBox2.Text, out int baudRate))
            {
                MessageBox.Show(DemoUtils.BaudRateInputWrong);
                return;
            }

            if (!int.TryParse(textBox16.Text, out int dataBits))
            {
                MessageBox.Show(DemoUtils.DataBitsInputWrong);
                return;
            }

            if (!int.TryParse(textBox17.Text, out int stopBits))
            {
                MessageBox.Show(DemoUtils.StopBitInputWrong);
                return;
            }


            if (!byte.TryParse(textBox15.Text, out byte station))
            {
                MessageBox.Show("Station input wrong!");
                return;
            }

            busRtuClient?.Close( );
            busRtuClient = new ModbusRtu(station);
            busRtuClient.AddressStartWithZero = checkBox1.Checked;


            ComboBox2_SelectedIndexChanged(null, new EventArgs( ));
            busRtuClient.IsStringReverse = checkBox3.Checked;


            try
            {
                busRtuClient.SerialPortInni(sp =>
                {
                    sp.PortName = comboBox3.Text;
                    sp.BaudRate = baudRate;
                    sp.DataBits = dataBits;
                    sp.StopBits = stopBits == 0 ? System.IO.Ports.StopBits.None : (stopBits == 1 ? System.IO.Ports.StopBits.One : System.IO.Ports.StopBits.Two);
                    sp.Parity   = comboBox1.SelectedIndex == 0 ? System.IO.Ports.Parity.None : (comboBox1.SelectedIndex == 1 ? System.IO.Ports.Parity.Odd : System.IO.Ports.Parity.Even);
                });
                busRtuClient.RtsEnable = checkBox5.Checked;
                busRtuClient.Open( );

                button2.Enabled = true;
                button1.Enabled = false;
                panel2.Enabled  = true;

                userControlReadWriteOp1.SetReadWriteNet(busRtuClient, "100", false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// 初始化modbusrtu对象
        /// </summary>
        private static void InitModbusRtu()
        {
            if (rtu != null)
            {
                if (rtu.IsOpen())
                    rtu.Close();
            }
            else
            {
                rtu = new ModbusRtu();
            }
            try
            {
                rtu.Station = _station;
                rtu.SerialPortInni(sp =>
                {
                    sp.PortName = _com;
                    sp.BaudRate = _baudRate;
                    sp.DataBits = _dataBit;
                    sp.StopBits = _stopBits;
                    sp.Parity = _parity;
                    sp.ReadTimeout = 500;
                    sp.WriteTimeout = 500;
                });
                // rtu.Open(); // 打开
            }
            catch (Exception ex)
            {
                MsgChannl.SendMsg(ex.Message);
            }

        }
예제 #5
0
        private void WriteExample( )
        {
            #region WriteExample2

            ModbusRtu modbus = new ModbusRtu( );   // 实例化
            // 此处忽略初始化
            // modbus.SerialPortInni( "COM3" );

            // 假设100存储了short的报警,101,102存储了float的温度,103,104存储了int的产量
            byte[] buffer = new byte[10];
            modbus.ByteTransform.TransByte((short)1).CopyTo(buffer, 0);
            modbus.ByteTransform.TransByte(123.456f).CopyTo(buffer, 2);
            modbus.ByteTransform.TransByte(45678922).CopyTo(buffer, 6);

            OperateResult write = modbus.Write("100", buffer);
            if (write.IsSuccess)
            {
                // success
            }
            else
            {
                // failed
            }


            #endregion
        }
예제 #6
0
        private void ReadExample( )
        {
            #region ReadExample2

            ModbusRtu modbus = new ModbusRtu( );   // 实例化
            // 此处忽略初始化
            // modbus.SerialPortInni( "COM3" );

            // 假设100存储了short的报警,101,102存储了float的温度,103,104存储了int的产量
            OperateResult <byte[]> read = modbus.Read("100", 5);
            if (read.IsSuccess)
            {
                // 共计10个字节的结果内容
                short alarm   = modbus.ByteTransform.TransInt16(read.Content, 0);
                float temp    = modbus.ByteTransform.TransSingle(read.Content, 2);
                int   product = modbus.ByteTransform.TransInt32(read.Content, 6);
            }
            else
            {
                // failed
            }


            #endregion
        }
예제 #7
0
        public void connect()
        {
            if (!int.TryParse(config.botelv, out int baudRate))
            {
                MessageBox.Show(DemoUtils.BaudRateInputWrong);
                return;
            }

            if (!int.TryParse(config.shujuwei, out int dataBits))
            {
                MessageBox.Show(DemoUtils.DataBitsInputWrong);
                return;
            }

            if (!int.TryParse(config.tingzhiwei, out int stopBits))
            {
                MessageBox.Show(DemoUtils.StopBitInputWrong);
                return;
            }


            if (!byte.TryParse(config.zhanhao, out byte station))
            {
                MessageBox.Show("Station input wrong!");
                return;
            }

            busRtuClient?.Close();
            busRtuClient = new ModbusRtu(station);

            busRtuClient.AddressStartWithZero = config.dataFromZero;

            busRtuClient.IsStringReverse = config.stringReverse;

            try
            {
                busRtuClient.SerialPortInni(sp =>
                {
                    sp.PortName = config.COM_Name;
                    sp.BaudRate = baudRate;
                    sp.DataBits = dataBits;
                    sp.StopBits = stopBits == 0 ? System.IO.Ports.StopBits.None : (stopBits == 1 ? System.IO.Ports.StopBits.One : System.IO.Ports.StopBits.Two);
                    sp.Parity   = config.checkInfo == 0 ? System.IO.Ports.Parity.None : (config.checkInfo == 1 ? System.IO.Ports.Parity.Odd : System.IO.Ports.Parity.Even);
                });
                busRtuClient.Open();

                // button2.Enabled = true;
                // button1.Enabled = false;
                //panel2.Enabled = true;
                //userControlCurve1.ReadWriteNet = busRtuClient;
            }
            catch (Exception ex)
            {
                MessageBox.Show("串口打开失败!!");
                MessageBox.Show(ex.Message);
            }
        }
예제 #8
0
        private void btnCom_Click(object sender, EventArgs e)
        {
            if (IsOpen)
            {
                try
                {
                    busRtuClient.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                btnCom.Text = "打开串口";
                picComStatus.BackgroundImage = Properties.Resources.redlight;
                IsOpen = false;
            }
            else
            {
                busRtuClient?.Close();
                busRtuClient = new ModbusRtu();


                busRtuClient.AddressStartWithZero = checkBox1.Checked;


                ComboBox2_SelectedIndexChanged(null, new EventArgs());
                busRtuClient.IsStringReverse = checkBox3.Checked;


                try
                {
                    busRtuClient.SerialPortInni(sp =>
                    {
                        sp.PortName = drpComList.SelectedItem.ToString();;
                        sp.BaudRate = Convert.ToInt32(drpBaudRate.SelectedItem.ToString());
                        sp.DataBits = Convert.ToInt32(drpDataBits.SelectedItem.ToString());
                        sp.StopBits = (StopBits)Convert.ToInt32(drpStopBits.SelectedItem.ToString());
                        sp.Parity   = (Parity)Convert.ToInt32(drpParity.SelectedIndex.ToString());
                    });
                    busRtuClient.Open();
                    btnCom.Text = "关闭串口";
                    picComStatus.BackgroundImage = Properties.Resources.greenlight;
                }
                catch (Exception ex)
                {
                    btnCom.Text = "打开串口";
                    picComStatus.BackgroundImage = Properties.Resources.redlight;
                    MessageBox.Show(ex.Message);
                }

                IsOpen = true;
            }



            // busRtuClient?.Close();
        }
예제 #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (!int.TryParse(textBox2.Text, out int baudRate))
            {
                MessageBox.Show("波特率输入错误!");
                return;
            }

            if (!int.TryParse(textBox16.Text, out int dataBits))
            {
                MessageBox.Show("数据位输入错误!");
                return;
            }

            if (!int.TryParse(textBox17.Text, out int stopBits))
            {
                MessageBox.Show("停止位输入错误!");
                return;
            }


            if (!byte.TryParse(textBox15.Text, out byte station))
            {
                MessageBox.Show("站号输入不正确!");
                return;
            }

            busRtuClient?.Close( );
            busRtuClient = new ModbusRtu(station);
            busRtuClient.AddressStartWithZero = checkBox1.Checked;
            busRtuClient.IsMultiWordReverse   = checkBox2.Checked;
            busRtuClient.IsStringReverse      = checkBox3.Checked;


            try
            {
                busRtuClient.SerialPortInni(sp =>
                {
                    sp.PortName = textBox1.Text;
                    sp.BaudRate = baudRate;
                    sp.DataBits = dataBits;
                    sp.StopBits = stopBits == 0 ? System.IO.Ports.StopBits.None : (stopBits == 1 ? System.IO.Ports.StopBits.One : System.IO.Ports.StopBits.Two);
                    sp.Parity   = comboBox1.SelectedIndex == 0 ? System.IO.Ports.Parity.None : (comboBox1.SelectedIndex == 1 ? System.IO.Ports.Parity.Odd : System.IO.Ports.Parity.Even);
                });
                busRtuClient.Open( );

                button2.Enabled = true;
                button1.Enabled = false;
                panel2.Enabled  = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #10
0
파일: DevicePlc.cs 프로젝트: Gz1d/Gz
        /// <summary>
        /// 停止
        /// </summary>
        public override void DoStop()
        {
            try
            {
                this.isClose = true;
                foreach (LD.Config.PlcTypeItem item in this.config.PlcTypeItems)
                {
                    if (!item.IsActive || !item.IsConnected)
                    {
                        continue;
                    }

                    switch (item.DevType)
                    {
                    case Common.DeviceType.S1200:
                    case Common.DeviceType.S1500:
                    case Common.DeviceType.S200:
                    case Common.DeviceType.S200Smart:
                    case Common.DeviceType.S300:
                    case Common.DeviceType.S400:
                        SiemensS7Net plc = (SiemensS7Net)item.Tag;
                        plc.ConnectClose();
                        break;

                    case Common.DeviceType.ModbusTcp:
                        ModbusTcpNet mdTcp = (ModbusTcpNet)item.Tag;
                        mdTcp.ConnectClose();
                        break;

                    case Common.DeviceType.ModbusRtu:
                        ModbusRtu mdRtu = (ModbusRtu)item.Tag;
                        mdRtu.Close();
                        break;

                    default:
                        break;
                    }

                    item.IsConnected = false;
                }

                foreach (LD.Config.PlcDataItem plc in this.config.PlcDataItems)
                {
                    plc.PropertyChanged -= new PropertyChangedEventHandler(plc_PropertyChanged);
                    plc.PropertyChanged -= new PropertyChangedEventHandler(Ui.frmSiemens.Instance.plc_PropertyChanged);
                }

                this.PlcValueChanged -= new LD.Config.PlcValueChangeEventHandler(PlcClient_PlcValueChanged);
            }
            catch (Exception ex)
            {
                throw new StopException(this.ToString(), ex.ToString());
            }
        }
예제 #11
0
        // 写设备的值
        public bool  WriteValue(Common.PlcDevice plcDevice, object value)
        {
            bool IsOk = false;

            try
            {
                Config.PlcDataItem devData = this.GetPlcDataItem(plcDevice);
                Config.PlcTypeItem devType = this.GetPlcTypeItem(devData.DeviceName);

                switch (devType.DevType)
                {
                //Keyence
                case Common.DeviceType.Keyence:
                    KeyenceMcNet kPlcClient = (KeyenceMcNet)devType.Tag;
                    IsOk = this.WriteSieTcpValue(devType, devData, kPlcClient, value);
                    break;

                //Melsec
                case Common.DeviceType.Qseries:
                    MelsecMcNet mPlcClient = (MelsecMcNet)devType.Tag;
                    IsOk = this.WriteSieTcpValue(devType, devData, mPlcClient, value);
                    break;


                case Common.DeviceType.S1200:
                case Common.DeviceType.S300:
                case Common.DeviceType.S400:
                case Common.DeviceType.S1500:
                case Common.DeviceType.S200Smart:
                case Common.DeviceType.S200:
                    SiemensS7Net sPlcClient = (SiemensS7Net)devType.Tag;
                    IsOk = this.WriteSieTcpValue(devType, devData, sPlcClient, value);
                    break;

                case Common.DeviceType.ModbusTcp:
                    ModbusTcpNet mTcpClient = (ModbusTcpNet)devType.Tag;
                    IsOk = this.WriteModTcpValue(devType, devData, mTcpClient, value);
                    break;

                case Common.DeviceType.ModbusRtu:
                    ModbusRtu mRtuClinet = (ModbusRtu)devType.Tag;
                    IsOk = this.WriteModRtuValue(devType, devData, mRtuClinet, value);
                    break;

                default:
                    break;
                }
            }
            catch { }
            return(IsOk);
        }
예제 #12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="portName">串口号</param>
 /// <param name="baudRate">波特率</param>
 /// <param name="station">站点号</param>
 /// <param name="isAddressStartWithZero"></param>
 /// <param name="dataBits">数据位</param>
 /// <param name="stopBits">停止位</param>
 /// <param name="parity">奇偶校验</param>
 /// <returns></returns>
 public ModbusRtuClient(string portName, int baudRate, byte station, bool isAddressStartWithZero = true, int dataBits = 8, int stopBits = 0, int parity = 0)
 {
     modbus = new ModbusRtu();
     modbus.SerialPortInni(sp =>
     {
         sp.PortName = portName;
         sp.BaudRate = baudRate;
         sp.DataBits = dataBits;
         sp.StopBits = stopBits == 0 ? System.IO.Ports.StopBits.None : (stopBits == 1 ? System.IO.Ports.StopBits.One : System.IO.Ports.StopBits.Two);
         sp.Parity   = parity == 0 ? System.IO.Ports.Parity.None : (parity == 1 ? System.IO.Ports.Parity.Odd : System.IO.Ports.Parity.Even);
     });
     modbus.Station = station;
     modbus.AddressStartWithZero = isAddressStartWithZero;
     modbus.IsStringReverse      = false;
 }
예제 #13
0
        // 读设备的值
        public object ReadValue(Common.PlcDevice plcDevice)
        {
            Config.PlcDataItem devData = this.GetPlcDataItem(plcDevice);
            if (devData == null)
            {
                return(null);
            }
            Config.PlcTypeItem devType = this.GetPlcTypeItem(devData.DeviceName);
            switch (devType.DevType)
            {
            //Keyence
            case Common.DeviceType.Keyence:
                KeyenceMcNet kPlcClient = (KeyenceMcNet)devType.Tag;
                return(this.ReadSieTcpValue(devType, devData, kPlcClient));

            //Melsec 三菱PLC
            case Common.DeviceType.Qseries:
                MelsecMcNet mPlcClient = (MelsecMcNet)devType.Tag;
                return(this.ReadSieTcpValue(devType, devData, mPlcClient));

            //Siemens
            case Common.DeviceType.S1200:
            case Common.DeviceType.S300:
            case Common.DeviceType.S400:
            case Common.DeviceType.S1500:
            case Common.DeviceType.S200Smart:
            case Common.DeviceType.S200:
                SiemensS7Net sPlcClient = (SiemensS7Net)devType.Tag;
                return(this.ReadSieTcpValue(devType, devData, sPlcClient));

            case Common.DeviceType.ModbusTcp:
                ModbusTcpNet mTcpClient = (ModbusTcpNet)devType.Tag;
                return(this.ReadModTcpValue(devType, devData, mTcpClient));

            case Common.DeviceType.ModbusRtu:
                ModbusRtu mRtuClinet = (ModbusRtu)devType.Tag;
                return(this.ReadModRtuValue(devType, devData, mRtuClinet));

            default:
                return(null);
            }
        }
예제 #14
0
        // 读设备的值
        public object ReadValue(string itemName)
        {
            //try
            //{
            Config.PlcDataItem devData = this.GetPlcDataItem(itemName);
            Config.PlcTypeItem devType = this.GetPlcTypeItem(devData.DeviceName);

            switch (devType.DevType)
            {
            case Common.DeviceType.S1200:
            case Common.DeviceType.S300:
            case Common.DeviceType.S400:
            case Common.DeviceType.S1500:
            case Common.DeviceType.S200Smart:
            case Common.DeviceType.S200:
                SiemensS7Net sPlcClient = (SiemensS7Net)devType.Tag;
                return(this.ReadSieTcpValue(devType, devData, sPlcClient));

            //break;

            case Common.DeviceType.ModbusTcp:
                ModbusTcpNet mTcpClient = (ModbusTcpNet)devType.Tag;
                return(this.ReadModTcpValue(devType, devData, mTcpClient));

            //break;

            case Common.DeviceType.ModbusRtu:
                ModbusRtu mRtuClinet = (ModbusRtu)devType.Tag;
                return(this.ReadModRtuValue(devType, devData, mRtuClinet));

            //break;

            default:
                return(null);
                //break;
            }
            //}
            //catch (Exception ex)
            //{

            //}
        }
예제 #15
0
        //Lettura dati da inverter tramite RS485 utilizzando un convertirore RS485-Eth con rete di polarizzazione
        public static void Test07()
        {
            ModbusRtu _inverter = new ModbusRtu("172.20.48.40", 4001);

            byte[] send     = new byte[6];
            byte   _cmd     = 0x02;
            ushort _strAddr = 0x3001;
            ushort _nr      = 0x80;
            byte   idDevice = 0x02;

            _inverter.sendRequest(idDevice, _cmd, _strAddr, _nr);
            _inverter.ReadModbusMsg();

            _cmd     = 0x02;
            _strAddr = 0x4001;
            _nr      = 0xF0;
            idDevice = 0x02;

            _inverter.sendRequest(idDevice, _cmd, _strAddr, _nr);
            _inverter.ReadModbusMsg();
        }
예제 #16
0
        // 写设备的值
        public bool  WriteValue(string itemName, object value)
        {
            bool IsOK = false;

            try
            {
                Config.PlcDataItem devData = this.GetPlcDataItem(itemName);
                Config.PlcTypeItem devType = this.GetPlcTypeItem(devData.DeviceName);

                switch (devType.DevType)
                {
                case Common.DeviceType.S1200:
                case Common.DeviceType.S300:
                case Common.DeviceType.S400:
                case Common.DeviceType.S1500:
                case Common.DeviceType.S200Smart:
                case Common.DeviceType.S200:
                    SiemensS7Net sPlcClient = (SiemensS7Net)devType.Tag;
                    IsOK = this.WriteSieTcpValue(devType, devData, sPlcClient, value);
                    break;

                case Common.DeviceType.ModbusTcp:
                    ModbusTcpNet mTcpClient = (ModbusTcpNet)devType.Tag;
                    IsOK = this.WriteModTcpValue(devType, devData, mTcpClient, value);
                    break;

                case Common.DeviceType.ModbusRtu:
                    ModbusRtu mRtuClinet = (ModbusRtu)devType.Tag;
                    IsOK = this.WriteModRtuValue(devType, devData, mRtuClinet, value);
                    break;

                default:
                    break;
                }
            }
            catch { }
            return(IsOK);
        }
예제 #17
0
        public static void Lab13()
        {
            bool   _loop = true;
            string _r;

            Serial485 com = new Serial485("COM3", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
            ModbusRtu net = new ModbusRtu("192.168.0.237", 4001);

            com.sendRequest(0x01, 0x03, 0x131, 0x1);
            net.ReadModbusMsg();
//
            net.sendRequest(0x01, 0x03, 0x131, 0x1);
            com.ReadModbusMsg(); // OCCHIO!!! sembra che al messaggio ricevudo venda messo in testa un byte di indirizzo e in coda ricalcolato il CRC!!!



//   Console.WriteLine("Press 1 key to send Request usb->net \n Press 2 to send Request net->usb. \nPress X to exit");
//   while( _loop==true)
//   {
//       _r=Console.ReadLine();
//       switch (_r.ToUpper())
//       {
//           case "X":
//             _loop=false;
//             break;
//           case "1": _loop=false;
//                 com.sendRequest(0x01,0x03,0x131,0x1);
//                break;
//           case "2": _loop=false;
//                 net.sendRequest(0x01,0x03,0x131,0x1);
//                break;
//           default:
//                 Console.WriteLine(_r + "Comando non riconosciuto");
//                 break;
//       }
//    }
            Console.WriteLine("exiting....");
        }
예제 #18
0
        public void ModbusRtuUnitTest( )
        {
            ModbusRtu modbus = new ModbusRtu(1);

            modbus.SerialPortInni("COM2", 9600);

            try
            {
                modbus.Open( );
            }
            catch
            {
                Console.WriteLine("无法连接modbus,将跳过单元测试。等待网络正常时,再进行测试");
                return;
            }

            // 开始单元测试,从coil类型开始测试
            string address = "1200";

            bool[] boolTmp = new bool[] { true, true, false, true, false, true, false };
            Assert.IsTrue(modbus.WriteCoil(address, true).IsSuccess);
            Assert.IsTrue(modbus.ReadCoil(address).Content == true);
            Assert.IsTrue(modbus.WriteCoil(address, boolTmp).IsSuccess);
            bool[] readBool = modbus.ReadCoil(address, (ushort)boolTmp.Length).Content;
            for (int i = 0; i < boolTmp.Length; i++)
            {
                Assert.IsTrue(readBool[i] == boolTmp[i]);
            }

            address = "300";
            // short类型
            Assert.IsTrue(modbus.Write(address, (short)12345).IsSuccess);
            Assert.IsTrue(modbus.ReadInt16(address).Content == 12345);
            short[] shortTmp = new short[] { 123, 423, -124, 5313, 2361 };
            Assert.IsTrue(modbus.Write(address, shortTmp).IsSuccess);
            short[] readShort = modbus.ReadInt16(address, (ushort)shortTmp.Length).Content;
            for (int i = 0; i < readShort.Length; i++)
            {
                Assert.IsTrue(readShort[i] == shortTmp[i]);
            }

            // ushort类型
            Assert.IsTrue(modbus.Write(address, (ushort)51234).IsSuccess);
            Assert.IsTrue(modbus.ReadUInt16(address).Content == 51234);
            ushort[] ushortTmp = new ushort[] { 5, 231, 12354, 5313, 12352 };
            Assert.IsTrue(modbus.Write(address, ushortTmp).IsSuccess);
            ushort[] readUShort = modbus.ReadUInt16(address, (ushort)ushortTmp.Length).Content;
            for (int i = 0; i < ushortTmp.Length; i++)
            {
                Assert.IsTrue(readUShort[i] == ushortTmp[i]);
            }

            // int类型
            Assert.IsTrue(modbus.Write(address, 12342323).IsSuccess);
            Assert.IsTrue(modbus.ReadInt32(address).Content == 12342323);
            int[] intTmp = new int[] { 123812512, 123534, 976124, -1286742 };
            Assert.IsTrue(modbus.Write(address, intTmp).IsSuccess);
            int[] readint = modbus.ReadInt32(address, (ushort)intTmp.Length).Content;
            for (int i = 0; i < intTmp.Length; i++)
            {
                Assert.IsTrue(readint[i] == intTmp[i]);
            }

            // uint类型
            Assert.IsTrue(modbus.Write(address, (uint)416123237).IsSuccess);
            Assert.IsTrue(modbus.ReadUInt32(address).Content == (uint)416123237);
            uint[] uintTmp = new uint[] { 81623123, 91712749, 91273123, 123, 21242, 5324 };
            Assert.IsTrue(modbus.Write(address, uintTmp).IsSuccess);
            uint[] readuint = modbus.ReadUInt32(address, (ushort)uintTmp.Length).Content;
            for (int i = 0; i < uintTmp.Length; i++)
            {
                Assert.IsTrue(readuint[i] == uintTmp[i]);
            }

            // float类型
            Assert.IsTrue(modbus.Write(address, 123.45f).IsSuccess);
            Assert.IsTrue(modbus.ReadFloat(address).Content == 123.45f);
            float[] floatTmp = new float[] { 123, 5343, 1.45f, 563.3f, 586.2f };
            Assert.IsTrue(modbus.Write(address, floatTmp).IsSuccess);
            float[] readFloat = modbus.ReadFloat(address, (ushort)floatTmp.Length).Content;
            for (int i = 0; i < readFloat.Length; i++)
            {
                Assert.IsTrue(floatTmp[i] == readFloat[i]);
            }

            // double类型
            Assert.IsTrue(modbus.Write(address, 1234.5434d).IsSuccess);
            Assert.IsTrue(modbus.ReadDouble(address).Content == 1234.5434d);
            double[] doubleTmp = new double[] { 1.4213d, 1223d, 452.5342d, 231.3443d };
            Assert.IsTrue(modbus.Write(address, doubleTmp).IsSuccess);
            double[] readDouble = modbus.ReadDouble(address, (ushort)doubleTmp.Length).Content;
            for (int i = 0; i < doubleTmp.Length; i++)
            {
                Assert.IsTrue(readDouble[i] == doubleTmp[i]);
            }

            // long类型
            Assert.IsTrue(modbus.Write(address, 123617231235123L).IsSuccess);
            Assert.IsTrue(modbus.ReadInt64(address).Content == 123617231235123L);
            long[] longTmp = new long[] { 12312313123L, 1234L, 412323812368L, 1237182361238123 };
            Assert.IsTrue(modbus.Write(address, longTmp).IsSuccess);
            long[] readLong = modbus.ReadInt64(address, (ushort)longTmp.Length).Content;
            for (int i = 0; i < longTmp.Length; i++)
            {
                Assert.IsTrue(readLong[i] == longTmp[i]);
            }

            // ulong类型
            Assert.IsTrue(modbus.Write(address, 1283823681236123UL).IsSuccess);
            Assert.IsTrue(modbus.ReadUInt64(address).Content == 1283823681236123UL);
            ulong[] ulongTmp = new ulong[] { 21316UL, 1231239127323UL, 1238612361283123UL };
            Assert.IsTrue(modbus.Write(address, ulongTmp).IsSuccess);
            ulong[] readULong = modbus.ReadUInt64(address, (ushort)ulongTmp.Length).Content;
            for (int i = 0; i < readULong.Length; i++)
            {
                Assert.IsTrue(readULong[i] == ulongTmp[i]);
            }

            // string类型
            Assert.IsTrue(modbus.Write(address, "123123").IsSuccess);
            Assert.IsTrue(modbus.ReadString(address, 3).Content == "123123");

            // byte类型
            byte[] byteTmp = new byte[] { 0x4F, 0x12, 0x72, 0xA7, 0x54, 0xB8 };
            Assert.IsTrue(modbus.Write(address, byteTmp).IsSuccess);
            Assert.IsTrue(SoftBasic.IsTwoBytesEquel(modbus.Read(address, 3).Content, byteTmp));

            modbus.Close( );
        }
예제 #19
0
        //modbusRtu read
        private object ReadModRtuValue(Config.PlcTypeItem plctype, Config.PlcDataItem plcdata, ModbusRtu mod)
        {
            try
            {
                //string[] strAdrss = plcdata.Address.Split('.');
                //string Address = strAdrss[0] + "." + Regex.Replace(strAdrss[1], @"^[A-Za-z]+", string.Empty);

                if (plctype == null || !plctype.IsConnected || plcdata == null || mod == null)
                {
                    return(null);
                }

                switch (plcdata.DataType)
                {
                case Common.DataTypes.Bool:    //Coil
                    plcdata.ValueNew = mod.ReadCoil(plcdata.Address).Content;
                    break;

                case Common.DataTypes.Discrete:    //Discrete
                    plcdata.ValueNew = mod.ReadDiscrete(plcdata.Address).Content;
                    break;

                case Common.DataTypes.Short:
                    plcdata.ValueNew = mod.ReadInt16(plcdata.Address).Content;
                    break;

                case Common.DataTypes.Ushort:
                    plcdata.ValueNew = mod.ReadUInt16(plcdata.Address).Content;
                    break;

                case Common.DataTypes.Int:
                    plcdata.ValueNew = mod.ReadInt32(plcdata.Address).Content;
                    break;

                case Common.DataTypes.UInt:
                    plcdata.ValueNew = mod.ReadUInt32(plcdata.Address).Content;
                    break;

                case Common.DataTypes.Long:
                    plcdata.ValueNew = mod.ReadInt64(plcdata.Address).Content;
                    break;

                case Common.DataTypes.ULong:
                    plcdata.ValueNew = mod.ReadUInt64(plcdata.Address).Content;
                    break;

                case Common.DataTypes.Float:
                    plcdata.ValueNew = mod.ReadFloat(plcdata.Address).Content;
                    break;

                case Common.DataTypes.Double:
                    plcdata.ValueNew = mod.ReadDouble(plcdata.Address).Content;
                    break;

                case Common.DataTypes.String:
                    plcdata.ValueNew = mod.ReadString(plcdata.Address, 10).Content;
                    break;

                default:
                    break;
                }
            }
            catch
            {
                //MessageBox.Show(ex.Message);
            }
            return(plcdata.ValueNew);
        }
예제 #20
0
        //modbusRtu write
        private bool  WriteModRtuValue(Config.PlcTypeItem plctype, Config.PlcDataItem plcdata, ModbusRtu mod, object value)
        {
            HslCommunication.OperateResult rlt = new HslCommunication.OperateResult();
            rlt.IsSuccess = false;
            try
            {
                //string[] strAdrss = plcdata.Address.Split('.');
                //string Address = strAdrss[0] + "." + Regex.Replace(strAdrss[1], @"^[A-Za-z]+", string.Empty);

                if (plctype == null || !plctype.IsConnected || plcdata == null || mod == null)
                {
                    return(rlt.IsSuccess);
                }

                switch (plcdata.DataType)
                {
                case Common.DataTypes.Bool:    //Bool
                    rlt = mod.WriteCoil(plcdata.Address, Convert.ToBoolean(value));
                    break;

                case Common.DataTypes.Short:
                    rlt = mod.Write(plcdata.Address, Convert.ToInt16(value));
                    break;

                case Common.DataTypes.Ushort:
                    rlt = mod.Write(plcdata.Address, Convert.ToUInt16(value));
                    break;

                case Common.DataTypes.Int:
                    rlt = mod.Write(plcdata.Address, Convert.ToInt32(value));
                    break;

                case Common.DataTypes.UInt:
                    rlt = mod.Write(plcdata.Address, Convert.ToUInt32(value));
                    break;

                case Common.DataTypes.Long:
                    rlt = mod.Write(plcdata.Address, Convert.ToInt64(value));
                    break;

                case Common.DataTypes.ULong:
                    rlt = mod.Write(plcdata.Address, Convert.ToUInt64(value));
                    break;

                case Common.DataTypes.Float:
                    rlt = mod.Write(plcdata.Address, float.Parse(value.ToString()));
                    break;

                case Common.DataTypes.Double:
                    rlt = mod.Write(plcdata.Address, Convert.ToDouble(value));
                    break;

                case Common.DataTypes.String:
                    rlt = mod.Write(plcdata.Address, Convert.ToString(value));
                    break;

                default: break;
                }
            }
            catch
            {
                //MessageBox.Show(ex.Message);
            }
            return(rlt.IsSuccess);
        }
예제 #21
0
파일: DevicePlc.cs 프로젝트: Gz1d/Gz
        //MudbusRTU设备初始化
        void DoInitMudbusRtu(LD.Config.PlcTypeItem item)
        {
            // 连接
            byte station;

            if (!byte.TryParse(item.Station, out station))
            {
                MessageBox.Show(string.Format("station {0} input is wrong!", item.Station));
                return;
            }

            int baudRate;

            if (!int.TryParse(item.BaudRate.ToString(), out baudRate))
            {
                MessageBox.Show(string.Format("baudRate {0} input wrong!", item.BaudRate));
                return;
            }

            int dataBits;

            if (!int.TryParse(item.DataBits.ToString(), out dataBits))
            {
                MessageBox.Show(string.Format("dataBits {0} input wrong!", item.DataBits));
                return;
            }

            int stopBits;

            if (!int.TryParse(item.StopBits.ToString(), out stopBits))
            {
                MessageBox.Show(string.Format("stopBits {0} input wrong!", item.StopBits));
                return;
            }

            ModbusRtu busRtuClient = new ModbusRtu(station);

            busRtuClient.AddressStartWithZero = item.AddressStartWithZero;
            if (busRtuClient != null)
            {
                busRtuClient.DataFormat = item.DataFormat;
            }
            busRtuClient.IsStringReverse = item.IsStringReverse;
            busRtuClient.SerialPortInni(sp =>
            {
                sp.PortName = item.PortName;
                sp.BaudRate = baudRate;
                sp.DataBits = dataBits;
                sp.StopBits = stopBits == 0 ? StopBits.None : (stopBits == 1 ? StopBits.One : StopBits.Two);
                sp.Parity   = item.Parity;
            });
            item.Tag = busRtuClient;

            busRtuClient.Open();
            if (busRtuClient.IsOpen())
            {
                item.IsConnected = true;
                //Plcs.Add(item.DevName, busRtuClient);
            }
            else
            {
                item.IsConnected = false;
            }
        }