/// <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 async Task InitializeModbusClient() { try { var modelReadAccessClient = ScadaModelReadAccessClient.CreateClient(); this.configData = await modelReadAccessClient.GetScadaConfigData(); this.modbusClient = new ModbusClient(configData.IpAddress.ToString(), configData.TcpPort); } catch (Exception e) { string message = $"{baseLogString} InitializeModbusClient => Exception: {e.Message}."; Logger.LogError(message, e); } if (modbusClient == null) { string message = $"{baseLogString} InitializeModbusClient => ModbusClient is null"; Logger.LogError(message); throw new Exception(message); } }
public static void Main(string[] args) { ///* banco = new Store.Store(); JavaScriptSerializer ser = new JavaScriptSerializer(); OEE.OEE foo = ser.Deserialize <OEE.OEE>(banco.Fabrica); oee = new OEE.OEE(foo.quantidade, foo.Linhas, foo.DXM_Endress, foo.emulador, foo.tickLog, foo.zerou_turno); oee.timeOut = foo.timeOut; if (oee.DXM_Tcp) { dxm = new ModbusClient(oee.DXM_Endress, 502); } else { dxm = new ModbusClient(oee.DXM_Endress); } ThreadStart start = new ThreadStart(leituraDXM); Thread acao = new Thread(start); ThreadStart log = new ThreadStart(DXMLog); Thread acao2 = new Thread(log); ThreadStart log2 = new ThreadStart(poolRegistro); Thread acao3 = new Thread(log2); acao3.Start(); acao.Start(); acao2.Start(); //*/ var pathToExec = Process.GetCurrentProcess().MainModule.FileName; _pathContentRoot = Path.GetDirectoryName(pathToExec); //CreateWebHostBuilder(args).Build().RunAsCustomService(); CreateWebHostBuilder(args).Build().Run(); }
public async Task ClientReadInputRegisterTest() { // Function Code 0x04 byte[] expectedRequest = new byte[] { 0, 0, 0, 6, 3, 4, 0, 6, 0, 3 }; var expectedResponse = new List <Register> { new Register { Address = 6, RegisterValue = 123, Type = ModbusObjectType.InputRegister }, new Register { Address = 7, RegisterValue = 0, Type = ModbusObjectType.InputRegister }, new Register { Address = 8, RegisterValue = 12345, Type = ModbusObjectType.InputRegister } }; using var server = new MiniTestServer { RequestHandler = (request, clientIp) => { CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect"); Console.WriteLine("Server sending response"); return(new byte[] { request[0], request[1], 0, 0, 0, 9, 3, 4, 6, 0, 123, 0, 0, 48, 57 }); } }; server.Start(); using var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger()); await client.Connect(); Assert.IsTrue(client.IsConnected); var registers = await client.ReadInputRegisters(3, 6, 3); Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError); CollectionAssert.AreEqual(expectedResponse, registers, "Response is incorrect"); }
public static void connectSKU(string ip, int port) { try { modbusClient = new ModbusClient(ip, port); //modbusClient.ConnectionTimeout = 50000; modbusClient.Connect(); int[] zavnomer = new int[4]; zavnomer = modbusClient.ReadHoldingRegisters(3 - 1, 4); zavnomer[2] = 0; zavnomer[3] = 0; ulong zavnomer1 = Convert.ToUInt64(ModbusClient.ConvertRegistersToLong(zavnomer)); MessageBox.Show("Подключение установлено. Заводской № " + zavnomer1.ToString()); Action action = () => Instance.labelConnectStatus.Text = "Подключение установлено"; Instance.labelConnectStatus.Invoke(action); action = () => Instance.ButtonConnectDevice.Enabled = false; Instance.ButtonConnectDevice.Invoke(action); } catch (ConnectionException ex) { if (ex.Message == "connection timed out") { MessageBox.Show("Подключение не установленно. Время ожидания подключения истекло"); } else { MessageBox.Show(ex.Message); } } catch (SocketException) { { MessageBox.Show("Не удалось подключиться к устройству."); } } }
public static void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); Console.WriteLine($"socket conncetion to {handler.RemoteEndPoint} has established"); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; modbus = new ModbusClient(handler); for (int j = 1; j == 1; j++) { //modbus.UnitIdentifier = Convert.ToByte(1); int unitId = modbus.ReportSlaveID(); //Thread.Sleep(1000); Console.WriteLine($"{handler.RemoteEndPoint} has UnitId: " + modbus.UnitIdentifier.ToString()); //modbus.UnitIdentifier = unitId; try { int[] serverResponse = modbus.ReadHoldingRegisters(1, 10); for (int i = 0; i < serverResponse.Length; i++) { Console.WriteLine($"data from {handler.RemoteEndPoint} recieved: {serverResponse[i]} "); } Thread.Sleep(2000); // modbus.ReadHoldingRegisters(1, 10); } catch { Console.WriteLine("time out in stream.Read"); } } }
public Device() { InitializeComponent(); //assembly = Assembly.Load("VisualUNITY"); //rm = new ResourceManager("VisualUNITY.Languages.language", assembly); //cultureInfo = new CultureInfo(Properties.Settings.Default.language); dispatcherTimer.Tick += timerWork; dispatcherTimer.Interval = TimeSpan.FromMilliseconds(1); seconds.Tick += secondsWork; seconds.Interval = TimeSpan.FromSeconds(1); SeriesCollection = new SeriesCollection { new LineSeries { Title = "Gergi Set", Values = new ChartValues <int> { } }, new LineSeries { Title = "Gergi", Values = new ChartValues <int> { } } }; DataContext = this; if (Vars.client == null) { init(); } else { modbusClient = Vars.client; } }
public void iniciarThreadConexao() { // Iniciando/Reiniciando travas. transmissionSemaphore = new Semaphore(1, 1); string enderecoModBus = modbusRegistry.obterModBusEndereco(); int portaModBus = modbusRegistry.obterModBusPorta(); ThreadConexao = new Thread(() => { bool conectado = false; databaseCheckerShouldRun = true; while (conectado == false && DatabaseCheckerShouldRun) { try { modbusClient = new ModbusClient(enderecoModBus, portaModBus); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); //Connect to Server conectado = true; ProcessIcon.ChangeIcon((int)ProcessIcon.ICONS.Normal); } catch (Exception ex) { logger.Error("Erro ao conectar ao servidor: " + ex.Message); logger.Warn("Tentando novamente em 3 segundos..."); Thread.Sleep(3000); } } iniciarThreadPrincipal(); iniciarThreadHeartBeat(); ThreadConexao.Join(); }); ThreadConexao.Name = "Conexão"; ThreadConexao.Start(); }
public void MasterShouldReadDiscreteInputsFromSlave() { var clientMemory = new ModbusMemoryMap(); var client = new ModbusClient(new ModbusRTUTransport(_clientStream)); var clientDevice = new ModbusDevice(clientMemory, 4); var serverMemory = new ModbusMemoryMap(); var server = new ModbusServer(new ModbusRTUTransport(_serverStream)); var serverDevice = new ModbusDevice(serverMemory, 4); serverMemory.InputCoils[10] = true; serverMemory.InputCoils[15] = true; clientMemory.InputCoils[10].ShouldBeFalse(); clientMemory.InputCoils[15].ShouldBeFalse(); Task.Run(() => server.HandleRequest(serverDevice)); //read only one input client.ReadDiscreteInputs(clientDevice, 10, 1); //slave memory not touched serverMemory.InputCoils[10].ShouldBeTrue(); serverMemory.InputCoils[15].ShouldBeTrue(); //master memory is synched clientMemory.InputCoils[10].ShouldBeTrue(); clientMemory.InputCoils[15].ShouldBeFalse(); Task.Run(() => server.HandleRequest(serverDevice)); //read another input client.ReadDiscreteInputs(clientDevice, 15, 1); //master memory is synched clientMemory.InputCoils[10].ShouldBeTrue(); clientMemory.InputCoils[15].ShouldBeTrue(); }
private void Btn_Init_Click(object sender, RoutedEventArgs e) { // Yolov3 process yoloWrapper = new YoloWrapper(Paras.Yolov3_Cfg.Value, Paras.Yolov3_Weights.Value, Paras.Yolov3_Names.Value); //var Items_Temp = yoloWrapper.Detect(this.DataByte_Public); //Dg_Debug.ItemsSource = Items_Temp; try // ---Modbus Server Setup { modbusClient = new ModbusClient(Paras.Modbus_Server_IP.Value, int.Parse(Paras.Modbus_Server_Port.Value)); modbusClient.LogFileFilename = Paras.Modbus_Server_LogFileFilename.Value; modbusClient.Connect(); Dt_Modbus.Start(); string TempStr = Paras.LoadAllParameters(); if (TempStr == "ERROR") { MessageBox.Show("Error105: MyConfiguration.LoadAllParameters() get error"); } try { StartCamera(VideoDevices[Cb_Camera.SelectedIndex].MonikerString); StateMachine_Auto(); } catch { MessageBox.Show("Error103: Failt to start Camera"); StopCamera(); StateMachine_NotInit(); } } catch { MessageBox.Show("Error102: Fail to connect to the Modbus Server at the address " + Paras.Modbus_Server_IP.Value + ":" + Paras.Modbus_Server_Port.Value); StateMachine_NotInit(); } }
/// <summary> /// 连接PLC /// </summary> /// <returns></returns> public static ModbusClient ModbusConnect() { try { string ip = MainForm.PLC_IP; ModbusClient modbusClient = new ModbusClient(ip, 502); modbusClient.Connect(); if (modbusClient.Connected) { return(modbusClient); } else { return(null); } } catch (Exception ex) { MessageBox.Show(ex.Message); return(null); } }
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 int OdczytajDanaRejestru(string plcIP, int port, int adresRejestru, int iloscRejestrow) { int[] wynik = new int[iloscRejestrow]; try { ModbusClient modbusClient = new ModbusClient(plcIP, port); //Ip-Address and Port of Modbus-TCP-Server modbusClient.ConnectionTimeout = 5000; //Increase the Connection Timeout to 5 seconds modbusClient.Connect(); //Connect to Server int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters((adresRejestru - 1), iloscRejestrow); //Read one or more Holding Registers from Server, starting with Address for (int i = 0; i < readHoldingRegisters.Length; i++) { wynik[i] = readHoldingRegisters[i]; } modbusClient.Disconnect(); //Disconnect from Server } catch (Exception) { zapiszLog("Błąd podczas OdczytajDanaRejestru"); } return(wynik[0]); }
public ConnectedSlave(ModbusMaster master, Socket connection, byte id) { Master = master; _socketConnection = connection; CommClient = _socketConnection.GetClient(); if (connection.RemoteEndPoint is IPEndPoint ipEndPoint) { Address = ipEndPoint.Address; Port = (ushort)ipEndPoint.Port; } else { throw new NotSupportedException("ConnectedSlave without IP endpoint"); } Id = id; var codec = new ModbusTcpCodec(); _client = new ModbusClient(codec) { Address = Id }; _failures = 0; }
private void bt_Connect_Click(object sender, EventArgs e) { if (connection_status == false) { try { modbusClient = new ModbusClient(tb_ModbusServerIP.Text, 502); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); lb_Status.Text = "Connected!"; lb_Status.ForeColor = Color.Green; tmr_Modbus_Com.Enabled = true; connection_status = true; bt_Connect.Enabled = false; bt_Disconnect.Enabled = true; } catch (Exception ex) { //MessageBox.Show(ex.Message, "Connection failed", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show(ex.Message); } } }
public async Task ClientReadHoldingRegisterTest() { // Function Code 0x03 var expectedRequest = new byte[] { 0, 0, 0, 6, 5, 3, 0, 10, 0, 2 }; var expectedResponse = new List <Register> { new Register { Address = 10, Value = 3 }, new Register { Address = 11, Value = 7 } }; using (var server = new MiniTestServer()) { server.RequestHandler = (request, clientIp) => { CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect"); Console.WriteLine("Server sending response"); return(new byte[] { request[0], request[1], 0, 0, 0, 7, 5, 3, 4, 0, 3, 0, 7 }); }; server.Start(); using (var client = new ModbusClient(IPAddress.Loopback, server.Port)) { await client.Connect(); Assert.IsTrue(client.IsConnected); var registers = await client.ReadHoldingRegisters(5, 10, 2); Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError); CollectionAssert.AreEqual(expectedResponse, registers, "Response is incorrect"); } } }
public List <int[]> getLogs(int startIndexRead) { modbusClient = ConnectUserControl.getModbusClient(); List <int[]> RecordNumbers = new List <int[]>(); if (modbusClient != null && modbusClient.Connected == true) { try { //long OldbestRecordNumber = getOldbestRecordNumber(); long NewbestRecordNumber = getNewbestRecordNumber(); if (startIndexRead != -1 && NewbestRecordNumber != -1) { modbusClient.WriteMultipleRegisters(1059, ModbusClient.ConvertIntToRegisters(768)); for (long i = startIndexRead; i <= NewbestRecordNumber; i++) { int[] numberCurrentWrite = new int[4]; numberCurrentWrite = ModbusClient.ConvertLongToRegisters(i); modbusClient.WriteMultipleRegisters(1060, numberCurrentWrite); int[] ArrayLogs = new int[64]; ArrayLogs = modbusClient.ReadHoldingRegisters(17344, 64); RecordNumbers.Add(ArrayLogs); } } return(RecordNumbers); } catch (Exception) { Console.WriteLine("Error: Неожиданный обрыв подключения"); return(RecordNumbers);// } } else { return(RecordNumbers); } }
public async Task ClientWriteRegistersTest() { // Function Code 0x10 var expectedRequest = new byte[] { 0, 0, 0, 11, 10, 16, 0, 2, 0, 2, 4, 0, 10, 1, 2 }; using (var server = new MiniTestServer()) { server.RequestHandler = (request, clientIp) => { CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect"); Console.WriteLine("Server sending response"); return(new byte[] { request[0], request[1], 0, 0, 0, 6, 10, 16, 0, 2, 0, 2 }); }; server.Start(); using (var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger())) { await client.Connect(); Assert.IsTrue(client.IsConnected); var registers = new List <Register> { new Register { Address = 2, Value = 10 }, new Register { Address = 3, Value = 258 } }; var success = await client.WriteRegisters(10, registers); Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError); Assert.IsTrue(success); } } }
public async Task ClientReadDiscreteInputsTest() { // Function Code 0x02 var expectedRequest = new byte[] { 0, 0, 0, 6, 1, 2, 0, 12, 0, 2 }; var expectedResponse = new List <DiscreteInput> { new DiscreteInput { Address = 12, Value = true }, new DiscreteInput { Address = 13, Value = true } }; using (var server = new MiniTestServer()) { server.RequestHandler = (request, clientIp) => { CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect"); Console.WriteLine("Server sending response"); return(new byte[] { request[0], request[1], 0, 0, 0, 4, 1, 2, 1, 3 }); }; server.Start(); using (var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger())) { await client.Connect(); Assert.IsTrue(client.IsConnected); var inputs = await client.ReadDiscreteInputs(1, 12, 2); Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError); CollectionAssert.AreEqual(expectedResponse, inputs, "Response is incorrect"); } } }
private void ConnectToStation() { try { ModbusClient StationClient = new ModbusClient("192.168.1.3"); StationConnectStatic = true; while (true) { Thread.Sleep(1000); try { RWLock.AcquireWriterLock(2000); StationClient.ReadHoldRegister(1, 0, 20).CopyTo(StationDataBuffer, 0); } catch (SocketException) { sockethandler(this, new SocketDisconnectEvent() { status = "與試車站連線中斷", TextColor = "Red" }); StationClient.Disconnect(); break; } finally { if (RWLock.IsWriterLockHeld) { RWLock.ReleaseWriterLock(); } } } } catch (SocketException) { StationConnectStatic = false; } }
public void GetValues(ConnectionProperties connectionProperties) { modbusClient = connectionProperties.modbusClient; if (!modbusClient.Connected) { modbusClient.IPAddress = connectionProperties.ModbusTCPAddress; modbusClient.Port = connectionProperties.Port; modbusClient.Connect(); } foreach (FunctionProperties functionProperty in connectionProperties.FunctionPropertiesList) { switch (functionProperty.FunctionCode) { case FunctionCode.ReadCoils: functionProperty.values = modbusClient.ReadCoils(functionProperty.StartingAdress, functionProperty.Quantity); break; case FunctionCode.ReadDiscreteInputs: functionProperty.values = modbusClient.ReadDiscreteInputs(functionProperty.StartingAdress, functionProperty.Quantity); break; case FunctionCode.ReadHoldingRegisters: functionProperty.values = modbusClient.ReadHoldingRegisters(functionProperty.StartingAdress, functionProperty.Quantity); break; case FunctionCode.ReadInputRegisters: functionProperty.values = modbusClient.ReadInputRegisters(functionProperty.StartingAdress, functionProperty.Quantity); break; default: break; } } if (valuesChanged != null) { valuesChanged(this); } }
public async Task InitAsync(string host, int port, string deviceConnStr, DesiredPropertyUpdateCallback desiredPropertyUpdateCallback, string currentDeviceid = "modbusdevice") { modbusClient = new ModbusClient(host, port); deviceId = currentDeviceid; try { modbusClient.Init(); modbusClientAlive = true; } catch (Exception ex) { Console.WriteLine($"[EXCEPTION] Exception while instantiating Modbus client: {ex.Message}"); Environment.Exit(-1); } deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr); var twin = await deviceClient.GetTwinAsync(); if (twin.Properties.Desired["pollingInterval"] != PoolingInterval) { Console.WriteLine("[DEBUG] Setting new pollingInterval: " + $"{twin.Properties.Desired["pollingInterval"]} seconds"); try { PoolingInterval = twin.Properties.Desired["pollingInterval"]; } catch (Exception ex) { Console.WriteLine($"[EXCEPTION] Unable to set pollingInterval: {ex.Message}"); } } await deviceClient.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback, null); }
public override void Initialize() { base.Initialize(); try { _modbusClient = new ModbusClient(PortSetting.CommPort.ToString()); _modbusClient.Baudrate = (int)PortSetting.BaudRate; _modbusClient.StopBits = PortSetting.StopBits; _modbusClient.Parity = PortSetting.Parity; _modbusClient.ConnectionTimeout = (int)PortSetting.ReadWriteTimeOut; _modbusClient.Available((int)PortSetting.ReadWriteTimeOut); _modbusClient.Connect(); if (!_modbusClient.Connected) { throw new ForceSimulateException(string.Format("Port {0} is not opened", PortSetting.CommPort.ToString())); } CheckStatus(2000); U.RegisterOnChanged(() => IsMoveSFTY, IsMoveSFTY_OnChanged); Simulate = eSimulate.None; } catch (Exception ex) { _modbusClient.Disconnect(); //throw new ForceSimulateException(ex); U.LogAlarmPopup(ex, this.Nickname); this.Simulate = eSimulate.SimulateDontAsk; } _updateLoop = new BackgroundWorker(); _updateLoop.DoWork += new DoWorkEventHandler(UpdateLoop); }
private void Form1_Load(object sender, EventArgs e) { //Rotina para atualizar comboBox com as portas COMs: foreach (string comStr in SerialPort.GetPortNames()) { //Adiciona todas as COM diponíveis na lista comboBox1.Items.Add(comStr); comboBox2.Items.Add(comStr); } //Seleciona a primeira posição da lista if (comboBox1.Items.Count > 0) { comboBox1.SelectedIndex = 0; } if (comboBox2.Items.Count > 0) { comboBox2.SelectedIndex = 0; } //Inicia comunicação MODBUS try { modbusClient = new ModbusClient("COM5"); modbusClient.UnitIdentifier = 1; //slaveID = 1 (CLP ID) modbusClient.Baudrate = 57600; modbusClient.Parity = System.IO.Ports.Parity.None; modbusClient.StopBits = System.IO.Ports.StopBits.One; modbusClient.ConnectionTimeout = 1000; modbusClient.Connect(); } catch (Exception ex) { modbusClient = null; MessageBox.Show(ex.Message, "Falha na conexão Modbus com o CLP!"); } }
public void RefreshSimulator() { List <ScadaBreaker> breakers = new List <ScadaBreaker>(); using (var context = new ScadaDB.ScadaContext()) { breakers = context.Breakers.Where(x => !x.IsDeleted).ToList(); } ModbusClient modbusClient = new ModbusClient("127.0.0.1", 502); //Ip-Address and Port of Modbus-TCP-Server //modbusClient.UnitIdentifier = 1; Not necessary since default slaveID = 1; //modbusClient.Baudrate = 9600; // Not necessary since default baudrate = 9600 //modbusClient.Parity = System.IO.Ports.Parity.None; // modbusClient.StopBits = System.IO.Ports.StopBits.Two; //modbusClient.Port = 502; modbusClient.Connect(); foreach (var breaker in breakers) { modbusClient.WriteSingleCoil(breaker.SimulatorAddress, breaker.Value); } }
private async void getDeviceConnect() { string filePath; try { using (StreamReader sr = File.OpenText(GetPathJson.getPathConfig(@"\Configuration\Config.json"))) { var obj = sr.ReadToEnd(); SettingModel export = JsonConvert.DeserializeObject <SettingModel>(obj.ToString()); filePath = export.ExportFilePath.Substring(0, export.ExportFilePath.LastIndexOf("\\")) + "\\" + $"{ DateTime.Now.ToString("yyyyMMddHHmmss")}.csv"; } foreach (KeyValuePair <string, DeviceModel> deviceUnit in deviceDic) { mobus = new ModbusClient(deviceUnit.Value.IP, deviceUnit.Value.Port); try { await Task.Run(() => ThreadConnect(filePath, deviceUnit)); } catch (Exception ex) { } } WriteValueToFileCSV(filePath); } catch (Exception ex) { tmrScheduler.Stop(); MessageBox.Show("Chọn đường dẫn đến thư mục"); WindowState = FormWindowState.Normal; ShowInTaskbar = true; btnStop.PerformClick(); btnSetting.PerformClick(); } }
public async Task <bool> ConnectAsync() { _logger.LogInformation($"Connecting to inverter at {_address}:{_port}"); if (_modbusClient != null) { _logger.LogError($"Already connected"); throw new InvalidOperationException("Already connected"); } _modbusClient = new ModbusClient(_address, _port); _modbusClient.connectedChanged += ConnectionChanged; try { await _modbusClient.ConnectAsync(); return(true); } catch (Exception) { return(false); } }
public async Task ClientReconnectTest() { using (var server = new MiniTestServer()) { server.Start(); using (var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger())) { await client.Connect(); Assert.IsTrue(client.IsConnected); await server.Stop(); await client.ReadHoldingRegisters(0, 0, 1); await EnsureWait(); // time to set all information Assert.IsFalse(client.IsConnected); server.Start(); await client.ConnectingTask; Assert.IsTrue(client.IsConnected); } } }
private void button_conect_Click(object sender, EventArgs e) { if (status.Text == "offline") { try { int port = Convert.ToInt32(portbox.Text); modbusClient = new ModbusClient(ipbox.Text, port); //Ip-Address and Port of Modbus-TCP-Server modbusClient.Connect(); status.Text = "online"; status.ForeColor = Color.Green; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString() + "\n\nСтандартный адресс для подключения: 192.168.100.8\nСтандартный порт: 502"); } } else { MessageBox.Show("Подключение уже выполнено!"); } }
public ModbusClient MdbusRtu(String port, byte id = 1, int baudrate = 9600, String parity = "Even", String stopbits = "One") { ModbusClient modbusClient = new ModbusClient(port); modbusClient.UnitIdentifier = id; modbusClient.Baudrate = baudrate; switch (parity) { case "Even": modbusClient.Parity = System.IO.Ports.Parity.Even; break; case "Odd": modbusClient.Parity = System.IO.Ports.Parity.Odd; break; default: modbusClient.Parity = System.IO.Ports.Parity.Even; break; } switch (stopbits) { case "Two": modbusClient.StopBits = System.IO.Ports.StopBits.Two; break; case "OnePointFive": modbusClient.StopBits = System.IO.Ports.StopBits.OnePointFive; break; case "One": modbusClient.StopBits = System.IO.Ports.StopBits.One; break; default: modbusClient.StopBits = System.IO.Ports.StopBits.One; break; } try { modbusClient.Connect(); Console.WriteLine("Client conected"); Console.ReadKey(true); } catch (SystemException) { Console.WriteLine("Unable to conect to the client"); Console.ReadKey(true); } return(modbusClient); }