Esempio n. 1
0
        public bool WriteRemoteIO()
        {
            ErrorCount = 0;
            //check
            if (!isMasterReady)
            {
                return(false);
            }

            //lock (LockObj)
            if (Monitor.TryEnter(LockObj, 5000))
            {
                //set remote status
                try
                {
                    ushort[] dat = new ushort[4] {
                        (ushort)(remoteio.Inport >> 16), (ushort)(remoteio.Inport & 0xFFFF), (ushort)(remoteio.Outport >> 16), (ushort)(remoteio.Outport & 0xFFFF)
                    };
                    master.WriteMultipleRegisters(Address, 124, dat);
                    ErrorCount = 0;
                    Monitor.Exit(LockObj);
                    return(true);
                }
                catch (Exception ex)
                {
                    ErrorCount++;
                    Monitor.Exit(LockObj);
                    return(false);
                }
            }
            return(false);
        }
Esempio n. 2
0
        public void ChangeHeaterState(bool shouldBeStarted)
        {
            SerialPort port = new SerialPort("COM2");

            port.BaudRate = 9600;
            port.DataBits = 8;
            port.Parity   = Parity.None;
            port.StopBits = StopBits.One;
            try
            {
                port.Open();

                IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                byte     slaveId      = 1;
                ushort   startAddress = 100;
                ushort[] registers    = new ushort[] { ((shouldBeStarted)? ushort.Parse("1"): ushort.Parse("0")), 21 };
                master.WriteMultipleRegisters(slaveId, startAddress, registers);
            }
            finally
            {
                if (port != null)
                {
                    if (port.IsOpen)
                    {
                        port.Close();
                    }
                    port.Dispose();
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 控制手爪
        /// </summary>
        /// <param name="positionReq"></param>位置
        /// <param name="speedReq"></param>速度
        /// <param name="forceReq"></param>力
        public static void ModbusSerialRtuMasterWriteRegisters(int positionReq, int speedReq, int forceReq)
        {
            if (positionReq > 100 || positionReq < 0 || speedReq > 100 || speedReq < 0 || forceReq > 100 || forceReq < 0)
            {
                MessageBox.Show("输入参数有误,请重新输入!");
            }
            else
            {
                using (SerialPort port = new SerialPort("COM3"))
                {
                    // configure serial port
                    port.BaudRate = 115200;
                    port.DataBits = 8;
                    port.Parity   = Parity.None;
                    port.StopBits = StopBits.One;
                    port.Open();

                    // create modbus master
                    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                    byte   slaveId           = 9;
                    ushort startAddress      = 1000;
                    int    realSpeedReq      = Convert.ToUInt16(speedReq * 255 / 100);
                    int    realForceReq      = Convert.ToUInt16(forceReq * 255 / 100);
                    ushort realSpeedForceReq = Convert.ToUInt16(realSpeedReq * 256 + realForceReq);
                    ushort realPositionReq   = Convert.ToUInt16(positionReq * 255 / 100);

                    ushort[] registers = new ushort[] { 2304, realPositionReq, realSpeedForceReq };

                    // write three registers
                    master.WriteMultipleRegisters(slaveId, startAddress, registers);
                }
            }
        }
Esempio n. 4
0
        public void setValue <T>(IModbusConfig config, T value)
        {
            lock (locker)
            {
                var toWrite = (ushort)Convert.ChangeType(value, typeof(ushort));

                SerialPort port = new SerialPort(config.portName, config.baudRate);
                if (port.IsOpen)
                {
                    port.Close();
                }
                lock (_locker)
                {
                    port.Open();
                    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
                    master.Transport.ReadTimeout  = 1000;
                    master.Transport.WriteTimeout = 1000;

                    //Запись
                    master.WriteMultipleRegisters(config.device_address, config.register_write_address, new ushort[] { toWrite });

                    port.Close();
                    Thread.Sleep(100);
                }
            }
        }
Esempio n. 5
0
        private static double SingleMeasure(IModbusSerialMaster master, byte IDAddress)
        {
            master.WriteMultipleRegisters(IDAddress, (ushort)32, new ushort[] { 100 });
            bool measuring = true;

            while (measuring)
            {
                ushort[] stateRead = new ushort[1];
                stateRead = master.ReadHoldingRegisters(IDAddress, (ushort)32, 1);
                short stateConnect = BitConverter.ToInt16(new byte[] {
                    BitConverter.GetBytes(stateRead[0])[0],
                    BitConverter.GetBytes(stateRead[0])[1]
                },
                                                          0);
                if (stateConnect <= 0)
                {
                    break;
                }
                System.Threading.Thread.Sleep(1000);
            }
            ushort[] result = new ushort[3];
            result = master.ReadHoldingRegisters(IDAddress, (ushort)58, 6);
            float responseDuration = BitConverter.ToSingle(new byte[] {
                BitConverter.GetBytes(result[2])[0],
                BitConverter.GetBytes(result[2])[1],
                BitConverter.GetBytes(result[2 + 1])[0],
                BitConverter.GetBytes(result[2 + 1])[1]
            },
                                                           0);

            return(responseDuration * 301.0 / 2.0);
        }
Esempio n. 6
0
        /// <summary>
        ///     Write a 32 bit value.
        /// </summary>
        public static void ReadWrite32BitValue()
        {
            using (SerialPort port = new SerialPort(PrimarySerialPortName))
            {
                // configure serial port
                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                var factory = new ModbusFactory();
                IModbusRtuTransport transport = factory.CreateRtuTransport(port);
                IModbusSerialMaster master    = factory.CreateMaster(transport);

                byte   slaveId      = 1;
                ushort startAddress = 1008;
                uint   largeValue   = UInt16.MaxValue + 5;

                ushort lowOrderValue  = BitConverter.ToUInt16(BitConverter.GetBytes(largeValue), 0);
                ushort highOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(largeValue), 2);

                // write large value in two 16 bit chunks
                master.WriteMultipleRegisters(slaveId, startAddress, new ushort[] { lowOrderValue, highOrderValue });

                // read large value in two 16 bit chunks and perform conversion
                ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, 2);
                uint     value     = ModbusUtility.GetUInt32(registers[1], registers[0]);
            }
        }
Esempio n. 7
0
        /// <summary>
        ///     Modbus serial ASCII master write input registers.
        /// </summary>
        private int ModbusSerialAsciiMasterWriteRegisters(int addr, ushort errStatus, ushort[] upperlow)
        {
            // 읽기 주소
            ushort startAddress = 0x6011;

            startAddress += Convert.ToUInt16(addr);

            ushort[] registers = new ushort[3];
            registers[0] = errStatus;
            registers[1] = upperlow[0];
            registers[2] = upperlow[1];

            //ushort registers = 500;
            try
            {
                int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString(mBMSID);
                mMaster.WriteMultipleRegisters(Convert.ToByte(value), startAddress, registers);

                //master.WriteSingleRegister(slaveId, startAddress, registers);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return(0);
        }
Esempio n. 8
0
        private void WriteRegisters(string portName)
        {
            try
            {
                using (var port = GetSerialPort(portName))
                {
                    var factory = new ModbusFactory();
                    IModbusSerialMaster master = factory.CreateRtuMaster(port);

                    master.WriteMultipleRegisters(_slaveID, 0, new ushort[]
                    {
                        (ushort)'M',
                        (ushort)'M',
                        (ushort)'r',
                        (ushort)DateTime.Now.Year,
                        (ushort)DateTime.Now.Month,
                        (ushort)DateTime.Now.Day,
                        (ushort)DateTime.Now.Hour,
                        (ushort)DateTime.Now.Minute,
                        (ushort)DateTime.Now.Second,
                        (ushort)CPU,
                        (ushort)GPU
                    });
                }
            }
            catch { }
        }
Esempio n. 9
0
        public string parameterSeting(byte addr, UInt16 reg_addr, byte reg_lenth, Single value, string type, SerialPort port)
        {
            string result = "Success";
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            master.Transport.ReadTimeout  = 1000;
            master.Transport.WriteTimeout = 1000;
            if (!port.IsOpen)
            {
                try
                {
                    port.Open();
                }
                catch (InvalidOperationException)
                {
                    result = "Port was open";
                }
                catch (UnauthorizedAccessException)
                {
                    result = "Port was open";
                }
                catch (IOException)
                {
                    result = "Port was not found";
                }
            }
            if (result == "Success")
            {
                try
                {
                    byte[] temp_bytes = BitConverter.GetBytes(value);
                    UInt32 temp_int   = 0;
                    temp_int += (uint)temp_bytes[3] << 3 * 8;
                    temp_int += (uint)temp_bytes[2] << 2 * 8;
                    temp_int += (uint)temp_bytes[1] << 1 * 8;
                    temp_int += (uint)temp_bytes[0] << 0 * 8;
                    ushort[] data = { (ushort)temp_int, (ushort)(temp_int >> 16) };
                    master.WriteMultipleRegisters(addr, reg_addr, data);
                }
                catch (InvalidOperationException)
                {
                    result = "Port not Found";
                }
                catch (TimeoutException)
                {
                    result = "Time out";
                }
                catch (Modbus.SlaveException ex)
                {
                    result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                }
            }
            port.Close();
            master.Dispose();
            return(result);
        }
Esempio n. 10
0
 private void ModbusTrasmit(byte slaveId, ushort startAddress, ushort[] numRegister)
 {
     try
     {
         master.WriteMultipleRegisters(slaveId, startAddress, numRegister);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Esempio n. 11
0
        private static int SettingAuton(IModbusSerialMaster master, byte IDAddress)
        {
            int date = portGetCurrentDate();
            int j    = 0;

            byte[]   arr        = BitConverter.GetBytes(date);
            ushort[] nameDevice = new ushort[2];
            for (int i = 0; i < arr.Length; i++)
            {
                nameDevice[j++] = BitConverter.ToUInt16(new byte[] {
                    arr[i],
                    arr[++i]
                }, 0);
            }
            master.WriteMultipleRegisters(IDAddress, (ushort)35, new ushort[] { nameDevice[0], nameDevice[1] });
            master.WriteMultipleRegisters(IDAddress, (ushort)64, new ushort[] { 0, 5, nameDevice[0], nameDevice[1] });
            master.WriteMultipleRegisters(IDAddress, (ushort)69, new ushort[] { 5, 1, 0, 0, 0, 52224, 52428, 52428, 52428, 52428, 52428, 52428, 52428, 2, 999, 20 });
            master.WriteMultipleRegisters(IDAddress, (ushort)67, new ushort[] { 32, 0 });
            return(0);
        }
Esempio n. 12
0
 /// <summary>
 /// 写入由1到123个连续寄存器组成的块。
 /// </summary>
 /// <param name="startAddress"></param>
 /// <param name="data"></param>
 public void WriteMultipleRegisters(ushort startAddress, short[] data)
 {
     Thread.Sleep(Delay_ms);
     try
     {
         CheckInitPort();
         master.WriteMultipleRegisters(slaveID, startAddress, data);
     }
     catch (Exception e)
     {
         throw;
     }
 }
Esempio n. 13
0
        public int writeMultiRegisters(ModbusRegisters regs)
        {
            if (master == null)
            {
                commsts = COMMSTS_UNKONOWN;
                return(RET_INITFAILURE);
            }

            if (port.IsOpen == false)
            {
                commsts = COMMSTS_PORTNOTOPEN;
                return(RET_INITFAILURE);
            }

            lock (locker)
            {
                try
                {
                    for (int i = 0; i < regs.numRegisters; i++)
                    {
                        regs.values[i] = regs.stReg[i].value;
                    }

                    master.WriteMultipleRegisters(regs.slaveid, regs.startAddress, regs.values);
                }
                catch (TimeoutException ex)
                {
                    LogClass.GetInstance().WriteLogFile("WriteMultipleRegisters Timeout:" + port.WriteTimeout.ToString());
                    //MessageBox.Show("Serial Port Write Timeout:" + port.WriteTimeout.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    if (rtycnt++ < MAX_RETYR_COUNT)
                    {
                        return(RET_TIMEOUT);
                    }
                    else
                    {
                        commsts = COMMSTS_FAILURE;
                        return(RET_COMMERROR);
                    }
                }
                catch (Exception ex)
                {
                    LogClass.GetInstance().WriteExceptionLog(ex);
                    //MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    commsts = COMMSTS_FAILURE;
                    return(RET_FAILURE);
                }
            }
            rtycnt  = 0;
            commsts = COMMSTS_NORMAL;
            return(RET_OK);
        }
Esempio n. 14
0
 public void WriteMultipleRegisters(ushort startAddress, short[] data)
 {
     Thread.Sleep(delayms);
     try
     {
         CheckInitPort();
         //Global.MBMutex.WaitOne();
         master.WriteMultipleRegisters(slaveID, startAddress, data);
         //Global.MBMutex.ReleaseMutex();
     }
     catch (Exception e)
     {
         //Global.MBMutex.ReleaseMutex();
     }
 }
Esempio n. 15
0
 //takes subset of surface register array and writes it to ROV register array
 private void WriteRegisters(int start, int n)
 {
     ushort[] subset = new ushort[n];
     for (int i = 0; i < n; i++)
     {
         subset[i] = registers[start + i];
     }
     if (serialPort.IsOpen && isConnected)
     {
         try
         {
             modbus.WriteMultipleRegisters(1, (ushort)start, subset);
         }
         catch { isConnected = false; }
     }
 }
Esempio n. 16
0
        public void writeMultiRegisters(ModbusRegisters regs)
        {
            if (master == null)
            {
                return;
            }

            lock (locker)
            {
                for (int i = 0; i < regs.numRegisters; i++)
                {
                    regs.values[i] = regs.stReg[i].value;
                }

                master.WriteMultipleRegisters(regs.slaveid, regs.startAddress, regs.values);
            }
        }
Esempio n. 17
0
        private static int Authenticate(IModbusSerialMaster master, byte IDAddress)
        {
            string pass = "******";

            byte[]   passBytes  = Encoding.ASCII.GetBytes(pass);
            ushort[] passUShort = new ushort[8];
            int      j          = 0;

            for (int i = 0; i < passBytes.Length; i++)
            {
                passUShort[j++] = BitConverter.ToUInt16(new byte[] {
                    passBytes[i],
                    (i + 1 < passBytes.Length) ? passBytes[++i] : (byte)0
                }, 0);
            }
            master.WriteMultipleRegisters(IDAddress, (ushort)1, passUShort);
            return(0);
        }
Esempio n. 18
0
        private void WritePackage()
        {
            try
            {
                System.Threading.Thread.Sleep(10000);
                DataCheck();
                if ((GlobalPramas.PWM1_Cycle < GlobalPramas.PWM1_Duty) || (GlobalPramas.PWM2_Cycle < GlobalPramas.PWM2_Duty))
                {
                    MessageBox.Show("Please check the PWM Set Value");
                }
                if ((GlobalPramas.PWM1_Cycle >= GlobalPramas.PWM1_Duty) && (GlobalPramas.PWM2_Cycle >= GlobalPramas.PWM2_Duty))
                {
                    GlobalPramas.DataWrite[0]  = Convert.ToUInt16(GlobalPramas.AO_Ch1_Value);
                    GlobalPramas.DataWrite[1]  = Convert.ToUInt16(GlobalPramas.AO_Ch2_Value);
                    GlobalPramas.DataWrite[2]  = Convert.ToUInt16(GlobalPramas.AO_Ch3_Value);
                    GlobalPramas.DataWrite[3]  = Convert.ToUInt16(GlobalPramas.AO_Ch4_Value);
                    GlobalPramas.DataWrite[4]  = GlobalPramas.DO1_Value;
                    GlobalPramas.DataWrite[5]  = GlobalPramas.DO1_Value;
                    GlobalPramas.DataWrite[6]  = GlobalPramas.DO1_Value;
                    GlobalPramas.DataWrite[7]  = GlobalPramas.DO1_Value;
                    GlobalPramas.DataWrite[8]  = GlobalPramas.PWM1_Cycle;
                    GlobalPramas.DataWrite[9]  = GlobalPramas.PWM1_Duty;
                    GlobalPramas.DataWrite[10] = GlobalPramas.PWM2_Cycle;
                    GlobalPramas.DataWrite[11] = GlobalPramas.PWM2_Duty;
                    GlobalPramas.DataWrite[12] = GlobalPramas.Start_Comm;
                    GlobalPramas.DataWrite[13] = GlobalPramas.Stop_Comm;
                    GlobalPramas.DataWrite[14] = Convert.ToUInt16(GlobalPramas.SetValue);
                }
                //create modbus master
                // IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(Serial_Params.my_serialPort);

                //配置参数
                master.Transport.ReadTimeout             = Serial_Params.ReTimeOut; //读取串口超时时间  1000ms
                master.Transport.WriteTimeout            = 1000;                    //写入串口超时时间 1000ms
                master.Transport.Retries                 = 3;                       //重试间隔次数 3次
                master.Transport.WaitToRetryMilliseconds = Serial_Params.DelayTime; //重试时间间隔  250ms
                master.WriteMultipleRegisters(MBConfig_Params.Slave_ID, MBConfig_Params.Start_Addr, GlobalPramas.DataWrite);
                //master.WriteSingleRegister(MBConfig_Params.Slave_ID, MBConfig_Params.Start_Addr, GlobalPramas.DataWrite[0]);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 19
0
        private static int AutonDeviceConnect(IModbusSerialMaster master, string deviceName, byte IDAddress)
        {
            ushort[] stateM = new ushort[1];
            stateM = master.ReadHoldingRegisters(IDAddress, (ushort)4113, 1);
            short state = BitConverter.ToInt16(new byte[] {
                BitConverter.GetBytes(stateM[0])[0],
                BitConverter.GetBytes(stateM[0])[1]
            },
                                               0);

            if (state > 0)
            {
                return(1);
            }

            byte[]   deviceNameBytes  = Encoding.ASCII.GetBytes(deviceName);
            ushort[] deviceNameUShort = new ushort[8];
            int      j = 0;

            for (int i = 0; i < deviceNameBytes.Length; i++)
            {
                deviceNameUShort[j++] = BitConverter.ToUInt16(new byte[] {
                    deviceNameBytes[i],
                    deviceNameBytes[++i]
                }, 0);
            }
            master.WriteMultipleRegisters(IDAddress, (ushort)4112, deviceNameUShort);
            System.Threading.Thread.Sleep(1000);
            for (int i = 0; i < 30; i++)
            {
                stateM = master.ReadHoldingRegisters(IDAddress, (ushort)4113, 1);
                state  = BitConverter.ToInt16(new byte[] {
                    BitConverter.GetBytes(stateM[0])[0],
                    BitConverter.GetBytes(stateM[0])[1]
                }, 0);
                if (state == 0)
                {
                    break;
                }
                System.Threading.Thread.Sleep(1000);
            }
            return(0);
        }
Esempio n. 20
0
        /// <summary>
        /// Simple Modbus serial RTU master write holding registers example.
        /// </summary>
        public static void ModbusSerialRtuMasterWriteRegisters()
        {
            using (SerialPort port = new SerialPort("COM1"))
            {
                // configure serial port
                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                // create modbus master
                IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                byte     slaveId      = 1;
                ushort   startAddress = 100;
                ushort[] registers    = new ushort[] { 1, 2, 3 };

                // write three registers
                master.WriteMultipleRegisters(slaveId, startAddress, registers);
            }
        }
Esempio n. 21
0
        private void WriteRegisters(ushort startAddress, float registerValue)
        {
            CheckPort();

            try
            {
                if (!port.IsOpen)
                {
                    port.Open();
                }
                IModbusSerialMaster master = ModbusSerialMaster.CreateAscii(port);
                var    registers           = new ushort[4];
                byte[] bytereg             = BitConverter.GetBytes(registerValue);
                registers[0] = BitConverter.ToUInt16(bytereg, 0);
                registers[1] = BitConverter.ToUInt16(bytereg, 2);

                master.WriteMultipleRegisters(slaveId, startAddress, registers);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 22
0
        private void WriteRegisters(Dictionary <string, float> sensorData)
        {
            try
            {
                using (var port = GetSerialPort())
                {
                    var factory = new ModbusFactory();
                    IModbusSerialMaster master = factory.CreateRtuMaster(port);

                    master.WriteMultipleRegisters(_slaveID, 0, new ushort[]
                    {
                        (ushort)'M',
                        (ushort)'M',
                        (ushort)'r',
                        (ushort)DateTime.Now.Year,
                        (ushort)DateTime.Now.Month,
                        (ushort)DateTime.Now.Day,
                        (ushort)DateTime.Now.Hour,
                        (ushort)DateTime.Now.Minute,
                        (ushort)DateTime.Now.Second,
                        (ushort)(sensorData.TryGetValue(_cpuSensorName, out var cpuValue)?cpuValue: 0f),
                        (ushort)(sensorData.TryGetValue(_gpuSensorName, out var gpuValue)?gpuValue: 0f)
                    });
                }
Esempio n. 23
0
        public static void ModbusSerialRtuMasterWriteRegisters(ushort a1)
        {
            using (SerialPort port = new SerialPort("COM4"))
            {
                // configure serial port
                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                // create modbus master
                IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                byte     slaveId      = 1;
                ushort   startAddress = 00008;
                ushort[] registers    = new ushort[] { a1 };

                // write three registers
                master.WriteMultipleRegisters(slaveId, startAddress, registers);
                //var values = master.ReadHoldingRegisters(slaveId, startAddress, 14);
                //Console.WriteLine(values);
            }
        }
Esempio n. 24
0
        /// <summary>
        ///     Simple Modbus serial RTU master write holding registers example.
        /// </summary>
        public async void ModbusSerialRtuMasterWriteRegisters()
        {
            using (SerialDevice port = await SerialDevice.FromIdAsync("COM1"))

            {
                // configure serial port

                port.BaudRate = 9600;

                port.DataBits = 8;

                port.Parity = SerialParity.None;

                port.StopBits = SerialStopBitCount.One;

                var adapter = new SerialPortAdapter(port);

                // create modbus master

                IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(adapter);



                byte slaveId = 1;

                ushort startAddress = 100;

                ushort[] registers = new ushort[] { 1, 2, 3 };



                // write three registers

                master.WriteMultipleRegisters(slaveId, startAddress, registers);
            }
        }
Esempio n. 25
0
        public string parameterSeting(byte addr, UInt16 reg_addr, byte reg_lenth, UInt32 value, string type, SerialPort port)
        {
            string result = "Success";
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            master.Transport.ReadTimeout  = 1000;
            master.Transport.WriteTimeout = 1000;
            if (!port.IsOpen)
            {
                try
                {
                    port.Open();
                }
                catch (InvalidOperationException)
                {
                    result = "Port was open";
                }
                catch (UnauthorizedAccessException)
                {
                    result = "Port was open";
                }
                catch (IOException)
                {
                    result = "Port was not found";
                }
            }
            if (result == "Success")
            {
                if (type == "uint16")
                {
                    try
                    {
                        master.WriteSingleRegister(addr, reg_addr, (UInt16)value);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
                else if (type == "uint32")
                {
                    try
                    {
                        ushort[] data = { (ushort)value, (ushort)(value >> 16) };
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
            }

            port.Close();
            master.Dispose();
            //stopwatch.Start();
            //stopwatch.Stop();
            //System.Diagnostics.Debug.WriteLine("modbuswriteTime:" + stopwatch.ElapsedMilliseconds.ToString());
            //stopwatch.Reset();
            return(result);
        }
Esempio n. 26
0
 private static int AutonDeviceDisconnect(IModbusSerialMaster master, byte IDAddress)
 {
     ushort[] nameDevice = { 52224, 52428, 52428, 52428, 52428, 52428, 52428, 52428 };
     master.WriteMultipleRegisters(IDAddress, (ushort)4112, nameDevice);
     return(0);
 }
Esempio n. 27
0
        public string parameterSeting(byte addr, UInt16 reg_addr, byte reg_lenth, String value, string type, SerialPort port)
        {
            string result = "Success";
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            master.Transport.ReadTimeout  = 1000;
            master.Transport.WriteTimeout = 1000;
            if (!port.IsOpen)
            {
                try
                {
                    port.Open();
                }
                catch (InvalidOperationException)
                {
                    result = "Port was open";
                }
                catch (UnauthorizedAccessException)
                {
                    result = "Port was open";
                }
                catch (IOException)
                {
                    result = "Port was not found";
                }
            }
            if (result == "Success")
            {
                if ((type == "uint16") && (reg_lenth == 1))
                {
                    try
                    {
                        master.WriteSingleRegister(addr, reg_addr, Convert.ToUInt16(value));
                    }
                    catch (System.Exception ex)
                    {
                        result = ex.Message;
                    }
                    //catch (InvalidOperationException)
                    //{

                    //    result = "Port not Found";
                    //}
                    //catch (TimeoutException)
                    //{
                    //    result = "Time out";
                    //}
                    //catch (Modbus.SlaveException ex)
                    //{
                    //    result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    //}
                }
                if ((type == "uint32") && (reg_lenth == 2))
                {
                    try
                    {
                        UInt32   Value = Convert.ToUInt32(value);
                        ushort[] data  = { (ushort)Value, (ushort)(Value >> 16) };
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
                if ((type == "float") && (reg_lenth == 2))
                {
                    try
                    {
                        float  Value      = float.Parse(value);
                        byte[] temp_bytes = BitConverter.GetBytes(Value);
                        UInt32 temp_int   = 0;
                        temp_int += (uint)temp_bytes[3] << 3 * 8;
                        temp_int += (uint)temp_bytes[2] << 2 * 8;
                        temp_int += (uint)temp_bytes[1] << 1 * 8;
                        temp_int += (uint)temp_bytes[0] << 0 * 8;
                        ushort[] data = { (ushort)temp_int, (ushort)(temp_int >> 16) };
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
                if ((type == "char") && ((reg_lenth == 8 || (reg_lenth == 16))))  //通常为设置序列号
                {
                    try
                    {
                        ushort[] data = new ushort[value.Length / 2 + 1];
                        int      rest = value.Length % 2;

                        for (int i = 0, j = 0; i < value.Length / 2; i++)
                        {
                            data[i] = (ushort)(value[j + 1] << 8 | value[j]);
                            j      += 2;
                        }
                        if (rest == 0)
                        {
                            data[value.Length / 2] = 0;
                        }
                        else
                        {
                            data[value.Length / 2] = value[value.Length - 1];
                        }
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
            }
            port.Close();
            master.Dispose();
            return(result);
        }
Esempio n. 28
0
        protected override void serialThread()
        {
            BPPacketModbus pckt;

            Byte[] txBuf= new Byte[0];

            if (cDataReceivedDelegate == null)
                throw new Exception("ReceiveDelegate not set!");

            log.Debug("Creating modbus protocol.");
            master = ModbusSerialMaster.CreateRtu(sp);

            log.Debug("Starting infinite receiving loop");
            while (true)
            {
                // Do we need to shutdown the thread?
                if ((shutdownThread == true) &&
                    (packets.Count == 0))
                {
                    log.Debug("Communication thread shutdown");
                    try
                    {
                        sp.Close();
                    }
                    catch (Exception e)
                    {
                        log.Error("Problem closing serial port", e);
                    }
                    return;
                }

                if (packets.Count != 0)
                {
                    log.Debug("New packet on queue to send");
                    lock (packets)
                    {
                        pckt = (BPPacketModbus)packets.Dequeue();
                        if(pckt.Data.Length>0)
                            txBuf = cHeaderSerializer.SerializeData(new object[] { pckt.Data });
                    }

                    try
                    {
                        if (pckt.Data.Length > 0)
                        {
                            log.Debug("Writing packet to modbus");
                            master.WriteMultipleRegisters((byte)100,
                                (ushort)GenAddress((Byte)pckt.LinkId,
                                    (Byte)pckt.BPProtocolHeader.cOperationId),
                                CreateRegisters(txBuf));
                        }
                        else
                        {
                            log.Debug("Reading packet from modbus");
                            master.ReadInputRegisters((byte)100,
                                (ushort)GenAddress((Byte)pckt.LinkId,
                                    (Byte)pckt.BPProtocolHeader.cOperationId),
                                (ushort)pckt.ExpectedLength);
                        }
                    }
                    catch (TimeoutException e)
                    {
                        log.Error("Timeout while writing packet to serial bus", e);
                    }
                    catch (Exception e)
                    {
                        log.Error("Problem writing packet to serial bus, closing serial port and communication thread", e);
                        sp.Close();
                        return;
                    }

                    log.Debug("Resetting state variables");
                    txBuf = new Byte[0];
                }

                // We don't want to hog up whole CPU
                Thread.Sleep(100);
            }
        }
Esempio n. 29
0
 public void WriteUnits(UnitsEnum units)
 {
     master.WriteMultipleRegisters(address, 5301, new ushort[] { (ushort)units });
 }
Esempio n. 30
0
 public int ModbusSerialAsciiWriteMultipleRegisters(IModbusSerialMaster master, byte slaveId, ushort startAddress, ushort[] data)
 {
     master.WriteMultipleRegisters(slaveId, startAddress, data);
     return(0);
 }
Esempio n. 31
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);
        }