// Async method to send simulated telemetry private static async Task SendDeviceToCloudMessagesAsync() { // Initial telemetry values double minTemperature = 20; double minHumidity = 60; Random rand = new Random(); ContinueLoop = true; while (ContinueLoop) { double currentTemperature = minTemperature + rand.NextDouble() * 15; double currentHumidity = minHumidity + rand.NextDouble() * 20; var telemetryDataPoint = await Weather.GetWeatherObj(); //Create JSON message //var telemetryDataPoint = new //{ // temperature = currentTemperature, // humidity = currentHumidity //}; MessageString = JsonConvert.SerializeObject(telemetryDataPoint); Message = new Message(Encoding.ASCII.GetBytes(MessageString)); //Stuff: //var mess2 = Encoding.ASCII.GetBytes(MessageString); //var qwe = Message.GetBytes(); //string MessageString2= Encoding.UTF8.GetString(qwe, 0, qwe.Length); // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. Message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); Message.Properties.Add("temperatureAlert2", (currentTemperature > 40) ? "true" : "false"); AzIoTHubModules.SyntheticIoTMessage iotmessage = new AzIoTHubModules.SyntheticIoTMessage(Message); MessageString = iotmessage.Serialise(); System.Diagnostics.Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, MessageString); OnDeviceStatusUpdateD?.Invoke(string.Format("{0} > Sending message: {1}", DateTime.Now, MessageString)); // Send the telemetry message if (!IsDeviceStreaming) { await s_deviceClient.SendEventAsync(Message); await Task.Delay(Delay); } else { ContinueLoop = false; } Weather.GetNextCity(); } }
// Asynchronously create a PartitionReceiver for a partition and then start // reading any messages sent from the simulated client. private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct) { // Create the receiver using the default consumer group. // For the purposes of this sample, read only messages sent since // the time the receiver is created. Typically, you don't want to skip any messages. var eventHubReceiver = s_eventHubClient.CreateReceiver("$Default", partition, EventPosition.FromEnqueuedTime(DateTime.Now)); System.Diagnostics.Debug.WriteLine("Create receiver on partition: " + partition); while (true) { if (ct.IsCancellationRequested) { break; } System.Diagnostics.Debug.WriteLine("Listening for messages on: " + partition); // Check for EventData - this methods times out if there is nothing to retrieve. var events = await eventHubReceiver.ReceiveAsync(100); // If there is data in the batch, process it. if (events == null) { continue; } foreach (EventData eventData in events) { string data = Encoding.UTF8.GetString(eventData.Body.Array); System.Diagnostics.Debug.WriteLine("Message received on partition {0}:", partition); System.Diagnostics.Debug.WriteLine(" {0}:", data); System.Diagnostics.Debug.WriteLine("Application properties (set by device):"); foreach (var prop in eventData.Properties) { System.Diagnostics.Debug.WriteLine(" {0}: {1}", prop.Key, prop.Value); } System.Diagnostics.Debug.WriteLine("System properties (set by IoT Hub):"); foreach (var prop in eventData.SystemProperties) { System.Diagnostics.Debug.WriteLine(" {0}: {1}", prop.Key, prop.Value); } OnDeviceStatusUpdateD?.Invoke(AzIoTHubModules.SyntheticIoTMessage.EventData_ToString(eventData)); } } }
private static int s_telemetryInterval = 1; // Seconds // Handle the direct method call private static Task <MethodResponse> SetTelemetryInterval(MethodRequest methodRequest, object userContext) { System.Diagnostics.Debug.WriteLine("1"); System.Diagnostics.Debug.WriteLine(methodRequest.Name); var data = Encoding.UTF8.GetString(methodRequest.Data); System.Diagnostics.Debug.WriteLine(data); if (methodRequest.Name == "SetTelemetryInterval") { System.Diagnostics.Debug.WriteLine("Interval"); // Check the payload is a single integer value if (Int32.TryParse(data, out s_telemetryInterval)) { Azure_IoTHub_Connections.MyConnections.TelemetryDelayBtwReadings = s_telemetryInterval; System.Diagnostics.Debug.WriteLine("Telemetry interval set to {0} seconds", data); OnDeviceStatusUpdateD?.Invoke(string.Format("Telemetry interval set to {0} seconds", data)); // Acknowlege the direct method call with a 200 success message string result = "{\"result\":\"Executed direct method: " + methodRequest.Name + "\"}"; return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200))); } else { // Acknowlege the direct method call with a 400 error message string result = "{\"result\":\"Invalid parameter\"}"; return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 400))); } } else if (methodRequest.Name == "SetTelemetryInterval2") { OnDeviceStatusUpdateD?.Invoke(string.Format("LED Toggle {0} seconds", data)); // Acknowlege the direct method call with a 200 success message string result = "{\"result\":\"Executed direct method: " + methodRequest.Name + "\"}"; return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200))); } else { System.Diagnostics.Debug.WriteLine("Other"); // Acknowlege the direct method call with a 400 error message string result = "{\"result\":\"Invalid method request\"}"; return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 400))); } }
// Async method to send simulated telemetry private static async Task SendDeviceToCloudMessagesAsync() { // Initial telemetry values //double minTemperature = 20; //double minHumidity = 60; //Random rand = new Random(); OnDeviceStatusUpdateD?.Invoke("IoT Hub Telemetry #2- Device sending messages."); ContinueLoop = true; while (ContinueLoop) { //double currentTemperature = minTemperature + rand.NextDouble() * 15; //double currentHumidity = minHumidity + rand.NextDouble() * 20; //// Create JSON message //var telemetryDataPoint = new //{ // temperature = currentTemperature, // humidity = currentHumidity //}; //var messageString = JsonConvert.SerializeObject(telemetryDataPoint); //var message = new Message(Encoding.ASCII.GetBytes(messageString)); //// Add a custom application property to the message. //// An IoT hub can filter on these properties without access to the message body. //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); //await s_deviceClient.SendEventAsync(message); Azure_IoTHub_Sensors.TelemetryDataPoint telemetryDataPoint; if (Azure_IoTHub_Sensors.Weather.CurrentWeather.DoAsync) { telemetryDataPoint = await Azure_IoTHub_Sensors.Weather.CurrentWeather.GetWeatherAsync(); } else { telemetryDataPoint = Azure_IoTHub_Sensors.Weather.CurrentWeather.GetWeather(); } MessageString = JsonConvert.SerializeObject(telemetryDataPoint); Message = new Message(Encoding.ASCII.GetBytes(MessageString)); //Message.UserId = Azure_IoTHub_Connections.MyConnections.IoTHubName; Message.Properties.Add("temperatureAlert", (telemetryDataPoint.temperature > 30) ? "true" : "false"); Message.Properties.Add("humidityAlert", (telemetryDataPoint.humidity > 80) ? "true" : "false"); Message.Properties.Add("pressureAlert", (telemetryDataPoint.pressure > 1010) ? "true" : "false"); Azure_IoTHub_Telemetry.SyntheticIoTMessage iotmessage = new Azure_IoTHub_Telemetry.SyntheticIoTMessage(Message); MessageString = iotmessage.Serialise(); SetDeviceSentMsg?.Invoke(string.Format("{0} > Sending message: {1}", DateTime.Now, MessageString)); // Send the tlemetry message await s_deviceClient.SendEventAsync(Message); SetDeviceSentMsg?.Invoke(string.Format("{0} > Sending message: {1}", DateTime.Now, MessageString)); s_telemetryInterval = Azure_IoTHub_Connections.MyConnections.TelemetryDelayBtwReadings; await Task.Delay(s_telemetryInterval * 1000); if (!ContinueLoop) { OnDeviceStatusUpdateD?.Invoke("Cancelled Telemetry - Device end"); } } }