public static async Task PublishMQTTMessageAsync(DeviceConfig deviceConfig, string payload, string alerter) { var topic = deviceConfig.FeedbackTopic + "/" + alerter; var message = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload) .WithExactlyOnceQoS() .WithRetainFlag() .Build(); if (MqttClient == null | !MqttClient.IsConnected) { MqttClient = await ConnectAsync("IoTEdgeModule"); } await MqttClient.PublishAsync(message); Console.WriteLine($"Message '{payload}' sent to {topic}"); }
private static async Task MessageReceivedAsync(object sender, MqttApplicationMessageReceivedEventArgs eventArgs) { var info = $"Timestamp: {DateTime.Now:O} | Topic: {eventArgs.ApplicationMessage.Topic} | Payload: {Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)} | QoS: {eventArgs.ApplicationMessage.QualityOfServiceLevel}"; Console.WriteLine($"Message: {info}"); var payload = Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload); try { string topic = eventArgs.ApplicationMessage.Topic; DeviceConfig deviceConfig = Devices.Find(d => d.DataTopic.Equals(topic)); string dataBuffer = "Unkown format"; if (deviceConfig.Schema.Equals("DefaultEngine")) { var messageBody = JsonConvert.DeserializeObject <MessageBody>(payload); if (messageBody.Machine.Temperature >= Temp_Threshold) { Console.WriteLine("Alert: over Temp_Threshold"); await PublishMQTTMessageAsync(deviceConfig, messageBody.TimeCreated.ToLongTimeString(), "MQTTClient"); } dataBuffer = JsonConvert.SerializeObject(messageBody); } var message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(dataBuffer)); //TODO: package sous forme de propriété // MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); // ITransportSettings[] settings = { mqttSetting }; // ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); // await ioTHubModuleClient.OpenAsync(); await ioTHubModuleClient.SendEventAsync("output1", message); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static async Task <MethodResponse> AlertAsync(MethodRequest methodRequest, object moduleClient) { try { Console.WriteLine("In AlertAsync"); var data = Encoding.UTF8.GetString(methodRequest.Data); Console.WriteLine("Received data: " + data.ToString()); var messageBody = new MessageBody(); DeviceConfig deviceConfig = Devices.Find(d => d.ID.Equals("Dev367")); await PublishMQTTMessageAsync(deviceConfig, messageBody.TimeCreated.ToLongTimeString(), "AlertingCloud"); var methodResponse = new MethodResponse(Encoding.UTF8.GetBytes("{\"status\": \"ok\"}"), 200); return(await Task.FromResult(methodResponse)); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); return(await Task.FromResult(new MethodResponse(500))); } }
static async Task <MessageResponse> ManageASAAlertsAsync(Microsoft.Azure.Devices.Client.Message message, object userContext) { ModuleClient moduleClient = (ModuleClient)userContext; byte[] messageBytes = message.GetBytes(); string messageString = Encoding.UTF8.GetString(messageBytes); Console.WriteLine($"Alert from ASA received: [{messageString}]"); try { var messageBody = JsonConvert.DeserializeObject <ASAAlert>(messageString); var deviceId = messageBody.DeviceId; DeviceConfig deviceConfig = Devices.Find(d => d.ID.Equals(deviceId)); await PublishMQTTMessageAsync(deviceConfig, messageBody.Command.ToString(), "AlertingASA"); return(MessageResponse.Completed); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", exception); } // Indicate that the message treatment is not completed. return(MessageResponse.Abandoned); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", ex.Message); // Indicate that the message treatment is not completed. return(MessageResponse.Abandoned); } }
static Task OnDesiredPropertiesUpdate(TwinCollection desiredProperties, object userContext) { try { Console.WriteLine($"{DateTime.Now.ToString()} - Desired property change:"); Console.WriteLine(JsonConvert.SerializeObject(desiredProperties)); if (desiredProperties.Contains("Temp_Threshold") && desiredProperties["Temp_Threshold"] != null) { if (int.TryParse(desiredProperties["Temp_Threshold"].ToString(), out int ts)) { Temp_Threshold = ts; Console.WriteLine($"value updated for Property 'Temp_Threshold': {Temp_Threshold}"); } else { Console.WriteLine($"Check the property Temp_Threshold ({desiredProperties["Temp_Threshold"]}) in the Module Twin. It must be an int"); } } if (desiredProperties.Contains("MQTT_BROKER_ADDRESS") && desiredProperties["MQTT_BROKER_ADDRESS"] != null) { MQTT_BROKER_ADDRESS = desiredProperties["MQTT_BROKER_ADDRESS"]; Console.WriteLine($"value updated for Property 'MQTT_BROKER_ADDRESS': {MQTT_BROKER_ADDRESS}"); } if (desiredProperties.Contains("MQTT_BROKER_PORT") && desiredProperties["MQTT_BROKER_PORT"] != null) { if (int.TryParse(desiredProperties["MQTT_BROKER_PORT"].ToString(), out int port)) { MQTT_BROKER_PORT = port; Console.WriteLine($"value updated for Property 'MQTT_BROKER_PORT': {MQTT_BROKER_PORT}"); } else { Console.WriteLine($"Check the property MQTT_BROKER_PORT ({desiredProperties["MQTT_BROKER_PORT"]}) in the Module Twin. It must be an int"); } } if (desiredProperties.Contains("NBDevices") && desiredProperties["NBDevices"] != null) { if (int.TryParse(desiredProperties["NBDevices"].ToString(), out int nb)) { NBDevices = nb; Console.WriteLine($"value updated for Property 'NBDevices': {NBDevices}"); } else { Console.WriteLine($"Check the property NBDevices ({desiredProperties["NBDevices"]}) in the Module Twin. It must be an int"); } } Devices = new List <DeviceConfig>(); for (int i = 1; i <= NBDevices; i++) { string deviceIdKey = $"Device{i}_ID"; string deviceSchemaKey = $"Device{i}_Schema"; string deviceDataTopicKey = $"Device{i}_DataTopic"; string deviceFeedbackTopicKey = $"Device{i}_FeedbackTopic"; DeviceConfig deviceConfig = new DeviceConfig(); if (desiredProperties.Contains(deviceIdKey) && desiredProperties[deviceIdKey] != null) { deviceConfig.ID = desiredProperties[deviceIdKey]; } if (desiredProperties.Contains(deviceSchemaKey) && desiredProperties[deviceSchemaKey] != null) { deviceConfig.Schema = desiredProperties[deviceSchemaKey]; } if (desiredProperties.Contains(deviceDataTopicKey) && desiredProperties[deviceDataTopicKey] != null) { deviceConfig.DataTopic = desiredProperties[deviceDataTopicKey]; } if (desiredProperties.Contains(deviceFeedbackTopicKey) && desiredProperties[deviceFeedbackTopicKey] != null) { deviceConfig.FeedbackTopic = desiredProperties[deviceFeedbackTopicKey]; } Devices.Add(deviceConfig); Console.WriteLine($"Device added: {deviceConfig.ID}"); } Console.WriteLine("Subscribing to Topics"); Task.Run(SubscribeMQTTTopicsAsync).Wait(); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error when receiving desired property: {0}", exception); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error when receiving desired property: {0}", ex.Message); } return(Task.CompletedTask); }