private ushort[] Read(int addr, EUT55ARegisterAddress register, int count)
        {
            ushort[] nValues;

            lock (master)
            {
                nValues = master.ReadHoldingRegisters((byte)addr, (ushort)register, (ushort)count);

                if (Logging == EEthernetLogging.All)
                {
                    logStr.Clear();
                    logStr.Append($"Address : {addr:X2}, Register : {register} -");

                    for (int i = 0; i < nValues.Length; i++)
                    {
                        if (i == 0)
                        {
                            logStr.Append($" {nValues[i]:X4}");
                        }
                        else
                        {
                            logStr.Append($", {nValues[i]:X4}");
                        }
                    }

                    Log(EEthernetLogItem.Receive, logStr.ToString());
                }
            }

            return(nValues);
        }
Beispiel #2
0
        private void buttonRead_Click(object sender, EventArgs e)
        {
            try
            {
                var datas = mMaster?.ReadHoldingRegisters(mSlaveAddress,
                                                          (ushort)(AddressConfig.DensityFactor - 1), 2);
                textboxDensityCoe.Text = UshortToFloat(datas, 0, 3).ToString();

                datas = mMaster?.ReadHoldingRegisters(mSlaveAddress,
                                                      (ushort)(AddressConfig.K0 - 1), 2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void Loop()
        {
            Task.Run(async delegate
            {
                try
                {
                    while (true)
                    {
                        ushort[] registers = _Master.ReadHoldingRegisters(_SlaveId, _StartAddress, _NumberOfPoints);

                        for (int i = 0; i < registers.Length; i++)
                        {
                            if (registers[i] != _Registers[i])
                            {
                                IMsgUart msg = CreateMsg((RegisterTypeByPosition)i, registers);
                                if (msg != null)
                                {
                                    Program.UartService.TreatMessage(msg);
                                }
                            }
                        }

                        _Registers = registers;

                        await Task.Delay(1000);
                    }
                }
                catch (Exception e)
                {
                }
            });
        }
Beispiel #4
0
        /// <summary>
        /// Write a 32 bit value.
        /// </summary>
        public static void ReadWrite32BitValue()
        {
            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
                ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                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]);
            }
        }
Beispiel #5
0
 private void btn_Get_address_Click(object sender, EventArgs e)
 {
     // display the current_address
     availabe_address     = master.ReadHoldingRegisters(0, 0, 1);
     current_address      = availabe_address[0];
     lbl_address.Text     = Convert.ToString(current_address);
     txt_Set_address.Text = lbl_address.Text;
 }
Beispiel #6
0
        private void ModbusMasterWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ModbusSerialMaster modbus = ModbusSerialMaster.CreateRtu(modbusCom);

            while (true)
            {
                Console.WriteLine("Addr = {0}", modbus.ReadHoldingRegisters(1, 104, 1));
                Thread.Sleep(1000);
            }
        }
Beispiel #7
0
 public void pcs_read_AFC(ModbusSerialMaster master)
 {
     try
     {
         master.ReadHoldingRegisters(1, 5395, 2);
     }
     catch (Exception ee)
     {
         Debug.Print(ee.Message);
     }
 }
Beispiel #8
0
        /// <summary>
        ///     Write a 32 bit value.
        /// </summary>
        public async void ReadWriteSerial32BitValue()
        {
            using (SerialDevice device = await SerialDevice.FromIdAsync("device_id"))

            {
                // configure serial port

                device.BaudRate = 9600;

                device.DataBits = 8;

                device.Parity = SerialParity.Even;

                device.StopBits = SerialStopBitCount.One;



                var adapter = new SerialPortAdapter(device);

                // create modbus master

                ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(adapter);



                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]);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Sends a request to addressed slave. Returns read and converted to string answer.
        /// </summary>
        /// <param name="messageFrame">A frame containing an address, a function code and a message to send.</param>
        /// <returns></returns>
        public MessageFrame SendRequest(MessageFrame messageFrame)
        {
            SendMessage(messageFrame);

            ushort[] rawResponse = _master.ReadHoldingRegisters((byte)messageFrame.TargetSlaveAddress,
                                                                (ushort)HoldingRegisterStartAddress, 123 * 2); //Read all available registers.

            var response = new MessageFrame();

            response.ReadMessageFromShorts(rawResponse);

            return(response);
        }
Beispiel #10
0
        private void ModbusWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ModbusSerialMaster ms = ModbusSerialMaster.CreateRtu(modbusCom);

            while (true)
            {
                ushort[] result = ms.ReadHoldingRegisters(1, 1, 10); //read register 1-10 di slave 1
                label1.Text = "EMEGENCY : " + result[1].ToString();  //read to label
                if (result[1] != lastCall)
                {
                    lastCall = result[1];
                    callAPI("DAISHA " + result[1].ToString(), "Location " + result[1].ToString());
                }
                Thread.Sleep(50);
            }
        }
        void timerReadSCom(object sender, ElapsedEventArgs e)
        {
            try
            {
                byte     slaveID      = Convert.ToByte(tbAddr.Text);
                ushort   startAddress = 32;//对应0x20H
                ushort   numofPoints  = 12;
                ushort[] valueTemp    = master.ReadHoldingRegisters(slaveID, startAddress, numofPoints);
                float[]  voltageValue = dataProcess(valueTemp);
                string   hexstr1      = string.Join(",", voltageValue);
                Console.WriteLine(DateTime.Now.ToString() + " =>" + hexstr1);

                voltageArrayCH1[voltageArrayCH1.Length - 1] = voltageValue[0];
                voltageArrayCH2[voltageArrayCH2.Length - 1] = voltageValue[1];
                voltageArrayCH3[voltageArrayCH3.Length - 1] = voltageValue[2];
                voltageArrayCH4[voltageArrayCH4.Length - 1] = voltageValue[3];
                voltageArrayCH5[voltageArrayCH5.Length - 1] = voltageValue[4];
                voltageArrayCH6[voltageArrayCH6.Length - 1] = voltageValue[5];

                Array.Copy(voltageArrayCH1, 1, voltageArrayCH1, 0, voltageArrayCH1.Length - 1);
                Array.Copy(voltageArrayCH2, 1, voltageArrayCH2, 0, voltageArrayCH2.Length - 1);
                Array.Copy(voltageArrayCH3, 1, voltageArrayCH3, 0, voltageArrayCH3.Length - 1);
                Array.Copy(voltageArrayCH4, 1, voltageArrayCH4, 0, voltageArrayCH4.Length - 1);
                Array.Copy(voltageArrayCH5, 1, voltageArrayCH5, 0, voltageArrayCH5.Length - 1);
                Array.Copy(voltageArrayCH6, 1, voltageArrayCH6, 0, voltageArrayCH6.Length - 1);


                if (voltageChart.IsHandleCreated)
                {
                    this.Invoke((MethodInvoker) delegate { UpdateVoltageChart(); });
                }
                else
                {
                    //......
                }
            }
            catch (Exception exception)
            {
                //Connection exception
                //No response from server.
                //The server maybe close the com port, or response timeout.
                if (exception.Source.Equals("System"))
                {
                    Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message);
                }
            }
        }
Beispiel #12
0
        public void ReadParametrsPVT3()
        {
            ModbusSerialMaster master    = ModbusSerialMaster.CreateRtu(serialPort1);
            List <string>      hexBuffer = new List <string>()
            {
            };
            byte   slaveID      = 32;
            ushort startAddress = 258;
            ushort numOfPoints  = 2;

            ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress, numOfPoints);
            Thread.Sleep(30);
            StringBuilder charT = new StringBuilder(Convert.ToString(holding_register[0]));
            StringBuilder charH = new StringBuilder(Convert.ToString(holding_register[1]));

            readBasicDrying.Add(Convert.ToString(charT[0]) + Convert.ToString(charT[1]) + "," + Convert.ToString(charT[2]) + Convert.ToString(charT[3]));
            readBasicDrying.Add(Convert.ToString(charH[0]) + Convert.ToString(charH[1]) + "," + Convert.ToString(charH[2]) + Convert.ToString(charH[3]));
        }
Beispiel #13
0
 public int GetData(out byte[] requestBytes, out byte[] responseBytes, out string errCode)
 {
     errCode = "OK";
     try
     {
         if (_config.SelectedMemType == Memtype.Coils)
         {
             CoilsArray = _modbus.ReadCoils(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         if (_config.SelectedMemType == Memtype.Inputs)
         {
             CoilsArray = _modbus.ReadInputs(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         if (_config.SelectedMemType == Memtype.InputRegisters)
         {
             RegisterArray = _modbus.ReadInputRegisters(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         if (_config.SelectedMemType == Memtype.HoldingRegisters)
         {
             RegisterArray = _modbus.ReadHoldingRegisters(_config.Slaves, _config.StartAddress, _config.Amount);
         }
         return(0);
     }
     catch (SlaveException ex)
     {
         errCode = ex.Message;
         return(1);
     }
     catch (Exception ex)
     {
         if (ex is InvalidOperationException)
         {
             throw;
         }
         errCode = ex.Message;
         return(2);
     }
     finally
     {
         requestBytes  = _modbus.Transport.RequestFrame;
         responseBytes = _modbus.Transport.ResponseFrame;
     }
 }
        public ushort[] ReadHoldingRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
        {
            if (!serialPort.IsOpen)
            {
                Open();
            }

            try
            {
                return(master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints));
            }
            catch (Exception ex)
            {
                AddMessage("Catch exception in function ReadHoldingRegisters(). " + ex.Message,
                           DebugLevel.ExceptionLevel);
                Close();
                return(null);
            }
        }
Beispiel #15
0
        float GetDesTemData(int dataAddress)
        {
            byte   slaveID      = Convert.ToByte(serialPortConfig.BiaoAddressValue);
            ushort startAddress = (ushort)dataAddress;
            ushort numofPoints  = 2; //数据帧中 word 的数量

            ushort[] holdingregister = master.ReadHoldingRegisters(slaveID, startAddress, numofPoints);
            byte[]   bytes           = { };
            for (int i = 0; i < numofPoints * 2; i++)
            {
                byte[] byteTemp;
                byteTemp = BitConverter.GetBytes(holdingregister[i]);
                bytes    = BitConverterHelper.BytesConnect(bytes, byteTemp);
            }
            float val = BitConverterHelper.ToSingle(bytes, 0);

            val = (float)(Math.Round(val, 3));
            return(val);
        }
Beispiel #16
0
 private void timerGetData_Tick(object sender, EventArgs e)
 {
     try
     {
         ushort[] regMW = modbusMasterRTU.ReadHoldingRegisters(1, 0, 8);
         textBox1.Text = regMW[0].ToString();
         textBox2.Text = regMW[1].ToString();
         textBox3.Text = regMW[2].ToString();
         textBox4.Text = regMW[3].ToString();
         textBox5.Text = regMW[4].ToString();
         textBox6.Text = regMW[5].ToString();
         textBox7.Text = regMW[6].ToString();
         textBox8.Text = regMW[7].ToString();
     }
     catch (Exception err)
     {
         MessageBox.Show(err.ToString());
     }
 }
Beispiel #17
0
        /// <summary>
        ///     Modbus serial ASCII master and slave example.
        /// </summary>
        public static void ModbusSerialAsciiMasterReadRegistersFromModbusSlave()
        {
            using (SerialPort masterPort = new SerialPort("COM1"))
                using (SerialPort slavePort = new SerialPort("COM2"))
                {
                    // configure serial ports
                    masterPort.BaudRate = slavePort.BaudRate = 9600;
                    masterPort.DataBits = slavePort.DataBits = 8;
                    masterPort.Parity   = slavePort.Parity = Parity.None;
                    masterPort.StopBits = slavePort.StopBits = StopBits.One;
                    masterPort.Open();
                    slavePort.Open();

                    var slaveAdapter = new SerialPortAdapter(slavePort);
                    // create modbus slave on seperate thread
                    byte        slaveId    = 1;
                    ModbusSlave slave      = ModbusSerialSlave.CreateAscii(slaveId, slaveAdapter);
                    var         listenTask = slave.ListenAsync();

                    var masterAdapter = new SerialPortAdapter(masterPort);
                    // create modbus master
                    ModbusSerialMaster master = ModbusSerialMaster.CreateAscii(masterAdapter);

                    master.Transport.Retries = 5;
                    ushort startAddress = 100;
                    ushort numRegisters = 5;

                    // read five register values
                    ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);

                    for (int i = 0; i < numRegisters; i++)
                    {
                        Console.WriteLine($"Register {(startAddress + i)}={registers[i]}");
                    }
                }

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }
Beispiel #18
0
        public bool SetSlaveMode()
        {
            DetectedSlaveAddress = 0; //redundant,only for notification

            _logger.Log("SetSlaveMode...");

            if (IsSlaveModeActive())
            {
                _logger.Log("Already in slave mode");
                return(true);
            }

            _logger.Log("RX: " + Convertor.ConvertByteArrayToHexString(_recievedPacket));

            if (!Crc16.CheckCrc(_recievedPacket))
            {
                return(false);
            }

            byte[] packetToSend = { _recievedPacket[0], (byte)(_recievedPacket[1] + 0x80), (byte)0x05 };
            Crc16.AddCrc(ref packetToSend);
            if (!SendPacket(packetToSend))
            {
                return(false);
            }

            _logger.Log("TX: " + Convertor.ConvertByteArrayToHexString(packetToSend));

            try
            {
                Thread.Sleep(2000);
                _logger.Log("TX: <ReadHoldingRegisters>");
                _modbusSerial.ReadHoldingRegisters(_recievedPacket[0], RegisterMappingOffsets.PasswordRegisterOffset, 1);
            }
            catch (Exception)
            {
                return(false);
            }
            _logger.Log("SetSlaveMode - OK");
            DetectedSlaveAddress = _recievedPacket[0];
            return(true);
        }
 /// <summary>
 /// Получение данных из регистров
 /// </summary>
 /// <param name="sender">Объект</param>
 /// <param name="e">Событие</param>
 private void GetRegisterToDevice(object sender, EventArgs e)
 {
     _viewRegs.Clear();
     _registers.Clear();
     _clnEllipseFittings.Clear();
     _countTimes += _readWriteConvert;
     ///Вывод всех регистров на экран
     try {
         if (_serial.IsOpen)
         {
             ushort[] result = _master.ReadHoldingRegisters(slaveID, startAddress, numburOfPoints);
             for (int i = 0; i < result.Length; i++)
             {
                 _viewRegs.Add(new ViewRegisterModel {
                     ID = i, Value = result[i].ToString()
                 });
             }
             foreach (var item in _viewRegs)
             {
                 _registers.Add($"Регистр: {item.ID}\t|  {item.Value}");
             }
             SetColorEllipses(result[9], result[10]);
             if (_countTimes % _readWriteConvert == 0)
             {
                 SetPointsSeries(result[0], 0, _volt);
                 SetPointsSeries(result[1], 1, _curr);
                 SetPointsSeries(result[4], 4, _torq);
                 SetPointsSeries(result[2], 2, _external);
                 SetPointsSeries(result[3], 3, _motor);
             }
         }
         else
         {
             _timer.Stop();
         }
     }
     catch (Exception err) {
         _registers.Add(err.Message.ToString());
         _timer.Stop();
     }
 }
        public void Open()
        {
            try
            {
                Console.WriteLine(propertiesSetting.PortName);
                serialPort.Open();
                master = ModbusSerialMaster.CreateRtu(serialPort);
                //ModbusIpMaster modbusIpMaster

                slaveID = 1;
                ushort   startAddress     = 0;
                ushort   numOfPoints      = 10;
                ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress, numOfPoints);

                Console.WriteLine(holding_register);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.WriteLine(ex);
            }
        }
Beispiel #21
0
        public (bool IsError, string Message, Dictionary <short, short> cellsValues) GetValuesWithResult(List <short> cellsAddreses)
        {
            SerialPort serialPort = new SerialPort(); //Create a new SerialPort object.

            serialPort.PortName = "COM1";
            serialPort.BaudRate = 9600;
            serialPort.DataBits = 8;
            serialPort.Parity   = Parity.None;
            serialPort.StopBits = StopBits.One;
            serialPort.Open();
            ModbusSerialMaster master = ModbusSerialMaster.CreateRtu((Modbus.IO.IStreamResource)serialPort);

            byte   slaveID      = 1;
            ushort startAddress = 0;
            ushort numOfPoints  = 1;

            ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress,
                                                                    numOfPoints);
            Console.WriteLine(holding_register);

            return(false, "", null);
        }
Beispiel #22
0
        public string ReadUnitData(ModbusExchangeableUnit unit)
        {
            if (_modbusSerial == null)
            {
                return("Нет подключения");
            }
            try
            {
                List <ushort> readRegisters = new List <ushort>();

                foreach (ModbusDataBlock block in unit.GetReadMap())
                {
                    readRegisters.AddRange(_modbusSerial.ReadHoldingRegisters(SlaveAddress,
                                                                              block.Offset, block.Size));
                }
                unit.SetPropertiesDataFromRegisters(readRegisters.ToArray());
            }
            catch (Exception exception)
            {
                return(exception.Message);
            }
            return("OK");
        }
Beispiel #23
0
        public object ReadVariableAt(ushort address, string typ, ushort regCount)
        {
            var registers = _master.ReadHoldingRegisters(_slaveId, address, regCount);
            var packRegs  = GetPackRegs(registers);
            var packBytes = GetPackBytes(packRegs);

            object variable;

            if (typ == "UInt16")
            {
                variable = BitConverter.ToUInt16(packBytes);
            }
            else if (typ == "Single")
            {
                variable = BitConverter.ToSingle(packBytes);
            }
            else
            {
                throw new ArgumentException("Not supported type!");
            }

            return(variable);
        }
Beispiel #24
0
        private void timer4_Tick(object sender, EventArgs e)
        {
            try
            {
                //serial_port = new SerialPort("COM" + textBox16.Text);

                // configure serial port
                serial_port.BaudRate = 57600;
                serial_port.DataBits = 8;
                serial_port.Parity   = Parity.None;
                serial_port.StopBits = StopBits.One;
                serial_port.Open();

                ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serial_port);
                master.Transport.ReadTimeout = Convert.ToInt32(textBox12.Text);
                //master.Transport.WriteTimeout= Convert.ToInt32()

                byte     slaveID          = 2;
                ushort   startAddress     = 0;
                ushort   numOfPoints      = 1;
                ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress, numOfPoints);
                if (holding_register.Count() != 0)
                {
                    //string s = System.Text.Encoding.UTF8.GetString(holding_register, 0, holding_register.Count);
                    label18.Text = holding_register[0].ToString();
                }
                else
                {
                    label18.Text      = "Ошибка!";
                    checkBox4.Checked = false;
                }
                master.Dispose();

                Application.DoEvents();
            }
            catch { label18.Text = "Ошибка!"; }
        }
Beispiel #25
0
 public float GetPressure()
 {
     return(ConvertToFloat(ModBus.ReadHoldingRegisters(AddrId, 2200, 2)));
 }
Beispiel #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            //çalışan kod

            TcpClient TCP_Client = new TcpClient();

            TCP_Client.SendTimeout    = 2000;
            TCP_Client.ReceiveTimeout = 2000;
            IAsyncResult result = TCP_Client.BeginConnect("192.168.4.187", 502, null, null);

            result.AsyncWaitHandle.WaitOne(2000, true);

            ModbusMaster MBus = ModbusIpMaster.CreateIp(TCP_Client);

            ushort[] datas = MBus.ReadHoldingRegisters(1, 10, 4);

            for (int i = 0; i < 4; i++)
            {
                _items.Add(datas[i].ToString());
            }
            listBox1.DataSource = _items;

            byte[] b1 = BitConverter.GetBytes(datas[0]);
            byte[] b2 = BitConverter.GetBytes(datas[3]);
            byte[] b3 = new byte[4];
            b3[0] = b1[0];
            b3[1] = b1[1];
            b3[2] = b2[0];
            b3[3] = b2[1];
            long volt = BitConverter.ToInt64(b3, 0);

            label3.Text = volt.ToString();

            TCP_Client.Close();


            UdpClient udpci = new UdpClient();

            udpci.Connect("192.168.4.187", 502);
            SerialPort   sp   = new SerialPort("COM1", 115200);
            ModbusMaster MBus = ModbusSerialMaster.CreateRtu(udpci);

            ushort[] datass = MBus.ReadHoldingRegisters(1, 0, 10);


            SerialPort sp = new SerialPort("COM1", 115000);

            sp.Open();
            ModbusSerialMaster MBus = ModbusSerialMaster.CreateRtu(sp);

            ushort[] readData = MBus.ReadHoldingRegisters(1, 0X1A, 3);
            MBus.Transport.ReadTimeout = 300;
            byte[] b1 = BitConverter.GetBytes(readData[1]);
            byte[] b2 = BitConverter.GetBytes(readData[0]);
            byte[] b3 = new byte[4];
            b3[0] = b1[0];
            b3[1] = b1[1];
            b3[2] = b2[0];
            b3[3] = b2[1];
            float watt = BitConverter.ToSingle(b3, 0);
        }
Beispiel #27
0
        /// <summary>
        /// 定时读取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerGetData_Tick(object sender, EventArgs e)
        {
            try
            {
                //GetDesTemData(250, out var des, out var tem);
                //地址减一读
                GetDesTemDrgData(out var des, out var tem, out var drg);
                //读取状态位
                var datasBitsDefine = master?.ReadInputRegisters(SlaveAddress,
                                                                 (ushort)(AddressConfig.BitsDefine - 1), 1);
                pictureBoxDriveGain.BackColor = (((datasBitsDefine[0]) >> (5)) & 0x01) == 1 ? Color.Red : Color.Lime;
                pictureBoxSensor.BackColor    = (((datasBitsDefine[0]) >> (10)) & 0x01) == 1 ? Color.Red : Color.Lime;
                //读取单位
                var datasUnits = master?.ReadHoldingRegisters(SlaveAddress,
                                                              (ushort)(AddressConfig.DensityUnit - 1), 2);
                desUnitsLabel.Text = ParaUnits.DesTable[datasUnits[0]];
                temUnitsLabel.Text = ParaUnits.TemTable[datasUnits[1]];
                //读取A37 A38
                var datasA37 = master?.ReadInputRegisters(SlaveAddress,
                                                          (ushort)(AddressConfig.A37 - 1), 1);
                pictureBoxSensorCheck.BackColor = (((datasA37[0]) >> (3)) & 0x01) == 1 ?
                                                  Color.Red : Color.Lime;
                var datasA38 = master?.ReadInputRegisters(SlaveAddress,
                                                          (ushort)(AddressConfig.A38 - 1), 1);
                pictureBoxTimeOutLimits.BackColor = (((datasA38[0]) >> (2)) & 0x01) == 1 ?
                                                    Color.Red : Color.Lime;

                paraDensity.Value   = des;
                paraTem.Value       = tem;
                paraDriveGain.Value = drg;
                labelDes.Text       = paraDensity.Value.ToString();
                LabelTem.Text       = paraTem.Value.ToString();
                labelDriveGain.Text = paraDriveGain.Value.ToString() + "%";
                labelStatus.Text    = "通信正常";
                timerDraw.Enabled   = true;
                timerSave.Enabled   = true;
                isShowInfoBox       = false;
            }
            catch (Exception exception)
            {
                //timerGetData.Enabled = false;
                //timerGetData.Stop();
                if (exception.Source.Equals("System"))
                {
                    if (!isShowInfoBox)
                    {
                        isShowInfoBox = true;
                        MessageBox.Show(DateTime.Now.ToString() + " " + "通信超时");
                    }
                    labelStatus.Text = "通信超时";
                }
                if (exception.Source.Equals("nModbusPC"))
                {
                    string str = exception.Message;
                    int    FunctionCode;
                    string ExceptionCode;

                    str          = str.Remove(0, str.IndexOf("\r\n", StringComparison.Ordinal) + 17);
                    FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n", StringComparison.Ordinal)));
                    //MessageBox.Show("Function Code: " + FunctionCode.ToString("X"));

                    str           = str.Remove(0, str.IndexOf("\r\n", StringComparison.Ordinal) + 17);
                    ExceptionCode = str.Remove(str.IndexOf("-", StringComparison.Ordinal));
                    switch (ExceptionCode.Trim())
                    {
                    case "1":
                        labelStatus.Text = "通信异常:非法的通信功能码";
                        //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!" );
                        break;

                    case "2":
                        labelStatus.Text = "通信异常:非法的数据地址";
                        //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!" );
                        break;

                    case "3":
                        labelStatus.Text = "通信异常:非法的数据值";
                        //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!"  );
                        break;

                    case "4":
                        labelStatus.Text = "从机故障";
                        //MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!" );
                        break;
                    }

                    //this.formMain.Close();
                }
                //labelStatus.Text = exception.Message.ToString();
            }
        }
Beispiel #28
0
        public void TestConnection(Slave slave)
        {
            var startAddress = GetStartAddress(slave.DeviceNumber);

            _modbusSerial.ReadHoldingRegisters(slave.SlaveId, startAddress, 1);
        }
        public void ReadParametrs(int adressIndex)
        {
            ModbusSerialMaster master    = ModbusSerialMaster.CreateRtu(serialPort1);
            List <string>      hexBuffer = new List <string>()
            {
            };

            for (ushort i = 2; i < 3; i++)
            {
                ushort   startAddress     = readAdressList[adressIndex];
                ushort   numOfPoints      = i;
                ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress,
                                                                        numOfPoints);
                Thread.Sleep(30);
                foreach (var item in holding_register)
                {
                    string intValue = item.ToString();
                    string hexValue = item.ToString("X");
                    hexBuffer.Add(hexValue);
                }
                if (hexBuffer[0] == "0")
                {
                    hexBuffer[0] = "0000";
                }
                else if (hexBuffer[1] == "0")
                {
                    hexBuffer[1] = "0000";
                }
                string hexParameter;
                if (hexBuffer[1].Length <= 1)
                {
                    hexParameter = hexBuffer[0] + hexBuffer[1] + "000";
                }
                else if (hexBuffer[1].Length <= 2)
                {
                    hexParameter = hexBuffer[0] + hexBuffer[1] + "00";
                }
                else if (hexBuffer[1].Length <= 3)
                {
                    hexParameter = hexBuffer[0] + hexBuffer[1] + "0";
                }
                else
                {
                    hexParameter = hexBuffer[0] + hexBuffer[1];
                }

                var   intConvertVar  = Convert.ToInt32(hexParameter, 16);
                var   byteConvertVar = BitConverter.GetBytes(intConvertVar);
                float temp           = BitConverter.ToSingle(byteConvertVar, 0);
                var   temperature    = Math.Round(temp, 2);
                if (temperature <= 0)
                {
                    readParameters.Add("0");
                }
                else
                {
                    readParameters.Add(Convert.ToString(temperature));
                }

                //hexList.Add(hexParameter);
            }
        }
Beispiel #30
0
        private void timer4_Tick(object sender, EventArgs e)
        {
            try
            {
                SerialPort serial_port = new SerialPort("COM" + textBox16.Text);
                serial_port.BaudRate = 57600;
                serial_port.DataBits = 8;
                serial_port.Parity   = Parity.None;
                serial_port.StopBits = StopBits.One;
                serial_port.Open();

                ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serial_port);
                master.Transport.ReadTimeout = Convert.ToInt32(textBox12.Text);
                //master.Transport.WriteTimeout= Convert.ToInt32()

                byte     slaveID          = 2;
                ushort   startAddress     = 0;
                ushort   numOfPoints      = 1;
                ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress, numOfPoints);
                if (holding_register.Count() != 0)
                {
                    //string s = System.Text.Encoding.UTF8.GetString(holding_register, 0, holding_register.Count);
                    textBox17.Text = holding_register[0].ToString();
                    //Передача нового значения
                    if ((checkBox1.Checked == true) & (holding_register[0] <= (Convert.ToInt32(textBox2.Text))))
                    {
                        show_alarm("Отсечка кода:" + holding_register[0]);
                    }
                    else
                    {
                        Wkr = holding_register[0];
                    }
                    firt_wav = true;
                    try
                    {
                        this.Player.Stop();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error playing sound");
                    }
                }
                else
                {
                    //Если Передача последнего значения, при ошибке ==TRUE
                    if (checkBox7.Checked == true)
                    {
                        show_alarm("Ошибка ответа");
                    }
                    else
                    {
                        Wkr = 0;
                        show_alarm("Ошибка ответа");
                    }
                }
                master.Dispose();
                serial_port.Close();

                //Application.DoEvents();
            }
            catch {
                if (checkBox7.Checked == true)
                {
                    show_alarm("Ошибка передачи");
                }
                else
                {
                    Wkr = 0;
                    show_alarm("Ошибка передачи");
                }
            }
        }