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)); }
/// <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() { 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); }
private static async Task RetrieveSettingsFromTwin(ModuleClient moduleClient) { Twin currentTwinProperties = await moduleClient.GetTwinAsync(); Console.WriteLine("Initialized Twin State Received"); if (currentTwinProperties.Properties.Desired.Contains(SendIntervalConfigKey)) { Console.WriteLine("SendInterval: " + currentTwinProperties.Properties.Desired[SendIntervalConfigKey]); var desiredInterval = (int)currentTwinProperties.Properties.Desired[SendIntervalConfigKey]; messageDelay = TimeSpan.FromMilliseconds(desiredInterval); } if (currentTwinProperties.Properties.Desired.Contains(EventCountConfigKey)) { Console.WriteLine("EventCount: " + currentTwinProperties.Properties.Desired[EventCountConfigKey]); var desiredCount = (int)currentTwinProperties.Properties.Desired[EventCountConfigKey]; eventCount = desiredCount; } if (currentTwinProperties.Properties.Desired.Contains(SendDataConfigKey)) { Console.WriteLine("SendData: " + currentTwinProperties.Properties.Desired[SendDataConfigKey]); sendData = (bool)currentTwinProperties.Properties.Desired[SendDataConfigKey]; if (!sendData) { Console.WriteLine("Sending data disabled. Change twin configuration to start sending again."); } } }
internal virtual async Task <T> GetTwinAsync <T>(string name) where T : TypeTwin, new() { var twin = await _ioTHubModuleClient.GetTwinAsync(); return(TypeTwin.CreateTwin <T>(name, twin)); }
static async Task <int> Main(string[] args) { WriteLineWithTimestamp("get-twin Main()\n"); (CancellationTokenSource cts, ManualResetEventSlim completed) = InitShutdownHandler(); try { WriteLineWithTimestamp("Connecting to edge hub...\n"); ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(); await moduleClient.OpenAsync(cts.Token); WriteLineWithTimestamp("Connected.\n"); while (!cts.Token.IsCancellationRequested) { WriteLineWithTimestamp("Requesting module twin...\n"); var twin = await moduleClient.GetTwinAsync(cts.Token); WriteLineWithTimestamp($"Received module twin:\n{twin.ToJson(Formatting.Indented)}\n"); await Task.Delay(TimeSpan.FromMinutes(1), cts.Token); } } catch (TaskCanceledException) { } completed.Set(); return(0); }
/// <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 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() { 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> 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}"); } } }
static void Main(string[] args) { try { try { ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(ModuleConnectionString); moduleClient.OpenAsync().Wait(); SendMessages(moduleClient).Wait(); Twin twin = moduleClient.GetTwinAsync().Result; Console.WriteLine($"Module Twin Desired Properties: {twin.Properties.Desired.ToJson(Formatting.Indented)}"); Console.WriteLine($"Module Twin Tags: {twin.Tags.ToJson(Formatting.Indented)}"); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Exited!\n"); } catch (Exception ex) { Console.WriteLine("Error in sample: {0}", ex.Message); } }
/// <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. /// </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."); }
/// <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."); }
public async Task <EdgeGatewayConfiguration> GetModuleConfigAsync() { ModuleClient client = await ModuleClient.CreateFromEnvironmentAsync(); await client.OpenAsync(); Twin twin = await client.GetTwinAsync(); TwinCollection collection = twin.Properties.Desired; if (!collection.Contains("luss") || !collection.Contains("serviceUrl")) { Console.WriteLine("Twin has no luss property"); return(null); } string luss = collection["luss"]; string serviceUrl = collection["serviceUrl"]; if (string.IsNullOrEmpty(luss) || string.IsNullOrEmpty(serviceUrl)) { Console.WriteLine("Twin has empty luss"); return(null); } return(await GetConfigurationAsync(luss, serviceUrl)); }
/// <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 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() { 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 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 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 }; 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); }
/// <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() { 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 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() { 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."); // 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(); }
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(); }
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'."); } }
private async Task ModuleClient_Gives_ConnectionStatus_DeviceDisabled_Base( Client.TransportType protocol, Func <RegistryManager, string, Task> registryManagerOperation) { AmqpTransportSettings amqpTransportSettings = new AmqpTransportSettings(protocol); ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings }; TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix + $"_{Guid.NewGuid()}", ModulePrefix).ConfigureAwait(false); ConnectionStatus? status = null; ConnectionStatusChangeReason?statusChangeReason = null; int deviceDisabledReceivedCount = 0; ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { if (r == ConnectionStatusChangeReason.Device_Disabled) { status = s; statusChangeReason = r; deviceDisabledReceivedCount++; } }; using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings)) { moduleClient.SetConnectionStatusChangesHandler(statusChangeHandler); _log.WriteLine($"Created {nameof(DeviceClient)} ID={TestLogging.IdOf(moduleClient)}"); Console.WriteLine("ModuleClient OpenAsync."); await moduleClient.OpenAsync().ConfigureAwait(false); // Receiving the module twin should succeed right now. Console.WriteLine("ModuleClient GetTwinAsync."); var twin = await moduleClient.GetTwinAsync().ConfigureAwait(false); Assert.IsNotNull(twin); // Delete/disable the device in IoT Hub. using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString)) { await registryManagerOperation(registryManager, testModule.DeviceId).ConfigureAwait(false); } // Artificial sleep waiting for the connection status change handler to get triggered. int sleepCount = 50; for (int i = 0; i < sleepCount; i++) { await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); if (deviceDisabledReceivedCount == 1) { break; } } Assert.AreEqual(1, deviceDisabledReceivedCount); Assert.AreEqual(ConnectionStatus.Disconnected, status); Assert.AreEqual(ConnectionStatusChangeReason.Device_Disabled, statusChangeReason); } }