Пример #1
0
        public float ReadAnalog(byte slaveId, ushort address, ushort size)
        {
            float ret = 0;

            if (size == 2)
            {
                ushort[] registers = master.ReadInputRegisters(slaveId, address, 1);
                ret = Convert.ToSingle(registers);
            }
            else

            if (size == 4)
            {
                ushort[] registers = master.ReadInputRegisters(slaveId, address, 2);
                ret = ModbusUtility.GetSingle(registers[0], registers[1]);
            }
            return(ret);
        }
Пример #2
0
        /// <summary>
        /// read the data from the PLC and parse it and save it to the database
        /// </summary>
        /// <param name="OmniMaster">Masters object</param>
        /// <param name="startAddress">start register of information (start offset)</param>
        /// <param name="numInputs">number of registers containing information</param>
        public static void ReadSlaveOmniID(ModbusIpMaster OmniMaster, ushort startAddress, ushort numInputs)
        {
            ushort[] inputs = OmniMaster.ReadInputRegisters(startAddress, numInputs);

            //parsing logic and send information somewhere
            for (int i = 0; i < numInputs; i++)
            {
                Console.WriteLine("Register {0}={1}", startAddress + i, inputs[i]);
            }
        }
Пример #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="header"></param>
        public void PrintReadInputRegsiterContents(string header)
        {
#if PRODUCTION_PLC_DRIVER_DEBUG
            System.Threading.Thread.Sleep(50);

            ushort[] inputRegisters = MCUModbusMaster.ReadInputRegisters(MCUConstants.ACTUAL_MCU_READ_INPUT_REGISTER_START_ADDRESS, 10);
            Console.WriteLine(header + ":");
            foreach (ushort us in inputRegisters)
            {
                string usString = Convert.ToString(us, 2);
                usString = new string('0', 16 - usString.Length) + usString;
                usString = usString.Insert(4, " ");
                usString = usString.Insert(9, " ");
                usString = usString.Insert(14, " ");

                Console.WriteLine('\t'.ToString() + usString);
            }
#endif
        }
Пример #4
0
        private ushort[] ModbusRead()
        {
            Error(false);
            try
            {
                startAddress = ushort.Parse(textBox_startAddress.Text);
                numInputs    = ushort.Parse(textBox_numInputs.Text);
                slaveID      = byte.Parse(textBox_SlaveID.Text);
                ushort[] datas = new ushort[numInputs];


                switch (comboBox_FunCode.SelectedIndex)
                {
                case 0:
                    bool[] coils = master.ReadCoils(slaveID, startAddress, numInputs);
                    for (int i = 0; i < numInputs; i++)
                    {
                        datas[i] = (ushort)(coils[i] ? 1 : 0);
                    }

                    break;

                case 1:

                    bool[] inputs = master.ReadInputs(slaveID, startAddress, numInputs);
                    for (int i = 0; i < numInputs; i++)
                    {
                        datas[i] = (ushort)(inputs[i] ? 1 : 0);
                    }
                    break;

                case 2:
                    ushort[] holdingRegisters = master.ReadHoldingRegisters(slaveID, startAddress, numInputs);
                    datas = holdingRegisters;
                    break;

                case 3:
                    ushort[] inputRegisters = master.ReadInputRegisters(slaveID, startAddress, numInputs);
                    datas = inputRegisters;
                    break;

                default:
                    MessageBox.Show("功能码错误");
                    datas = null;
                    break;
                }
                txt_show.AppendText("\r\nModbusRead Success");
                return(datas);
            }
            catch (Exception eee)
            {
                Error(true, eee);
                return(null);
            }
        }
Пример #5
0
        /// <summary>
        /// Simple Modbus TCP master read inputs example.
        /// </summary>
        public static void ModbusTcpMasterReadInputs()
        {
            using (TcpClient client = new TcpClient("192.168.31.44", 502))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                // read five input values
                ushort startAddress = 0;
                ushort numInputs    = 10;
                //bool[] inputs = master.ReadInputs(startAddress, numInputs);

                //for (int i = 0; i < numInputs; i++)
                //    Console.WriteLine("Input {0}={1}", startAddress + i, inputs[i] ? 1 : 0);
                //    Console.ReadLine();

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

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

                for (int j = 0; j < 10; j++)
                {
                    inputs = master.ReadInputRegisters(startAddress, numInputs);
                    for (int i = 0; i < numInputs; i++)
                    {
                        Console.WriteLine("Register {0}={1}", startAddress + i, inputs[i]);
                    }
                }
            }

            // output:
            // Input 100=0
            // Input 101=0
            // Input 102=0
            // Input 103=0
            // Input 104=0
        }
Пример #6
0
        /// <summary>
        /// 获取IO节点地址
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public string GetIoNode(ref List <CT2.CIoNode> list)
        {
            list.Clear();
            for (int i = 0; i < 19; i++)
            {
                //5个节点上传一次
                ushort[] inputs5;
                try
                {
                    ushort addrStart = (ushort)(CT2.ECT2InputReg.nodeInfo +
                                                i * 5 * CT2.CIoNode.NODE_INFO_LENGTH);
                    Thread.Sleep(5);
                    inputs5 = master.ReadInputRegisters(
                        addrStart, CT2.CIoNode.NODE_INFO_LENGTH * 5);
                }
                catch (Exception e)
                {
                    return(e.Message);
                }

                for (int j = 0; j < 5; j++)
                {
                    ushort[] inputs = new ushort[CT2.CIoNode.NODE_INFO_LENGTH];
                    for (int k = j * CT2.CIoNode.NODE_INFO_LENGTH;
                         k < (j + 1) * CT2.CIoNode.NODE_INFO_LENGTH;
                         k++)
                    {
                        inputs[k - j * CT2.CIoNode.NODE_INFO_LENGTH] = inputs5[k];
                    }
                    CT2.CIoNode cIoNode = new CT2.CIoNode(inputs, (ushort)(i * 5 + j + 1));
                    if (cIoNode.CheckIfExist() == true)
                    {
                        list.Add(cIoNode);
                    }
                }
            }
            return("NO_ERR");
        }
Пример #7
0
        /// <summary>
        /// use the master to poll the slave, investigating the flag register. on flag condition read information, parse and send to
        /// database.
        /// </summary>
        /// <param name="OmniMaster">Masters object</param>
        /// <param name="startAddress">start register of polling flag</param>
        /// <param name="numInputs"># of registers for the polling flag</param>
        /// <param name="dataStartAddress">start register of information</param>
        /// <param name="dataNumInputs"># of registers for the data</param>
        public static void PollSlaveOmniId(ModbusIpMaster OmniMaster, ushort startAddress, ushort numInputs, ushort dataStartAddress, ushort dataNumInputs)
        {
            // read polling register and do action when set high
            while (_shouldpoll)
            {
                ushort[] inputs = OmniMaster.ReadInputRegisters(startAddress, numInputs);
                int      flag   = inputs[0];

                if (flag > 0)
                {
                    ReadSlaveOmniID(OmniMaster, dataStartAddress, dataNumInputs);
                }
            }
        }
Пример #8
0
        /// <summary>
        ///     Modbus TCP master and slave example.
        /// </summary>
        public async 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();

            ModbusSlave slave = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener);

            var listenTask = slave.ListenAsync();

            // create the master

            TcpClient masterTcpClient = new TcpClient();

            masterTcpClient.ReceiveTimeout = 3000;
            masterTcpClient.SendTimeout    = 3000;
            await masterTcpClient.ConnectAsync(IpAddressInputBox.Text, int.Parse(TcpPortInputBox.Text));

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTcpClient);

            ushort numInputs = 5;

            ushort startAddress = 100;

            // read five register values

            ushort[] inputs = master.ReadInputRegisters(startAddress, numInputs);

            for (int i = 0; i < numInputs; i++)
            {
                ResultsTextBox.Text += ($"Register {(startAddress + i)}={(inputs[i])}") + "\r\n";
            }



            // clean up

            masterTcpClient.Dispose();

            slaveTcpListener.Stop();
        }
Пример #9
0
        private void ReadValues()
        {
            System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
            myWatch.Start();

            isreading = true;
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.CoilStatuses.Maps != null)
            {
                foreach (var item in myDevice.Collection.CoilStatuses.Maps)
                {
                    bool[] values = master.ReadCoils(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.CoilStatuses.RefreshValues(item, values);
                }
            }
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.InputStatuses.Maps != null)
            {
                foreach (var item in myDevice.Collection.InputStatuses.Maps)
                {
                    bool[] values = master.ReadInputs(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.InputStatuses.RefreshValues(item, values);
                }
            }
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.HoldingRegisters.Maps != null)
            {
                foreach (var item in myDevice.Collection.HoldingRegisters.Maps)
                {
                    ushort[] values = master.ReadHoldingRegisters(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.HoldingRegisters.RefreshValues(item, values);
                }
            }
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.InputRegisters.Maps != null)
            {
                foreach (var item in myDevice.Collection.InputRegisters.Maps)
                {
                    ushort[] values = master.ReadInputRegisters(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.InputRegisters.RefreshValues(item, values);
                }
            }
            isreading = false;
            myWatch.Stop();
        }
Пример #10
0
        public static ushort[] Read_InputRegisters(ushort read_start_addr, ushort num_register)
        {
            num_register    = _numOfInputRegister;
            read_start_addr = _readstartAddress;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            ushort[] read_result = master.ReadInputRegisters(read_start_addr, num_register);

            Stop_MBClient();
            Stop_MBServer();
            return(read_result);
        }
Пример #11
0
        public static void ModbusTcpMasterReadInputRegisters()
        {
            //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();
            //ModbusSlave slave = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener);
            //Thread slaveThread = new Thread(slave.Listen);
            //slaveThread.Start();

            // create the master
            TcpClient      masterTcpClient = new TcpClient(address.ToString(), port);
            ModbusIpMaster master          = ModbusIpMaster.CreateIp(masterTcpClient);

            ushort numInputs    = 10;
            ushort startAddress = 0;

            // read five register values


            while (true)
            {
                ushort[] inputs = master.ReadInputRegisters(startAddress, numInputs);
                for (int i = 0; i < numInputs; i++)
                {
                    Console.WriteLine($"Register {(startAddress + i)}={(inputs[i])}");
                }
                Thread.Sleep(1000);
            }


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

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }
Пример #12
0
        public ushort[] ReadInputRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
        {
            if (!status)
            {
                Connect();
            }

            try
            {
                return(master.ReadInputRegisters(slaveAddress, startAddress, numberOfPoints));
            }
            catch (Exception ex)
            {
                status = false;
                AddMessage("Catch exception in function ReadInputRegisters(). " + ex.Message,
                           DebugLevel.ExceptionLevel);
                return(null);
            }
        }
Пример #13
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 slaveTcp = new TcpListener(address, port);

            slaveTcp.Start();
            ModbusSlave slave      = ModbusTcpSlave.CreateTcp(slaveId, slaveTcp);
            var         listenTask = slave.ListenAsync();

            // create the master
            TcpClient masterTcp = new TcpClient();

            masterTcp.ConnectAsync(address.ToString(), port);
            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTcp);

            ushort numInputs    = 4;
            ushort startAddress = 100;

            // read five register values
            ushort[] inputs = master.ReadInputRegisters(startAddress, numInputs);
            bool[]   inp    = master.ReadCoils(startAddress, 10);

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

            // clean up
            masterTcp.Dispose();
            slaveTcp.Stop();

            //    // output
            //    // Register 100=0
            //    // Register 101=0
            //    // Register 102=0
            //    // Register 103=0
            //    // Register 104=0
            //}
        }
Пример #14
0
        private static void CommunicationTest()
        {
            TcpClient      client = new TcpClient("127.0.0.1", 502);
            ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

            // read five input values
            ushort startAddress = 0;
            ushort numInputs    = 16;

            bool[] inputs = master.ReadCoils(startAddress, numInputs);


            // Odczyt cyfrowych
            var digitalInputs = master.ReadInputs(startAddress, 16);

            /// Odczyt analogowych
            var analogInputs = master.ReadInputRegisters(0, 16);

            var numbers = new ushort[] { 55, 66 };

            master.WriteMultipleRegisters(0, numbers);


            // Zapis
            master.WriteSingleCoil(18, true);



            // Zapis do Holding Registers
            master.WriteSingleRegister(1, 254);

            var holding = master.ReadHoldingRegisters(0, 2);

            var digitalInputs2 = master.ReadInputs(startAddress, 16);

            for (int i = 0; i < numInputs; i++)
            {
                Console.WriteLine("Input {0}={1}", startAddress + i, inputs[i] ? 1 : 0);
            }
        }
Пример #15
0
        public static PlcFrame Read(string plcHostName)
        {
            // setup connection to plc
            if (!EnsureConnected(plcHostName))
            {
                return(null);
            }

            try
            {
                var result = master.ReadInputRegisters(0, 15);
                var frame  = new PlcFrame(result);
                Log.Debug(frame.ToString);

                return(frame);
            }
            catch (Exception ex)
            {
                Log.ErrorException("Read PLC failed", ex);

                return(null);
            }
        }
Пример #16
0
        public ushort[] ReadRegisters(FunctionCode fc, int baseAddress, int length)
        {
            ushort[] regData;
            if (this.CheckConnection())
            {
                try {
                    using TcpClient client = new TcpClient(this.IpAddress, this.Port);
                    ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                    switch (fc)
                    {
                    case FunctionCode.ReadInputRegisters: {
                        regData = master.ReadInputRegisters(this.SlaveAddress, (ushort)baseAddress, (ushort)length);
                        client.Close();
                        master.Dispose();
                        return(regData);
                    }

                    case FunctionCode.ReadHoldingRegisters: {
                        regData = master.ReadHoldingRegisters(this.SlaveAddress, (ushort)baseAddress, (ushort)length);
                        client.Close();
                        master.Dispose();
                        return(regData);
                    }

                    default: {
                        client.Close();
                        master.Dispose();
                        return(null);
                    }
                    }
                } catch {
                    return(null);
                }
            }
            return(null);
        }
Пример #17
0
        private void DataRetrievingThread()
        {
#if DEMO
            Random rnd = new Random();
#endif
            while (true)
            {
                // Get time
                DateTime now = DateTime.Now;
                // Read
                lock (DataContainer.Data.DataQueue)
                {
                    // Register
                    for (int i = 0; i < N3PR.REG_ADDRESS.Count; i++)
                    {
                        try
                        {
                            ushort[] regs = new ushort[2];
#if !DEMO
                            if (N3PR.REG_FUNCTION_CODES[i] == "0x04")
                            {
                                regs = _master.ReadInputRegisters(N3PR.REG_ADDRESS[i], 1);
                            }
                            else if (N3PR.REG_FUNCTION_CODES[i] == "0x02")
                            {
                                bool[] _hh = _master.ReadInputs(N3PR.REG_ADDRESS[i], 1);
                                for (int j = 0; j < _hh.Count(); j++)
                                {
                                    regs[j] = Convert.ToUInt16(_hh[j]);
                                }
                            }
#endif
                            if (regs != null && regs.Count() > 0)
                            {
#if DEMO
                                var mp = new MeasurePoint
                                {
                                    Date     = now,
                                    Reg_Name = N3PR.REG_NAMES[i],
                                    b_val    = Convert.ToBoolean(rnd.Next(0, 2)),
                                    i_val    = Convert.ToInt32((uint)rnd.Next(0, 32766)),
                                    ui_val   = (uint)rnd.Next(0, 65535)
                                };
                                DataContainer.Data.DataQueue.Add(mp);
#else
                                if (regs[0] < 32766)
                                {
                                    var mp = new MeasurePoint
                                    {
                                        Date     = now,
                                        Reg_Name = N3PR.REG_NAMES[i],
                                        b_val    = Convert.ToBoolean(regs[0]),
                                        i_val    = Convert.ToInt32(regs[0]),
                                        ui_val   = (uint)regs[0]
                                    };
                                    DataContainer.Data.DataQueue.Add(mp);
                                }
                                else
                                {
                                    var mp = new MeasurePoint
                                    {
                                        Date     = now,
                                        Reg_Name = N3PR.REG_NAMES[i],
                                        b_val    = Convert.ToBoolean(regs[0]),
                                        i_val    = Convert.ToInt32(regs[0] - 65532),
                                        ui_val   = (uint)regs[0]
                                    };
                                    DataContainer.Data.DataQueue.Add(mp);
                                }
#endif
                                OnDataReceivedEvent?.Invoke(this, null);
                            }
                        }
                        catch
                        {
                            Status = "Error reading Data ModBus register.\n";
                            return;
                        }
                    }
                }
                Thread.Sleep(1000 * FreqReadSec);
            }
        }
Пример #18
0
    public bool Read_pq_kwh(ref ModbusIpMaster master) //tcp使用
    {
        if (master != null)
        {
            try
            {
                Thread.Sleep(Form1.WaitingTime);
                //ushort[] data0 = new ushort[28];
                data0 = master.ReadInputRegisters(this.slaveID, address_v, 28);
                v_a   = ushortToFloat(data0[0], data0[1]);
                v_b   = ushortToFloat(data0[2], data0[3]);
                v_c   = ushortToFloat(data0[4], data0[5]);
                v     = ushortToFloat(data0[6], data0[7]);
                vl_ab = ushortToFloat(data0[8], data0[9]);
                vl_bc = ushortToFloat(data0[10], data0[11]);
                vl_ca = ushortToFloat(data0[12], data0[13]);
                vl    = ushortToFloat(data0[14], data0[15]);
                i_a   = ushortToFloat(data0[16], data0[17]);
                i_b   = ushortToFloat(data0[18], data0[19]);
                i_c   = ushortToFloat(data0[20], data0[21]);
                i     = ushortToFloat(data0[22], data0[23]);
                i_n   = ushortToFloat(data0[24], data0[25]);
                f     = ushortToFloat(data0[26], data0[27]);

                Thread.Sleep(Form1.WaitingTime);
                data        = master.ReadInputRegisters(this.slaveID, address_power_a, 24);
                power_a     = ushortToFloat(data[0], data[1]);
                power_b     = ushortToFloat(data[2], data[3]);
                power_c     = ushortToFloat(data[4], data[5]);
                power_total = ushortToFloat(data[6], data[7]);
                Q1          = ushortToFloat(data[8], data[9]);
                Q2          = ushortToFloat(data[10], data[12]);
                Q3          = ushortToFloat(data[12], data[13]);
                Q_total     = ushortToFloat(data[14], data[15]);
                s_a         = ushortToFloat(data[16], data[17]);
                s_b         = ushortToFloat(data[18], data[19]);
                s_c         = ushortToFloat(data[20], data[21]);
                s           = ushortToFloat(data[22], data[23]);
                Thread.Sleep(Form1.WaitingTime);
                data2 = master.ReadInputRegisters(slaveID, address_energy, 18);

                exp_wh_h   = ushortToFloat(data2[0], data2[1]);
                imp_wh_h   = ushortToFloat(data2[2], data2[3]);
                tot_wh_h   = ushortToFloat(data2[4], data2[5]);
                net_wh_h   = ushortToFloat(data2[6], data2[7]);
                exp_varh_h = ushortToFloat(data2[10], data2[11]);
                imp_varh_h = ushortToFloat(data2[8], data2[9]);
                tot_varh_h = ushortToFloat(data2[12], data2[13]);
                net_varh_h = ushortToFloat(data2[14], data2[15]);
                vah_h      = ushortToFloat(data2[16], data2[17]);

                Thread.Sleep(Form1.WaitingTime);

                data3 = master.ReadInputRegisters(slaveID, address_PF, 8);
                pf_a  = ushortToFloat(data3[0], data3[1]);
                pf_b  = ushortToFloat(data3[2], data3[3]);
                pf_c  = ushortToFloat(data3[4], data3[5]);
                pf    = ushortToFloat(data3[6], data3[7]);

                CommFailureFlag = false;
                Fault_info      = "Communication is normal";
                return(true);
            }
            catch (Exception e)
            {
                CommFailureFlag = true;
                Fault_info      = e.Message;
                return(false);
            }
        }
        return(false);
    }
Пример #19
0
        public Dictionary <string, object> ReadAll()
        {
            if (MyModFieldStore == null || MyModFieldStore.TheValues.Count == 0)
            {
                return(null);
            }
            var timestamp = DateTimeOffset.Now;
            var dict      = new Dictionary <string, object>();

            dict["Timestamp"] = timestamp;

            // Read configured data items via Modbus
            int tMainOffset   = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "Offset");
            int tSlaveAddress = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "SlaveAddress");
            int tReadWay      = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "ConnectionType");

            foreach (var field in MyModFieldStore.TheValues)
            {
                try
                {
                    int address = field.SourceOffset + tMainOffset;

                    ushort[] data = null;

                    float scale = field.ScaleFactor;
                    if (scale == 0)
                    {
                        scale = 1.0f;
                    }

                    switch (tReadWay)
                    {
                    case 1:
                    {
                        bool[] datab = MyModMaster.ReadCoils((ushort)address, (ushort)field.SourceSize);
                        for (int i = 0; i < field.SourceSize && i < datab.Length; i++)
                        {
                            dict[$"{field.PropertyName}_{i}"] = datab[i];
                        }
                        field.Value = dict[$"{field.PropertyName}_0"];
                    }
                        continue;

                    case 2:
                    {
                        bool[] datab = MyModMaster.ReadInputs((ushort)address, (ushort)field.SourceSize);
                        for (int i = 0; i < field.SourceSize && i < datab.Length; i++)
                        {
                            dict[$"{field.PropertyName}_{i}"] = datab[i];
                        }
                        field.Value = dict[$"{field.PropertyName}_0"];
                    }
                        continue;

                    case 4:
                        data = MyModMaster.ReadInputRegisters((byte)tSlaveAddress, (ushort)address, (ushort)field.SourceSize);
                        break;

                    default:
                        data = MyModMaster.ReadHoldingRegisters((byte)tSlaveAddress, (ushort)address, (ushort)field.SourceSize);
                        break;
                    }
                    if (data == null)
                    {
                        continue;
                    }
                    if (field.SourceType == "float")
                    {
                        var value1 = TypeFloat.Convert(data, TypeFloat.ByteOrder.CDAB);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "float-abcd")
                    {
                        var value1 = TypeFloat.Convert(data, TypeFloat.ByteOrder.ABCD);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "double")
                    {
                        var value1 = TypeDouble.Convert(data, TypeDouble.ByteOrder.ABCD);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "double-cdab")
                    {
                        var value1 = TypeDouble.Convert(data, TypeDouble.ByteOrder.CDAB);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "int32")
                    {
                        var value    = TypeInt32.Convert(data);
                        var dblValue = Convert.ToDouble(value);
                        dict[field.PropertyName] = dblValue / scale;
                    }
                    else if (field.SourceType == "int64")
                    {
                        var value    = TypeInt64.Convert(data);
                        var dblValue = Convert.ToDouble(value);
                        dict[field.PropertyName] = dblValue / scale;
                    }
                    else if (field.SourceType == "float32")
                    {
                        var value = TypeFloat.Convert(data, TypeFloat.ByteOrder.SinglePrecIEEE);
                        dict[field.PropertyName] = value / scale;
                    }
                    else if (field.SourceType == "uint16")
                    {
                        var value = TypeUInt16.Convert(data);
                        dict[field.PropertyName] = value / scale;
                    }
                    else if (field.SourceType == "int16")
                    {
                        var value = TheCommonUtils.CInt(data[0]);
                        dict[field.PropertyName] = value / scale;
                    }
                    else if (field.SourceType == "utf8")
                    {
                        var value = TypeUTF8.Convert(data);
                        dict[field.PropertyName] = value;
                    }
                    else if (field.SourceType == "byte")
                    {
                        byte value = (byte)(data[0] & 255);
                        dict[field.PropertyName] = value;
                    }
                    field.Value = dict[field.PropertyName];

                    //dict[$"[{field.PropertyName}].[Status]"] = $"";
                }
                catch (Exception e)
                {
                    try
                    {
                        // Future: convey per-tag status similar to OPC statuscode?
                        //dict[$"[{field.PropertyName}].[Status]"] = $"##cdeError: {e.Message}";
                        TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, $"Error reading property {field.PropertyName}", eMsgLevel.l2_Warning, e.ToString()));
                    }
                    catch { }
                }
            }
            return(dict);
        }
Пример #20
0
 /* 读多个输入寄存器(AI)*/
 public void ReadInputRegisters(ushort startAddress, ushort numberOfPoints, ref List <ushort> list)
 {
     ushort[] data;
     data = master.ReadInputRegisters(startAddress, numberOfPoints);
     list = data.ToList();
 }
Пример #21
0
        static void Main(string[] args)
        {
            try{
                /*
                 *  Connecting via TCP
                 */
                TcpClient      client = new TcpClient("192.168.42.114", 502); //IP and port of the TOTUS unit
                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                master.Transport.ReadTimeout = 1000;                          //ms


                {
                    // read multiple int16 values
                    string[] totusTemps =
                    {
                        "Thermal/AmbientTemp",
                        "Thermal/AmbientTemp/1hAvg",
                        "Thermal/AmbientHumidity",
                        "Thermal/AmbientHumidity/1hAvg",
                        "Thermal/TopOilTemp",
                        "Thermal/TopOilTemp/1hAvg",
                        "Thermal/BottomOilTemp",
                        "Thermal/BottomOilTemp/1hAvg",
                        "Thermal/TapChangerTemp",
                        "Thermal/TapChangerTemp/1hAvg"
                    };

                    {
                        //read int16 temperatures
                        ushort   numInputs    = 10;
                        byte     slaveID      = 1;
                        ushort   startAddress = 1000;                                                        //select address from Totus Modbus table
                        ushort[] temps        = master.ReadInputRegisters(slaveID, startAddress, numInputs); //*2 because we are reading 2byte unsigned short that needs converted to 4 byte floats

                        for (int i = 0; i < numInputs; i++)
                        {
                            Console.WriteLine("{0} = {1}°C", totusTemps[i], (float)temps[i] / 10); // divide by 10 as specified in Scaling column
                        }
                    }
                }
                {
                    //read alarms
                    byte   slaveID      = 1;
                    ushort numInputs    = 2;
                    ushort startAddress = 100;
                    bool[] alarms       = master.ReadInputs(slaveID, startAddress, numInputs);

                    string[] totusAlarms =
                    {
                        "ALARM/System/HL/State",
                        "ALARM/System/HHLL/State"
                    };
                    for (int i = 0; i < numInputs; i++)
                    {
                        Console.WriteLine("{0} = {1}", totusAlarms[i], alarms[i]);
                    }
                }
                {
                    //read DGA float32 gases
                    string[] totusDGA =
                    {
                        "DGA/SourceA/CH4",
                        "DGA/SourceA/C2H6",
                        "DGA/SourceA/C2H4",
                        "DGA/SourceA/C2H2",
                        "DGA/SourceA/CO",
                        "DGA/SourceA/CO2",
                        "DGA/SourceA/O2",
                        "DGA/SourceA/N2",
                        "DGA/SourceA/H2",
                        "DGA/SourceA/H2O",
                        "DGA/SourceA/TDCG",
                        "DGA/SourceA/THC"
                    };
                    byte     slaveID      = 1;
                    ushort   numInputs    = 12;
                    ushort   startAddress = 2200;                                                                      //select address from Totus Modbus table
                    ushort[] inputsdga    = master.ReadInputRegisters(slaveID, startAddress, (ushort)(numInputs * 2)); //*2 because we are reading 2byte unsigned short that needs converted to 4 byte floats

                    for (int i = 0; i < numInputs; i++)
                    {
                        Console.WriteLine("{0} = {1} ppm", totusDGA[i], Convert2Float(inputsdga[i * 2], inputsdga[i * 2 + 1]));
                    }
                }
                master.Dispose();
            }
            catch (Exception exception)
            {
                //Connection exception
                //No response from server.
                //The server maybe close the connection, or response timeout.
                Console.WriteLine(exception.Message);
            }
            Console.Read();
        }
Пример #22
0
 /// <summary>
 /// Чтение по 4 функции ReadInput
 /// </summary>
 /// <param name="master"></param>
 /// <param name="reg"></param>
 /// <returns></returns>
 public string ReadInputRegisters(ModbusIpMaster master, ushort reg)
 {
     return(Convert.ToString(master.ReadInputRegisters(1, reg, 1)[0]));
 }
        private static void ChannelUpdaterThreadProc(object obj)
        {
            try
            {
                ModbusStation self = (ModbusStation)obj;
                for (; ;)
                {
                    try
                    {
                        using (TcpClient client = new TcpClient(self.ipAddress, self.tcpPort))
                        {
                            ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                            for (; ;)
                            {
                                foreach (ModbusBuffer buf in self.buffers)
                                {
                                    ushort startAddress = buf.startAddress;
                                    ushort numInputs    = buf.numInputs;
                                    switch (buf.ModbusDataType)
                                    {
                                    case ModbusDataType.InputRegister:
                                        ushort[] registers = master.ReadInputRegisters(startAddress, numInputs);
                                        DateTime dt        = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                ch.DoUpdate((int)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                ch.DoUpdate((uint)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                ch.DoUpdate((float)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;

                                    case ModbusDataType.Coil:
                                        bool[] inputs = master.ReadCoils(startAddress, numInputs);
                                        dt = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                int val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                uint val = (uint)(inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0);
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                float val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;

                                    case ModbusDataType.Input:
                                        inputs = master.ReadInputs(startAddress, numInputs);
                                        dt     = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                int val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                uint val = (uint)(inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0);
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                float val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;

                                    case ModbusDataType.HoldingRegister:
                                        registers = master.ReadHoldingRegisters(startAddress, numInputs);
                                        dt        = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                ch.DoUpdate((int)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                ch.DoUpdate((uint)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                ch.DoUpdate((float)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;
                                    }
                                }
                                Thread.Sleep(100);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (e is ThreadAbortException)
                        {
                            throw e;
                        }
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException)
            {
            }
        }
Пример #24
0
        //public static void HandleRunningInstance(Process instance)
        //{
        //    // 相同時透過ShowWindowAsync還原,以及SetForegroundWindow將程式至於前景
        //    ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
        //    tcp.F_SetForegroundWindow(instance.MainWindowHandle);
        //}
        long Form1_Load()
        {
            cThirdPartyToolControl tpc = new cThirdPartyToolControl();

            string[] file_name = { "CoilStatus_250_Sync_20160331", "HoldingRegister_250_Sync_20160401", "InputRegister_250_Sync_20160331", "InputStatus_250_Sync_20160401" };

            try
            {
                Process[] processes = Process.GetProcessesByName("ModSim32");
                foreach (Process p in processes)
                {
                    // 關閉目前程序前先等待 1000 毫秒
                    p.WaitForExit(1000);
                    p.CloseMainWindow();
                }
                EventLog.AddLog("Check existed ModSim and Close it");
                System.Threading.Thread.Sleep(1000);

                string str = this.GetType().Assembly.Location;
                str = str.Substring(0, str.LastIndexOf(@"\"));
                string sourceDirName = @"\ModSim";
                string destDirName   = @"c:\ModSim";
                bool   copySubDirs   = true;
                DirectoryCopy(str + sourceDirName, destDirName, copySubDirs);

                string sExePath = Directory.GetCurrentDirectory();  // 如果是用iATester執行初始exe 也是指到iATester執行檔位置
                                                                    // 如果是用初始exe檔直接執行 則是指到初始exe檔執行位置
                string sCurrentFilePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(this.GetType()).Location);
                //sCurrentFilePath無論用什麼執行 就是指到初始exe檔執行位置
                for (int i = 0; i < file_name.Length; i++)
                {
                    string sourceFile = sCurrentFilePath + "\\ModSim\\" + file_name[i];
                    string destFile   = sExePath + "\\" + file_name[i];
                    EventLog.AddLog("copy " + sourceFile + " to " + destFile);
                    System.IO.File.Copy(sourceFile, destFile, true);
                }
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred Delete ModSim and Move it to C:\ : " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                Process ModSim = new Process();
                // FileName 是要執行的檔案
                ModSim.StartInfo.FileName = @"C:\ModSim\ModSim32.exe";
                ModSim.Start();

                EventLog.AddLog("Excute ModSim");
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred Excute ModSim: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                System.Threading.Thread.Sleep(3000);
                //EventLog.AddLog("enter");
                tpc.F_KeybdEvent(tpc.V_VK_ESCAPE, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                //EventLog.AddLog("wait 1 sec");
                System.Threading.Thread.Sleep(1000);

                foreach (Process pTarget in Process.GetProcesses())
                {
                    if (pTarget.ProcessName == "ModSim32")  // 取得處理序名稱並與指定程序名稱比較
                    {
                        //HandleRunningInstance(pTarget);
                        ShowWindowAsync(pTarget.MainWindowHandle, WS_SHOWNORMAL);
                        tpc.F_SetForegroundWindow((int)pTarget.MainWindowHandle);
                    }
                }

                EventLog.AddLog("Load script");

                //string[] file_name = { "CoilStatus_250_Sync_20160331" };

                for (int i = 0; i < file_name.Length; i++)
                {
                    System.Threading.Thread.Sleep(2000);
                    SendKeys.SendWait("^o");
                    System.Threading.Thread.Sleep(1000);

                    int           iRecipeList_Handle = tpc.F_FindWindow("#32770", "Open");
                    StringBuilder lpString           = new StringBuilder(10);
                    int           bb          = tpc.F_GetWindowText(iRecipeList_Handle, lpString, 100);
                    int           iEnterText2 = tpc.F_FindWindowEx(iRecipeList_Handle, 0, "Edit", "");
                    if (iEnterText2 > 0)
                    {
                        byte[] ch = (ASCIIEncoding.ASCII.GetBytes(file_name[i]));
                        for (int j = 0; j < ch.Length; j++)
                        {
                            //SendMessage(PW, WM_CHAR, ch, 0);
                            tpc.F_PostMessage(iEnterText2, tpc.V_WM_CHAR, ch[j], 0);
                            //System.Threading.Thread.Sleep(100);
                        }
                        tpc.F_PostMessage(iEnterText2, tpc.V_WM_KEYDOWN, tpc.V_VK_RETURN, 0);

                        //tpc.F_PostMessage(iEnterText2, tpc.V_WM_CHAR, 'a', 0);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred Load file: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                EventLog.AddLog("connect to TCP");

                System.Threading.Thread.Sleep(2000);
                SendKeys.SendWait("%c");
                System.Threading.Thread.Sleep(1000);
                SendKeys.SendWait("%c");
                System.Threading.Thread.Sleep(1000);
                tpc.F_KeybdEvent(tpc.V_VK_RETURN, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                System.Threading.Thread.Sleep(1000);
                tpc.F_KeybdEvent(tpc.V_VK_UP, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                System.Threading.Thread.Sleep(1000);
                tpc.F_KeybdEvent(tpc.V_VK_RETURN, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                System.Threading.Thread.Sleep(2000);
                tpc.F_KeybdEvent(tpc.V_VK_RETURN, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred connect to TCP: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                if (master != null)
                {
                    master.Dispose();
                }
                if (tcpClient != null)
                {
                    tcpClient.Close();
                }
                tcpClient = new TcpClient();
                IAsyncResult asyncResult = tcpClient.BeginConnect(ipAddress, tcpPort, null, null);
                asyncResult.AsyncWaitHandle.WaitOne(3000, true); //wait for 3 sec
                if (!asyncResult.IsCompleted)
                {
                    tcpClient.Close();
                    EventLog.AddLog("Cannot connect to ModSim.");
                    return(-1);
                }
                //tcpClient = new TcpClient(ipAddress, tcpPort);

                // create Modbus TCP Master by the tcp client
                //document->Modbus.Device.Namespace->ModbusIpMaster Class->Create Method
                master = ModbusIpMaster.CreateIp(tcpClient);
                master.Transport.Retries     = 0; //don't have to do retries
                master.Transport.ReadTimeout = 1500;
                //this.Text = "On line " + DateTime.Now.ToString();
                EventLog.AddLog("Connect to ModSim.");

                //read DI(1xxxx), start address=0, points=4
                byte   slaveID = 1;
                bool[] status  = master.ReadInputs(slaveID, 0, 1);
                if ((status[0] == true) || (status[0] == false))
                {
                }
                else
                {
                    EventLog.AddLog("read DI(10001) fail");
                    return(-1);
                }
                //read DO(00001), start address=0, points=1
                bool[] coils = master.ReadCoils(slaveID, 0, 1);
                if ((coils[0] == true) || (coils[0] == false))
                {
                }
                else
                {
                    EventLog.AddLog("read DO(00001) fail");
                    return(-1);
                }
                //read AI(30001), start address=0, points=1
                ushort[] register = master.ReadInputRegisters(1, 0, 1);
                if (register[0] > 0)
                {
                }
                else
                {
                    EventLog.AddLog("read AI(30001) fail");
                    return(-1);
                }
                //read AO(40001), start address=0, points=1
                ushort[] holding_register = master.ReadHoldingRegisters(1, 0, 1);
                if (holding_register[0] > 0)
                {
                }
                else
                {
                    EventLog.AddLog("read AO(40001) fail");
                    return(-1);
                }
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred verification: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            #region Result judgement
            int iTotalSeleniumAction = dataGridView1.Rows.Count;
            for (int i = 0; i < iTotalSeleniumAction - 1; i++)
            {
                DataGridViewRow row             = dataGridView1.Rows[i];
                string          sSeleniumResult = row.Cells[2].Value.ToString();
                if (sSeleniumResult != "PASS")
                {
                    bFinalResult = false;
                    EventLog.AddLog("Test Fail !!");
                    EventLog.AddLog("Fail TestItem = " + row.Cells[0].Value.ToString());
                    EventLog.AddLog("BrowserAction = " + row.Cells[1].Value.ToString());
                    EventLog.AddLog("Result = " + row.Cells[2].Value.ToString());
                    EventLog.AddLog("ErrorCode = " + row.Cells[3].Value.ToString());
                    EventLog.AddLog("ExeTime(ms) = " + row.Cells[4].Value.ToString());
                    break;
                }
            }

            if (bFinalResult)
            {
                Result.Text      = "PASS!!";
                Result.ForeColor = Color.Green;
                EventLog.AddLog("Test Result: PASS!!");
                return(0);
            }
            else
            {
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }
            #endregion
        }
Пример #25
0
        override public void Run() // переопределяемая функция запуска програмного потока для обслуживания работающего драйвера ModbusTCPMaster
        {
            do
            {
                // счетчик таймера операций ModbusTCPMaster

                DateTime tm = DateTime.Now;  // переменная хранит начальное время запуска потока
                Util.time = tm;
                if (!device.ready)
                {
                    master.Dispose();
                    tcpClient.Close();
                    device.status = 200;
                    device.ready  = false;
                    break;
                }
                cleanQuery();
                try
                {
                    if (lencoils > 0)
                    {
                        varcoils = master.ReadCoils(0, lencoils);
                    }
                    if (lendi > 0)
                    {
                        vardi = master.ReadInputs(0, lendi);
                    }
                    if (lenir > 0)
                    {
                        ushort stadr = 0;
                        int    len   = lenir;
                        do
                        {
                            ushort lenl = (len > 100) ? (ushort)100 : (ushort)len;
                            ir = master.ReadInputRegisters(stadr, lenl);
                            for (int i = 0; i < lenl; i++)
                            {
                                varir[stadr + i] = ir[i];
                            }
                            stadr += 100;
                            len   -= 100;
                        } while (len > 0);
                    }
                    if (lenhr > 0)
                    {
                        ushort stadr = 0;
                        int    len   = lenhr;
                        do
                        {
                            ushort lenl = (len > 100) ? (ushort)100 : (ushort)len;
                            hr = master.ReadHoldingRegisters(stadr, lenl);
                            //hr = master.ReadHoldingRegisters(stadr, 1000);
                            for (int i = 0; i < lenl; i++)
                            {
                                varhr[stadr + i] = hr[i];
                            }
                            stadr += 100;
                            len   -= 100;
                        } while (len > 0);
                    }
                }
                catch (Exception err)
                {
                    Util.errorTCP();
                    Util.errorMessage(err.Message, description);
                    device.status = err.HResult;
                    master.Dispose();
                    tcpClient.Close();
                    device.status = 200;
                    device.ready  = false;
                    break;
                }
                writeVariable();

                DateTime tmnow = DateTime.Now;                            // переменная хранит время завершения операции в потоке
                int      st    = (int)((tmnow.Ticks - tm.Ticks) / 10000); // если превышено время обхода в 100 миллисекунд генерируется предупреждение с указанием колличества циклов
                                                                          // Util.errorMessage("Время потраченное на операции в ModbusTCPMaster : ", st.ToString());
                                                                          //if (st > device.steptime) { Util.errorMessage("Очень долго...." + st.ToString() + " | step time system=" + device.steptime, "; << ModbusTCPMaster >>"); st = 0; }
                if (st > device.steptime)
                {
                    Util.errorMessage("Время обработки цикла " +
                                      st.ToString() +
                                      " превысило заданный период  " +
                                      device.steptime + "  для устройства ",
                                      description);

                    st = 0;
                }



                else
                {
                    st = device.steptime - st;
                }
                if (st > 0)
                {
                    Thread.Sleep(st);
                }

                //Thread.Sleep(device.steptime);
            } while (true);
        }