public async Task <string> GetDeviceTwinAsync() { _logging.LogMessage("Getting device twin", LoggingLevel.Verbose); try { if (_deviceClient != null) { Twin twin = await _deviceClient.GetTwinAsync(); _logging.LogMessage(twin.ToJson(), LoggingLevel.Verbose); return(twin.Properties.Desired.ToJson()); } else { _logging.LogMessage($"GetDeviceTwinAsync: DeviceClient was empty.", LoggingLevel.Error); return(null); } } catch (Exception he) when( he is IotHubCommunicationException || he is UnauthorizedException || he is TimeoutException) { _logging.LogMessage($"GetDeviceTwinAsync Handled Exception: {he.Message}", LoggingLevel.Error); Connected = false; return(null); } catch (Exception e) { _logging.LogMessage($"GetDeviceTwinAsync: {e.Message}", LoggingLevel.Critical); Connected = false; throw e; } }
static async Task UpdateDesiredProperty() { Twin x = new Twin(DEVICE_ID); x.Properties.Desired["Config"] = new { TemperatureMeanValue = 100.5, TelemetryInterval = 50 }; try { x = await registryManager.UpdateTwinAsync(DEVICE_ID, x, E_TAG); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Desired Property successfully updated to {x.ToJson()}..."); Console.ResetColor(); } catch (Exception ex) { Console.WriteLine($"An error occurred while updating desired properties of the twin..."); Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException.Message); } }
public async Task RunSampleAsync() { await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null); Console.WriteLine("Retrieving twin..."); Twin twin = await _deviceClient.GetTwinAsync(); Console.WriteLine("\tInitial twin value received:"); Console.WriteLine($"\t{twin.ToJson()}"); Console.WriteLine("Sending sample start time as reported property"); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["DateTimeLastAppLaunch"] = DateTime.UtcNow; await _deviceClient.UpdateReportedPropertiesAsync(reportedProperties); Console.WriteLine("Press Control+C to quit the sample."); using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cts.Cancel(); Console.WriteLine("Sample execution cancellation requested; will exit."); }; Console.WriteLine($"Use the IoT Hub Azure Portal or IoT Explorer utility to change the twin desired properties."); while (!cts.IsCancellationRequested) { await Task.Delay(1000); } }
private async Task GetTwinAndDetectChangesAsync(CancellationToken cancellationToken) { Twin twin = null; // Allow a single thread to call GetTwin here await _initSemaphore.WaitAsync(cancellationToken); await RetryOperationHelper.RetryTransientExceptionsAsync( operationName : "GetTwin", asyncOperation : async() => { twin = await s_deviceClient.GetTwinAsync(); _logger.LogInformation($"Device retrieving twin values: {twin.ToJson()}"); TwinCollection twinCollection = twin.Properties.Desired; long serverDesiredPropertyVersion = twinCollection.Version; // Check if the desired property version is outdated on the local side. if (serverDesiredPropertyVersion > s_localDesiredPropertyVersion) { _logger.LogDebug($"The desired property version cached on local is changing from {s_localDesiredPropertyVersion} to {serverDesiredPropertyVersion}."); await HandleTwinUpdateNotificationsAsync(twinCollection, cancellationToken); } }, shouldExecuteOperation : () => IsDeviceConnected, logger : _logger, exceptionsToBeIgnored : _exceptionsToBeIgnored, cancellationToken : cancellationToken); _initSemaphore.Release(); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // Register twin update notifications await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false); // Get current Twin properties Twin twin = await ioTHubModuleClient.GetTwinAsync().ConfigureAwait(false); Console.WriteLine("Initial twin value received:"); Console.WriteLine($"{twin.ToJson()}"); }
private async Task GetWritablePropertiesAndHandleChangesAsync() { Twin twin = await _deviceClient.GetTwinAsync(); _logger.LogInformation($"Device retrieving twin values on CONNECT: {twin.ToJson()}"); TwinCollection twinCollection = twin.Properties.Desired; long serverWritablePropertiesVersion = twinCollection.Version; // Check if the writable property version is outdated on the local side. // For the purpose of this sample, we'll only check the writable property versions between local and server // side without comparing the property values. if (serverWritablePropertiesVersion > s_localWritablePropertiesVersion) { _logger.LogInformation($"The writable property version cached on local is changing " + $"from {s_localWritablePropertiesVersion} to {serverWritablePropertiesVersion}."); foreach (KeyValuePair <string, object> propertyUpdate in twinCollection) { string propertyName = propertyUpdate.Key; if (propertyName == TargetTemperatureProperty) { await TargetTemperatureUpdateCallbackAsync(twinCollection, propertyName); } else { _logger.LogWarning($"Property: Received an unrecognized property update from service:" + $"\n[ {propertyUpdate.Key}: {propertyUpdate.Value} ]."); } } _logger.LogInformation($"The writable property version on local is currently {s_localWritablePropertiesVersion}."); } }
private async void btnUpdate_Click(object sender, RoutedEventArgs e) { if (registryManager != null) { Device device = (cbDevices.SelectedItem as ComboBoxItem).Tag as Device; if (device != null) { Twin twin = await registryManager.GetTwinAsync(device.Id); try { await registryManager.UpdateTwinAsync(device.Id, tbNew.Text, twin.ETag); twin = await registryManager.GetTwinAsync(device.Id); tbTwin.Text = FormatJson(twin.ToJson()); } catch (Exception exc) { MessageDialog dlg = new MessageDialog(exc.ToString(), "ERROR"); await dlg.ShowAsync(); } } } }
public async Task <ActionResult> GetTwin(string deviceId) { Twin twin = await _helper.GetTwin(deviceId); JObject twinJson = (JObject)JsonConvert.DeserializeObject(twin.ToJson()); return(Json(twinJson.ToString())); }
static void PrintTwin(Twin twin) { twin.Properties.Desired = null; // for compact view as we only update tags Console.WriteLine(); Console.WriteLine("============= Updated twin: =================="); Console.WriteLine(twin.ToJson(Newtonsoft.Json.Formatting.Indented)); Console.WriteLine("=============================================="); }
public static async Task GetDeviceTwinAsync() { CreateClient(); Console.WriteLine("Getting device twin"); Twin twin = await deviceClient.GetTwinAsync(); Console.WriteLine(twin.ToJson()); }
private async void cbDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (registryManager != null) { Device device = (cbDevices.SelectedItem as ComboBoxItem).Tag as Device; if (device != null) { Twin twin = await registryManager.GetTwinAsync(device.Id); tbTwin.Text = FormatJson(twin.ToJson()); } } }
static void InfiniteLoop(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Twin twin = ioTHubModuleClient.GetTwinAsync().Result; string jsonString = twin.ToJson(); Console.WriteLine("---- Twin Loop ---"); Console.WriteLine(jsonString); Console.WriteLine("--------------------"); Task.Delay(15000).Wait(); } }
public async Task <ActionResult> GetDevice(string deviceId) { Device device = null; Twin twin = null; DEVICE_DATA deviceData = new DEVICE_DATA(); try { device = await _helper.GetDevice(deviceId).ConfigureAwait(false); twin = await _helper.GetTwin(deviceId).ConfigureAwait(false); if (device == null) { return(BadRequest()); } var jsonData = JsonConvert.SerializeObject(device); deviceData.deviceId = device.Id; deviceData.connectionState = device.ConnectionState.ToString(); deviceData.status = device.Status.ToString(); deviceData.authenticationType = device.Authentication.Type.ToString(); if (device.Authentication.Type == AuthenticationType.Sas) { deviceData.primaryKey = device.Authentication.SymmetricKey.PrimaryKey; deviceData.secondaryKey = device.Authentication.SymmetricKey.SecondaryKey; } if (twin != null) { JObject twinJson = (JObject)JsonConvert.DeserializeObject(twin.ToJson()); if (twinJson.ContainsKey("modelId")) { deviceData.modelId = twin.ModelId; } } } catch (Exception ex) { _logger.LogError($"Error {ex}"); } return(Json(deviceData)); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); tbNew.Text = @"{"; tbNew.Text += "\r\n 'properties': {"; tbNew.Text += "\r\n 'desired': { }"; tbNew.Text += "\r\n }"; tbNew.Text += "\r\n}"; if (App.IoTHubClient != null) { Twin twin = await App.IoTHubClient.GetTwinAsync(); tbTwin.Text = FormatJson(twin.ToJson()); } }
static async Task RetreiveDeviceTwinAsync() { try { deviceTwin = await deviceClient.GetTwinAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"device twin: {deviceTwin.ToJson(Formatting.Indented)}"); Console.ResetColor(); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"An error occurred while retreiving device twin from Azure IoT Hub..."); Debug.WriteLine($"error: {ex.Message}"); } }
public async Task <string> GetDeviceTwinBySharedAccess(string deviceId) { var deviceClient = await ResolveDeviceClient(deviceId); try { Twin twin = await deviceClient.GetTwinAsync().ConfigureAwait(false); this.logger.LogInformation($"Device twin retrieved for device{deviceId} using shared access."); return(twin.ToJson()); } catch (Exception ex) { this.logger.LogError(ex, $"Could not retrieve device twin (device: {deviceId})"); throw; } }
private async Task GetWritablePropertiesAndHandleChangesAsync() { Twin twin = await _deviceClient.GetTwinAsync(); _logger.LogInformation($"Device retrieving twin values on CONNECT: {twin.ToJson()}"); TwinCollection twinCollection = twin.Properties.Desired; long serverWritablePropertiesVersion = twinCollection.Version; // Check if the writable property version is outdated on the local side. // For the purpose of this sample, we'll only check the writable property versions between local and server // side without comparing the property values. if (serverWritablePropertiesVersion > s_localWritablePropertiesVersion) { _logger.LogInformation($"The writable property version cached on local is changing " + $"from {s_localWritablePropertiesVersion} to {serverWritablePropertiesVersion}."); foreach (KeyValuePair <string, object> propertyUpdate in twinCollection) { string componentName = propertyUpdate.Key; switch (componentName) { case Thermostat1: case Thermostat2: // This will be called when a device client gets initialized and the _temperature dictionary is still empty. if (!_temperature.TryGetValue(componentName, out double value)) { _temperature[componentName] = 21d; // The default temperature value is 21°C. } await TargetTemperatureUpdateCallbackAsync(twinCollection, componentName); break; default: _logger.LogWarning($"Property: Received an unrecognized property update from service:" + $"\n[ {propertyUpdate.Key}: {propertyUpdate.Value} ]."); break; } } _logger.LogInformation($"The writable property version on local is currently {s_localWritablePropertiesVersion}."); } }
public async Task <bool> CreateIoTEdgeDeviceAsync(string deviceId, string os) { // create new device Device newDevice = await registryManager.AddDeviceAsync(new Device(deviceId)); if (newDevice != null) { // make it an IoT Edge device newDevice.Capabilities.IotEdge = true; newDevice = await registryManager.UpdateDeviceAsync(newDevice, true); if (newDevice == null) { // update failed return(false); } // enable layered deployment for Industrial IoT Edge devices Twin twin = await registryManager.GetTwinAsync(deviceId); if (twin != null) { string patch = string.Empty; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { patch = "\"tags\": { \"__type__\": \"iiotedge\", \"os\": \"" + os + "\" },"; } if (Environment.OSVersion.Platform == PlatformID.Unix) { patch = "\"tags\": { \"__type__\": \"iiotedge\", \"os\": \"Linux\" },"; } string twinJSON = twin.ToJson(); twinJSON = twinJSON.Insert(twinJSON.IndexOf("\"version\""), patch); return(await registryManager.UpdateTwinAsync(twin.DeviceId, twinJSON, twin.ETag) != null); } return(twin != null); } return(newDevice != null); }
static async Task UpdateReportedProperties(TwinCollection reportedConfig) { try { await deviceClient.UpdateReportedPropertiesAsync(reportedConfig); Twin updatedtwin = await deviceClient.GetTwinAsync(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Updated Twin: {updatedtwin.ToJson(Formatting.Indented)}"); Console.ResetColor(); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Debug.WriteLine($"An error occurred while updateing reported configuration from the twin: {ex.Message}"); Debug.WriteLine($"{ex.InnerException}"); Console.ResetColor(); } }
public static async Task twinSample() { await deviceClient.SetDesiredPropertyUpdateCallbackAsync(onPropertyChange, null).ConfigureAwait(false); Twin twin = await deviceClient.GetTwinAsync(); JObject jsonTwin = (JObject)JsonConvert.DeserializeObject(twin.ToJson()); JObject twinProperties = (JObject)jsonTwin["properties"]; //returns another jobject // Console.WriteLine((string)twinProperties["desired"]["cat"]); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["non-cat"] = "not best friend"; await deviceClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false); await Task.Delay(30 * 1000); }
private async void btnUpdate_Click(object sender, RoutedEventArgs e) { if (App.IoTHubClient != null) { try { TwinCollection reportedProperties = new TwinCollection(tbNew.Text); await App.IoTHubClient.UpdateReportedPropertiesAsync(reportedProperties); Twin twin = await App.IoTHubClient.GetTwinAsync(); tbTwin.Text = FormatJson(twin.ToJson()); } catch (Exception exc) { MessageDialog dlg = new MessageDialog(exc.ToString(), "ERROR"); await dlg.ShowAsync(); } } }
public async Task RunSampleAsync() { await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null); Console.WriteLine("Retrieving twin..."); Twin twin = await _deviceClient.GetTwinAsync(); Console.WriteLine("\tInitial twin value received:"); Console.WriteLine($"\t{twin.ToJson()}"); Console.WriteLine("Sending sample start time as reported property"); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["DateTimeLastAppLaunch"] = DateTime.UtcNow; await _deviceClient.UpdateReportedPropertiesAsync(reportedProperties); Console.WriteLine("Press Control+C to quit the sample."); using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cts.Cancel(); Console.WriteLine("Cancellation requested; will exit."); }; var waitTime = TimeSpan.FromMinutes(1); var timer = Stopwatch.StartNew(); Console.WriteLine($"Use the IoT Hub Azure Portal or IoT Explorer utility to change the twin desired properties."); Console.WriteLine($"Waiting up to {waitTime} for receiving twin desired property updates ..."); while (!cts.IsCancellationRequested && timer.Elapsed < waitTime) { await Task.Delay(1000); } // This is how one can unsubscribe a callback for properties using a null callback handler. await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(null, null); }
private Twin BuildRetrievedTwin() { var twin = new Twin(); twin.Tags["Location"] = new { Country = "China", City = "Beijing", Zip = 100080 }; twin.Tags["LastTelemetry"] = new { Compress = false, Timestamp = new DateTime(2016, 1, 1), Telemetry = new { Temperature = 30.5, Humidity = 20 } }; twin.Tags["DisplayName"] = "Device001"; twin.Tags["DeletedName"] = null; var build = new TwinCollection(); build["Year"] = 2016; build["Month"] = 11; var version = new TwinCollection(); version["Major"] = 3; version["Minor"] = 0; version["Build"] = build; twin.Properties.Desired["FirmwareVersion"] = version; twin.Properties.Desired["DeletedName"] = null; return(JsonConvert.DeserializeObject <Twin>(twin.ToJson())); }
public async Task RunSampleAsync() { await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null).ConfigureAwait(false); Console.WriteLine("Retrieving twin..."); Twin twin = await _deviceClient.GetTwinAsync().ConfigureAwait(false); Console.WriteLine("\tInitial twin value received:"); Console.WriteLine($"\t{twin.ToJson()}"); Console.WriteLine("Sending sample reported property"); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["RoadGoesOnForever"] = true; await _deviceClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false); Console.WriteLine("Waiting 90 seconds for IoT Hub Twin updates..."); Console.WriteLine($"Use the IoT Hub Azure Portal to change the Twin desired properties within this time."); await Task.Delay(90 * 1000); }
public async Task RunSampleAsync() { await _moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false); Console.WriteLine("Retrieving twin..."); Twin twin = await _moduleClient.GetTwinAsync().ConfigureAwait(false); Console.WriteLine("\tInitial twin value received:"); Console.WriteLine($"\t{twin.ToJson()}"); Console.WriteLine("Sending sample start time as reported property"); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["DateTimeLastAppLaunch"] = DateTime.Now; await _moduleClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false); Console.WriteLine("Waiting 30 seconds for IoT Hub Twin updates..."); Console.WriteLine($"Use the IoT Hub Azure Portal to change the Twin desired properties within this time."); await Task.Delay(30 * 1000); }
// Functions that handling DeviceTwin public void DeviceTwinHandler() { //await s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false) .GetAwaiter().GetResult(); Console.WriteLine("Retrieving twin..."); Twin twin = s_deviceClient.GetTwinAsync().ConfigureAwait(false) .GetAwaiter().GetResult(); Console.WriteLine("\tInitial twin value received:"); Console.WriteLine($"\t{twin.ToJson()}"); Console.WriteLine("Desired Properties {0}", twin.Properties.Desired.ToString()); Console.WriteLine("Sending sample start time as reported property"); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["MyReportedProperty"] = DateTime.Now; s_deviceClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false) .GetAwaiter().GetResult(); }
public async Task <string> GetDeviceTwinByToken(string deviceId, string sasToken, DateTime tokenExpiration) { var deviceClient = await ResolveDeviceClient(deviceId, sasToken, tokenExpiration); if (deviceClient == null) { throw new DeviceConnectionException($"Failed to connect to device {deviceId}"); } try { Twin twin = await deviceClient.GetTwinAsync().ConfigureAwait(false); this.logger.LogInformation($"Device twin retrieved for device {deviceId} using device token."); return(twin.ToJson()); } catch (Exception ex) { this.logger.LogError(ex, $"Could not retrieve device twin (device: {deviceId})"); throw; } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Twin twin = ioTHubModuleClient.GetTwinAsync().Result; string jsonString = twin.ToJson(); Console.WriteLine("---- Initial Twin ---"); Console.WriteLine(jsonString); Console.WriteLine("---------------------"); //Just register for handling the desired property update await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallBackMethod, ioTHubModuleClient); Console.WriteLine("IoT Hub module client initialized."); }
internal async Task <string> GetDeviceTwinAsync() { _logging.LogMessage("Getting device twin", LoggingLevel.Verbose); try { Twin twin = await _deviceClient.GetTwinAsync(); _logging.LogMessage(twin.ToJson(), LoggingLevel.Verbose); return(twin.Properties.Desired.ToJson()); } catch (UnauthorizedException eu) { _logging.LogMessage($"GetDeviceTwinAsync: Unauthorized access. It can happen if the connection was lost.", LoggingLevel.Error); Connected = false; return(null); } catch (Exception e) { _logging.LogMessage($"GetDeviceTwinAsync: {e.Message}", LoggingLevel.Critical); Connected = false; return(null); } }
public async Task Run() { // runs loop to send telemetry // set up a callback for connection status change _client.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler); // set up callback for Desired Property update (Settings/Properties in IoT Central) await _client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null).ConfigureAwait(false); // set up callback for Methond (Command in IoT Central) await _client.SetMethodHandlerAsync("displayMessage", DisplayMessage, null).ConfigureAwait(false); Twin twin = await _client.GetTwinAsync().ConfigureAwait(false); Console.WriteLine("\r\nDevice Twin received:"); Console.WriteLine($"{twin.ToJson(Newtonsoft.Json.Formatting.Indented)}"); // Properties in IoT Central looks like this // "properties": { // "desired": { // "isCelsius": { // "value": true // }, // "$version": 2 // }, if (twin.Properties.Desired.Contains("isCelsius") && twin.Properties.Desired["isCelsius"]["value"] != null) { _bCelsius = twin.Properties.Desired["isCelsius"]["value"]; // update reported properties to keep UI and device state in synch TwinCollection twinValue = new TwinCollection(); twinValue["desiredVersion"] = twin.Properties.Desired["$version"]; twinValue["statusCode"] = 200; twinValue["value"] = _bCelsius; TwinCollection reportedProperties = new TwinCollection(); reportedProperties["isCelsius"] = twinValue; await _client.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false); } if (_hasSenseHat) { // read sensor data from SenseHat using (var settings = RTIMUSettings.CreateDefault()) using (var imu = settings.CreateIMU()) using (var humidity = settings.CreateHumidity()) using (var pressure = settings.CreatePressure()) { while (true) { var imuData = imu.GetData(); var humidityReadResult = humidity.Read(); if (humidityReadResult.HumidityValid && humidityReadResult.TemperatureValid) { string buffer; // format telemetry based on settings from Cloud if (_bCelsius) { buffer = $"{{\"humidity\":{humidityReadResult.Humidity:F2},\"tempC\":{humidityReadResult.Temperatur:F2}}}"; } else { double fahrenheit = (humidityReadResult.Temperatur * 9 / 5) + 32; buffer = $"{{\"humidity\":{humidityReadResult.Humidity:F2},\"tempF\":{fahrenheit:F2}}}"; } using (var telemetryMessage = new Message(Encoding.UTF8.GetBytes(buffer))) { Console.WriteLine($"Message Out : {buffer}"); await _client.SendEventAsync(telemetryMessage).ConfigureAwait(false); } } else { Console.WriteLine("Err : Sensor data not valid"); } await Task.Delay(3 * 1000); } } } else { // simulate sensor date string buffer; var simulatorData = new SimulatorData { TempCMax = 36, HumidityMax = 100, TempC = 30, Humidity = 40, }; while (true) { if (simulatorData.TempC > simulatorData.TempCMax) { simulatorData.TempC += Rnd.NextDouble() - 0.5; // add value between [-0.5..0.5] } else { simulatorData.TempC += -0.25 + (Rnd.NextDouble() * 1.5); // add value between [-0.25..1.25] - average +0.5 } if (simulatorData.Humidity > simulatorData.HumidityMax) { simulatorData.Humidity += Rnd.NextDouble() - 0.5; // add value between [-0.5..0.5] } else { simulatorData.Humidity += -0.25 + (Rnd.NextDouble() * 1.5); // add value between [-0.25..1.25] - average +0.5 } // format telemetry based on settings from Cloud if (_bCelsius) { buffer = $"{{\"humidity\":{simulatorData.Humidity:F2},\"tempC\":{simulatorData.TempC:F2}}}"; } else { double fahrenheit = (simulatorData.TempC * 9 / 5) + 32; buffer = $"{{\"humidity\":{simulatorData.Humidity:F2},\"tempF\":{fahrenheit:F2}}}"; } using (var telemetryMessage = new Message(Encoding.UTF8.GetBytes(buffer))) { Console.WriteLine($"Message Out : {buffer}"); await _client.SendEventAsync(telemetryMessage).ConfigureAwait(false); } await Task.Delay(3 * 1000); } } }