public override Result Open() { modbus.Open(); return(new Result { IsSuccess = modbus.IsOpen() }); }
protected override bool Connect() { try { _modbusDevice.SerialPortInni(sp => { sp.PortName = Port; sp.StopBits = StopBits.One; sp.DataBits = DataBit; sp.BaudRate = BaudRate; sp.Parity = parity; }); try { _modbusDevice.Close(); } catch { } _modbusDevice.Open(); if (_modbusDevice.IsOpen()) { LOG.Info($"Connect to ModbusRtu device [{SourceName}] success."); return(true); } else { LOG.Info($"Connect to ModbusRtu device [{SourceName}] failed."); return(false); } } catch (Exception ex) { LOG.Error($"Connect to ModbusRtu device [{SourceName}] Exception:{ex.Message}"); return(false); } }
//MudbusRTU设备初始化 void DoInitMudbusRtu(LD.Config.PlcTypeItem item) { // 连接 byte station; if (!byte.TryParse(item.Station, out station)) { MessageBox.Show(string.Format("station {0} input is wrong!", item.Station)); return; } int baudRate; if (!int.TryParse(item.BaudRate.ToString(), out baudRate)) { MessageBox.Show(string.Format("baudRate {0} input wrong!", item.BaudRate)); return; } int dataBits; if (!int.TryParse(item.DataBits.ToString(), out dataBits)) { MessageBox.Show(string.Format("dataBits {0} input wrong!", item.DataBits)); return; } int stopBits; if (!int.TryParse(item.StopBits.ToString(), out stopBits)) { MessageBox.Show(string.Format("stopBits {0} input wrong!", item.StopBits)); return; } ModbusRtu busRtuClient = new ModbusRtu(station); busRtuClient.AddressStartWithZero = item.AddressStartWithZero; if (busRtuClient != null) { busRtuClient.DataFormat = item.DataFormat; } busRtuClient.IsStringReverse = item.IsStringReverse; busRtuClient.SerialPortInni(sp => { sp.PortName = item.PortName; sp.BaudRate = baudRate; sp.DataBits = dataBits; sp.StopBits = stopBits == 0 ? StopBits.None : (stopBits == 1 ? StopBits.One : StopBits.Two); sp.Parity = item.Parity; }); item.Tag = busRtuClient; busRtuClient.Open(); if (busRtuClient.IsOpen()) { item.IsConnected = true; //Plcs.Add(item.DevName, busRtuClient); } else { item.IsConnected = false; } }