static void Main(string[] args) { // The Edge runtime gives us the connection string we need -- it is injected as an environment variable string connectionString = Environment.GetEnvironmentVariable("EdgeHubConnectionString"); // Cert verification is not yet fully functional when using Windows OS for the container bool bypassCertVerification = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (!bypassCertVerification) { InstallCert(); } IoTEdgeModuleState state = null; try { state = Init(connectionString, bypassCertVerification).GetAwaiter().GetResult(); } catch (Exception ex) { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] Error in the initialization\n{ex.ToString()}"); Environment.ExitCode = 1; return; } var outputName = Environment.GetEnvironmentVariable("OutputName"); if (string.IsNullOrEmpty(outputName)) { outputName = "sensor"; } ; using (sensorReader = new SensorReader(state, outputName)) { sensorReader.StartReading(); // Wait until the app unloads or is cancelled var cts = new CancellationTokenSource(); AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel(); Console.CancelKeyPress += (sender, cpe) => cts.Cancel(); WhenCancelled(cts.Token).Wait(); } }
/// <summary> /// Initializes the DeviceClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task <IoTEdgeModuleState> Init(string connectionString, bool bypassCertVerification = false) { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] Connection String {connectionString}"); var state = new IoTEdgeModuleState() { ConnectionString = connectionString, BypassCertVerification = bypassCertVerification, }; // open connection to edge var ioTHubModuleClient = await state.CreateAndOpenClient(); if (ioTHubModuleClient == null) { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] Could not connect to {state.ConnectionString}. Aborting"); } Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] IoT Hub module client initialized."); await ioTHubModuleClient.SetMethodHandlerAsync("bme280status", HandleStatusMethod, null); return(state); }
public SensorReader(IoTEdgeModuleState state, string outputName) { this.state = state; this.outputName = outputName; }