private bool                    readRegSegment(byte aSlaveID, ERegisterType aRegisterType, ushort aRegister, ref ushort[] aValue)
        {
            int lFrame = (int)mFrame;
            int lDiv   = aValue.Length / lFrame;
            int lStart = 0;

            ushort[] lArray;

            for (int i = 0; i < lDiv; i++)
            {
                try
                {
                    if (aRegisterType == ERegisterType.HOLDING_REGISTER)
                    {
                        lArray = mMaster.ReadHoldingRegisters(aSlaveID, (ushort)(aRegister + lStart), (ushort)mFrame);
                    }
                    else
                    {
                        lArray = mMaster.ReadInputRegisters(aSlaveID, (ushort)(aRegister + lStart), (ushort)mFrame);
                    }
                }
                catch (Exception lExc)
                {
                    reportError("Error reading data for one or group of Items: " + lExc.Message);
                    return(false);
                }

                Array.Copy(lArray, 0, aValue, lStart, mFrame);

                lStart = lStart + lFrame;
            }

            int lLastPart = aValue.Length - lStart;

            if (lLastPart > 0)
            {
                try
                {
                    if (aRegisterType == ERegisterType.HOLDING_REGISTER)
                    {
                        lArray = mMaster.ReadHoldingRegisters(aSlaveID, (ushort)(aRegister + lStart), (ushort)lLastPart);
                    }
                    else
                    {
                        lArray = mMaster.ReadInputRegisters(aSlaveID, (ushort)(aRegister + lStart), (ushort)lLastPart);
                    }
                }
                catch (Exception lExc)
                {
                    reportError("Error reading data for one or group of Items: " + lExc.Message);
                    return(false);
                }

                Array.Copy(lArray, 0, aValue, lStart, lLastPart);
            }

            return(true);
        }
Esempio n. 2
0
        public static int[] LayDuLieuCOMInputRegisters(SerialPort serialPort, ushort quantityInputRegisters, ushort minAddressInputRegisters, ThietBiModel thietBiModel)
        {
            IModbusMaster master       = ModbusSerialMaster.CreateRtu(serialPort);
            List <ushort> readRegister = new List <ushort>();

            if (quantityInputRegisters != 0)
            {
                try
                {
                    byte slaveAddress    = 1;
                    int  soNguyenSauChia = quantityInputRegisters / DonViQuantityMoiLanDoc;
                    for (int i = 0; i <= soNguyenSauChia; i++)
                    {
                        if (i != soNguyenSauChia)
                        {
                            int startAddress = i * DonViQuantityMoiLanDoc + minAddressInputRegisters;
                            int quantity     = DonViQuantityMoiLanDoc - minAddressInputRegisters;
                            var temp         = master.ReadInputRegisters(slaveAddress, (ushort)startAddress, (ushort)(quantity));
                            readRegister.AddRange(temp.ToList());
                        }
                        else if (i == soNguyenSauChia)
                        {
                            int startAddress = i * DonViQuantityMoiLanDoc + minAddressInputRegisters;
                            int quantity     = quantityInputRegisters % DonViQuantityMoiLanDoc - minAddressInputRegisters;
                            if (quantity != 0)
                            {
                                var temp = master.ReadInputRegisters(slaveAddress, (ushort)startAddress, (ushort)(quantity));
                                readRegister.AddRange(temp.ToList());
                            }
                        }
                    }
                }
                catch (TimeoutException ex)
                {
                    ExceptionTimeOut(ex, thietBiModel);
                    throw;
                    //lỗi không đọc được dữ liệu
                }
                catch (Modbus.SlaveException ex)
                {
                    ExceptionErrorSlave(ex, thietBiModel);
                    throw;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }

            return(ConvertArrayUshortToIntArray(readRegister));
        }
Esempio n. 3
0
        private void ReadByFunction(IModbusMaster master, bool isFirstRead)
        {
            switch (_configurationSettings.Function)
            {
            case 1:
                UpdateUI(master.ReadCoils(_configurationSettings.SlaveId,
                                          _configurationSettings.StartAddress, _configurationSettings.Count), isFirstRead);
                break;

            case 2:
                UpdateUI(master.ReadInputs(_configurationSettings.SlaveId,
                                           _configurationSettings.StartAddress, _configurationSettings.Count), isFirstRead);
                break;

            case 3:
                UpdateUI(master.ReadHoldingRegisters(_configurationSettings.SlaveId,
                                                     _configurationSettings.StartAddress, _configurationSettings.Count), isFirstRead);
                break;

            case 4:
                UpdateUI(master.ReadInputRegisters(_configurationSettings.SlaveId,
                                                   _configurationSettings.StartAddress, _configurationSettings.Count), isFirstRead);
                break;

            default:
                throw new ArgumentException();
            }
        }
Esempio n. 4
0
 public static float ReadFloat(IModbusMaster master, byte slaveId, ushort address)
 {
     ushort[] registers = master.ReadInputRegisters(slaveId, address, sizeof(float) / sizeof(ushort));
     var result = new byte[registers.Length * sizeof(ushort)];
     Buffer.BlockCopy(registers, 0, result, 0, result.Length);
     return BitConverter.ToSingle(result, 0);
 }
Esempio n. 5
0
        public ushort[] ReadInputs(byte id, ushort address, byte count)
        {
            if (mConnection != null)
            {
                lock (mConnectionLock)
                {
                    try
                    {
                        return(mConnection.ReadInputRegisters(id, address, count));
                    }
                    catch (Exception e)
                    {
                        if (e is FormatException ||
                            e is NotImplementedException ||
                            e is TimeoutException ||
                            e is IOException ||
                            e is NullReferenceException ||
                            e is ObjectDisposedException)
                        {
                            //Console.ForegroundColor = ConsoleColor.Red;
                            //Console.WriteLine("inputs f**k");
                            //Console.ForegroundColor = ConsoleColor.Gray;

                            return(null);
                        }

                        throw;
                    }
                }
            }

            return(null);
        }
Esempio n. 6
0
 /// <summary>
 /// Scans in data from the IED and writes it
 /// </summary>
 /// <param name="master"></param>
 /// <returns></returns>
 private static void ScanIn(IModbusMaster master)
 {
     for (int i = 0; i < 272; i += 2)
     {
         ushort[] items = master.ReadInputRegisters(1, (ushort)i, 2);
         //float itemsFloat = BinaryToFloat(items); // Checks that the data is correct
         WriteValues(items, i);
     }
 }
Esempio n. 7
0
        private void RequestCommunicationState()
        {
            if (!_connectionEstablished)
            {
                throw new InvalidOperationException(_connectionErrorMessage);
            }

            try
            {
                var requestsAmount       = _client.ReadInputRegisters(_slaveAddress, 0x0D, 1)[0];
                var responsesAmount      = _client.ReadInputRegisters(_slaveAddress, 0x0E, 1)[0];
                var checkSumErrorsAmount = _client.ReadInputRegisters(_slaveAddress, 0x0F, 1)[0];

                var firstDiscreteInput  = _client.ReadHoldingRegisters(_slaveAddress, 0x80, 1)[0];
                var secondDiscreteInput = _client.ReadHoldingRegisters(_slaveAddress, 0x81, 1)[0];
                var thirdDiscreteInput  = _client.ReadHoldingRegisters(_slaveAddress, 0x82, 1)[0];
                var fourthDiscreteInput = _client.ReadHoldingRegisters(_slaveAddress, 0x83, 1)[0];

                _logger.Trace($@"Controller: {_controllerId}|Requests: {requestsAmount}; Responses: {responsesAmount}; Check sum errors: {checkSumErrorsAmount}; 
                                 di1: {firstDiscreteInput}; di2: {secondDiscreteInput}; di3: {thirdDiscreteInput}; di4: {fourthDiscreteInput}");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, ex.FullErrorMessage());
                _connectionEstablished = false;
                throw;
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Read multiple registers
        /// </summary>
        /// <param name="slaveaddress"></param>
        /// <param name="registertype"></param>
        /// <param name="start"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public override ushort[] ReadRegister(byte slaveaddress, int registertype, ushort start, ushort amount)
        {
            switch (registertype)
            {
            case (0x01):
                return(Master.ReadHoldingRegisters(slaveaddress, start, amount));

            case (0x02):
                return(Master.ReadInputRegisters(slaveaddress, start, amount));

            default:
                throw new TypeAccessException("Invalid type");
            }
        }
Esempio n. 9
0
        /// <summary>
        ///     Modbus TCP master and slave example.
        /// </summary>
        public static void ModbusTcpMasterReadInputsFromModbusSlave()
        {
            byte      slaveId = 1;
            int       port    = 502;
            IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });

            // create and start the TCP slave
            TcpListener slaveTcpListener = new TcpListener(address, port);

            slaveTcpListener.Start();

            var factory = new ModbusFactory();

            var network = factory.CreateSlaveNetwork(slaveTcpListener);

            IModbusSlave slave = factory.CreateSlave(slaveId);

            network.AddSlave(slave);

            var listenTask = network.ListenAsync();

            // create the master
            TcpClient     masterTcpClient = new TcpClient(address.ToString(), port);
            IModbusMaster master          = factory.CreateMaster(masterTcpClient);

            ushort numInputs    = 5;
            ushort startAddress = 100;

            // read five register values
            ushort[] inputs = master.ReadInputRegisters(0, startAddress, numInputs);

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

            // clean up
            masterTcpClient.Close();
            slaveTcpListener.Stop();

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }
Esempio n. 10
0
 /// <summary>
 /// IEnumerable<[address,value]>
 /// </summary>
 public static IEnumerable <KeyValuePair <ushort, ushort> > ReadInputRegisters(
     this IModbusMaster master, byte slaveAddress, IEnumerable <ushort> addresses)
 {
     foreach (var bucket in GetRegisterBucketsToRead(addresses))
     {
         ushort   startAddress   = bucket.Item1;
         ushort   numberOfPoints = bucket.Item2;
         ushort[] values         = master.ReadInputRegisters(slaveAddress, startAddress, numberOfPoints);
         ushort   i = 0;
         foreach (var value in values)
         {
             ushort address = (ushort)(startAddress + i);
             ++i;
             yield return(new KeyValuePair <ushort, ushort>(address, value));
         }
     }
 }
Esempio n. 11
0
        /// <summary>
        ///     Read contiguous block of 32 bit input registers.
        /// </summary>
        /// <param name="master">The Modbus master.</param>
        /// <param name="slaveAddress">Address of device to read values from.</param>
        /// <param name="startAddress">Address to begin reading.</param>
        /// <param name="numberOfPoints">Number of holding registers to read.</param>
        /// <returns>Input registers status</returns>
        public static uint[] ReadInputRegisters32(
            this IModbusMaster master,
            byte slaveAddress,
            ushort startAddress,
            ushort numberOfPoints)
        {
            if (master == null)
            {
                throw new ArgumentNullException(nameof(master));
            }

            ValidateNumberOfPoints(numberOfPoints, 62);

            var rawRegisters = master.ReadInputRegisters(
                slaveAddress,
                startAddress,
                (ushort)(numberOfPoints * 2));

            return(Convert(rawRegisters).ToArray());
        }
Esempio n. 12
0
        public static object ReadSingleObject(
            this IModbusMaster master, ObjectType objectType, byte slaveId, ushort address)
        {
            switch (objectType)
            {
            case ObjectType.Coil:
                return(master.ReadCoils(slaveId, address, 1)[0]);

            case ObjectType.DiscreteInput:
                return(master.ReadInputs(slaveId, address, 1)[0]);

            case ObjectType.HoldingRegister:
                return(master.ReadHoldingRegisters(slaveId, address, 1)[0]);

            case ObjectType.InputRegister:
                return(master.ReadInputRegisters(slaveId, address, 1)[0]);

            default:
                throw new ArgumentException("objectType");
            }
        }
Esempio n. 13
0
 /// <summary>
 /// Проверка наличия измененеий в состоянии входов
 /// </summary>
 /// <param name="master">Транспорт</param>
 /// <returns>Список изменившихся входов</returns>
 public IEnumerable<int> UpdateAllInputState(IModbusMaster master)
 {
     List<int> res = new List<int>();
     var answer = master.ReadInputRegisters(_address, RegisterStartInputs, CountRegistersInputs);
     if (_lastState == null)
     {
         _lastState = answer;
         for (int i = 0; i < (_lastState.Length * 16); i++)
             res.Add(i);
     }
     else
     {
         for(int i = 0; i< answer.Length; i++)
         {
             if(answer[i]==_lastState[i])
                 continue;
             for(int bit = 0; bit<16; bit++)
                 if (GetBitFromUShortArray(_lastState, (i * 16 + bit)) != GetBitFromUShortArray(answer, (i * 16 + bit)))
                     res.Add(i * 16 + bit);
         }
     }
     return res;
 }
Esempio n. 14
0
 private ushort[] ReadInputRegisters(ushort startAddress, ushort pointCount)
 {
     return(m_modbusConnection.ReadInputRegisters(m_unitID, startAddress, pointCount));
 }
Esempio n. 15
0
        public JObject ReadModbusToJson(int siteId, int DeviceIndex, GroupPoint slaves, out HashEntry[] hashEntries)
        {
            JObject          datarow = new JObject();
            List <HashEntry> entries = new List <HashEntry>();

            hashEntries = entries.ToArray();
            try
            {
                if (master == null)
                {
                    return(datarow);
                }
                ushort   startAddr = slaves.StartAddress;
                ushort   pointCnt  = (ushort)slaves.AiMaps.Sum(x => x.DataType.Size);
                ushort[] datas     = null;
                lock (lockerObj)
                {
                    switch ((modbus_io)slaves.IoType)
                    {
                    case modbus_io.ANALOG_INPUT:
                        datas = master.ReadInputRegisters(_config.SlaveId, startAddr, pointCnt);
                        break;

                    case modbus_io.HOLDING_REGISTER:
                        datas = master.ReadHoldingRegisters(_config.SlaveId, startAddr, pointCnt);
                        break;
                    }
                }
                DateTime timeStamp = DateTime.Now;
                datarow.Add("groupid", slaves.GroupId);
                datarow.Add("groupname", slaves.GroupName);
                datarow.Add("deviceId", _config.DeviceName);
                datarow.Add("siteId", siteId);
                string normalizedeviceid = slaves.GroupId == 1 ? "PCS" : "BMS";

                datarow.Add("normalizedeviceid", normalizedeviceid + DeviceIndex.ToString());
                entries.Add(new HashEntry("timestamp", timeStamp.ToString()));
                datarow.Add("timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                int bitIdx = 0;
                foreach (AiMap register in slaves.AiMaps)
                {
                    if (register.Disable == 1)
                    {
                        continue;
                    }
                    //Console.WriteLine("READ REGISTER: " + register.Name);
                    byte[] buffer = GetReadBytes(register.DataType, bitIdx, datas);
                    bitIdx += register.DataType.Size;
                    dynamic value = 0f;
                    switch ((modbus_type)register.DataType.TypeCode)
                    {
                    case modbus_type.DT_BOOLEAN:
                        value = BitConverter.ToBoolean(buffer);
                        break;

                    case modbus_type.DT_INT32:
                        value = BitConverter.ToInt32(buffer);
                        break;

                    case modbus_type.DT_INT16:
                        value = BitConverter.ToInt16(buffer);
                        break;

                    case modbus_type.DT_UINT32:
                        value = BitConverter.ToUInt32(buffer);
                        break;

                    case modbus_type.DT_UINT16:
                        value = BitConverter.ToUInt16(buffer);
                        break;

                    case modbus_type.DT_FLOAT:
                        value = BitConverter.ToSingle(buffer);
                        break;
                    }

                    value = register.ConvertValue(value);
                    entries.Add(new HashEntry(register.Name, value.ToString()));
                    datarow.Add(register.Name, value.ToString());
                    //registers.Add(register.ConvertRegister(Convert.ToSingle(value)));
                }
                hashEntries = entries.ToArray();
                return(datarow);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return(null);
            }
        }
Esempio n. 16
0
        private async void ExecuteFunction()
        {
            try
            {
                //重新实例化是为了 modbus slave更换连接时不报错
                master = modbusFactory.CreateMaster(new TcpClient("127.0.0.1", 502));
                if (functionCode != null)
                {
                    switch (functionCode)
                    {
                    case "01 Read Coils":    //读取单个线圈
                        SetReadParameters();
                        coilsBuffer = master.ReadCoils(slaveAddress, startAddress, numberOfPoints);

                        for (int i = 0; i < coilsBuffer.Length; i++)
                        {
                            SetMsg(coilsBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "02 Read DisCrete Inputs":    //读取输入线圈/离散量线圈
                        SetReadParameters();

                        coilsBuffer = master.ReadInputs(slaveAddress, startAddress, numberOfPoints);
                        for (int i = 0; i < coilsBuffer.Length; i++)
                        {
                            SetMsg(coilsBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "03 Read Holding Registers":    //读取保持寄存器
                        SetReadParameters();
                        registerBuffer = master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints);
                        for (int i = 0; i < registerBuffer.Length; i++)
                        {
                            SetMsg(registerBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "04 Read Input Registers":    //读取输入寄存器
                        SetReadParameters();
                        registerBuffer = master.ReadInputRegisters(slaveAddress, startAddress, numberOfPoints);
                        for (int i = 0; i < registerBuffer.Length; i++)
                        {
                            SetMsg(registerBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "05 Write Single Coil":    //写单个线圈
                        SetWriteParametes();
                        await master.WriteSingleCoilAsync(slaveAddress, startAddress, coilsBuffer[0]);

                        break;

                    case "06 Write Single Registers":    //写单个输入线圈/离散量线圈
                        SetWriteParametes();
                        await master.WriteSingleRegisterAsync(slaveAddress, startAddress, registerBuffer[0]);

                        break;

                    case "0F Write Multiple Coils":    //写一组线圈
                        SetWriteParametes();
                        await master.WriteMultipleCoilsAsync(slaveAddress, startAddress, coilsBuffer);

                        break;

                    case "10 Write Multiple Registers":    //写一组保持寄存器
                        SetWriteParametes();
                        await master.WriteMultipleRegistersAsync(slaveAddress, startAddress, registerBuffer);

                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    MessageBox.Show("请选择功能码!");
                }
                master.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 17
0
        public void OnButtonMbusExecuteClicked(object sender, RoutedEventArgs e)
        {
            if (mbus_client.Connected)
            {
                ushort offset   = ushort.Parse(boxRegOffset.Text);
                ushort quantity = ushort.Parse(boxRegNumber.Text);
                byte   slave    = 0x00;
                ushort val      = ushort.Parse(boxModbusWriteValue.Text);
                switch (boxModbusOp.Text)
                {
                case "Чтение дискретных входов":
                    bool[] discrete_output;
                    try
                    {
                        discrete_output = mbus_master.ReadInputs(slave, offset, quantity);
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                        discrete_output = new bool[0];
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                        discrete_output = new bool[0];
                    }
                    foreach (bool b in discrete_output)
                    {
                        if (b)
                        {
                            Console.Write("1 ");
                        }
                        else
                        {
                            Console.Write("0 ");
                        }
                    }
                    Console.Write('\n');
                    break;

                case "Чтение дискретных выходов":
                    bool[] coil_output;
                    try
                    {
                        coil_output = mbus_master.ReadCoils(slave, offset, quantity);
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                        coil_output = new bool[0];
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                        coil_output = new bool[0];
                    }
                    foreach (bool b in coil_output)
                    {
                        if (b)
                        {
                            Console.Write("1 ");
                        }
                        else
                        {
                            Console.Write("0 ");
                        }
                    }
                    Console.Write('\n');
                    break;

                case "Чтение выходных регистров":
                    ushort[] holding_output;

                    try
                    {
                        holding_output = mbus_master.ReadHoldingRegisters(slave, offset, quantity);
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                        holding_output = new ushort[0];
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                        holding_output = new ushort[0];
                    }
                    foreach (int i in holding_output)
                    {
                        Console.Write(i.ToString() + " ");
                    }
                    Console.WriteLine("");
                    break;

                case "Чтение входных регистров":
                    ushort[] inreg_output;

                    try
                    {
                        inreg_output = mbus_master.ReadInputRegisters(slave, offset, quantity);
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                        inreg_output = new ushort[0];
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                        inreg_output = new ushort[0];
                    }
                    foreach (int i in inreg_output)
                    {
                        Console.Write(i.ToString() + " ");
                    }
                    Console.WriteLine("");
                    break;

                case "Запись в дискретный выход":

                    bool coil = val > 0 ? true : false;
                    try
                    {
                        mbus_master.WriteSingleCoil(slave, offset, coil);
                        Console.WriteLine("ЗАП OK");
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                    }
                    break;

                case "Запись в регистр":
                    try
                    {
                        mbus_master.WriteSingleRegister(slave, offset, val);
                        Console.WriteLine("ЗАП OK");
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                    }
                    break;

                case "Запись в несколько дискретных выходов":
                    bool[] coil_input = new bool[quantity];
                    for (int i = 0; i < quantity; i++)
                    {
                        coil_input[i] = val > 0 ? true : false;
                    }
                    try
                    {
                        mbus_master.WriteMultipleCoils(slave, offset, coil_input);
                        Console.WriteLine("ЗАП OK");
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                    }
                    break;

                case "Запись в несколько регистров":
                    ushort[] reg_out = new ushort[quantity];
                    for (int i = 0; i < quantity; i++)
                    {
                        reg_out[0] = val;
                    }
                    try
                    {
                        mbus_master.WriteMultipleRegisters(slave, offset, reg_out);
                        Console.WriteLine("ЗАП OK");
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                    }
                    catch (InvalidModbusRequestException)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                    }
                    break;

                case "Чтение/Запись в несколько регистров":
                    ushort[] reg_write = new ushort[quantity];
                    ushort[] reg_read;
                    ushort   offset_write = ushort.Parse(boxRegOffsetWr.Text);
                    for (int i = 0; i < quantity; i++)
                    {
                        reg_write[i] = val;
                    }
                    try
                    {
                        reg_read = mbus_master.ReadWriteMultipleRegisters(slave, offset, quantity, offset_write, reg_write);
                        Console.WriteLine("ЧТЕН OK");
                        foreach (int i in reg_read)
                        {
                            Console.Write(i + " ");
                        }
                        Console.WriteLine("\nЗАП OK");
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("Ошибка соединения. Соединение сброшено");
                        mbus_client.Close();
                    }
                    catch (InvalidModbusRequestException ex)
                    {
                        Console.WriteLine("Что-то пошло не так...");
                    }
                    break;
                }
            }
        }
Esempio n. 18
0
 /// <summary>
 /// Метод для чтения содержимого регистров входных (AI - на модуле, сигнал к модулю)
 /// Read input registers value
 /// </summary>
 /// <param name="slaveID">Address of device to read values from</param>
 /// <param name="startAddress">Address to begin reading</param>
 /// <param name="numOfPoints">Number of input registers to read.</param>
 /// <returns> ushort[] </returns>
 public ushort[] ReadInputRegisters(byte slaveID, ushort startAddress, ushort numOfPoints) // функциональный код 04
 {
     return(NetworkIsOk ? master.ReadInputRegisters(slaveID, startAddress, numOfPoints) : null);
 }
Esempio n. 19
0
 /// <summary>
 /// Get state relay by index
 /// </summary>
 /// <param name="master">modbus transport</param>
 /// <param name="index">aim index</param>
 /// <returns>state relay</returns>
 public bool GetRelayState(IModbusMaster master, int index)
 {
     var answer = master.ReadInputRegisters(_address, RegisterStartRelays, CountRegistersRelays);
     return GetBitFromUShortArray(answer, index);
 }
        protected void ReadBuffer(ModbusBaseClientStation self, IModbusMaster master, ModbusBuffer buf)
        {
            try
            {
                ushort[] registers;
                byte[]   adr;
                bool[]   inputs;

                if (buf.pauseCounter == 0)
                {
                    ushort startAddress = buf.startAddress;
                    ushort numInputs    = buf.numInputs;
                    switch (buf.ModbusDataType)
                    {
                    case ModbusDataTypeEx.InputRegister:
                    case ModbusDataTypeEx.HoldingRegister:
                        if (buf.ModbusDataType == ModbusDataTypeEx.InputRegister)
                        {
                            registers = master.ReadInputRegisters(buf.slaveId, startAddress, numInputs);
                        }
                        else
                        {
                            registers = master.ReadHoldingRegisters(buf.slaveId, startAddress, numInputs);
                        }
                        DateTime dt      = DateTime.Now;
                        int      iresult = 0;
                        uint     uresult = 0;
                        double   fresult = 0.0;
                        foreach (ModbusChannelImp ch in buf.channels)
                        {
                            switch (ch.DeviceDataType)
                            {
                            case ModbusDeviceDataType.Int:
                                adr = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress]);
                                switch (ch.ConversionType)
                                {
                                case ModbusConversionType.SwapBytes:
                                    byte tmp = adr[0]; adr[0] = adr[1]; adr[1] = tmp;
                                    iresult = BitConverter.ToInt16(adr, 0);
                                    break;

                                default:
                                    iresult = BitConverter.ToInt16(adr, 0);
                                    break;
                                }
                                if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Int32)
                                {
                                    ch.DoUpdate(iresult, dt, ChannelStatusFlags.Good);
                                }
                                else if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Double)
                                {
                                    ch.DoUpdate((double)(ch.K * iresult + ch.D), dt, ChannelStatusFlags.Good);
                                }
                                else
                                if (self.LoggingLevel >= ModbusLog.logWarnings)
                                {
                                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                                self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                                }
                                break;

                            case ModbusDeviceDataType.UInt:
                                adr = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress]);
                                switch (ch.ConversionType)
                                {
                                case ModbusConversionType.SwapBytes:
                                    byte tmp = adr[0]; adr[0] = adr[1]; adr[1] = tmp;
                                    uresult = BitConverter.ToUInt16(adr, 0);
                                    break;

                                default:
                                    uresult = BitConverter.ToUInt16(adr, 0);
                                    break;
                                }
                                if (ch.ModbusFs2InternalType == ModbusFs2InternalType.UInt32)
                                {
                                    ch.DoUpdate(uresult, dt, ChannelStatusFlags.Good);
                                }
                                else if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Double)
                                {
                                    ch.DoUpdate((double)(ch.K * uresult + ch.D), dt, ChannelStatusFlags.Good);
                                }
                                else
                                if (self.LoggingLevel >= ModbusLog.logWarnings)
                                {
                                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                                self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                                }
                                break;

                            case ModbusDeviceDataType.DInt:
                                byte[] adr0 = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress]);
                                byte[] adr1 = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress + 1]);
                                byte[] res  = new byte[4];
                                res     = self.SwapBytesIn(adr0, adr1, ch.ConversionType);
                                iresult = BitConverter.ToInt32(res, 0);
                                if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Int32)
                                {
                                    ch.DoUpdate(iresult, dt, ChannelStatusFlags.Good);
                                }
                                else if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Double)
                                {
                                    ch.DoUpdate((double)(ch.K * iresult + ch.D), dt, ChannelStatusFlags.Good);
                                }
                                else
                                if (self.LoggingLevel >= ModbusLog.logWarnings)
                                {
                                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                                self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                                }
                                break;

                            case ModbusDeviceDataType.DUInt:

                                adr0    = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress]);
                                adr1    = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress + 1]);
                                res     = self.SwapBytesIn(adr0, adr1, ch.ConversionType);
                                uresult = BitConverter.ToUInt32(res, 0);
                                if (ch.ModbusFs2InternalType == ModbusFs2InternalType.UInt32)
                                {
                                    ch.DoUpdate(uresult, dt, ChannelStatusFlags.Good);
                                }
                                else if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Double)
                                {
                                    ch.DoUpdate((double)(ch.K * uresult + ch.D), dt, ChannelStatusFlags.Good);
                                }
                                else
                                if (self.LoggingLevel >= ModbusLog.logWarnings)
                                {
                                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                                self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                                }
                                break;

                            case ModbusDeviceDataType.Float:

                                adr0    = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress]);
                                adr1    = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress + 1]);
                                res     = self.SwapBytesIn(adr0, adr1, ch.ConversionType);
                                fresult = BitConverter.ToSingle(res, 0);
                                if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Double)
                                {
                                    ch.DoUpdate((double)(ch.K * fresult + ch.D), dt, ChannelStatusFlags.Good);
                                }
                                else
                                if (self.LoggingLevel >= ModbusLog.logWarnings)
                                {
                                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                                self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                                }
                                break;

                            case ModbusDeviceDataType.Bool:

                                bool bit = (registers[ch.ModbusDataAddress - buf.startAddress] & (0x01 << ch.BitIndex)) > 0;
                                if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Boolean)
                                {
                                    ch.DoUpdate(bit, dt, ChannelStatusFlags.Good);
                                }
                                else
                                if (self.LoggingLevel >= ModbusLog.logWarnings)
                                {
                                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                                self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                                }
                                break;

                            case ModbusDeviceDataType.String:

                                byte[]  str       = new byte[2 * ch.DeviceDataLen];
                                Decoder ascii     = (new ASCIIEncoding()).GetDecoder();
                                int     bytesUsed = 0;
                                int     charsUsed = 0;
                                bool    completed = false;
                                int     j         = 0;
                                // Conversion strategy: FIRST NONPRINTABLE CHARACTER (ORD < 32) BREAKS CONVERSION, string consists of printables converted before
                                for (int i = 0; i < ch.DeviceDataLen; i++)
                                {
                                    byte[] word = BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress + i]);
                                    if (ch.ConversionType == ModbusConversionType.SwapBytes)
                                    {
                                        if (word[1] < 32)
                                        {
                                            break;          // nonprintable character
                                        }
                                        str[j++] = word[1];
                                        if (word[0] < 32)
                                        {
                                            break;          // nonprintable character
                                        }
                                        str[j++] = word[0];
                                    }
                                    else
                                    {
                                        if (word[0] < 32)
                                        {
                                            break;          // nonprintable character
                                        }
                                        str[j++] = word[0];
                                        if (word[1] < 32)
                                        {
                                            break;          // nonprintable character
                                        }
                                        str[j++] = word[1];
                                        //Array.Copy(BitConverter.GetBytes(registers[ch.ModbusDataAddress - buf.startAddress + i]), 0, str, 2 * i, 2);
                                    }
                                }
                                string sresult;
                                if (j > 0)
                                {
                                    char[] chars = new char[j];
                                    ascii.Convert(str, 0, j, chars, 0, j, true, out bytesUsed, out charsUsed, out completed);
                                    sresult = new String(chars);
                                }
                                else
                                {
                                    sresult = "";
                                }
                                if (ch.ModbusFs2InternalType == ModbusFs2InternalType.String)
                                {
                                    ch.DoUpdate(sresult, dt, ChannelStatusFlags.Good);
                                }
                                else
                                if (self.LoggingLevel >= ModbusLog.logWarnings)
                                {
                                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                                self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                                }
                                break;
                            }
                        }
                        break;

                    case ModbusDataTypeEx.Coil:
                    case ModbusDataTypeEx.Input:
                        if (buf.ModbusDataType == ModbusDataTypeEx.Coil)
                        {
                            inputs = master.ReadCoils(buf.slaveId, startAddress, numInputs);
                        }
                        else
                        {
                            inputs = master.ReadInputs(buf.slaveId, startAddress, numInputs);
                        }
                        dt = DateTime.Now;
                        foreach (ModbusChannelImp ch in buf.channels)
                        {
                            if (ch.ModbusFs2InternalType == ModbusFs2InternalType.UInt32)
                            {
                                uint val = (uint)(inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0);
                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                            }
                            else if (ch.ModbusFs2InternalType == ModbusFs2InternalType.Boolean)
                            {
                                bool val = inputs[ch.ModbusDataAddress - buf.startAddress];
                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                            }
                            else
                            if (self.LoggingLevel >= ModbusLog.logWarnings)
                            {
                                Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrConvert,
                                                                            self.Name, ch.Name, ch.DeviceDataType.ToString(), ch.ModbusFs2InternalType.ToString()));
                            }
                        }
                        break;
                    }   // Case
                    if (self.failures.ContainsKey(buf.slaveId))
                    {
                        // failure signal defined
                        self.failures[buf.slaveId].Value = false;
                    }
                }   // If
                else
                {
                    buf.pauseCounter--;
                }
            }   // Try
            catch (Modbus.SlaveException e)
            {
                buf.pauseCounter = self.FailedCount;
                if (self.failures.ContainsKey(buf.slaveId))
                {
                    // failure signal defined
                    self.failures[buf.slaveId].Value = true;
                }
                foreach (ModbusChannelImp ch in buf.channels)
                {
                    ch.StatusFlags = ChannelStatusFlags.Bad;
                }
                if (self.LoggingLevel >= ModbusLog.logWarnings)
                {
                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrReceive,
                                                                self.Name, buf.slaveId, buf.ModbusDataType.ToString(), buf.startAddress, buf.numInputs, e.Message));
                }
            }
            catch (TimeoutException e)
            {
                buf.pauseCounter = self.FailedCount;
                if (self.failures.ContainsKey(buf.slaveId))
                {
                    // failure signal defined
                    self.failures[buf.slaveId].Value = true;
                }
                foreach (ModbusChannelImp ch in buf.channels)
                {
                    ch.StatusFlags = ChannelStatusFlags.Bad;
                }
                if (self.LoggingLevel >= ModbusLog.logWarnings)
                {
                    Env.Current.Logger.LogWarning(string.Format(StringConstants.ErrReceive,
                                                                self.Name, buf.slaveId, buf.ModbusDataType.ToString(), buf.startAddress, buf.numInputs, e.Message));
                }
            }
        }
Esempio n. 21
0
 public ushort GetOverride()
 {
     //ushort addr = 7101;
     // ADDR = 7101
     return(master.ReadInputRegisters(0, ADDR_STICK_OVERRIDE, 1)[0]);
 }
Esempio n. 22
0
        private async void ExecuteFunction()
        {
            try
            {
                //每次操作是要开启串口 操作完成后需要关闭串口
                //目的是为了slave更换连接是不报错
                if (port.IsOpen == false)
                {
                    port.Open();
                }
                //根据功能码写操作方法
                if (functionCode != null)
                {
                    switch (functionCode)
                    {
                    case "01 Read Coils":    //读取单个线圈
                        SetReadParameters();
                        coilsBuffer = master.ReadCoils(slaveAddress, startAddress, numberOfPoints);

                        for (int i = 0; i < coilsBuffer.Length; i++)
                        {
                            SetMsg(coilsBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "02 Read DisCrete Inputs":    //读取输入线圈/离散量线圈
                        SetReadParameters();

                        coilsBuffer = master.ReadInputs(slaveAddress, startAddress, numberOfPoints);
                        for (int i = 0; i < coilsBuffer.Length; i++)
                        {
                            SetMsg(coilsBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "03 Read Holding Registers":    //读取保持寄存器
                        SetReadParameters();
                        registerBuffer = master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints);
                        for (int i = 0; i < registerBuffer.Length; i++)
                        {
                            SetMsg(registerBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "04 Read Input Registers":    //读取输入寄存器
                        SetReadParameters();
                        registerBuffer = master.ReadInputRegisters(slaveAddress, startAddress, numberOfPoints);
                        for (int i = 0; i < registerBuffer.Length; i++)
                        {
                            SetMsg(registerBuffer[i] + " ");
                        }
                        SetMsg("\r\n");
                        break;

                    case "05 Write Single Coil":    //写单个线圈
                        SetWriteParametes();
                        await master.WriteSingleCoilAsync(slaveAddress, startAddress, coilsBuffer[0]);

                        break;

                    case "06 Write Single Registers":    //写单个输入线圈/离散量线圈
                        SetWriteParametes();
                        await master.WriteSingleRegisterAsync(slaveAddress, startAddress, registerBuffer[0]);

                        break;

                    case "0F Write Multiple Coils":    //写一组线圈
                        SetWriteParametes();
                        await master.WriteMultipleCoilsAsync(slaveAddress, startAddress, coilsBuffer);

                        break;

                    case "10 Write Multiple Registers":    //写一组保持寄存器
                        SetWriteParametes();
                        await master.WriteMultipleRegistersAsync(slaveAddress, startAddress, registerBuffer);

                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    MessageBox.Show("请选择功能码!");
                }
                //关闭串口
                port.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 23
0
 protected override ushort[] ReadCore(IModbusMaster modbusMaster, byte slaveId, ushort startAddress, ushort numberOfPoints)
 {
     return(modbusMaster.ReadInputRegisters(slaveId, startAddress, numberOfPoints, BlockSize));
 }
Esempio n. 24
0
        public ushort Read_reg(byte addr, ushort reg_addr, ushort num, string str, bool need = true)
        {
            ushort one_reg = 0xFF;

            ushort[] buf;
            try
            {
                switch (str)
                {
                case "input":
                    buf     = master.ReadInputRegisters(addr, reg_addr, num);
                    one_reg = buf[0];
                    if (need == true)
                    {
                        for (int i = 0; i < buf.Length; i++)
                        {
                            output += (addr).ToString("D3") + ":" + (reg_addr + i).ToString("D3") + " " + str + ": " + buf[i].ToString("D5") + "\n";
                        }
                    }
                    break;

                case "holding":
                    buf     = master.ReadHoldingRegisters(addr, reg_addr, num);
                    one_reg = buf[0];
                    if (need == true)
                    {
                        for (int i = 0; i < buf.Length; i++)
                        {
                            output += (addr).ToString("D3") + ":" + (reg_addr + i).ToString("D3") + " " + str + ": " + buf[i].ToString("D5") + "\n";
                        }
                    }
                    break;

                default:
                    reg_addr = 31;
                    num      = 1;
                    buf      = master.ReadInputRegisters(addr, reg_addr, num);
                    one_reg  = buf[0];
                    buf      = master.ReadInputRegisters(addr, (ushort)(reg_addr + 1), (ushort)(one_reg * 8));
                    if (need == true)
                    {
                        for (int i = 0; i < buf.Length; i++)
                        {
                            if (i % 8 == 0)
                            {
                                output += "\n";
                            }
                            if (i % 8 < 4)
                            {
                                output += ((byte)buf[i]).ToString("X2") + ((byte)(buf[i] >> 8)).ToString("X2");
                            }
                            if (i % 8 == 4)
                            {
                                output += " " + ((double)buf[i] / 10).ToString("F1") + " ";
                            }
                            if (i % 8 > 4)
                            {
                                output += buf[i].ToString() + " ";
                            }
                        }
                        output += "\n";
                    }
                    break;
                }
            }
            catch
            {
                output += (addr).ToString("D3") + " " + str + ":" + "Time out\n";
            }
            RaisePropertyChanged("Terminal");
            return(one_reg);
        }
Esempio n. 25
0
 /// <summary>
 /// Set state relay by index
 /// </summary>
 /// <param name="master">modbus transport</param>
 /// <param name="index">aim index relay</param>
 /// <param name="value">aim value relay</param>
 public void SetRelayState(IModbusMaster master, int index, bool value)
 {
     var answer = master.ReadInputRegisters(_address, RegisterStartRelays, CountRegistersRelays);
     var state = SetBitToUShortArray(answer, index, value);
     master.WriteMultipleRegisters(_address, RegisterStartRelays, state);
 }
Esempio n. 26
0
        private void SendPackage(IModbusMaster modbus, Device dv, DataBlock db)
        {
            try
            {
                SendDone.WaitOne(-1);

                switch (db.DataType)
                {
                case "Bit":
                    byte[] bitArys = null;
                    switch (db.TypeOfRead)
                    {
                    case "ReadCoilStatus":
                        bitArys = modbus.ReadCoilStatus((byte)dv.SlaveId, $"{db.StartAddress}",
                                                        db.Length);
                        break;

                    case "ReadInputStatus":
                        bitArys = modbus.ReadInputStatus((byte)dv.SlaveId, $"{db.StartAddress}",
                                                         db.Length);
                        break;

                    default:
                        break;
                    }
                    var BitRs = Bit.ToArray(bitArys);
                    if (bitArys.Length > db.Tags.Count)
                    {
                        return;
                    }
                    for (var j = 0; j < db.Tags.Count; j++)
                    {
                        db.Tags[j].Value        = BitRs[j];
                        db.Tags[j].Checked      = BitRs[j];
                        db.Tags[j].Enabled      = BitRs[j];
                        db.Tags[j].Visible      = BitRs[j];
                        db.Tags[j].ValueSelect1 = BitRs[j];
                        db.Tags[j].ValueSelect2 = BitRs[j];
                        db.Tags[j].Timestamp    = DateTime.Now;
                    }
                    break;

                case "Int":
                    var IntArys = modbus.ReadHoldingRegisters((byte)dv.SlaveId,
                                                              $"{db.StartAddress}", db.Length);
                    var IntRs = Int.ToArray(IntArys);
                    if (IntRs.Length > db.Tags.Count)
                    {
                        return;
                    }
                    for (var j = 0; j < IntRs.Length; j++)
                    {
                        db.Tags[j].Value     = IntRs[j];
                        db.Tags[j].Timestamp = DateTime.Now;
                    }
                    break;

                case "DInt":
                    var DIntArys = modbus.ReadHoldingRegisters((byte)dv.SlaveId,
                                                               $"{db.StartAddress}", db.Length);
                    var DIntRs = Int.ToArray(DIntArys);
                    if (DIntRs.Length > db.Tags.Count)
                    {
                        return;
                    }
                    for (var j = 0; j < DIntRs.Length; j++)
                    {
                        db.Tags[j].Value     = DIntRs[j];
                        db.Tags[j].Timestamp = DateTime.Now;
                    }
                    break;

                case "Word":
                    byte[] wdArys = null;
                    switch (db.TypeOfRead)
                    {
                    case "ReadHoldingRegisters":
                        wdArys = modbus.ReadHoldingRegisters((byte)dv.SlaveId, $"{db.StartAddress}", db.Length);

                        break;

                    case "ReadInputRegisters":
                        wdArys = modbus.ReadInputRegisters((byte)dv.SlaveId, $"{db.StartAddress}", db.Length);

                        break;

                    default:
                        break;
                    }
                    var wdRs = Word.ToArray(wdArys);
                    if (wdRs.Length > db.Tags.Count)
                    {
                        return;
                    }

                    for (var j = 0; j < wdRs.Length; j++)
                    {
                        db.Tags[j].Value     = wdRs[j];
                        db.Tags[j].Timestamp = DateTime.Now;
                    }
                    break;

                case "DWord":
                    var dwArys = modbus.ReadHoldingRegisters((byte)dv.SlaveId,
                                                             $"{db.StartAddress}", db.Length);
                    var dwRs = DWord.ToArray(dwArys);
                    for (var j = 0; j < dwRs.Length; j++)
                    {
                        db.Tags[j].Value     = dwRs[j];
                        db.Tags[j].Timestamp = DateTime.Now;
                    }
                    break;

                case "Real":
                    var rl1Arys = modbus.ReadHoldingRegisters((byte)dv.SlaveId,
                                                              $"{db.StartAddress}", db.Length);
                    var rl1Rs = Real.ToArray(rl1Arys);
                    for (var j = 0; j < rl1Rs.Length; j++)
                    {
                        db.Tags[j].Value     = rl1Rs[j];
                        db.Tags[j].Timestamp = DateTime.Now;
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                EventscadaException?.Invoke(this.GetType().Name + "   XModbus.SendPackage", ex.Message);
            }
        }