public Task <object> GetDataAsync() { while (!modbusClientAlive) { try { modbusClient.Init(); modbusClientAlive = true; } catch (Exception ex) { Console.WriteLine($"[EXCEPTION] Exception while instantiating Modbus client: {ex.Message}"); Console.WriteLine("\nSleeping for 15 seconds before retrying to talk to Modbus host...\n"); Task.Delay(TimeSpan.FromSeconds(15)).Wait(); } } var ct = new CancellationToken(); Task <object> t = Task.Run <object>(async() => { var voltage = Array.Empty <short>(); var current = Array.Empty <short>(); var hardwareId = String.Empty; try { voltage = await modbusClient.ReadRegistersAsync(40001, 3); current = await modbusClient.ReadRegistersAsync(41001, 3); hardwareId = "Function Code 0x2b (43)"; } catch (Exception ex) { Console.WriteLine( $"[EXCEPTION] Exception while calling ReadRegistersAsync(): {ex.Message}"); Console.WriteLine( "\nSleeping for 5 seconds before retrying...\n"); Task.Delay(TimeSpan.FromSeconds(5), ct).Wait(ct); } return(new { deviceId, voltage, current, hardwareId }); }, ct); if (t.Wait(9000, ct)) { return(t); } Console.WriteLine("Aborting modbus Task, took too long to return."); //Console.WriteLine("Restarting collector...\n"); //Assembly a = Assembly.GetExecutingAssembly(); //System.Diagnostics.Process.Start("dotnet.exe", a.Location); //Environment.Exit(-2); return(null); }
public void SocketTimeoutTest() { Console.WriteLine("Running SocketTimeoutTest..."); int TEST_TIMEOUT = 6000; int MODBUS_CALL_TIMEOUT = 3000; Int32 port = 50222; string v4Loopback = ("127.0.0.1"); TcpListener server = new TcpListener(IPAddress.Parse(v4Loopback), port); server.Start(); CancellationTokenSource cts = new CancellationTokenSource(TEST_TIMEOUT); CancellationToken ct = cts.Token; var t = Task.Run(() => { server.AcceptTcpClientAsync(); ModbusClient mc = new ModbusClient(v4Loopback, port, MODBUS_CALL_TIMEOUT); mc.Init(); short[] r = mc.ReadRegistersAsync(4304, 2, 1).Result; }, ct); try { t.Wait(ct); } catch (OperationCanceledException) { Assert.True(false, "The call to ReadRegistersAsync() did not return " + $"within expected time window of {MODBUS_CALL_TIMEOUT / 1000} seconds."); } catch (Exception ex) { if (ex.InnerException.InnerException is TimeoutException || ex.InnerException.InnerException is IOException) { // We expect a TimeoutException or IOException if ReadRegistersAsync() adheres to our timeout Assert.True(true); } else { throw; } } finally { server.Server.Close(); server.Server.Dispose(); } }
public async Task <TelemetryPoint> GetDataAsync() { string iotHubDeviceId = AppSettings.iotHubDeviceId; decimal temperature; float[] analogInput; bool[] digitalInput; try { if (!modbusClientAlive) { modbusClient = new ModbusClient( AppSettings.modbusHost, AppSettings.modbusPort); modbusClient.Init(); modbusClientAlive = true; } analogInput = await modbusClient.ReadRegistersFloatsAsync( AppSettings.temperatureInputOffset, AppSettings.temperatureInputCount, AppSettings.unitIdentifier); temperature = decimal.Round( (decimal)analogInput[0], 3); // 3 decimals digitalInput = await modbusClient.ReadInputStatusAsync( AppSettings.digitalInputOffset, // 10001 + offset AppSettings.digitalInputCount, AppSettings.unitIdentifier); } catch (Exception ex) { Misc.LogException($"Exception while calling ReadRegistersAsync(): {ex.Message}\n" + $"Stack Trace --\n{ex.StackTrace}"); modbusClientAlive = false; return(null); } TelemetryPoint sensorData = new TelemetryPoint() { iotHubDeviceId = iotHubDeviceId, temperature = temperature, digitalInput = digitalInput }; return(sensorData); }
public async Task InitAsync( string host, int port, string iotHubDeviceConnStr, DesiredPropertyUpdateCallback desiredPropertyUpdateCallback) { modbusClient = new ModbusClient(host, port); try { modbusClient.Init(); modbusClientAlive = true; } catch (Exception ex) { Misc.LogException($"Exception while instantiating Modbus client: {ex.Message}"); } deviceClient = DeviceClient.CreateFromConnectionString(iotHubDeviceConnStr); Twin twin = new Twin(); try { twin = await deviceClient.GetTwinAsync(); if (twin.Properties.Desired["pollingInterval"] != PollingInterval) { Misc.LogDebug("Setting new pollingInterval: " + $"{twin.Properties.Desired["pollingInterval"]} seconds"); try { PollingInterval = twin.Properties.Desired["pollingInterval"]; } catch (Exception ex) { Misc.LogException($"Unable to set pollingInterval: {ex.Message}"); } } await deviceClient.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback, null); } catch (Exception ex) { Misc.LogException(ex.Message); } }
public async Task ReadRtTagAsync() { try { if (!modbusClient.Connected) { modbusClient.Init(); } foreach (var block in settings.ReadBlocks) { var data = await ReadBlockAsync(block); ParseBlock(block, data); } prevException = null; processInfo.ScanDateTime = DateTime.Now; processInfo.ScanCounter += 1; processInfo.ScanRetry = 0; processInfo.ScanLastErrror = ""; await processInfo.SetValuesFromPropertiesAsync(new[] { nameof(processInfo.ScanCounter) }); } catch (Exception e) { if (e.Message != prevException?.Message) { logger.LogError(e, "Scan Fail!"); prevException = e; processInfo.ScanLastErrror = e.Message; } processInfo.ScanRetry += 1; processInfo.ScanCounter = 0; modbusClient.Terminate(); } }
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); }