/// <summary> /// Inicializa o ModuleClient e configura o retorno de chamada para receber /// mensagens contendo informações de temperatura /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Abra uma conexão com o tempo de execução do Edge ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("*** Cliente do módulo IoT Hub inicializado ***"); // Obtem os valores das *propriedades desejadas* do módulo gêmeo var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); // Atribui *propriedades desejadas* ao método de tratamento await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Anexa método para tratar as *propriedades desejadas* do módulo gêmeo sempre que tiver atualizações. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Registra um método responsável por tratar as mensagens recebidas pelo módulo (filtrar e encaminhar). await ioTHubModuleClient.SetInputMessageHandlerAsync(_inputName, FilterMessages, ioTHubModuleClient); }
/// <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 ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); // register our TWIN callback await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, ioTHubModuleClient); // get our first TWIN update var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // register our callback await ioTHubModuleClient.SetMethodDefaultHandlerAsync(MethodCallback, null); Console.WriteLine("IoT Hub module client initialized."); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> internal static async Task Init() { Logger.LoggingLevel = LogSeverity.Verbose; AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient .CreateFromEnvironmentAsync(settings) .ConfigureAwait(false); await ioTHubModuleClient.OpenAsync().ConfigureAwait(false); Console.WriteLine("IoT Hub module client initialized."); // Register callbacks for messages to the module await ioTHubModuleClient .SetInputMessageHandlerAsync(EndpointNames.FromLeafDevice, LeafDeviceInputMessageHandler, ioTHubModuleClient) .ConfigureAwait(false); await ioTHubModuleClient .SetInputMessageHandlerAsync(EndpointNames.FromClassifier, ClassifierCallbackMessageHandler, ioTHubModuleClient) .ConfigureAwait(false); // Register a callback for updates to the module twin's desired properties. await ioTHubModuleClient .SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null) .ConfigureAwait(false); }
/// <summary> /// Initializes the Azure IoT Client for the Edge Module /// </summary> private static async Task Init() { try { MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); ITransportSettings[] settings = { mqttSetting }; ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); // Read config from Twin and Start Twin moduleTwin = await ioTHubModuleClient.GetTwinAsync(); await UpdateStartFromTwin(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach callback for Twin desired properties updates await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, ioTHubModuleClient); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error when initializing module: {0}", exception); } } }
/// <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()}"); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// serial port data /// </summary> static async Task Init() { try { var setting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { setting }; // Open a connection to the Edge runtime _ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); //HOLD: when publishing to Azure IoT Edge Modules Marketplace //ioTHubModuleClient.ProductInfo = "..."; await _ioTHubModuleClient.OpenAsync(); Log.Information($"IoT Hub module client initialized"); // Execute callback method for Twin desired properties updates var twin = await _ioTHubModuleClient.GetTwinAsync(); await OnDesiredPropertiesUpdate(twin.Properties.Desired, _ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await _ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, _ioTHubModuleClient); Log.Information($"Module '{Environment.GetEnvironmentVariable("IOTEDGE_MODULEID")}' initialized"); Log.Information($".Net framework version '{Environment.GetEnvironmentVariable("DOTNET_VERSION")}' in use"); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Log.Error($"Error when initializing module: {exception}"); } } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async void Init(CancellationToken token) { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Apre la connessione ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(token); // Recupera la connessione allo storage Storage = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"); Console.WriteLine($"Storage: {Storage}"); await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyUpdate, null, token); Console.WriteLine("IoT Hub module client initialized."); while (!token.IsCancellationRequested) { await Task.Delay(5000, token); try { await SendPhoto(ioTHubModuleClient, token); } catch (Exception ex) when(!(ex is OperationCanceledException)) { Console.WriteLine(ex.ToString()); } } }
public async Task Initialize(IApplicationBuilder applicationBuilder) { await _moduleClient.SetInputMessageHandlerAsync(Constants.Inputs.SubscriberInbound, new MessageHandler(async(message, userContext) => { 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); var healthJob = new HealthCheckJob(_jobDependencyLocator, JsonConvert.DeserializeObject <ElapsedScheduleMessage>(messageString)); await healthJob.Run(); await moduleClient.CompleteAsync(message); return(MessageResponse.Completed); }), _moduleClient, _tokenSource.Token); await _moduleClient.SetDesiredPropertyUpdateCallbackAsync( new DesiredPropertyUpdateCallback(async(mr, o) => { var job = new DesiredPropertyChangedJob(_jobDependencyLocator, mr); await job.Run(); }), _moduleClient); var twin = await _moduleClient.GetTwinAsync(); var spinupJob = new DesiredPropertyChangedJob(_jobDependencyLocator, twin.Properties.Desired); await spinupJob.Run(); }
/// <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."); // Read the TemperatureThreshold value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); InitFileWatcher(); DisplayImage(logoImagePath); Console.WriteLine("Successfully initialized ScreenshotWatcher module."); }
/// <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."); // Read the TemperatureThreshold value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); // Execute callback function during Init for Twin desired properties await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Register a callback for messages that are received by the module. await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterMessages, ioTHubModuleClient); }
/// <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); // Attach callback for Twin desired properties updates await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, ioTHubModuleClient); // Execute callback method for Twin desired properties updates var twin = await ioTHubModuleClient.GetTwinAsync(); await onDesiredPropertiesUpdate(twin.Properties.Desired, ioTHubModuleClient); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); var thread = new Thread(() => ThreadBody(ioTHubModuleClient)); thread.Start(); }
/// <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 ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // Kevin var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); await ioTHubModuleClient.SetMethodDefaultHandlerAsync(methodHandler, null); Console.Write("starting the Timer"); moduleTimer.Interval = timerInterval * 1000; moduleTimer.Elapsed += OnTimedEvent; moduleTimer.AutoReset = true; moduleTimer.Enabled = true; moduleTimer.Start(); // Register callback to be called when a message is received by the module Console.Write("setting the callback"); await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task InitEdgeModule() { MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); ITransportSettings[] settings = { mqttSetting }; /* 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."); // Read Module Twin Desired Properties Console.WriteLine("Reading module Twin from IoT Hub."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); // Parse Twin Json and initialize gateway Console.WriteLine("Starting Gateway controller handler process."); ServiceBusClientModel gatewayConfigModel = ServiceBusClientModel.InitClientModel(moduleTwin.Properties.Desired); serviceBusClient = ServiceBusClient.Init(gatewayConfigModel, ioTHubModuleClient); // Attach callback for Twin desired properties updates await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); }
/// <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."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; Console.WriteLine("Got Device Twin configuration."); desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection); // callback for updating desired properties through the portal or rest api await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); await ioTHubModuleClient.SetMethodHandlerAsync("capture", CaptureMethod, ioTHubModuleClient); }
/// <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 ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings).ConfigureAwait(false); await ioTHubModuleClient.OpenAsync().ConfigureAwait(false); Console.WriteLine("IoT Hub module client initialized."); // Read the TemperatureThreshold value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync().ConfigureAwait(false); await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null).ConfigureAwait(false); // Register a callback for messages that are received by the module. await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterMessagesAsync, ioTHubModuleClient).ConfigureAwait(false); await ioTHubModuleClient.SetMethodHandlerAsync(heartbeat, HeartbeatAsync, null).ConfigureAwait(false); Console.WriteLine("Set Heartbeat Method Handler:HeartbeatAsync."); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { // Use Mqtt as it is more reliable than ampq 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(); wrappedModuleClient = new WrappedModuleClient(ioTHubModuleClient); Logger.LogInfo("IoT Hub module client initialized."); // get module twin settings var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync(TrackerModule.TelemetryInputName, ProcessTelemetry, ioTHubModuleClient); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync(TrackerModule.BalloonInputName, ProcessBalloonData, ioTHubModuleClient); }
/// <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("Proxy module client initialized."); // Register callback to be called when a direct method message is received by the module await ioTHubModuleClient.SetMethodHandlerAsync("GetDeviceIdFromDirectMethod", DelegateDirectMethod, ioTHubModuleClient); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("MessageFromConverter", DelegateMessageEvents, ioTHubModuleClient); // Read the Threshold value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); //await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); }
/// <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); // Read the TemperatureThreshold value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { temperatureThreshold = moduleTwinCollection["TemperatureThreshold"]; } catch (ArgumentOutOfRangeException e) { Console.WriteLine($"Property TemperatureThreshold not exist: {e.Message}"); } // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Register a callback for messages that are received by the module. await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterMessages, ioTHubModuleClient); }
/// <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."); // Read TemperatureThreshold from Module Twin Desired Properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { await DoTwinUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); } catch (ArgumentOutOfRangeException e) { Console.WriteLine($"Error setting desired properties: {e.Message}"); } // Attach callback for Twin desired properties updates await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, ioTHubModuleClient); }
/// <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."); // Execute callback function during Init for Twin desired properties var twin = await ioTHubModuleClient.GetTwinAsync(); await onDesiredPropertiesUpdate(twin.Properties.Desired, ioTHubModuleClient); //Register the desired property callback await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, ioTHubModuleClient); //start the main thread that will do the real job of the module var thread = new Thread(() => mainThreadBody(ioTHubModuleClient)); thread.Start(); }
/// <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."); // Read the Humidity value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { humidityFilter = moduleTwinCollection["Humidity"]; } catch (ArgumentOutOfRangeException e) { Console.WriteLine($"Property Humidity does not exist: {e.Message}"); } // Attach a callback for updates to the module twin's properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterHumidityMessage, ioTHubModuleClient); }
/// <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."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection); // callback for updating desired properties through the portal or rest api await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // this direct method will allow to reset the temperature sensor values back to their initial state //await ioTHubModuleClient.SetMethodHandlerAsync("reset", ResetMethod, null); // Register callback to be called when a message is received by the module //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // as this runs in a loop we don't await await SendSimulationData(ioTHubModuleClient); Console.WriteLine("Simulating data..."); }
/// <summary> /// Initializes the ModuleClient. /// </summary> static void Init() { MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) { RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true }; ITransportSettings[] settings = { mqttSetting }; // Open a connection to the Edge runtime var mcTask = ModuleClient.CreateFromEnvironmentAsync(settings); mcTask.Wait(); s_moduleClient = mcTask.Result; s_moduleClient.OpenAsync().Wait(); // Read configuration from Module Twin Task <Twin> twinTask = s_moduleClient.GetTwinAsync(); twinTask.Wait(); Twin twin = twinTask.Result; OnDesiredPropertiesUpdate(twin.Properties.Desired, null); s_moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); Console.WriteLine("IoT Hub module client initialized."); }
private static async Task RunSampleAsync() { // This sample follows the following workflow: // -> Initialize device client instance. // -> Set handler to receive "targetTemperature" updates, and send the received update over reported property. // -> Set handler to receive "getMaxMinReport" command, and send the generated report as command response. // -> Periodically send "temperature" over telemetry. // -> Send "maxTempSinceLastReboot" over property update, when a new max temperature is set. s_logger.LogDebug($"Initialize the device client."); InitializeDeviceClientAsync(); s_logger.LogDebug($"Set handler to receive \"targetTemperature\" updates."); await s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(TargetTemperatureUpdateCallbackAsync, s_deviceClient); s_logger.LogDebug($"Set handler for \"getMaxMinReport\" command."); await s_deviceClient.SetMethodHandlerAsync("getMaxMinReport", HandleMaxMinReportCommandAsync, s_deviceClient); bool temperatureReset = true; await Task.Run(async() => { while (true) { if (temperatureReset) { // Generate a random value between 5.0°C and 45.0°C for the current temperature reading. s_temperature = Math.Round(s_random.NextDouble() * 40.0 + 5.0, 1); temperatureReset = false; } await SendTemperatureAsync(); await Task.Delay(5 * 1000); } }); }
/// <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 }; Console.WriteLine("ENV: " + JsonConvert.SerializeObject(Environment.GetEnvironmentVariables())); // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); Console.WriteLine("Init value: "); Console.WriteLine(JsonConvert.SerializeObject(moduleTwin)); var moduleTwinCollection = moduleTwin.Properties.Desired; try { Console.WriteLine("Props: " + JsonConvert.SerializeObject(moduleTwinCollection)); await OnDesiredPropertiesUpdate(moduleTwinCollection, ioTHubModuleClient); } catch (Exception e) { Console.WriteLine($"Property not exist: {e}"); } await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, ioTHubModuleClient); runningThread = Task.Run(() => GenerateData(ioTHubModuleClient)); // Attach a callback for updates to the module twin's desired properties. //GenerateData(ioTHubModuleClient); // Register a callback for messages that are received by the module. //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", GenerateData, ioTHubModuleClient); }
async Task InitCallBack() { try { ITransportSettings transportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { transportSettings }; //if running as Edge module if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("IOTEDGE_APIVERSION"))) { ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); Console.WriteLine("Getting properties from module twin..."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { LoraDeviceInfoManager.FacadeServerUrl = moduleTwinCollection["FacadeServerUrl"]; Console.WriteLine($"Facade function url: {LoraDeviceInfoManager.FacadeServerUrl}"); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Module twin FacadeServerName not exist"); } try { LoraDeviceInfoManager.FacadeAuthCode = moduleTwinCollection["FacadeAuthCode"]; } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Module twin facadeAuthCode not exist"); } await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null); await ioTHubModuleClient.SetMethodHandlerAsync("ClearCache", ClearCache, null); } //todo ronnie what to do when not running as edge? //running as non edge module for test and debugging else { LoraDeviceInfoManager.FacadeServerUrl = "http://localhost:7071/api/"; LoraDeviceInfoManager.FacadeAuthCode = ""; } // Attach callback for Twin desired properties updates } catch (Exception ex) { Console.WriteLine($"Initialization failed with error: {ex.Message}.\nWaiting for update desired property 'FacadeServerName' and 'FacadeAuthCode'."); } }
/// <summary> /// Ctor for the class. /// </summary> public HubClient(ModuleClient edgeHubClient, Logger logger) { _edgeHubClient = edgeHubClient; MonitoredSettingsCollection = new Dictionary <string, string>(); _edgeHubClient.SetDesiredPropertyUpdateCallbackAsync(HandleSettingChanged, null); _edgeHubClient.SetMethodHandlerAsync("DesiredPropertiesUpdated", DesiredPropertiesUpdated, null); _logger = logger; }
static async Task Main(string[] args) { levelSwitch.MinimumLevel = LogEventLevel.Debug; Log.Logger = new LoggerConfiguration().MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Console(outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss K} {Level:u3}] {Message:lj}{NewLine}{Exception}") .CreateLogger(); //To enable the debug wait code, pass 'true' to Init here Init(true); ModuleClient ioTHubModuleClient = await Init(); Log.Information("DeviceId: {deviceId}, ModuleId: {moduleId}, Start Window: {StartWindow}, End Window: {EndWindow}, Beat Frequency: {BeatFrequency}" , deviceId, moduleId, startWindow, endWindow, hartbeatFrequency); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); // If any variables are set in the desired properties of the module twin, // update them here await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Int64 has a max value of 9,223,372,036,854,775,807 and wraps to -9,223,372,036,854,775,808 // if it overflows // This number of message at 28,000,000,000 (billion) will not overflow for // ~902,482 years (MaxValue / 28B / 365) Int64 msgId = 0; // Send heartbeats to IoTHub at a specified frequency while (true) { await SendHeartbeat(ioTHubModuleClient, Interlocked.Read(ref msgId)); // delay for window, check internal state for update await Task.Delay(endWindow); if (HbStatus[msgId] != MessageStatus.Acked) { DeviceTimeout(); } else if (connectivityStatus == DeviceStatus.Offline) { Log.Information("Device ID: {deviceId} is online.", deviceId); connectivityStatus = DeviceStatus.Online; endWindow = defaultEndWindow; } HbStatus.Remove(msgId); Interlocked.CompareExchange(ref msgId, 0, System.Int64.MaxValue); Interlocked.Increment(ref msgId); if (hartbeatFrequency - endWindow > TimeSpan.Zero) { await Task.Delay(hartbeatFrequency - endWindow); } } }
static async Task <int> MainAsync() { Console.WriteLine($"{DateTime.Now.ToLocalTime()}>\t The PumpSimulator Main() has started."); SetupTelemetry(); try { RetrieveSettingsFromConfig(); var simulatorParameters = SimulatorParameters.Create(); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); Console.WriteLine( $"Initializing simulated sensor to send {(SendUnlimitedMessages(messageCount) ? "unlimited" : messageCount.ToString())} " + $"messages, at an interval of {messageDelay.TotalSeconds} seconds.\n" + $"To change this, set the environment variable {MessageCountConfigKey} to the number of messages that should be sent (set it to -1 to send unlimited messages)."); moduleClient = await ModuleUtil.CreateModuleClientAsync( protocol, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy); ModuleClient userContext = moduleClient; reportedProperties = new TwinCollection(); await moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdated, userContext); await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null); await moduleClient.SetMethodHandlerAsync("ping", PingMethod, null); await moduleClient.SetMethodHandlerAsync("check", CheckMethod, null); await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext); await RetrieveSettingsFromTwin(moduleClient); await SendEvents(moduleClient, messageCount, simulatorParameters, cts); await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Console.WriteLine("SimulatedTemperatureSensor Main() finished."); return(0); } catch (System.Exception ex) { Console.WriteLine($"{DateTime.Now.ToLocalTime()}>\t PumpSimulator Main() error."); Console.WriteLine(ex.Message); var telemetry = new ExceptionTelemetry(ex); telemetryClient.TrackException(telemetry); return(-1); } }
public async Task InitiateSimulationAsync() { string logPrefix = "system".BuildLogPrefix(); IoTTools.CheckModuleConnectionStringData(ModuleSettings.ConnectionString, _logger); // Connect to the IoT hub using the MQTT protocol _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Module client created."); if (SimulationSettings.EnableTwinPropertiesDesiredChangesNotifications) { await _moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChange, null); _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Twin Desired Properties update callback handler registered."); } //Configuration if (SimulationSettings.EnableC2DDirectMethods) { //Register C2D Direct methods handlers await RegisterC2DDirectMethodsHandlersAsync(_moduleClient, ModuleSettings, _logger); } if (SimulationSettings.EnableC2DMessages) { //Start receiving C2D messages ReceiveC2DMessagesAsync(_moduleClient, ModuleSettings, _logger); } //Messages if (SimulationSettings.EnableTelemetryMessages) { SendDeviceToCloudMessagesAsync(_moduleClient, ModuleSettings.DeviceId, ModuleSettings.ModuleId, _logger); //interval is a global variable changed by processes } if (SimulationSettings.EnableReadingTwinProperties) { //Twins _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::INITIALIZATION::Retrieving twin."); Twin twin = await _moduleClient.GetTwinAsync(); if (twin != null) { _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::INITIALIZATION::Device twin: {JsonConvert.SerializeObject(twin, Formatting.Indented)}."); } else { _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::INITIALIZATION::No device twin."); } } _moduleClient.SetConnectionStatusChangesHandler(new ConnectionStatusChangesHandler(ConnectionStatusChanged)); }