static async Task Run() { while (true) { Message IoTMessage; dynamic messageToSend = new JObject(); try { Thread.Sleep(1000 * POLLINGfrequency); modbusClient = new ModbusClient(POLLINGHost, 502); await modbusClient.Connect(); counter += 1; messageToSend["messagecounter"] = counter; messageToSend["POLLINGHost"] = POLLINGHost; messageToSend["dateTime"] = DateTime.Now.ToString(); messageToSend["Las Vegas"] = getRegister(0).Result; messageToSend["Stockholm"] = getRegister(1).Result; messageToSend["Wadi Halfa"] = getRegister(2).Result; messageToSend["MSFT Stock"] = getRegister(3).Result; messageToSend["HPE Stock"] = getRegister(4).Result; await modbusClient.Disconnect(); } catch (Exception e) { messageToSend["Error"] = e.Message; if (modbusClient.IsConnected) { modbusClient.Disconnect().Wait(); } } Console.WriteLine("Sending message: " + messageToSend.ToString()); IoTMessage = new Message(Encoding.UTF8.GetBytes(messageToSend.ToString())); await ioTHubModuleClient.SendEventAsync("output1", IoTMessage); } }
private void init() { if (modbusClient.Connected) { modbusClient.Disconnect(); } try { string[] ports = SerialPort.GetPortNames(); modbusClient.SerialPort = ports[0]; modbusClient.UnitIdentifier = Convert.ToByte(Properties.Settings.Default.tensionSlave); modbusClient.Baudrate = Properties.Settings.Default.tensionBaudRate; modbusClient.Parity = Parity.None; modbusClient.StopBits = StopBits.Two; modbusClient.ConnectionTimeout = 500; modbusClient.Connect(); VarsTension.client = modbusClient; if (!backgroundWorkerRead.IsBusy) { backgroundWorkerRead.RunWorkerAsync(); } } catch { backgroundWorkerRead.CancelAsync(); modbusClient.Disconnect(); } }
public void WriteInRegisters <T>(int startingAddress, T value) { int[] values = ConvertingValueHandler.ConvertToRegister(value); modbusClient.Connect(); modbusClient.WriteMultipleRegisters(startingAddress, values); modbusClient.Disconnect(); }
public void ReadHoldingRegister() { try { Console.WriteLine("Please Enter The Starting Address of ReadHoldingRegister:"); string holdingregister = Console.ReadLine(); int register = Convert.ToInt32(holdingregister); //Console.WriteLine("Please Enter The Quantity Length:"); //string holdingregisterlength = Console.ReadLine(); //int registerlength = Convert.ToInt32(holdingregisterlength); int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters(register, 50);//40017 if (readHoldingRegisters != null) { for (int i = 0; i < readHoldingRegisters.Length; i++) { Console.ForegroundColor = ConsoleColor.Green; Decimal _toDecimal = Convert.ToDecimal(readHoldingRegisters[i]); Console.WriteLine((register) + ":" + "<" + _toDecimal + ">"); register++; } } Console.ResetColor(); modbusClient.Disconnect(); Console.ReadKey(); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message); Console.ResetColor(); Console.ReadLine(); } }
private void WriteRegister(int address, int value) { if (ConnectToSlave(tb_IPAddress.Text)) { address = address - 1; modbusClient.WriteSingleRegister(address, value); modbusClient.Disconnect(); } }
private void ConnectToStation(object IP) { ModbusClient StationClient; try { StationClient = new ModbusClient((string)IP); sockethandler(this, new SocketDisconnectEvent() { status = "試車站PLC在線", TextColor = "WhiteSmoke" }); CallButtonChangeDel(Btn_StationDisconnect, Btn_StationConnect, Lab_StationConnecting); DisConnectToStation = true; while (true) { if (DisConnectToStation) { Thread.Sleep(1000); Form1.RWLock.AcquireWriterLock(2000); try { StationClient.ReadHoldRegister(1, 1, 20).CopyTo(Form1.StationDataBuffer, 0); } catch (SocketException) { sockethandler(this, new SocketDisconnectEvent() { status = "與試車站連線中斷", TextColor = "Red" }); CallButtonChangeDel(Btn_StationConnect, Btn_StationDisconnect, Lab_StationConnecting); StationClient.Disconnect(); break; } finally { Form1.RWLock.ReleaseWriterLock(); } } else { StationClient.Disconnect(); break; } } } catch (SocketException) { MessageBox.Show("未取得與伺服器的連線\n請檢察線路及IP是否正確", "連接錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); sockethandler(this, new SocketDisconnectEvent() { status = "未與試車站建立連結", TextColor = "Red" }); CallButtonChangeDel(Btn_StationConnect, Btn_StationDisconnect, Lab_StationConnecting); } //Customize_Function_Stop }
public void readPlc() { _client.Connect(); //Thread.Sleep(100); registers = _client.ReadHoldingRegisters(0, 4); _client.Disconnect(); register1 = registers[0]; register2 = registers[1]; register3 = registers[2]; register4 = registers[3]; }
private void cbbSelctionModbus_SelectedIndexChanged(object sender, EventArgs e) { if (modbusClient.Connected) { modbusClient.Disconnect(); } if (cbbSelctionModbus.SelectedIndex == 0) { txtIpAddress.Visible = true; txtIpAddressInput.Visible = true; txtPort.Visible = true; txtPortInput.Visible = true; txtCOMPort.Visible = false; cbbSelectComPort.Visible = false; txtSlaveAddress.Visible = false; txtSlaveAddressInput.Visible = false; lblBaudrate.Visible = false; lblParity.Visible = false; lblStopbits.Visible = false; txtBaudrate.Visible = false; cbbParity.Visible = false; cbbStopbits.Visible = false; } if (cbbSelctionModbus.SelectedIndex == 1) { cbbSelectComPort.SelectedIndex = 0; cbbParity.SelectedIndex = 0; cbbStopbits.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; lblBaudrate.Visible = true; lblParity.Visible = true; lblStopbits.Visible = true; txtBaudrate.Visible = true; cbbParity.Visible = true; cbbStopbits.Visible = true; } }
private void button_disconnect_Click(object sender, EventArgs e) { modbusClient.Disconnect(); status.Text = "offline"; status.ForeColor = Color.Crimson; }
public void Disconnect() { timerReadCoil.Enabled = false; if (modbusTCP.Connected == true) { try { modbusTCP.Disconnect(); grpBoxCoils.Enabled = false; grpBoxRegisters.Enabled = false; btnCon.Enabled = true; groupIHM.Enabled = false; btnDisconnect.Enabled = false; txtConexao.BackColor = Color.Red; txtConexao.Text = " Desconectado"; txtConexao.Enabled = true; txtModo.BackColor = Color.Blue; txtModo.Text = " Manual"; txtModo.Enabled = true; LabelStrip001.Text = " Desconectado com sucesso. "; } catch { LabelStrip001.Text = " Erro ao desconectar. "; } } else { LabelStrip001.Text = " PLC não está conectado. "; } }
public void disconnectSKU() { if (modbusClient != null) { modbusClient.Disconnect(); } }
private void FetchFromModbusServer() { ModbusClient modbusClient = null; try { modbusClient = new ModbusClient(ModbusHost.Value, ModbusPort.Value); modbusClient.Connect(); OutputValue.Value = (modbusClient.ReadHoldingRegisters(ModbusAddress.Value, ReadCount.Value)[0] / 10.0); this.ErrorMessage.Value = ""; this.SchedulerService.InvokeIn(new TimeSpan(0, 0, 10), FetchFromModbusServer); } catch (Exception e) { this.ErrorMessage.Value = e.ToString(); this.SchedulerService.InvokeIn(new TimeSpan(0, 1, 0), FetchFromModbusServer); } finally { if (modbusClient != null) { modbusClient.Disconnect(); } } }
public Task DisconnectAsync() { _modbusClient.Disconnect(); _modbusClient = null; return(Task.CompletedTask); }
//点击断连接 private void b_disconnect_Click(object sender, RoutedEventArgs e) { modbusClient.Disconnect(); Thread.Sleep(1000); ConnectStatus.Content = "未连接..."; ConnectStatus.Foreground = new SolidColorBrush(Colors.Red); }
public void Close() { Evt_ModBusConnection?.Invoke(this, false); modbusClnt.ConnectedChanged -= On_Connected; modbusClnt.Disconnect(); modbusClnt = null; }
/// <summary> /// 启动指示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Start_Click(object sender, EventArgs e) { try { ModbusClient modbusClient = Common.ModbusConnect(); if (modbusClient != null) { int start = 2056; //启动对应Q10--2056 if (this.led_Start.GridentColor == Color.Green) { modbusClient.WriteSingleCoil(start, false); } else { modbusClient.WriteSingleCoil(start, true); } //关闭连接 modbusClient.Disconnect(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Destroy this Compopnent /// </summary> public override void Destroy() { if (_readerTimer != null) { _readerTimer.Dispose(); _readerTimer = null; } if (_writerTimer != null) { _writerTimer.Dispose(); _writerTimer = null; } base.Destroy(); if (_mbReaderClient != null) { _mbReaderClient.Disconnect(); _mbReaderClient = null; } if (_mbWriterClient != null) { _mbWriterClient.Disconnect(); _mbWriterClient = null; } }
private void timer1_Tick(object sender, EventArgs e) { //Connect to Server if (modbusClient.Connected && modbusClient.Available(1)) { try { int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 10); //Read 10 Holding Registers from Server, starting with Address 1 var new_text = String.Join(" - ", readHoldingRegisters); if (old_registers != new_text) { old_registers = new_text; var to_print = readHoldingRegisters[0]; if (to_print == 1) { var number = readHoldingRegisters[1].ToString(); listBox1.SelectedIndex = -1; for (int i = 0; i < listBox1.Items.Count; i++) { if (listBox1.Items[i].ToString().StartsWith(number)) { listBox1.SelectedIndex = i; var selected_prn = listBox1.Items[i].ToString(); var selected_bin = Path.ChangeExtension(selected_prn, "bin"); listBox2.Items.Add("printing " + selected_bin); var text_to_print = File.ReadAllText(trabajo_folder + "\\" + selected_bin); RawPrinterHelper.SendStringToPrinter(printerName.Text, text_to_print); print_count++; label7.Text = print_count.ToString(); } } } listBox2.Items.Add(new_text); } } catch (Exception ex) { plcStatus.Text = ex.Message; modbusClient.Disconnect(); } } else { modbusClient.Disconnect(); connect_to_plc(); } }
//Discon 버튼 private void button4_Click(object sender, EventArgs e) { if (MBClient.Connected == true) { MBClient.Disconnect(); listBox1.Items.Clear(); label1.Text = "정지중"; label1.ForeColor = Color.Black; threadrun = false; rdTh.Join(); button1.Enabled = true; button2.Enabled = false; button3.Enabled = false; button4.Enabled = false; } }
private void btnStartPomiaru(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); modbusClient.WriteSingleCoil(2267, true); modbusClient.Disconnect(); }
// Write single coil and check connection private void WriteSingleCoilValue(int address, bool value) { try { modbusClient.WriteSingleCoil(address, value); } //catch (EasyModbus.Exceptions.ConnectionException ex) catch (Exception ex) { Console.WriteLine(ex); MessageBox.Show("Erro de conexão com a placa Modbus", "Erro de conexão", MessageBoxButtons.OK, MessageBoxIcon.Error); modbusClient.Disconnect(); groupBox1.Enabled = false; groupBox2.Enabled = false; btConnect.Checked = false; textBox1.Enabled = true; } }
private void FetchFromModbusServer() { if (ModbusHost.HasValue && ModbusAddress1.Value > 0) { ModbusClient modbusClient = null; try { modbusClient = new ModbusClient(ModbusHost.Value, ModbusPort.Value); modbusClient.Connect(); modbusClient.UnitIdentifier = (byte)ModbusID.Value; // Register 1 // read + 1 register ???!!! bug in the EasyModbus ????!!! lowest byte 0x00 !!! // [0] Hugh Byte // [1] Low Byte // [2] Dummy (High Byte) // [3] Dummy (Low Byte) = 0x00 in X1 (not in the X1 SImulation!) int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters(ModbusAddress1.Value, ReadCount1.Value + 2); double result = 0; string result_str = ""; //byte[] tmp; for (int i = 0; i < (readHoldingRegisters.Length - 2); i++) { int tmp = readHoldingRegisters[i]; if (tmp == -32768) // fix for 0x00 { tmp = 0; } if (tmp < 0) // no negative values ! { tmp = tmp + (int)Math.Pow(2, 16); } result = result + (tmp * Math.Pow(2, (16 * ((readHoldingRegisters.Length - 2) - (i + 1))))); result_str = result_str + " 0x" + tmp.ToString("X4"); } OutputValue1.Value = result; ErrorMessage.Value = result_str; this.SchedulerService.InvokeIn(new TimeSpan(0, 0, TimeSpan.Value), FetchFromModbusServer); } catch (Exception e) { this.ErrorMessage.Value = e.ToString(); this.SchedulerService.InvokeIn(new TimeSpan(0, 1, 0), FetchFromModbusServer); } finally { if (modbusClient != null) { modbusClient.Disconnect(); } } } }
private static void ConnectBarcode() { if (BarcodeClient.Connected) { BarcodeClient.Disconnect(); } try { _cancelBarcodeSource.Cancel(); } catch (Exception) { //ignored } BarcodeClient.IPAddress = "192.168.0.100"; BarcodeClient.Port = 51236; BarcodeClient.SerialPort = null; try { BarcodeClient.Connect(); } catch (Exception ex) { MessageBox.Show(@"Kaynak: Barkod okuyucu." + ex.Message, @"Bağlantı Hatası", MessageBoxButtons.OK, MessageBoxIcon.Hand); } _cancelBarcodeSource = new CancellationTokenSource(); _cancelBarcode = _cancelBarcodeSource.Token; var barcodeListener = new Task(() => Listen()); barcodeListener.ContinueWith( t => { MessageBox.Show(@"Barkod okuyucu dinleyicisinde bilinmeyen bir hata gerçekleşti."); }, TaskContinuationOptions.OnlyOnFaulted); barcodeListener.Start(); var args = EventArgs.Empty; OnBarcodeConnectionChanged(args); }
private void ExecuteCommand(IModbusFunction command) { try { command.Execute(ModbusClient); } catch (Exception e) { string message = "Exception on currentCommand.Execute()."; Logger.LogWarn(message, e); ModbusClient.Disconnect(); return; } if (command is IReadAnalogModusFunction readAnalogCommand) { MakeAnalogEntryToMeasurementCache(readAnalogCommand.Data, true); } else if (command is IReadDiscreteModbusFunction readDiscreteCommand) { MakeDiscreteEntryToMeasurementCache(readDiscreteCommand.Data, true); } else if (command is IWriteModbusFunction writeModbusCommand) { CommandValue commandValue = new CommandValue() { Address = writeModbusCommand.ModbusWriteCommandParameters.OutputAddress, Value = writeModbusCommand.ModbusWriteCommandParameters.Value, CommandOrigin = writeModbusCommand.CommandOrigin, }; PointType pointType; switch (writeModbusCommand.ModbusWriteCommandParameters.FunctionCode) { case (byte)ModbusFunctionCode.WRITE_SINGLE_REGISTER: pointType = PointType.ANALOG_OUTPUT; break; case (byte)ModbusFunctionCode.WRITE_SINGLE_COIL: pointType = PointType.DIGITAL_OUTPUT; break; default: Logger.LogError($"Function code {writeModbusCommand.ModbusWriteCommandParameters.FunctionCode} is not comatible with write command."); return; } if (SCADAModel.CurrentAddressToGidMap[pointType].ContainsKey(commandValue.Address)) { long gid = SCADAModel.CurrentAddressToGidMap[pointType][commandValue.Address]; SCADAModel.CommandedValuesCache[gid] = commandValue; } } }
private void btnTemperatuaZadana(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); float TemperaturaZadana = float.Parse(txtTemperaturaZadana.Text); int[] aaa = ModbusClient.ConvertFloatToRegisters(TemperaturaZadana); modbusClient.WriteMultipleRegisters(4506, aaa); modbusClient.Disconnect(); }
public static void CloseConnection() { try { modbusClient.Disconnect(); } catch { Console.WriteLine("Connection cannot be closed"); } }
private void Button_Click_1(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); float TolerancjaTemperatury = float.Parse(txtTolerancjaTemperatury.Text); int[] aaa = ModbusClient.ConvertFloatToRegisters(TolerancjaTemperatury); modbusClient.WriteMultipleRegisters(4508, aaa); modbusClient.Disconnect(); }
private void BtnUstawProbkowanieTemperatury_Click(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); int ProbkowanieTemperatury = int.Parse(txtProbkowanieTemperatury.Text); //int[] aaa = ModbusClient.ConvertIntToRegisters(CzasPomiaru_N1); modbusClient.WriteSingleRegister(4505, ProbkowanieTemperatury); modbusClient.Disconnect(); }
private void BtnUstawTolerancjeCisnienia_N4_Click(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); float TolerancjaCisnienia_N4 = float.Parse(txtCisnienieTolerancja_N4.Text); int[] aaa = ModbusClient.ConvertFloatToRegisters(TolerancjaCisnienia_N4); modbusClient.WriteMultipleRegisters(4530, aaa); modbusClient.Disconnect(); }
private void BtnCzasPomiaru_N4_Click(object sender, RoutedEventArgs e) { ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); int CzasPomiaru_N4 = int.Parse(txtCzasPomiaru_N4.Text); int[] aaa = ModbusClient.ConvertIntToRegisters(CzasPomiaru_N4); modbusClient.WriteMultipleRegisters(4532, aaa); modbusClient.Disconnect(); }