/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); ITransportSettings[] settings = { mqttSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // reset reported properties var reportedProperties = new Microsoft.Azure.Devices.Shared.TwinCollection(); reportedProperties["highTemperature"] = (float)0; reportedProperties["highTemperatureDate"] = string.Empty; await ioTHubModuleClient.UpdateReportedPropertiesAsync(reportedProperties); Console.WriteLine("Reset Reported Properties"); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("reporter", PipeMessage, ioTHubModuleClient); }
private static async Task OnDesiredPropertyChanged(Microsoft.Azure.Devices.Shared.TwinCollection desiredProperties, object userContext) { Console.WriteLine("desired property change:"); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(desiredProperties)); await Task.Delay(100); return; }
/// <summary> /// This method is called whenever the module is sent a message from the EdgeHub. /// It just pipe the messages without any change. /// It prints all the incoming messages. /// </summary> static async Task <MessageResponse> PipeMessage(Message message, object userContext) { int counterValue = Interlocked.Increment(ref counter); var moduleClient = userContext as ModuleClient; if (moduleClient == null) { throw new InvalidOperationException("UserContext doesn't contain " + "expected values"); } byte[] messageBytes = message.GetBytes(); string messageString = Encoding.UTF8.GetString(messageBytes); // update reported properties var reportedMessage = JObject.Parse(messageString); var reportedProperties = new Microsoft.Azure.Devices.Shared.TwinCollection(); var highTemperature = (float)reportedMessage["temperature"]; reportedProperties["highTemperature"] = highTemperature; reportedProperties["highTemperatureDate"] = DateTime.Now.ToShortTimeString(); // report the high temperature back to the module twin await moduleClient.UpdateReportedPropertiesAsync(reportedProperties); Console.WriteLine("Updated Reported Properties"); // send message to output (not required) var outputString = JsonConvert.SerializeObject( new { message = "high temperature alert reported!", temperature = highTemperature }); var outputBytes = Encoding.UTF8.GetBytes(outputString); using (var pipeMessage = new Message(outputBytes)) { await moduleClient.SendEventAsync("output1", pipeMessage); Console.WriteLine("Sent output message"); } return(MessageResponse.Completed); }
static void Main(string[] args) { _registryManager = RegistryManager.CreateFromConnectionString(_iotHubConnectionString); _cityData = File.ReadAllLines("CityData.csv"); _devices = new List <WaterLevelSensorReading>(); _runningBlocks = new List <ITargetBlock <string> >(); _cancellationToken = new CancellationTokenSource(); _random = new Random(); for (var i = 0; i < _numberOfDevices; i++) { //set information that needs set once var deviceId = $"{_devicePrefix}_{i + 1}"; var device = new WaterLevelSensorReading(deviceId); var cityIdx = _random.Next(1, _maxLocationId); var cityDataLine = _cityData.First(c => c.StartsWith(cityIdx.ToString())); var tokens = cityDataLine.Split(','); device.Latitude = Convert.ToDouble(tokens[3]); device.Longitude = Convert.ToDouble(tokens[4]); device.AzureDevice = GetOrRegisterDeviceInAzureAsync(deviceId).GetAwaiter().GetResult(); device.AzureDeviceClient = DeviceClient.Create(_iotHubHostName, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, device.AzureDevice.Authentication.SymmetricKey.PrimaryKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt); var rp = new Microsoft.Azure.Devices.Shared.TwinCollection(); rp["Type"] = "WaterLevelSensor"; rp["Latitude"] = device.Latitude; rp["Longitude"] = device.Longitude; rp["Firmware"] = "1.0.0"; rp["SupportedMethods"] = ""; var telemetryNested = new Microsoft.Azure.Devices.Shared.TwinCollection(); telemetryNested[device.MessageSchema] = WaterLevelSensorReading.GetTelemetryObject(); rp["Telemetry"] = telemetryNested; device.AzureDeviceClient.UpdateReportedPropertiesAsync(rp).GetAwaiter().GetResult(); _devices.Add(device); //blocks take a random reading, then run indefinitely until cancelled var block = CreateEmulatedDeviceReading(_cancellationToken.Token); _runningBlocks.Add(block); block.Post(deviceId); } Console.ReadLine(); _cancellationToken.Cancel(); Console.WriteLine("Finished (press any key to continue)"); Console.ReadLine(); }
static List <(long, TestOperationResult)> GetStoreData(string source, string resultType, IEnumerable <string> resultValues, int start = 0) { var storeData = new List <(long, TestOperationResult)>(); int count = start; foreach (string value in resultValues) { var tc = new Microsoft.Azure.Devices.Shared.TwinCollection(); var values = value.Split(";"); foreach (var item in values) { tc[item] = "1"; } var twinTestResult = new TwinTestResult(source, DateTime.UtcNow) { Properties = tc }; storeData.Add((count, twinTestResult.ToTestOperationResult())); count++; } return(storeData); }