Ejemplo n.º 1
0
        public void CloseModBus()
        {
            try
            {
                MyModMaster?.Dispose();
            }
            catch { }
            MyModMaster = null;

            try
            {
                tcpClient?.Close();
            }
            catch { }
            tcpClient = null;
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
0
        protected override void Start()
        {
            if (master != null)
            {
                master.Dispose();
            }


            if (tcpClient != null)
            {
                tcpClient.Close();
                tcpClient.Dispose();
                tcpClient = null;
            }

            if (tcpClient == null)
            {
                tcpClient = new TcpClient(new IPEndPoint(IPAddress.Parse(Tcp_PARA.LocalTCP_IP), int.Parse(Tcp_PARA.LocalTCP_Port)));
            }
            tcpClient.ReceiveTimeout    = 1000;
            tcpClient.SendTimeout       = 1000;
            tcpClient.SendBufferSize    = Tcp_PARA.WriteBufferSize;
            tcpClient.ReceiveBufferSize = Tcp_PARA.ReadBufferSize;
            master = ModbusIpMaster.CreateIp(tcpClient);
            //通用部分设置
            master.Transport.ReadTimeout             = Tcp_PARA.ReadTimeout;           //读取数据超时1000ms
            master.Transport.WriteTimeout            = Tcp_PARA.WriteTimeout;          //写入数据超时1000ms
            master.Transport.Retries                 = Tcp_PARA.CollectFaultsNumber;   //重试次数
            master.Transport.WaitToRetryMilliseconds = Tcp_PARA.CollectFaultsInternal; //重试间隔

            Thread.Sleep(800);
            //此处采用多线程技术创建一个实时读取数据的任务
            for (int i = 0; i < this.RealDevices.Count; i++)
            {
                RealData mRealData = this.RealDevices[i];
                //创建一个子任务
                Task.Run(() =>
                {
                    while (true && this.ServerIsRun)
                    {
                        if (this.ServerIsSuspend)
                        {
                            continue;
                        }

                        try
                        {
                            Task.Run(() =>
                            {
                                //发送获取数据的命令
                                string error = "";
                                if (!this.RequestData(mRealData.Device, mRealData, out error, mRealData.Fragment))
                                {
                                    this.DeviceException("ERROR=Modbus_Serial_10001," + error);
                                }
                            });
                        }
                        catch (Exception e)
                        {
                            this.DeviceException("ERROR=Modbus_Serial_10002," + e.Message);
                        }


                        //更新周期
                        Thread.Sleep(mRealData.Device.IO_DEVICE_UPDATECYCLE * 1000);
                    }
                });
            }

            this.CommunctionStartChanged(this.IOServer, this.IOServer.SERVER_IP + " " + this.IOServer.SERVER_NAME + "启动服务");
        }