/// <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."); }
public static async Task <Task> SetModuleReceiveMethodDefaultHandlerAsync(ModuleClient moduleClient, string methodName, MsTestLogger logger) { var methodCallReceived = new TaskCompletionSource <bool>(); await moduleClient.SetMethodDefaultHandlerAsync( (request, context) => { logger.Trace($"{nameof(SetDeviceReceiveMethodDefaultHandlerAsync)}: ModuleClient method: {request.Name} {request.ResponseTimeout}."); try { Assert.AreEqual(methodName, request.Name, $"The expected method name should be {methodName} but was {request.Name}"); Assert.AreEqual(ServiceRequestJson, request.DataAsJson, $"The expected respose payload should be {ServiceRequestJson} but was {request.DataAsJson}"); methodCallReceived.SetResult(true); } catch (Exception ex) { methodCallReceived.SetException(ex); } return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200))); }, null).ConfigureAwait(false); return(methodCallReceived.Task); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages /// </summary> static async Task <ModuleClient> Init(bool debug = false) { //This debug code enables code execution to pause while you attach the debugger //See instructions in the Main method to pass true to the debug variable. //Otherwise, when debugging, some code will run before you can attach the debugger. #if DEBUG while (debug && !Debugger.IsAttached) { Log.Verbose("Module waiting for debugger to attach..."); await Task.Delay(1000); } ; #endif 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(); Log.Information("IoT Hub Heartbeat module client on {deviceId} initialized", deviceId); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetMethodDefaultHandlerAsync(AckMessage, ioTHubModuleClient); return(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(); 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); }
static async Task Init() { MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); ITransportSettings[] settings = { mqttSetting }; // Open a connection to the Edge runtime moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await moduleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); await moduleClient.SetMethodDefaultHandlerAsync(directMethodHandler, moduleClient); await moduleClient.SetInputMessageHandlerAsync("messageInput", inputMessageHandler, moduleClient); }
/// <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.SetMethodDefaultHandlerAsync(HandleMethodAsync, ioTHubModuleClient); Console.WriteLine("Default method handler registered."); }
public async Task Initialize(ConnectionStatusChangesHandler connectionStatusHander, MessageHandler messageCallback, DesiredPropertyUpdateCallback twinCallback, MethodCallback methodCallback, object context, CancellationToken ct) { var option = new ClientOptions { ModelId = ModuleClientConnector.PnPModelId }; moduleClient = await ModuleClient.CreateFromEnvironmentAsync(envSettings, options : option); Console.WriteLine($"Connected to Edge Hub as Plug and Play Model Id={ModuleClientConnector.PnPModelId}"); await moduleClient.OpenAsync(); moduleClient.SetConnectionStatusChangesHandler(connectionStatusHander); await moduleClient.SetInputMessageHandlerAsync(this.msgInputName, messageCallback, context); await moduleClient.SetDesiredPropertyUpdateCallbackAsync(twinCallback, context); await moduleClient.SetMethodDefaultHandlerAsync(methodCallback, context); }
private async Task RegisterC2DDirectMethodsHandlersAsync(ModuleClient moduleClient, ModuleSettings settings, ILogger logger) { string logPrefix = "c2ddirectmethods".BuildLogPrefix(); try { // Create a handler for the direct method call await moduleClient.SetMethodHandlerAsync("SetTelemetryInterval", SetTelemetryInterval, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD SetTelemetryInterval registered."); await moduleClient.SetMethodHandlerAsync("Reboot", Reboot, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD Reboot registered."); await moduleClient.SetMethodHandlerAsync("OnOff", StartOrStop, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD OnOff registered."); await moduleClient.SetMethodHandlerAsync("ReadTwins", ReadTwinsAsync, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD ReadTwins registered."); await moduleClient.SetMethodHandlerAsync("GenericJToken", GenericJToken, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD GenericJToken registered."); await moduleClient.SetMethodHandlerAsync("Generic", Generic, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD Generic registered."); await moduleClient.SetMethodDefaultHandlerAsync(DefaultC2DMethodHandler, null); _logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD Default handler registered."); } catch (Exception ex) { _logger.LogError($"{logPrefix}::{ModuleSettings.ArtifactId}::ERROR:RegisterC2DDirectMethodsHandlersAsync:{ex.Message}."); } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task <int> InitAsync() { configuration = CameraConfiguration.CreateFromEnvironmentVariables(); camera = new Camera(configuration); if (!camera.Initialize()) { return(-1); } var transportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { transportSettings }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Logger.Log("Initializing Pi camera module"); var twin = await ioTHubModuleClient.GetTwinAsync(); HandleTwinChanges(twin.Properties.Desired); await ioTHubModuleClient.SetMethodDefaultHandlerAsync(ModuleMethodHandlerAsync, ioTHubModuleClient); Logger.Log("Default method handler initialized"); await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync((updatedTwin, _) => { HandleTwinChanges(updatedTwin); return(Task.FromResult(0)); }, null); Logger.Log("Twin changes callback is set"); Logger.Log("Ready!"); return(0); }
/// <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."); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // Register direct method handlers await ioTHubModuleClient.SetMethodHandlerAsync("BackfillMethod", BackfillMethodHandler, ioTHubModuleClient); await ioTHubModuleClient.SetMethodHandlerAsync("SkipMessageMethod", SkipMessageMethodHandler, ioTHubModuleClient); await ioTHubModuleClient.SetMethodDefaultHandlerAsync(DefaultMethodHandler, ioTHubModuleClient); }
public static async void ConnectionStatusChanged(ConnectionStatus status, ConnectionStatusChangeReason reason) { Console.WriteLine($"ConnectionStatusChanged: {status}, reason={reason}"); if (status == ConnectionStatus.Connected) { // Register callback to be called when a message is received by the module //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // Register callback to be called when method is called await ioTHubModuleClient.SetMethodDefaultHandlerAsync(DefaultMethodCallback, ioTHubModuleClient); Console.WriteLine("Default method handler registered."); await ioTHubModuleClient.SetMethodHandlerAsync("setleds", SetLedsCallback, ioTHubModuleClient); Console.WriteLine("Method handler 'setleds' registered."); } if (status != ConnectionStatus.Connected && status != ConnectionStatus.Disconnected_Retrying) { Console.WriteLine("Reconnect"); await ioTHubModuleClient.OpenAsync(); } }
private async Task RegisterC2DDirectMethodsHandlersAsync(ModuleClient moduleClient, ModuleSettings settings, ILogger logger) { string logPrefix = "modules.c2ddirectmethods".BuildLogPrefix(); try { // Create a handler for the direct method call await moduleClient.SetMethodHandlerAsync("SetTelemetryInterval", SetTelemetryInterval, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD SetTelemetryInterval registered."); await moduleClient.SetMethodHandlerAsync("Reboot", Reboot, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD Reboot registered."); await moduleClient.SetMethodHandlerAsync("OnOff", StartOrStop, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD OnOff registered."); await moduleClient.SetMethodHandlerAsync("ReadTwins", ReadTwinsAsync, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD ReadTwins registered."); await moduleClient.SetMethodHandlerAsync("GenericJToken", GenericJToken, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD GenericJToken registered."); await moduleClient.SetMethodHandlerAsync("Generic", Generic, null); logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD Generic registered."); //Default await moduleClient.SetMethodDefaultHandlerAsync(DefaultC2DMethodHandler, null); _logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD Default handler registered."); //DTDL Commands var modelWithCommands = await _dtdlCommandService.GetCommandsAsync(ModuleSettings.DefaultModelId, _defaultModel.ModelPath); if (modelWithCommands != null && modelWithCommands.Any()) { _logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD DTDL command handlers."); foreach (var model in modelWithCommands) { if (model.Value != null && model.Value.Commands != null && model.Value.Commands.Count > 0) { string commandName = string.Empty; foreach (JObject command in model.Value.Commands) { if (command.Properties().Any()) { commandName = command.Properties().First().Name; await moduleClient.SetMethodHandlerAsync( commandName, DTDLCommandHandler, new DTDLCommandHandlerContext { CommandName = commandName, CommandRequestPayload = command.Descendants().Where(d => d is JObject && d["request"] != null).SingleOrDefault(), //TODO: replace this with the actual JSON Schema of the request CommandResponsePayload = command.Descendants().Where(d => d is JObject && d["response"] != null).SingleOrDefault() //TODO: replace this with the actual JSON Schema of the response }); _logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD DTDL commands handlers registered:: {commandName}"); } else { _logger.LogError($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD DTDL commands handlers::bad formed command structure."); } } } else { _logger.LogTrace($"{logPrefix}::{ModuleSettings.ArtifactId}::DIRECT METHOD DTDL commands:: no commands have been declared in this model."); } } } } catch (Exception ex) { _logger.LogError($"{logPrefix}::{ModuleSettings.ArtifactId}::ERROR:RegisterC2DDirectMethodsHandlersAsync:{ex.Message}."); } }