private void cbbSelctionModbus_SelectedIndexChanged(object sender, EventArgs e) { if (cbbSelctionModbus.SelectedIndex == 0) { modbusClient = new EasyModbus.ModbusClient(); txtIpAddress.Visible = true; txtIpAddressInput.Visible = true; txtPort.Visible = true; txtPortInput.Visible = true; txtCOMPort.Visible = false; cbbSelectComPort.Visible = false; txtSlaveAddress.Visible = false; txtSlaveAddressInput.Visible = false; } if (cbbSelctionModbus.SelectedIndex == 1) { cbbSelectComPort.SelectedIndex = 0; if (cbbSelectComPort.SelectedText == "") { cbbSelectComPort.SelectedItem.ToString(); } txtIpAddress.Visible = false; txtIpAddressInput.Visible = false; txtPort.Visible = false; txtPortInput.Visible = false; txtCOMPort.Visible = true; cbbSelectComPort.Visible = true; txtSlaveAddress.Visible = true; txtSlaveAddressInput.Visible = true; modbusClient = new EasyModbus.ModbusClient(cbbSelectComPort.SelectedItem.ToString()); modbusClient.UnitIdentifier = byte.Parse(txtSlaveAddressInput.Text); modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateReceiveData); modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateSendData); } }
private EasyModbus.ModbusClient TryGetConnectedClient(string ip, int port) { lock (_clientLock) { var modbusDescriptor = ModbusServerDescriptor.Create(ip, port); var client = _modbusClientCache.GetValueOrDefault(modbusDescriptor); if (client == null) { client = new EasyModbus.ModbusClient(ip, port); _modbusClientCache.Add(modbusDescriptor, client); } try { if (!client.Connected) { client.Connect(); } } catch (Exception exception) { Logger.Error("ModbusTcp connection error", exception); client.Disconnect(); _modbusClientCache.Remove(modbusDescriptor); throw exception; } return(client); } }
private void cbbSelectComPort_SelectedIndexChanged(object sender, EventArgs e) { modbusClient = new EasyModbus.ModbusClient(cbbSelectComPort.SelectedItem.ToString()); modbusClient.UnitIdentifier = byte.Parse(txtSlaveAddressInput.Text); modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateReceiveData); modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateSendData); }
public void GetValues(ConnectionProperties connectionProperties, int functionPropertyID) { modbusClient = connectionProperties.modbusClient; if (!modbusClient.Connected) { modbusClient.IPAddress = connectionProperties.ModbusTCPAddress; modbusClient.Port = connectionProperties.Port; modbusClient.Connect(); } switch (connectionProperties.FunctionPropertiesList[functionPropertyID].FunctionCode) { case FunctionCode.ReadCoils: connectionProperties.FunctionPropertiesList[functionPropertyID].values = modbusClient.ReadCoils(connectionProperties.FunctionPropertiesList[functionPropertyID].StartingAdress, connectionProperties.FunctionPropertiesList[functionPropertyID].Quantity); break; case FunctionCode.ReadDiscreteInputs: connectionProperties.FunctionPropertiesList[functionPropertyID].values = modbusClient.ReadDiscreteInputs(connectionProperties.FunctionPropertiesList[functionPropertyID].StartingAdress, connectionProperties.FunctionPropertiesList[functionPropertyID].Quantity); break; case FunctionCode.ReadHoldingRegisters: connectionProperties.FunctionPropertiesList[functionPropertyID].values = modbusClient.ReadHoldingRegisters(connectionProperties.FunctionPropertiesList[functionPropertyID].StartingAdress, connectionProperties.FunctionPropertiesList[functionPropertyID].Quantity); break; case FunctionCode.ReadInputRegisters: connectionProperties.FunctionPropertiesList[functionPropertyID].values = modbusClient.ReadInputRegisters(connectionProperties.FunctionPropertiesList[functionPropertyID].StartingAdress, connectionProperties.FunctionPropertiesList[functionPropertyID].Quantity); break; default: break; } if (valuesChanged != null) { valuesChanged(this); } }
/// <summary> /// Starts the DataFetcher. /// </summary> public void Start() { lock (locker) { if (modbusClient == null) { log.Info($"Starting {nameof(DataFetcher)}"); modbusClient = new EasyModbus.ModbusClient { IPAddress = IPAdress, Port = ModBusPort, ConnectionTimeout = ConnectionTimeoutMs }; dataValidTimeoutTimer = new Timer { AutoReset = false, Interval = DataInvalidAfterMs }; dataValidTimeoutTimer.Elapsed += DataValidTimeoutTimer_Elapsed; updateTimer = new Timer() { AutoReset = false, Interval = 10, }; updateTimer.Elapsed += UpdateTimer_Elapsed; updateTimer.Start(); log.Info($"{nameof(DataFetcher)} started"); } else { log.Warn($"Cant start {nameof(DataFetcher)}, since it has already been started."); } } }
private void button3_Click(object sender, EventArgs e) { try { if (cbbSelctionModbus.SelectedIndex == 0) { modbusClient = new EasyModbus.ModbusClient(txtIpAddressInput.Text, int.Parse(txtPortInput.Text)); modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateReceiveData); modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateSendData); modbusClient.connectedChanged += new EasyModbus.ModbusClient.ConnectedChanged(UpdateConnectedChanged); modbusClient.Connect(); } if (cbbSelctionModbus.SelectedIndex == 1) { modbusClient = new EasyModbus.ModbusClient(cbbSelectComPort.SelectedItem.ToString()); modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateReceiveData); modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateSendData); modbusClient.connectedChanged += new EasyModbus.ModbusClient.ConnectedChanged(UpdateConnectedChanged); modbusClient.UnitIdentifier = byte.Parse(txtSlaveAddressInput.Text); modbusClient.Baudrate = int.Parse(txtBaudrate.Text); if (cbbParity.SelectedIndex == 0) { modbusClient.Parity = System.IO.Ports.Parity.Even; } if (cbbParity.SelectedIndex == 1) { modbusClient.Parity = System.IO.Ports.Parity.Odd; } if (cbbParity.SelectedIndex == 2) { modbusClient.Parity = System.IO.Ports.Parity.None; } if (cbbStopbits.SelectedIndex == 0) { modbusClient.StopBits = System.IO.Ports.StopBits.One; } if (cbbStopbits.SelectedIndex == 1) { modbusClient.StopBits = System.IO.Ports.StopBits.OnePointFive; } if (cbbStopbits.SelectedIndex == 2) { modbusClient.StopBits = System.IO.Ports.StopBits.Two; } modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateReceiveData); modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateSendData); modbusClient.Connect(); } } catch (Exception exc) { MessageBox.Show(exc.Message, "Unable to connect to Server", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main(string[] args) { // int[] registers = EasyModbus.ModbusClient.ConvertStringToRegisters("hello"); // SerialPort serialport = new SerialPort("COM3"); /* serialport.PortName = "COM3"; * serialport.BaudRate = 9600; * serialport.Parity = Parity.None; * serialport.StopBits = StopBits.One; * byte[] buffer = new byte[50]; * serialport.Open(); * byte[] bufferout = new byte[50]; * int numberOfBytesRead = 0; * do * { * int quantity = serialport.Read(buffer, 0, 15); * Buffer.BlockCopy(buffer, 0, bufferout, numberOfBytesRead, quantity); * numberOfBytesRead = numberOfBytesRead + quantity; * } * while (numberOfBytesRead < 5); * for (int i = 0; i < 15; i++) * Console.WriteLine(bufferout[i].ToString()); * serialport.Write("ddddddddd");*/ EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient("COM3"); modbusClient.SerialPort = "COM3"; //EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient("127.0.0.1", 502); modbusClient.ConnectionTimeout = 5000; modbusClient.LogFileFilename = "test.txt"; modbusClient.UnitIdentifier = 0xF7; modbusClient.Connect(); while (true) { // Console.WriteLine("Execute FC5"); // modbusClient.WriteSingleCoil(0, true); // Console.WriteLine("Execute FC6"); // modbusClient.WriteSingleRegister(0, 1234); // Console.WriteLine("Execute FC15"); // modbusClient.WriteMultipleCoils(0, new bool[] { true, false, true, false, true, false, true }); //Console.WriteLine("Execute FC16"); //modbusClient.WriteMultipleRegisters(0, EasyModbus.ModbusClient.ConvertStringToRegisters("hallo2")); //modbusClient.Disconnect(); //System.Threading.Thread.Sleep(100); //modbusClient.Connect(); //Console.WriteLine("Execute FC3"); //Console.WriteLine("Value of Holding Register 1000: " + modbusClient.ReadHoldingRegisters(1000, 1)[0]); Console.WriteLine("Read and Publish Input Registers"); modbusClient.WriteSingleRegister(60, 1234); int[] holdingRegister = modbusClient.ReadHoldingRegisters(60, 2); //Console.WriteLine(holdingRegister[0]); // System.Threading.Thread.Sleep(1000); } modbusClient.Disconnect(); Console.ReadKey(); }
public Form1() { InitializeComponent(); modbusClient = new EasyModbus.ModbusClient(); modbusClient.ReceiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateReceiveData); modbusClient.SendDataChanged += new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateSendData); modbusClient.ConnectedChanged += new EasyModbus.ModbusClient.ConnectedChangedHandler(UpdateConnectedChanged); }
public MainForm() { InitializeComponent(); modbusClient = new EasyModbus.ModbusClient(); modbusClient.ConnectedChanged += new EasyModbus.ModbusClient.ConnectedChangedHandler(UpdateConnectedChanged); CB_DataType.DataSource = Enum.GetValues(typeof(DataType)); RefreshGUI(); }
public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); modbusClient = new EasyModbus.ModbusClient(); // modbusClient.LogFileFilename = "logFiletxt.txt"; //modbusClient.Baudrate = 9600; //modbusClient.UnitIdentifier = 2; }
static void Main(string[] args) { Console.WriteLine("Hello World!"); EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient(); modbusClient.Connect("127.0.0.1", 502); bool[] response = modbusClient.ReadDiscreteInputs(0, 2); modbusClient.Disconnect(); Console.WriteLine("Value of Discrete Input #1: " + response[0].ToString()); Console.WriteLine("Value of Discrete Input #2: " + response[1].ToString()); Console.ReadKey(); }
public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); modbusClient = new EasyModbus.ModbusClient(); // modbusClient.LogFileFilename = "logFiletxt.txt"; modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateReceiveData); modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateSendData); //modbusClient.Baudrate = 9600; //modbusClient.UnitIdentifier = 2; }
public void TestEasyModbus() { EasyModbus.ModbusClient mc = new EasyModbus.ModbusClient() { IPAddress = "127.0.0.1", Port = 502, ConnectionTimeout = 5 * 1000, }; mc.Connect(); if (mc.Connected) { var data = mc.ReadHoldingRegisters(0, 10); Console.WriteLine(string.Join(" ", data)); } }
/// <summary> /// use properties to specify the client /// </summary> public ModbusClient() { try { modbusClient = new EasyModbus.ModbusClient(); } catch (EasyModbus.Exceptions.ModbusException ex) { // log this error in to log file. IoC.Logger.Log($"{ex.Message}"); // inform the user about this error IoC.Communication.Log += $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: ModbusException error. {ex.Message}.\n"; } }
/// <summary> /// Constructor for Modbus TCP and Modbus UDP connection. /// </summary> /// <param name="ipAddress">IpAddress of the server</param> /// <param name="port">port of the server</param> public ModbusClient(string ipAddress, int port) { try { modbusClient = new EasyModbus.ModbusClient(ipAddress, port); } catch (EasyModbus.Exceptions.ConnectionException ex) { // log this error in to log file. IoC.Logger.Log($"{ex.Message}"); // inform the user about this error IoC.Communication.Log += $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Connection error. Please check connection.\n"; } }
void UpdateTextBoxSend(object sender) { EasyModbus.ModbusClient modbusClient = (EasyModbus.ModbusClient)sender; if (textBox1.InvokeRequired) { UpdateSendDataCallback d = new UpdateSendDataCallback(UpdateTextBoxSend); this.Invoke(d, new object[] { modbusClient }); } else { textBox1.AppendText("To: " + modbusClient.IPAddress.ToString() + "Tx: "); string hex = BitConverter.ToString(modbusClient.sendData); hex = hex.Replace("-", " "); textBox1.AppendText(hex); textBox1.AppendText(System.Environment.NewLine); } }
private void ButtonNew_Click(object sender, EventArgs e) { if (modbusClient != null) { modbusClient.Disconnect(); modbusClient = null; } if (cbbSelctionModbus.SelectedIndex == 0 || cbbSelctionModbus.SelectedIndex == 2) { modbusClient = new EasyModbus.ModbusClient(txtIpAddressInput.Text, int.Parse(txtPortInput.Text), cbbSelctionModbus.SelectedIndex == 2); } else { modbusClient = new EasyModbus.ModbusClient(); } modbusClient.ReceiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateReceiveData); modbusClient.SendDataChanged += new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateSendData); modbusClient.ConnectedChanged += new EasyModbus.ModbusClient.ConnectedChangedHandler(UpdateConnectedChanged); }
static void Main(string[] args) { int[] registers = EasyModbus.ModbusClient.ConvertStringToRegisters("hello"); SerialPort serialport = new SerialPort("COM3"); /* serialport.PortName = "COM3"; * serialport.BaudRate = 9600; * serialport.Parity = Parity.None; * serialport.StopBits = StopBits.One; * byte[] buffer = new byte[50]; * serialport.Open(); * byte[] bufferout = new byte[50]; * int numberOfBytesRead = 0; * do * { * int quantity = serialport.Read(buffer, 0, 15); * Buffer.BlockCopy(buffer, 0, bufferout, numberOfBytesRead, quantity); * numberOfBytesRead = numberOfBytesRead + quantity; * } * while (numberOfBytesRead < 5); * for (int i = 0; i < 15; i++) * Console.WriteLine(bufferout[i].ToString()); * serialport.Write("ddddddddd");*/ EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient("192.168.178.75", 502); modbusClient.Connect(); // Console.WriteLine("Execute FC5"); // modbusClient.WriteSingleCoil(0, true); // Console.WriteLine("Execute FC6"); // modbusClient.WriteSingleRegister(0, 1234); // Console.WriteLine("Execute FC15"); // modbusClient.WriteMultipleCoils(0, new bool[] { true, false, true, false, true, false, true }); Console.WriteLine("Execute FC16"); modbusClient.WriteMultipleRegisters(0, EasyModbus.ModbusClient.ConvertStringToRegisters("hallo2")); // Console.WriteLine("Execute FC3"); // Console.WriteLine("Value of Holding Register 1000: " + modbusClient.ReadHoldingRegisters(1000, 1)[0]); Console.ReadKey(); }
private void ConnectPLC(object item) { try { List <string[]> informations = excelInfors.FindAll(x => x[1] != "" && x[2] != "" && x[3] != ""); float Temperature = 0; float Humidity = 0; foreach (string[] infor in informations) { float value = 0; var tagName = infor[0]; var ip = (string)infor[1]; var port = Int32.Parse(infor[2]); EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient(ip, port); try { ////Increase the Connection Timeout to 5 seconds modbusClient.ConnectionTimeout = 5000; modbusClient.Connect(); var address = Int32.Parse(infor[3]); var length = Int32.Parse(infor[4]); int[] holdingRegister = modbusClient.ReadHoldingRegisters(address - 1, length); var rawValue = holdingRegister[0]; value = Convert.ToSingle(Decimal.Divide(rawValue, 10)); } catch (Exception ex) { } try { using (SqlConnection connection = new SqlConnection(conString)) using (SqlCommand command = new SqlCommand("Insert into [ADVANTECH WISE-4220] (Time, TagName, Value, MachineIRAI, SensorIRAI) values(@date,@tagName,@value,@irai,@sensorIrai)", connection)) { command.Parameters.AddWithValue("date", System.DateTime.Now); command.Parameters.AddWithValue("tagName", tagName); command.Parameters.AddWithValue("value", value); command.Parameters.AddWithValue("irai", infor[5]); command.Parameters.AddWithValue("sensorIrai", infor[6]); connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } catch (Exception ex) { } if (tagName == "Temperature") { Temperature = value; } if (tagName == "Humidity") { Humidity = value; } PropertyState matrix = (PropertyState)FindPredefinedNode(new NodeId(infor[0], NamespaceIndex), typeof(PropertyState)); matrix.Value = value; matrix.ClearChangeMasks(SystemContext, true); modbusClient.Disconnect(); } var data = new Record(); data.Temperature = Temperature; data.Humidity = Humidity; MongoHelper.Asset.UpdatePrimaryValue("0990-MY.0027101.0000000001-#TS-00058200.0000000005.0002", data); } catch (Exception e) { Utils.Trace(e, "Unexpected error during simulation."); } }
/// <summary> /// Starts a test with the values specified in Nominal Values page and /// Communication page. /// </summary> public async Task StartCommunicationAsync() { // start point of all test steps with the first mouse click and it will ignore subsequent mouse clicks await AsyncAwaiter.AwaitAsync(nameof(StartCommunicationAsync), async() => { using (IoC.Commands.TokenSource) { try { // update the user Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Communication starts."; // get new construct of ModbusClient EAModbusClient = new EasyModbus.ModbusClient { IPAddress = IpAddress, Port = Convert.ToInt32(Port), ConnectionTimeout = 20000, // LogFileFilename = @"C:\Users\TBircek\Documents\metering\modbus.log" }; // Checks if the Server IPAddress is available if (EAModbusClient.Available(20000)) { // connect to the server EAModbusClient.Connect(); // find any CMCEngine attached to this computer if (IoC.FindCMC.Find()) { // Is there Omicron Test Set attached to this app? if (IoC.CMCControl.DeviceID > 0) { // indicates the test is running. IoC.CMCControl.IsTestRunning = true; try { // perform initial set up on CMCEngine await IoC.Task.Run(async() => await IoC.InitialCMCSetup.InitialSetupAsync()); // there is a test set attached so run specified tests. await IoC.Task.Run(async() => await IoC.CMCControl.TestAsync(IoC.Commands.Token)); } catch (OperationCanceledException ex) { // inform the developer about error IoC.Logger.Log($"Exception is : {ex.Message}"); // update the user about the error. IoC.Communication.Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Exception: {ex.Message}."; } catch (Exception ex) { // inform developer IoC.Logger.Log($"Exception: {ex.Message}"); // update the user about failed test. IoC.Communication.Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Test failed: {ex.Message}."; // catch inner exceptions if exists if (ex.InnerException != null) { // inform the user about more details about error. IoC.Communication.Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Inner exception: {ex.InnerException}."; } } finally { // Trying to stop the app gracefully. await IoC.Task.Run(() => IoC.ReleaseOmicron.ProcessErrorsAsync(false)); } } else { // inform the user Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Failed: Omicron Test Set ID is a zero."; } } else { // inform the user Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Failed: There is no attached Omicron Test Set. Please attached a Omicron Test Set before test."; } } else { // inform the user Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Failed: The server is not available: {EAModbusClient.IPAddress}."; } } catch (Exception ex) { // inform the user about error. Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Start Communication failed: {ex.Message}."; // catch inner exceptions if exists if (ex.InnerException != null) { // inform the user about more details about error. Log = $"{DateTime.Now.ToLocalTime():MM/dd/yy HH:mm:ss.fff}: Inner exception: {ex.InnerException}."; } } } });