private void bWriteOpT_Click(object sender, RoutedEventArgs e) { //批量写输出信号 bool[] WriteCoilsT = { true, true, true }; modbusClient.WriteMultipleCoils(8, WriteCoilsT); label3_Copy9.Background = new SolidColorBrush(Colors.Green); label3_Copy9.Content = "TRUE"; label3_Copy10.Background = new SolidColorBrush(Colors.Green); label3_Copy10.Content = "TRUE"; label3_Copy11.Background = new SolidColorBrush(Colors.Green); label3_Copy11.Content = "TRUE"; }
private void tmr_Modbus_Com_Tick(object sender, EventArgs e) { tmr_Modbus_Com.Enabled = false; modbusClient.WriteMultipleCoils(4, new bool[] { true, true, true, true, true, true, true, true, true, true }); //Write Coils starting with Address 5 bool[] readCoils = modbusClient.ReadCoils(0, 10); //Read 10 Coils from Server, starting with address 0 int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 10); //Read 10 Holding Registers from Server, starting with Address 1 aGauge1.Value = readHoldingRegisters[0]; cb_coil_1.Checked = readCoils[0]; cb_coil_2.Checked = readCoils[1]; tmr_Modbus_Com.Enabled = true; }
public void GetValueFromPLC() { ModbusClient modbusClient = new ModbusClient("190.201.100.100", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); //Connect to Server modbusClient.WriteMultipleCoils(4, new bool[] { true, true, true, true, true, true, true, true, true, true }); //Write Coils starting with Address 5 bool[] readCoils = modbusClient.ReadCoils(9, 10); //Read 10 Coils from Server, starting with address 10 int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 10); //Read 10 Holding Registers from Server, starting with Address 1 // Console Output for (int i = 0; i < readCoils.Length; i++) { Console.WriteLine("Value of Coil " + (9 + i + 1) + " " + readCoils[i].ToString()); } for (int i = 0; i < readHoldingRegisters.Length; i++) { Console.WriteLine("Value of HoldingRegister " + (i + 1) + " " + readHoldingRegisters[i].ToString()); } modbusClient.Disconnect(); //Disconnect from Server Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
private void btnWriteMultipleCoils_Click(object sender, EventArgs e) { try { if (!modbusClient.Connected) { button3_Click(null, null); } bool[] coilsToSend = new bool[lsbWriteToServer.Items.Count]; for (int i = 0; i < lsbWriteToServer.Items.Count; i++) { coilsToSend[i] = bool.Parse(lsbWriteToServer.Items[i].ToString()); } modbusClient.WriteMultipleCoils(int.Parse(txtStartingAddressOutput.Text) - 1, coilsToSend); } catch (Exception exc) { MessageBox.Show(exc.Message, "Exception writing values to Server", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
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; }
static async Task RunClientAsync() { //InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false)); ModbusClient client = new ModbusClient(0x01, "127.0.0.1"); try { await client.Connect(); while (true) { Console.WriteLine(@" <-------------------------------------------------------> 1: Read Coils; 2: Read Discrete Inputs; 3: Read Holding Registers; 4: Read Input Registers; 5: Write Single Coil; 6: Write Single Register; 15: Write Multiple Coils; 16: Write Multiple Registers; <------------------------------------------------------->"); var line = Console.ReadLine(); if (string.IsNullOrEmpty(line)) { break; } Console.WriteLine("<------------------------------------------------------->"); var command = Convert.ToInt32(line); ModbusFunction response = null; ushort startingAddress = 0x0000; ushort quantity = 0x000A; var state = true; ushort value = 0x0001; switch (command) { case 1: response = client.ReadCoils(startingAddress, quantity); var coils = (response as ReadCoilsResponse).Coils; for (int i = 0; i < quantity; i++) { Console.WriteLine(coils[i]); } break; case 2: response = client.ReadDiscreteInputs(startingAddress, quantity); var inputs = (response as ReadDiscreteInputsResponse).Inputs; for (int i = 0; i < quantity; i++) { Console.WriteLine(inputs[i]); } break; case 3: response = client.ReadHoldingRegisters(startingAddress, quantity); foreach (var register in (response as ReadHoldingRegistersResponse).Registers) { Console.WriteLine(register); } break; case 4: response = client.ReadInputRegisters(startingAddress, quantity); foreach (var register in (response as ReadInputRegistersResponse).Registers) { Console.WriteLine(register); } break; case 5: response = client.WriteSingleCoil(startingAddress, state); Console.WriteLine((response as WriteSingleCoilResponse).State == state ? "Successed" : "Failed"); break; case 6: response = client.WriteSingleRegister(startingAddress, value); Console.WriteLine((response as WriteSingleRegisterResponse).Value == value ? "Successed" : "Failed"); break; case 15: var states = new bool[] { true, true, true, true, true, true, true, true, true, true }; response = client.WriteMultipleCoils(startingAddress, states); Console.WriteLine((response as WriteMultipleCoilsResponse).Quantity == states.Length); break; case 16: var registers = new ushort[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; response = client.WriteMultipleRegisters(startingAddress, registers); Console.WriteLine((response as WriteMultipleRegistersResponse).Quantity == registers.Length); break; } } await client.Close(); Console.ReadLine(); } catch (Exception exception) { Console.WriteLine(exception.Message); } }
private void buttonWExecute_Click(object sender, EventArgs e) { start = Int32.Parse(addBox3.Text); if (functionBox2.SelectedItem == "05 Write Single Coil") { modbusClient.WriteSingleCoil(start, bool.Parse(listBox2.Items[0].ToString())); /*if (listBox2.Text == "TRUE") * { * modbusClient.WriteSingleCoil(start, true); * } * if (listBox2.Text == "FALSE") * { * modbusClient.WriteSingleCoil(start, false); * } */ //modbusClient.WriteSingleCoil(start, bool.Parse(lista[0])); } else if (functionBox2.SelectedItem == "06 Write Single Register") { modbusClient.WriteSingleRegister(start, int.Parse(listBox2.Items[0].ToString())); } else if (functionBox2.SelectedItem == "15 Write Multiple Coils") { bool[] tab; int l = 0; int j = 0; foreach (string b in listBox2.Items) { l++; } tab = new bool[l]; foreach (string b in listBox2.Items) { tab[j] = bool.Parse(b); j++; } modbusClient.WriteMultipleCoils(start, tab); } else if (functionBox2.SelectedItem == "16 Write Multiple Registers") { int[] tab; int l = 0; int j = 0; foreach (string b in listBox2.Items) { l++; } tab = new int[l]; foreach (string b in listBox2.Items) { tab[j] = int.Parse(b); j++; } modbusClient.WriteMultipleRegisters(start, tab); } else { int[] tab; int l = 0; int j = 0; foreach (string b in listBox2.Items) { l++; } tab = new int[l]; foreach (string b in listBox2.Items) { tab[j] = int.Parse(b); j++; } modbusClient.WriteMultipleRegisters(start, tab); } }
} // End Read Function /// <summary> /// Write data to the Server Device.</summary> public bool Write(DataExtClass[] DataIn) { bool retVar = false; int i, j, jj, SAddress, boolReg, boolBit; uint intFloat; DAConfClass thisArea; var bitArray = new System.Collections.BitArray(16); var BitInt = new int[1]; //If is not initialized and not connected return error if (!(isInitialized && (DataIn != null))) { Status.NewStat(StatType.Bad, "Not Ready for Writing"); return false; } //If the DataIn and Internal data doesnt have the correct amount of data areas return error. if (!((DataIn.Length == MasterDriverConf.NDataAreas) && (IntData.Length == MasterDriverConf.NDataAreas))) { Status.NewStat(StatType.Bad, "Data Containers Mismatch"); return false; } if (!(isConnected && ModTCPObj.Connected)) { Status.NewStat(StatType.Bad, "Connection Error..."); this.Disconect(); return false; } for (i = 0; i < MasterDriverConf.NDataAreas; i++) { thisArea = MasterDataAreaConf[i]; SAddress = int.Parse(thisArea.StartAddress); if (thisArea.Enable && thisArea.Write) { jj = 0; //Index reinitialize for (j = 0; j < thisArea.Amount; j++) { switch (thisArea.dataType) { case DriverConfig.DatType.Bool: if (thisArea.DBnumber == 1) { if ((IntData[i].dBool.Length > j) && (DataIn[i].Data.dBoolean.Length > j)) { IntData[i].dBool[j] = DataIn[i].Data.dBoolean[j]; } } else if (thisArea.DBnumber == 3) { boolReg = Math.DivRem(j, 16, out boolBit); if ((IntData[i].dInt.Length > boolReg) && (DataIn[i].Data.dBoolean.Length > j)) { if (boolBit == 0) { bitArray.SetAll(false); BitInt[0] = 0; } bitArray.Set(boolBit, DataIn[i].Data.dBoolean[j]); bitArray.CopyTo(BitInt, 0); IntData[i].dInt[boolReg] = BitInt[0]; } } break; case DriverConfig.DatType.Byte: IntData[i].dInt[j] = DataIn[i].Data.dByte[j]; break; case DriverConfig.DatType.Word: IntData[i].dInt[j] = DataIn[i].Data.dWord[j]; break; case DriverConfig.DatType.DWord: //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); } else { IntData[i].dInt[jj] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); } jj = jj + 2; break; case DriverConfig.DatType.Real: //Float point decimal. //Convert the intFloat = (uint)Math.Abs(Math.Round(DataIn[i].Data.dReal[j] * 1000.0)); //Turn ON/OFF the sign bit. if (DataIn[i].Data.dReal[j] < 0) { intFloat = intFloat | MaskNeg; } else { intFloat = intFloat & MaskiNeg; } //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((intFloat & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(intFloat & MaskWord); } else { IntData[i].dInt[jj] = (int)(intFloat & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((intFloat & MaskHWord) >> 16); } jj = jj + 2; break; default: Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config."); break; } } // For j try { //Write the data to the device if ((thisArea.DBnumber == 1) && (thisArea.dataType == DriverConfig.DatType.Bool)) { ModTCPObj.WriteMultipleCoils(SAddress, IntData[i].dBool); retVar = true; } else if (thisArea.DBnumber == 3) { ModTCPObj.WriteMultipleRegisters(SAddress, IntData[i].dInt); retVar = true; } else { retVar = false; Status.NewStat(StatType.Warning, "Wrong FC for Write, Check Config."); } //Report Good if (retVar) Status.NewStat(StatType.Good); } catch (Exception e) { Status.NewStat(StatType.Bad, e.Message); return false; } }// Area Enable } //For Data Areas. return retVar; }// END Write Function
private async Task ExecuteWriteMultipleDiscreteCommand(ushort startAddress, int[] commandValues, CommandOriginType commandOrigin) { StringBuilder commandValuesSB = new StringBuilder(); commandValuesSB.Append("[ "); foreach (int value in commandValues) { commandValuesSB.Append(value); commandValuesSB.Append(" "); } commandValuesSB.Append("]"); string verboseMessage = $"{baseLogString} entering ExecuteWriteMultipleDiscreteCommand method, command's startAddress: {startAddress}, commandValues: {commandValuesSB}, commandOrigin: {commandOrigin}."; Logger.LogVerbose(verboseMessage); var modelReadAccessClient = ScadaModelReadAccessClient.CreateClient(); var modelUpdateAccessClient = ScadaModelUpdateAccessClient.CreateClient(); //LOGIC int quantity = commandValues.Length; var addressToGidMap = await modelReadAccessClient.GetAddressToGidMap(); //this.commandDescriptions = new Dictionary<long, CommandDescription>(); this.commandDescriptions.Clear(); bool[] booleanCommands = new bool[quantity]; StringBuilder booleanCommandsSB = new StringBuilder(); booleanCommandsSB.Append("[ "); //LOGIC for (ushort index = 0; index < quantity; index++) { ushort address = (ushort)(startAddress + index); if (commandValues[index] == 0) { booleanCommands[index] = false; booleanCommandsSB.Append(false); if (index < quantity - 1) { booleanCommandsSB.Append(" "); } else { booleanCommandsSB.Append(" ]"); } } else if (commandValues[index] == 1) { booleanCommands[index] = true; booleanCommandsSB.Append(true); if (index < quantity - 1) { booleanCommandsSB.Append(" "); } else { booleanCommandsSB.Append(" ]"); } } else { string errorMessage = $"{baseLogString} ExecuteWriteMultipleDiscreteCommand => Non-boolean value in write single coil command parameter."; Logger.LogError(errorMessage); throw new ArgumentException(); } var pointType = (short)PointType.DIGITAL_OUTPUT; if (!addressToGidMap.ContainsKey(pointType)) { Logger.LogWarning($"{baseLogString} ExecuteWriteMultipleDiscreteCommand => Point type: {pointType} is not in the current addressToGidMap."); continue; } if (addressToGidMap[pointType].ContainsKey(address)) { long gid = addressToGidMap[pointType][address]; CommandDescription commandDescription = new CommandDescription() { Gid = gid, Address = address, Value = commandValues[index], CommandOrigin = commandOrigin, }; //LOGIC this.commandDescriptions.Add(gid, commandDescription); string message = $"{baseLogString} ExecuteWriteMultipleDiscreteCommand => CommandDescription added to the collection of commandDescriptions. Gid: {commandDescription.Gid:X16}, Address: {commandDescription.Address}, Value: {commandDescription.Value}, CommandOrigin: {commandDescription.CommandOrigin}"; Logger.LogDebug(message); } } string debugMessage = $"{baseLogString} ExecuteWriteMultipleDiscreteCommand => About to send collection of CommandDescriptions to CommandDescriptionCache. collection count: {commandDescriptions.Count}"; Logger.LogDebug(debugMessage); //LOGIC await modelUpdateAccessClient.AddOrUpdateMultipleCommandDescriptions(this.commandDescriptions); debugMessage = $"{baseLogString} ExecuteWriteMultipleDiscreteCommand => about to call ModbusClient.WriteMultipleCoils({startAddress - 1}, {booleanCommandsSB}) method. StartAddress: {startAddress}, Quantity: {quantity}"; Logger.LogDebug(debugMessage); //KEY LOGIC modbusClient.WriteMultipleCoils(startAddress - 1, booleanCommands); string infoMessage = $"{baseLogString} ExecuteWriteMultipleDiscreteCommand => ModbusClient.WriteMultipleCoils() method SUCCESSFULLY executed. StartAddress: {startAddress}, Quantity: {quantity}"; Logger.LogInformation(infoMessage); }
public void WriteMultipleCoils(int startReg, bool[] bits) { _client.WriteMultipleCoils(startReg, bits); }