public void startServer() { modbusServer = new ModbusServer(); modbusServer.UnitIdentifier = 255; modbusServer.holdingRegisters[1012] = 1100; modbusServer.holdingRegisters[1022] = 1200; modbusServer.holdingRegisters[1032] = 1300; modbusServer.holdingRegisters[1042] = 1400; modbusServer.holdingRegisters[1052] = 1500; modbusServer.HoldingRegistersChanged += holdingRegistersChanged; modbusServer.NumberOfConnectedClientsChanged += ModbusServer_NumberOfConnectedClientsChanged; modbusServer.Listen(); Console.WriteLine("ModbusTCP server started"); while (true) { try { var read = Console.ReadLine().Trim(); if (read.Contains(" ")) { var addressAndValue = read.Split(' '); var address = int.Parse(addressAndValue[0]); var value = short.Parse(addressAndValue[1]); modbusServer.holdingRegisters[address] = value; } else if (read == "q4" || read == "p4") { for (int i = 0; i < modbusServer.holdingRegisters.localArray.Length; i++) { if (modbusServer.holdingRegisters[i] != 0) { PrintHoldingRegister(i); } } } else if (read == "exit" || read == "quit") { break; } } catch (Exception ex) { Console.WriteLine(ex.Message); } } modbusServer.StopListening(); }
private void AddServerMethod() { var server = new ModbusServer { Port = port }; server.Listen(); server.HoldingRegistersChanged += Ser_HoldingRegistersChanged; servers.Add(server); MessageBox.Show("Server added."); server.holdingRegisters[0] = 11; // register is changed, but no event is fired }
public void StartServer() { try { // _modbusServer.LogFileFilename = _logFilePath; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); _modbusServer.Listen(); _eventLog.WriteEntry(_modbusServer.LocalIPAddress + ", Server started!"); } catch (Exception ex) { _eventLog.WriteEntry("Start server ex: " + ex.Message, System.Diagnostics.EventLogEntryType.Error); } }
/// <summary> /// Initializes a new instance of the <see cref="MainWindow"/> class. /// </summary> public MainWindow() : base(Gtk.WindowType.Toplevel) { Build(); statusbar1.TooltipText = ""; //Modbus client initialize and read - just for testing modbusClient = new ModbusClient(ipAddress, port); modbusClient.Baudrate = baudRate; modbusClient.Connect(); if (modbusClient.Connected) { bool[] readCoils = modbusClient.ReadCoils(0, 2); modbusClient.Disconnect(); } //Modbus server modbusServer = new ModbusServer(); modbusServer.Baudrate = baudRate; modbusServer.Listen(); modbusServer.StopListening(); }
private void FetchDetails() { easyModbusTCPServer.Listen(); string DateTimefetch; count = 0; string URLString = "http://" + txt_IPAddress.Text + "/datagate/api/MessagingAPI.ashx?format=XML&username="******"&password="******"&software=DataGate2Admin&number=" + lbl_MobileNo.Text + "&beginDate=" + yest + "&endDate=" + today + ""; //string URLString = "http://103.11.117.219/Datagate/api/MessagingAPI.ashx?format=XML&username=admin&password=Admin@123&software=DataGate2Admin&number=919726419628&beginDate=17/10/18&endDate=18/10/18"; //string URLString = "http://103.11.117.219/Datagate/api/MessagingAPI.ashx?format=XML&username=admin&password=Admin@123&software=DataGate2Admin&number=919726419628&beginDate="+yest+"&endDate="+today; //string URLString = "http://122.179.137.69/datagate/api/MessagingAPI.ashx?format=XML&username=pcmc&password=pcmc&software=DataGate2Admin&number=917447797235&beginDate=10/10/2018&endDate=15/10/2018"; var httpRequest = (HttpWebRequest)WebRequest.Create(URLString); //geting the response from the request url var response = (HttpWebResponse)httpRequest.GetResponse(); //create a stream to hold the contents of the response (in this case it is the contents of the XML file var receiveStream = response.GetResponseStream(); //creating XML document var mySourceDoc = new XmlDocument(); //load the file from the stream mySourceDoc.Load(receiveStream); //close the stream receiveStream.Close(); XmlNodeList rankList = mySourceDoc.SelectNodes("/messages/message/message"); if (rd_GasLogger.Checked == true) { GasLogger(rankList); } else if (rd_WaterLogger.Checked == true) { WaterLogger(rankList); } }
private void button1_Click(object sender, EventArgs e) { if (statusServer.Text == "offline") { modbusServer = new EasyModbus.ModbusServer(); modbusServer.holdingRegisters = new EasyModbus.ModbusServer.HoldingRegisters(modbusServer); modbusServer.holdingRegisters[5] = 99; //Для примера зададим одному из регистров конкретное значение statusServer.Text = "online"; statusServer.ForeColor = Color.Green; modbusServer.Listen(); Console.Read(); } else { modbusServer.StopListening(); statusServer.Text = "offline"; statusServer.ForeColor = Color.Crimson; } }
void SetEnableds(bool val) { var gogo = true; if (!val) { if (startAddr.Text.Trim() == "") { startAddr.Focus(); return; } if (endAddr.Text.Trim() == "") { endAddr.Text = startAddr.Text; } if (startRange.Text.Trim() == "") { startRange.Focus(); return; } if (endRange.Text.Trim() == "") { endRange.Text = (Convert.ToInt32(startRange.Text) + 100).ToString(); } if (IsServer.Checked) { _mbSrv = new ModbusServer(); _mbSrv._output += (byte[] bytes, string type) => Log?.Invoke(type + " : " + BitConverter.ToString(TrimeZeros(bytes)).Replace('-', ' ')); if (radioButton1.Checked) { _mbSrv.Port = Convert.ToInt32(port.Text); _mbSrv.Listen(); } else { if (serialPort.Items.Count <= 0) { MessageBox.Show("Comport yok dedik ya.."); return; } _mbSrv.SerialPort = serialPort.SelectedItem.ToString(); _mbSrv.StopBits = System.IO.Ports.StopBits.One; _mbSrv.Parity = System.IO.Ports.Parity.None; _mbSrv.Baudrate = Convert.ToInt32(baudRate.Text); } _mbSrv.UnitIdentifier = Convert.ToByte(uID.Text); } else { _mbClt = new ModbusClient(ipAddr.Text, Convert.ToInt32(port.Text)) { UnitIdentifier = Convert.ToByte(uID.Text) }; _mbClt._output += (byte[] bytes, string type) => Log?.Invoke(type + " : " + BitConverter.ToString(TrimeZeros(bytes)).Replace('-', ' ')); try { _mbClt.Connect(); } catch (Exception ex) { gogo = false; MessageBox.Show(ex.Message); } } if (!gogo) { return; } running = true; Task.Run(async() => { var dly = Convert.ToInt32(delay.Text); var startAddress = Convert.ToInt32(startAddr.Text); var endAddress = Convert.ToInt32(endAddr.Text); var startRn = Convert.ToInt32(startRange.Text); var endRn = Convert.ToInt32(endRange.Text); while (running) { if (randomWriteChk.Checked) { if (IsServer.Checked) { for (int i = startAddress; i < endAddress; i++) { var rndVal = Convert.ToInt32(_rnd.Next(startRn, endRn >= 65536 ? 65535 : endRn)); if (rndVal >= 32768) { rndVal = ((65536 - rndVal) * -1); } var booVal = _rnd.Next(0, 2) == 1; if (radHR.Checked) { _mbSrv.holdingRegisters.localArray[i] = Convert.ToInt16(rndVal); } else if (radIR.Checked) { _mbSrv.inputRegisters.localArray[i] = Convert.ToInt16(rndVal); } else if (radCO.Checked) { _mbSrv.coils.localArray[i] = booVal; } else if (radDis.Checked) { _mbSrv.discreteInputs.localArray[i] = booVal; } } } else { if (radHR.Checked) { List <int> _values = new List <int>(); for (int i = startAddress; i < endAddress; i++) { var rndVal = _rnd.Next(startRn, endRn >= 65536 ? 65535 : endRn); if (rndVal >= 32768) { rndVal = ((65536 - rndVal) * -1); } _values.Add(rndVal); } _mbClt.WriteMultipleRegisters(startAddress, _values.ToArray()); } else if (radCO.Checked) { List <bool> _values = new List <bool>(); for (int i = startAddress; i < endAddress; i++) { _values.Add(_rnd.Next(0, 2) == 1); } _mbClt.WriteMultipleCoils(startAddress, _values.ToArray()); } } } await Task.Delay(dly); } }); } else { running = false; if (IsServer.Checked) { _mbSrv.StopListening(); } else { _mbClt.Disconnect(); } } button2.Enabled = !val; button1.Enabled = val; startAddr.Enabled = val; endAddr.Enabled = val; startRange.Enabled = val; endRange.Enabled = val; delay.Enabled = val; port.Enabled = val; uID.Enabled = val; radioButton1.Enabled = val; radioButton2.Enabled = val; showSignalPanel.Enabled = !val; }
private void Opc2Modbus_Load(object sender, EventArgs e) { if (ReadItemsCSV()) { // Visualize only in nofification bar. this.Hide(); this.WindowState = FormWindowState.Minimized; //Subscrib to OPC Server try { ObjOPCServer = new OPCServer(); ObjOPCGroup = new OPCGroup[Compressors]; String GroupName; //Conect to the server ObjOPCServer.Connect("POPCS.DAServer.1"); //Create a group ObjOPCGroups = ObjOPCServer.OPCGroups; for (int c = 0; c < Compressors; c++) { GroupName = "C" + (c + 1).ToString("00"); ObjOPCGroup[c] = ObjOPCGroups.Add(GroupName); //Define event DataChange ObjOPCGroup[c].DataChange += new DIOPCGroupEvent_DataChangeEventHandler(OPCGroup_DataChange); //Define DefaultAccessPath (necessary for POPCS.DAServer.1) ObjOPCGroup[c].OPCItems.DefaultAccessPath = GroupName; //Define Items. for (int i = 1; i <= numItemsCSV; i++) { ObjOPCGroup[c].OPCItems.AddItem(Items[(c * numItems) + i].ItemID, (c * numItems) + i); } //Group properties ObjOPCGroup[c].UpdateRate = 1000; ObjOPCGroup[c].IsActive = true; ObjOPCGroup[c].IsSubscribed = true; } } catch (Exception ex) { OPC2Modbus.Program.Log.Fatal("Error al suscribirse al servidor OPC", ex); MessageBox.Show("Error al suscribirse al servidor OPC.\n La aplicación va ha cerrarse.", "Error fatal", MessageBoxButtons.OK, MessageBoxIcon.Error); bExit = true; bFatal = true; Application.Exit(); } // Start modbus server. try { modbusServer.Listen(); } catch (Exception ex) { OPC2Modbus.Program.Log.Fatal("Error al iniciar el servidor Modbus TCP", ex); MessageBox.Show("Error al iniciar el servidor Modbus TCP.\n La aplicación va ha cerrarse.", "Error fatal", MessageBoxButtons.OK, MessageBoxIcon.Error); bExit = true; bFatal = true; Application.Exit(); } } }