示例#1
0
        public async Task <bool> TryOpenConnectionAsync(bool isThrowingException, IComPortConfiguration comPortConfiguration)
        {
            //if ((_openedPort != null) && (_openedPort == PortName)) return true;
            try
            {
                IModbusSerialMaster modbusSerialMaster = null;
                await Task.Run((() =>
                {
                    IStreamResource streamResource = _connectionManager.GetSerialPortAdapter(PortName, comPortConfiguration);
                    modbusSerialMaster = ModbusSerialMaster.CreateRtu(streamResource);
                }));

                if (modbusSerialMaster != null)
                {
                    _currentModbusMaster?.Dispose();
                    _currentModbusMaster = modbusSerialMaster;
                }
                else
                {
                    throw new Exception();
                }
                _slaveId = SlaveId;
                //  QueryQueue.Initialize(_currentModbusSerialMaster,deviceLogger,(() => LastQueryStatusChangedAction?.Invoke()));
                _openedPort = PortName;
            }
            catch (Exception e)
            {
                if (isThrowingException)
                {
                    throw e;
                }
                return(false);
            }
            return(true);
        }
        public void                         connect()
        {
            if (mMaster != null)
            {
                mMaster.Dispose();
                mMaster = null;
            }

            if (mTransport == ETransportType.TCP)
            {
                mMaster = new ModbusFactory().CreateMaster(new TcpClient(mIP, mIPPort));
            }
            else
            {
                var lPort = new SerialPort(mCOMPort);
                lPort.BaudRate = mBaud;
                lPort.DataBits = mDataBits;
                lPort.Parity   = mParity;
                lPort.StopBits = mStopBits;
                lPort.Open();

                if (mProtocol == EProtocol.RTU)
                {
                    mMaster = new ModbusFactory().CreateRtuMaster(new SerialPortAdapter(lPort));
                }
                else
                {
                    mMaster = new ModbusFactory().CreateAsciiMaster(new SerialPortAdapter(lPort));
                }
            }

            mMaster.Transport.ReadTimeout  = (int)mTimeoutMS;
            mMaster.Transport.WriteTimeout = (int)mTimeoutMS;
            mMaster.Transport.Retries      = 0;

            if (mMainCycleTimer == null)
            {
                mMainCycleTimer           = new System.Timers.Timer(MiscUtils.TimeSlice);
                mMainCycleTimer.Elapsed  += new ElapsedEventHandler(MainCycle);
                mMainCycleTimer.AutoReset = false;
            }

            mConnected     = true;
            mDisconnect    = false;
            mWriteRequests = 0;
            mMainCycleTimer.Start();

            raiseConnectionState();
        }
示例#3
0
 private void DisposeConnections()
 {
     m_tcpClient?.Dispose();
     m_udpClient?.Dispose();
     m_serialClient?.Dispose();
     m_modbusConnection?.Dispose();
 }
示例#4
0
        void MakeSureClientIsConnected()
        {
            if (_client != null && !_client.Connected)
            {
                _client.Dispose();
                _client = null;
                _adapter.Dispose();
                _adapter = null;
                _master.Dispose();
                _master = null;
            }

            if (_client == null)
            {
                _client  = new TcpClient(_configuration.Ip, _configuration.Port);
                _adapter = new TcpClientAdapter(_client);
                var factory = new ModbusFactory();
                if (_configuration.UseASCII)
                {
                    _master = factory.CreateAsciiMaster(_adapter);
                }
                else if (_configuration.Protocol == Protocol.Tcp)
                {
                    _master = factory.CreateMaster(_client);
                }
                else
                {
                    _master = factory.CreateRtuMaster(_adapter);
                }
            }
        }
示例#5
0
 protected override void OnDisposing()
 {
     ConnectionLostAction     = null;
     ConnectionRestoredAction = null;
     _modbusMaster?.Dispose();
     base.OnDisposing();
 }
示例#6
0
 public void Dispose()
 {
     if (GetTcpClient() != null)
     {
         master.Dispose();
         GetTcpClient().Dispose();
     }
 }
示例#7
0
 private void ConnectIP()
 {
     if (_master != null)
     {
         _master.Dispose();
     }
     Connect();
 }
示例#8
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         PLC.Dispose();
         ComPort.Dispose();
     }
 }
示例#9
0
 /// <inheritdoc/>
 public void Dispose()
 {
     _client?.Dispose();
     _client = null;
     _adapter?.Dispose();
     _adapter = null;
     _master?.Dispose();
     _master = null;
 }
示例#10
0
        public void Dispose()
        {
            if (!_isDisposed)
            {
                _isDisposed = true;

                _master.Dispose();
            }
        }
示例#11
0
 private void ReleaseConnection()
 {
     _modbusMaster?.Dispose();
     _modbusMaster = null;
     _tcpClient?.Dispose();
     _tcpClient = null;
     _udpClient?.Dispose();
     _udpClient = null;
     _serialPort?.Dispose();
     _serialPort = null;
 }
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _master.Dispose();
                    _master = null;

                    _client.Dispose();
                    _client = null;
                }

                disposedValue = true;
            }
        }
示例#13
0
        private bool[] ReadInputs(string modbus_address)
        {
            try
            {
                using (TcpClient client = new TcpClient(modbus_address, 502))
                {
                    var    factory = new ModbusFactory();
                    bool[] inputs;

                    using (IModbusMaster master = factory.CreateMaster(client))
                    {
                        master.Transport.Retries      = 0;
                        master.Transport.ReadTimeout  = 300;
                        master.Transport.WriteTimeout = 300;

                        ushort startAddress = 0;
                        ushort numInputs    = 16;
                        inputs = master.ReadInputs(0, startAddress, numInputs);

                        master.Dispose();
                    }

                    factory = null;

                    if (client.Connected)
                    {
                        client.Close();
                    }

                    // log.Debug($"got data from {modbus_address}");

                    return(inputs);
                }
            }
            catch (ThreadAbortException)
            {
                log.Error($"timeout checking modbus address {modbus_address}");
            }
            catch (Exception ex)
            {
                log.Error($"Exception checking modbus address {modbus_address}", ex);
            }
            return(null);
        }
示例#14
0
 /// <summary>
 /// Метод соединения
 /// </summary>
 /// <returns> true - есть подключение; false - подключение отсутсвуете </returns>
 private bool Connect()
 {
     if (master != null)
     {
         master.Dispose();
     }
     if (tcpClient != null)
     {
         tcpClient.Close();
     }
     try
     {
         tcpClient = new TcpClient();
         IAsyncResult asyncResult = tcpClient.BeginConnect(_ipAddress, tcpPort, null, null);
         asyncResult.AsyncWaitHandle.WaitOne(3000, true); // ожидание 3 секунды
         if (!asyncResult.IsCompleted)
         {
             tcpClient.Close();
             messageConnect = String.Format(DateTime.Now.ToString() + ": Не удается подключиться к приборам");
             return(false);
         }
         // создание мастера Modbus TCP с помощью tcpclient
         //  master = IModbusIpMaster.CreateIp(tcpClient);
         var factory = new ModbusFactory();
         master = factory.CreateMaster(tcpClient);
         master.Transport.Retries     = 0; // не нужно делать повторные попытки
         master.Transport.ReadTimeout = 1500;
         messageConnect = String.Format(DateTime.Now.ToString() + ": Подключение к приборам...");
         return(true);
     }
     catch (Exception ex)
     {
         messageConnect = String.Format(DateTime.Now.ToString() + ": Идет подключение..." + ex.StackTrace + "==>" + ex.Message);
         return(false);
     }
 }
示例#15
0
 /// <summary>
 /// Dispose the object master
 /// </summary>
 public override void Destory()
 {
     Master.Dispose();
     return;
 }
示例#16
0
        private async void ExecuteFunction()
        {
            try
            {
                //重新实例化是为了 modbus slave更换连接时不报错
                master = modbusFactory.CreateMaster(new TcpClient("127.0.0.1", 502));
                if (functionCode != null)
                {
                    switch (functionCode)
                    {
                    case "01 Read Coils":    //读取单个线圈
                        SetReadParameters();
                        coilsBuffer = master.ReadCoils(slaveAddress, startAddress, numberOfPoints);

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

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

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

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

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

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

                        break;

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

                        break;

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

                        break;

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

                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    MessageBox.Show("请选择功能码!");
                }
                master.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#17
0
 public void CloseConnection()
 {
     _currentModbusMaster.Dispose();
 }
示例#18
0
 public void Dispose()
 {
     _client.Dispose();
 }
示例#19
0
 public static void CloseConnection()
 {
     _semaphoreSlim?.Dispose();
     _modbusMaster?.Dispose();
 }