public Tuple <ushort[], bool[]> ReadRegistersAndCoils(int regAddress, int regLength, int coilAddr, int coilLength)
 {
     ushort[] regData;
     bool[]   coilData;
     if (this.CheckConnection())
     {
         try {
             using TcpClient client = new TcpClient(this.IpAddress, this.Port);
             ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
             if (this.SlaveAddress != 0)
             {
                 regData  = master.ReadHoldingRegisters(this.SlaveAddress, (ushort)regAddress, (ushort)regLength);
                 coilData = master.ReadCoils(this.SlaveAddress, (ushort)coilAddr, (ushort)coilLength);
             }
             else
             {
                 regData  = master.ReadHoldingRegisters((ushort)regAddress, (ushort)regLength);
                 coilData = master.ReadCoils((ushort)coilAddr, (ushort)coilLength);
             }
             client.Close();
             master.Dispose();
             return(new Tuple <ushort[], bool[]>(regData, coilData));
         } catch {
             return(null);
         }
     }
     return(null);
 }
Пример #2
0
        public void ModbusUdpSlave_SingleMasterPollingMultipleSlaves()
        {
            DataStore slave1DataStore = new DataStore();

            slave1DataStore.CoilDiscretes.Add(true);

            DataStore slave2DataStore = new DataStore();

            slave2DataStore.CoilDiscretes.Add(false);

            using (UdpClient slave1 = CreateAndStartUdpSlave(502, slave1DataStore))
                using (UdpClient slave2 = CreateAndStartUdpSlave(503, slave2DataStore))
                    using (UdpClient masterClient = new UdpClient())
                    {
                        masterClient.Connect(ModbusMasterFixture.DefaultModbusIPEndPoint);
                        ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient);

                        for (int i = 0; i < 5; i++)
                        {
                            // we would need to create an overload taking in a port argument
                            Assert.IsTrue(master.ReadCoils(0, 1)[0]);
                            Assert.IsFalse(master.ReadCoils(1, 1)[0]);
                        }
                    }
        }
Пример #3
0
 /// <summary>
 /// 设置高压标0
 /// </summary>
 public bool SendGYBD(bool logon = false)
 {
     if (!IsTCPLink)
     {
         return(false);
     }
     try
     {
         _StartAddress = BFMCommand.GetCommandDict(BFMCommand.高压标0_交替型按钮);
         bool[] readCoils = _MASTER.ReadCoils(_SlaveID, _StartAddress, _NumOfPoints);
         if (readCoils[0])
         {
             _MASTER.WriteSingleCoil(_StartAddress, false);
         }
         else
         {
             if (logon == false)
             {
                 _MASTER.WriteSingleCoil(_StartAddress, true);
             }
         }
     }
     catch (Exception ex)
     {
         Logger.Error(ex);
         return(false);
     }
     return(true);
 }
 public bool[] ReadCoils(int address, int length)
 {
     bool[] regData;
     if (this.CheckConnection())
     {
         try {
             using TcpClient client = new TcpClient(this.IpAddress, this.Port);
             ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
             if (this.SlaveAddress != 0)
             {
                 regData = master.ReadCoils(this.SlaveAddress, (ushort)address, (ushort)length);
             }
             else
             {
                 regData = master.ReadCoils((ushort)address, (ushort)length);
             }
             client.Close();
             master.Dispose();
             return(regData);
         } catch {
             return(null);
         }
     }
     return(null);
 }
Пример #5
0
        private string GetDataArrayFromRegion(ERegionType eType,
                                              List <List <ushort> > listlistRegion,
                                              ref bool[] regionData)
        {
            List <short[]> listData = new List <short[]>();

            foreach (var listT in listlistRegion)
            {
                for (int j = 0; j < listT.Count; j = j + 5)
                {
                    ushort num;
                    if (((listT.Count - j) * 16) > 80)
                    {
                        num = 80;
                    }
                    else
                    {
                        num = (ushort)((listT.Count - j) * 16);
                    }
                    bool[] bData;
                    try
                    {
                        switch (eType)
                        {
                        case ERegionType.Region_DI:
                        {
                            Thread.Sleep(5);
                            bData = master.ReadInputs(
                                (ushort)(CT2.ECT2Descrites.RegionDI + (listT[j]) * 16),
                                (ushort)num);
                            bData.CopyTo(regionData, listT[j] * 16);
                            break;
                        }

                        case ERegionType.Region_DO:
                        {
                            Thread.Sleep(5);
                            bData = master.ReadCoils(
                                (ushort)(CT2.ECT2Coils.RegionDO + (listT[j]) * 16),
                                (ushort)num);
                            bData.CopyTo(regionData, listT[j] * 16);
                            break;
                        }

                        case ERegionType.Region_AO:
                        case ERegionType.Region_AI:
                        default:
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        return(e.Message);
                        //throw;
                    }
                }
            }
            return("NO_ERR");
        }
Пример #6
0
        private void readOutputs_Click(object sender, EventArgs e)
        {
            //connect to modbus...
            TcpClient      tcpClient = ConnectTcpClient();
            ModbusIpMaster master    = ConnectModbusMaster(tcpClient);

            ushort startAddress = 512;
            ushort numOfPoints  = 16;

            master.Transport.ReadTimeout = Convert.ToInt16(textBox5.Text);

            try
            {
                bool[] outputArr = master.ReadCoils(startAddress, numOfPoints);

                listView1.Items.Clear();

                for (int i = 0; i < numOfPoints; i++)
                {
                    int n = i + 1;
                    listView1.Items.Add(comboBox1.Items[i].ToString()).SubItems.Add(outputArr[i].ToString());
                }

                tcpClient.Close();
                master.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.ToString());
                //throw;
            }
        }
Пример #7
0
        private void readSingleCoil_Click(object sender, EventArgs e)
        {
            //connect to modbus...
            TcpClient      tcpClient = ConnectTcpClient();
            ModbusIpMaster master    = ConnectModbusMaster(tcpClient);

            master.Transport.ReadTimeout = Convert.ToInt16(textBox5.Text);

            int    selectedOutput = Convert.ToInt16(comboBox1.SelectedIndex.ToString());
            int    startAddress   = 512;
            int    o           = selectedOutput + startAddress;
            ushort readAddress = (ushort)o;

            try
            {
                bool[] outputValue = master.ReadCoils(readAddress, 1);
                textBox1.Text = outputValue[0].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.ToString());
                throw;
            }

            tcpClient.Close();
            master.Dispose();
        }
Пример #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // Taking ip from the text box.
                using (TcpClient client = new TcpClient(txtIPAddress.Text, 502))
                {
                    // Clearing register values to be read.
                    txtStatusCheck.Text = "";

                    // Establishing a connection.
                    ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                    // Assign Modbus-StartAddress and number of registers to be read.
                    ushort TrackAddress = Convert.ToUInt16(txtTrackNumber.Text);

                    // Read input register values.
                    bool[] value = master.ReadCoils(TrackAddress, 1);

                    // Write the register values.
                    txtStatusCheck.Text += value[0].ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #9
0
        /*
         * Reads Coil Register values based on the address received from the 'textReadCoilAddress' and
         * the count of the holding registers to be read from 'txtReadCoilCount'.
         * */
        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                // Taking ip from the text box.
                using (TcpClient client = new TcpClient(txtIPAddress.Text, 502))
                {
                    // Clearing register values to be read.
                    txtReadCoilValue.Text = "";

                    // Establishing a connection.
                    ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                    // Assign Modbus-StartAddress and number of registers to be read.
                    ushort StartAddress  = Convert.ToUInt16(textReadCoilAddress.Text);
                    ushort RegisterCount = Convert.ToUInt16(txtReadCoilCount.Text);

                    // Read input register values.
                    bool[] values = master.ReadCoils(StartAddress, RegisterCount);

                    // Write the register values.
                    foreach (bool us in values)
                    {
                        txtReadCoilValue.Text += us.ToString() + "; ";
                    }
                }
            }catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #10
0
        public void ModbusTcpSlave_ConnectionSlowlyClosesGracefully()
        {
            TcpListener slaveListener = new TcpListener(ModbusMasterFixture.TcpHost, ModbusMasterFixture.Port);

            slaveListener.Start();
            ModbusTcpSlave slave       = ModbusTcpSlave.CreateTcp(ModbusMasterFixture.SlaveAddress, slaveListener);
            Thread         slaveThread = new Thread(slave.Listen);

            slaveThread.IsBackground = true;
            slaveThread.Start();

            using (TcpClient masterClient = new TcpClient(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient);
                master.Transport.Retries = 0;

                bool[] coils = master.ReadCoils(1, 1);
                Assert.AreEqual(1, coils.Length);

                Assert.AreEqual(1, slave.Masters.Count);
                // wait a bit to let slave move on to read header
                Thread.Sleep(50);
            }

            // give the slave some time to remove the master
            Thread.Sleep(50);
            Assert.AreEqual(0, slave.Masters.Count);
            slaveListener.Stop();
        }
Пример #11
0
 private static void ReadDigital24v()
 {
     Console.Clear();
     Console.WriteLine("Retrieving Values, Please Wait");
     if (CheckConnection(IpAddress, 100))
     {
         bool[] coilData;
         using (TcpClient client = new TcpClient(IpAddress, 502)) {
             ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
             coilData = master.ReadCoils(0, 48);
             client.Close();
         }
         Console.WriteLine();
         Console.WriteLine("Digitals 24Volt");
         for (int i = 22; i < 38; i++)
         {
             Console.WriteLine(" D{0}: {1}", i - 22, coilData[i]);
         }
         Console.WriteLine();
         Console.WriteLine("Press any key to continue");
         Console.ReadKey();
     }
     else
     {
         Console.WriteLine("Connection Failed");
     }
 }
Пример #12
0
 private bool ReadCoil()
 {
     //Console.Write("Read..");
     this.coil_input = master.ReadCoils(40, 8);
     //Console.WriteLine(".. finished");
     return(true);
 }
Пример #13
0
        private bool ReadCoil()
        {
            //Console.Write("Read..");
            ushort startAdr = (ushort)(offset + inputLength);

            this.coil_input = master.ReadCoils(startAdr, inputLength);
            //Console.WriteLine(".. finished");
            return(true);
        }
Пример #14
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);
            }
        }
Пример #15
0
        private void RefreshValues()
        {
            lock (_locker)
            {
                {
                    if (ConnectionState == ConnectionStates.Online)
                    {
                        if (_master.Transport != null)
                        {
                            bool[] readCoils = _master.ReadCoils(1, 0, 50);

                            AutoManual       = readCoils[16];
                            RoterMoveing     = readCoils[17];
                            RoteryPosMoveing = readCoils[18];
                            ShorterMoveing   = readCoils[19];

                            ShorterGripperState  = readCoils[12];
                            ShorterCylinderState = readCoils[13];
                            MainGripperState     = readCoils[14];


                            AligmentCheck      = readCoils[27];
                            CrackCheck         = readCoils[28];
                            DustCheck          = readCoils[29];
                            TestResultState    = readCoils[30];
                            VisiontestComplete = readCoils[31];



                            ushort[] readHoldingRegister = _master.ReadHoldingRegisters(1, 0, 50);

                            InletPumpSpeed  = Convert.ToInt32(readHoldingRegister[40]);
                            OutletPumpSpeed = Convert.ToInt32(readHoldingRegister[41]);

                            ReadRoterJogSpeed = Convert.ToInt32(readHoldingRegister[1]);
                            ReadRoterPosSpeed = Convert.ToInt32(readHoldingRegister[2]);
                            ReadRoterCmdPos   = Convert.ToInt32(readHoldingRegister[3]);

                            ReadRoteryPosJogSpeed = Convert.ToInt32(readHoldingRegister[7]);
                            ReadRoteryPosPosSpeed = Convert.ToInt32(readHoldingRegister[6]);
                            ReadRoteryPosCmdPos   = Convert.ToInt32(readHoldingRegister[5]);

                            ReadShorterJogSpeed = Convert.ToInt32(readHoldingRegister[12]);
                            ReadShorterPosSpeed = Convert.ToInt32(readHoldingRegister[13]);
                            ReadShorterCmdPos   = Convert.ToInt32(readHoldingRegister[14]);

                            ProductselectedCount = Convert.ToInt32(readHoldingRegister[28]);
                            TotalPartCount       = Convert.ToInt32(readHoldingRegister[29]);
                            GoodPartCount        = Convert.ToInt32(readHoldingRegister[30]);
                            NotGoodPartCount     = Convert.ToInt32(readHoldingRegister[31]);
                        }
                    }
                }
            }
        }
Пример #16
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();
        }
Пример #17
0
        private static void ReadAndDisplay()
        {
            if (CheckConnection(IpAddress, 100))
            {
                ushort[] regData;
                bool[]   coilData;
                while (true)
                {
                    using (TcpClient client = new TcpClient(IpAddress, 502)) {
                        ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                        regData  = master.ReadHoldingRegisters(0, 16);
                        coilData = master.ReadCoils(0, 48);
                        client.Close();
                        master.Dispose();
                    }
                    Console.WriteLine("Analog");
                    for (int i = 0; i < regData.Length; i++)
                    {
                        //double x = regData[i];
                        //x = (x / 1000);
                        //double y = SlopeValues[i] * x + OffsetValues[i];
                        //double current = (RValues[i] != 0) ? (y / RValues[i]) * 1000 : 0.00;

                        Console.WriteLine(" A{0}: Voltage: {1} Current: {2}", i, regData[i]);
                    }
                    Console.WriteLine();
                    Console.WriteLine("Digitals Pull-up: ");
                    for (int i = 0; i < 22; i++)
                    {
                        Console.WriteLine(" D{0}: {1}", i, coilData[i]);
                    }

                    Console.WriteLine();
                    Console.WriteLine("Press C to continue");
                    var key = Console.ReadKey();
                    if (key.Key != ConsoleKey.C)
                    {
                        break;
                    }
                }
            }
            else
            {
                Console.WriteLine("Connection Failed");
            }
            Console.ReadKey();
        }
Пример #18
0
        public static bool[] Read_Coils(ushort read_start_addr, ushort num_coils)
        {
            num_coils       = _numOfCoils;
            read_start_addr = _readstartAddress;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            bool[] read_result = master.ReadCoils(read_start_addr, num_coils);

            Stop_MBClient();
            Stop_MBServer();
            return(read_result);
        }
Пример #19
0
        private static void ReadOnOwnThread(object state)
        {
            using (TcpClient masterClient = new TcpClient(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient);
                master.Transport.Retries = 0;

                var random = new Random();
                for (int i = 0; i < 5; i++)
                {
                    bool[] coils = master.ReadCoils(1, 1);
                    Assert.AreEqual(1, coils.Length);
                    Debug.WriteLine(String.Format("{0}: Reading coil value", Thread.CurrentThread.ManagedThreadId));
                    Thread.Sleep(random.Next(100));
                }
            }
        }
Пример #20
0
        public bool[] ReadCoils(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
        {
            if (!status)
            {
                Connect();
            }

            try
            {
                return(master.ReadCoils(slaveAddress, startAddress, numberOfPoints));
            }
            catch (Exception ex)
            {
                status = false;
                AddMessage("Catch exception in function ReadCoils(). " + ex.Message, DebugLevel.ExceptionLevel);
                return(null);
            }
        }
Пример #21
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
            //}
        }
Пример #22
0
 private static void PutInMaintenceMode()
 {
     Console.Clear();
     Console.WriteLine("Switching To Maintence Mode Please Wait....");
     if (CheckConnection(IpAddress, 500))
     {
         ushort[] regData = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 };
         using (TcpClient client = new TcpClient(IpAddress, 502)) {
             bool[]         com    = { true, false, false, false };
             ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
             com[1] = true;
             com[2] = false;
             com[3] = false;
             master.WriteMultipleCoils(39, com);
             bool success = false;
             while (true)
             {
                 var check = master.ReadCoils(39, 1);
                 if (!check[0])
                 {
                     Console.WriteLine("Success, Waiting 5 sec then turning off Warning");
                     success = true;
                     break;
                 }
             }
             //if (success) {
             //    System.Threading.Thread.Sleep(5000);
             //    com[1] = false;
             //    com[2] = false;
             //    com[3] = false;
             //    master.WriteMultipleCoils(39, com);
             //}
             client.Close();
         }
         Console.WriteLine("Press any key to continue");
         Console.ReadKey();
     }
     else
     {
         Console.WriteLine("Connection Failed");
     }
 }
Пример #23
0
        private void timerReadModbus_Tick(object sender, EventArgs e)
        {
            try
            {
                coilM22 = modbusMasterTCP.ReadCoils(22, 1);
            }
            catch (Exception err)
            {
                //timerReadModbus.Enabled = false;
                //MessageBox.Show("Failed Connect To Modbus, Check Serial Port Or Ethernet Connection !!!\r\n\r\n" + err.ToString());
            }

            // Check Rising Of M55 // Print From HMI

            if (lastCoilM22[0] == false && coilM22[0] == true)
            {
                updateExcelData();
                int a = textBoxReference.Text.IndexOf('T', 4);
                if (a == 4)
                {
                    printLabel(3);
                    //MessageBox.Show("4P");
                }
                else
                {
                    if (textBoxAA1.Text == "")
                    {
                        printLabel(2); // 3 pole no kc
                        //MessageBox.Show("3pkc");
                    }
                    else
                    {
                        printLabel(1); // 3 pole
                        //MessageBox.Show("3P");
                    }
                }
                //printing = true;
                MessageBox.Show("Manual Printing Successful !");
            }

            lastCoilM22[0] = coilM22[0];
        }
Пример #24
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);
            }
        }
        //private void AddModbusItem(string Name, Int16 Address)
        //{
        //}

        //public void AsyncReadAllData()
        //{
        //    Thread checkThread = new Thread(SyncReadAllData);
        //    checkThread.Start();
        //}

        public void SyncReadAllData(ModbusAddressType address)
        {
            try
            {
                //LOG.Info("ModbusTCP_Driver");
                if (!_connected)
                {
                    return;
                }

                // Read from device to Buffer
                //_inputStatus = _master.ReadInputs(InputStatusStartAddress, InputStatusSize);

                //if (InputRegisterSize > 0)
                //{
                //    _inputRegister = _master.ReadInputRegisters(InputRegisterStartAddress, InputRegisterSize);
                //}
                if (address == ModbusAddressType.IC)
                {
                    if (InputStatusSize > 0)
                    {
                        _inputStatus = _master.ReadCoils(InputStatusStartAddress, InputStatusSize);
                    }
                }
                else
                {
                    LOG.Error(string.Format("读取ModbusTCPDriver数据出错:不支持{0}类型", address.ToString()));
                    return;
                }

                // Notification
                ModbusTCPDataUpdatedEventArgs Evargs = new ModbusTCPDataUpdatedEventArgs();
                DataArrivalEvent(this, Evargs);
            }
            catch (Exception ex)
            {
                _connected = false;
                LOG.Error(string.Format("读取ModbusTCPDriver数据出错:{0}", ex.Message));
            }
        }
        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)
            {
            }
        }
Пример #27
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);
        }
Пример #28
0
        /* 4.调用master通讯对象的相关通讯方法 即可读取Modbus相关区域数据
         *
         * 备注:这里不再列出写modbus数据的方法,原理和下面四个函数一样,只是调用的Modbus.dll内部方法函数不一样
         */

        /* 读多个线圈(DO) */
        public void ReadCoils(ushort startAddress, ushort numberOfPoints, ref List <bool> list)
        {
            bool[] data;
            data = master.ReadCoils(startAddress, numberOfPoints);
            list = data.ToList();
        }
Пример #29
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
        }
Пример #30
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);
        }