public async void ReceiveCommandsAsync() { ModuleClient ioTHubModuleClient = Program.IoTHubModuleClient; // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetMethodHandlerAsync("GetGarageStatus", GetGarageStatus, null); }
/// <summary> /// Inicializa o ModuleClient e configura o retorno de chamada para receber /// mensagens contendo informações de temperatura /// </summary> static async Task Init() { Util.Log.Info($"[Init] v.1.15 em 20200423-0130"); Util.Log.Info($"[Init] Inicio - {DateTime.Now}"); try { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; Util.Log.Info("[Init] Inicializando Cliente do modulo IoT Hub ***"); // Abra uma conexão com o tempo de execução do Edge ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Util.Log.Info("[Init] Cliente do modulo 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(Util.Message.CONST_MODCENTRAL_INPUT_MSG_FROM_MODBUS, FilterMessages, ioTHubModuleClient); // Registra um método responsável por tratar as mensagens recebidas pelo módulo (filtrar e encaminhar). await ioTHubModuleClient .SetMethodHandlerAsync("LigarMedidorDeNivel", Util.Message.LigarMedidorDeNivel, ioTHubModuleClient) .ConfigureAwait(false); await ioTHubModuleClient .SetMethodHandlerAsync("DesligarMedidorDeNivel", Util.Message.DesligarMedidorDeNivel, ioTHubModuleClient) .ConfigureAwait(false); await ioTHubModuleClient .SetMethodHandlerAsync("PiscarLED", Util.Message.PiscarLED, ioTHubModuleClient) .ConfigureAwait(false); //Console.WriteLine("Waiting 30 seconds for IoT Hub method calls ..."); //await Task.Delay(TimeSpan.FromSeconds(30)).ConfigureAwait(false); Util.Log.Info($"[Init] Fim - {DateTime.Now}"); } catch (AggregateException ex) { int cont = 0; foreach (Exception exception in ex.InnerExceptions) { Util.Log.Error($"Init: Error{cont++}: {exception}"); } } catch (Exception ex) { Util.Log.Error($"Init: Error: {ex.Message}"); } Util.Log.Info($"[Init] Fim - {DateTime.Now}"); }
public async Task InvokeMethodOnModuleTest(ITransportSettings[] transportSettings) { // Arrange string deviceName = string.Format("moduleMethodTest-{0}", transportSettings.First().GetTransportType().ToString("g")); string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString); ModuleClient receiver = null; string edgeDeviceConnectionString = ConfigHelper.TestConfig[Constants.ConfigKey.IotHubConnectionString]; Client.IotHubConnectionStringBuilder edgeHubConnectionStringBuilder = Client.IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString); string edgeDeviceId = edgeHubConnectionStringBuilder.DeviceId; Device edgeDevice = await rm.GetDeviceAsync(edgeDeviceId); var request = new TestMethodRequest("Prop1", 10); var response = new TestMethodResponse("RespProp1", 20); TestMethodRequest receivedRequest = null; Task <MethodResponse> MethodHandler(MethodRequest methodRequest, object context) { receivedRequest = JsonConvert.DeserializeObject <TestMethodRequest>(methodRequest.DataAsJson); return(Task.FromResult( new MethodResponse( Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)), 200))); } string receiverModuleName = "method-module"; (string deviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice(deviceName, iotHubConnectionString, rm, true, false, edgeDevice.Scope); try { ServiceClient sender = ServiceClient.CreateFromConnectionString(iotHubConnectionString); string receiverModuleConnectionString = await RegistryManagerHelper.CreateModuleIfNotExists(rm, connectionStringBuilder.HostName, deviceId, receiverModuleName); receiver = ModuleClient.CreateFromConnectionString(receiverModuleConnectionString, transportSettings); await receiver.OpenAsync(); await receiver.SetMethodHandlerAsync("poke", MethodHandler, null); // Need longer sleep to ensure receiver is completely initialized await Task.Delay(TimeSpan.FromSeconds(10)); // Act CloudToDeviceMethodResult cloudToDeviceMethodResult = await sender.InvokeDeviceMethodAsync( deviceId, receiverModuleName, new CloudToDeviceMethod("poke").SetPayloadJson(JsonConvert.SerializeObject(request))); // Assert Assert.NotNull(cloudToDeviceMethodResult); Assert.NotNull(receivedRequest); Assert.Equal(receivedRequest.RequestProp1, request.RequestProp1); Assert.Equal(receivedRequest.RequestProp2, request.RequestProp2); Assert.Equal(200, cloudToDeviceMethodResult.Status); var receivedResponse = JsonConvert.DeserializeObject <TestMethodResponse>(cloudToDeviceMethodResult.GetPayloadAsJson()); Assert.NotNull(receivedResponse); Assert.Equal(receivedResponse.ResponseProp1, response.ResponseProp1); Assert.Equal(receivedResponse.ResponseProp2, response.ResponseProp2); } finally { await rm.CloseAsync(); if (receiver != null) { await receiver.CloseAsync(); } try { await RegistryManagerHelper.RemoveDevice(deviceId, rm); } catch (Exception) { // ignored } } // wait for the connection to be closed on the Edge side await Task.Delay(TimeSpan.FromSeconds(10)); }
static async Task <int> MainAsync() { try { Logger.LogInformation("Validate Metrics Main() started."); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); var transportType = configuration.GetValue("ClientTransportType", Microsoft.Azure.Devices.Client.TransportType.Mqtt); Logger.LogInformation("Make Client"); using (ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync( transportType, new ClientOptions(), ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger)) using (MetricsScraper scraper = new MetricsScraper(new List <string> { "http://edgeHub:9600/metrics", "http://edgeAgent:9600/metrics" })) { Logger.LogInformation("Open Async"); await moduleClient.OpenAsync(); Logger.LogInformation("Set method handler"); await moduleClient.SetMethodHandlerAsync( "ValidateMetrics", async (MethodRequest methodRequest, object _) => { Logger.LogInformation("Validating metrics"); TestReporter testReporter = new TestReporter("Metrics Validation"); List <TestBase> tests = new List <TestBase> { new ValidateMessages(testReporter, scraper, moduleClient, transportType), new ValidateDocumentedMetrics(testReporter, scraper, moduleClient), // new ValidateHostRanges(testReporter, scraper, moduleClient), }; using (testReporter.MeasureDuration()) { await Task.WhenAll(tests.Select(test => test.Start(cts.Token))); } return(new MethodResponse(Encoding.UTF8.GetBytes(testReporter.ReportResults()), (int)HttpStatusCode.OK)); }, null); Logger.LogInformation("Ready to validate metrics"); await cts.Token.WhenCanceled(); } completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Logger.LogInformation("Validate Metrics Main() finished."); } catch (Exception e) { Logger.LogError(e.ToString()); } return(0); }
public async Task SetMethodHandlerAsync(string methodName, MethodCallback methodHandler, object userContext) { await ModuleClient.SetMethodHandlerAsync(methodName, methodHandler, userContext); Log.Information($"Method Handler Set for {methodName}"); }
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); if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("IOTEDGE_TIMEOUT"))) { ioTHubModuleClient.OperationTimeoutInMilliseconds = Convert.ToUInt32(Environment.GetEnvironmentVariable("IOTEDGE_TIMEOUT")); Logger.Log($"Changing timeout to {ioTHubModuleClient.OperationTimeoutInMilliseconds} ms", Logger.LoggingLevel.Info); } Logger.Init(ioTHubModuleClient); Logger.Log("Getting properties from module twin...", Logger.LoggingLevel.Info); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { LoraDeviceInfoManager.FacadeServerUrl = moduleTwinCollection["FacadeServerUrl"]; Logger.Log($"Facade function url: {LoraDeviceInfoManager.FacadeServerUrl}", Logger.LoggingLevel.Always); } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeServerName not exist", Logger.LoggingLevel.Error); throw e; } try { LoraDeviceInfoManager.FacadeAuthCode = moduleTwinCollection["FacadeAuthCode"]; } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeAuthCode does not exist", Logger.LoggingLevel.Error); throw e; } await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null); await ioTHubModuleClient.SetMethodHandlerAsync("ClearCache", ClearCache, null); } //running as non edge module for test and debugging else { LoraDeviceInfoManager.FacadeServerUrl = Environment.GetEnvironmentVariable("FacadeServerUrl"); LoraDeviceInfoManager.FacadeAuthCode = Environment.GetEnvironmentVariable("FacadeAuthCode"); } } catch (Exception ex) { Logger.Log($"Initialization failed with error: {ex.Message}", Logger.LoggingLevel.Error); throw ex; } }
static async Task <int> MainAsync() { Console.WriteLine("SampleModule Main() started."); var appSettings = ConfigurationManager.AppSettings; if (!TimeSpan.TryParse(appSettings["MessageDelay"], out messageDelay)) { messageDelay = TimeSpan.FromSeconds(5); } int messageCount; if (!int.TryParse(Environment.GetEnvironmentVariable(MessageCountConfigKey), out messageCount)) { if (!int.TryParse(appSettings[MessageCountConfigKey], out messageCount)) { messageCount = -1; } } var simulatorParameters = SimulatorParameters.Create(); ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync( TransportType.Amqp_Tcp_Only, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy); await moduleClient.OpenAsync(); await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null); await moduleClient.SetMethodHandlerAsync("ping", PingMethod, null); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); 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.FromSeconds(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."); } } ModuleClient userContext = moduleClient; await moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdated, userContext); await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext); await SendEvents(moduleClient, messageCount, simulatorParameters, cts); await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Console.WriteLine("SampleModule Main() finished."); return(0); }
public async Task ModulesClient_InvokeMethodOnModule() { if (!this.IsAsync) { // TODO: Tim: The module client doesn't appear to open a connection to iothub or start // listening for method invocations when this test is run in Sync mode. Not sure why though. // calls to track 1 library don't throw, but seem to silently fail return; } string testDeviceId = $"InvokeMethodDevice{GetRandom()}"; string testModuleId = $"InvokeMethodModule{GetRandom()}"; DeviceIdentity device = null; ModuleIdentity module = null; ModuleClient moduleClient = null; IotHubServiceClient serviceClient = GetClient(); try { // Create a device to house the modules device = (await serviceClient.Devices .CreateOrUpdateIdentityAsync( new DeviceIdentity { DeviceId = testDeviceId }) .ConfigureAwait(false)) .Value; // Create the module on the device module = (await serviceClient.Modules.CreateOrUpdateIdentityAsync( new ModuleIdentity { DeviceId = testDeviceId, ModuleId = testModuleId }).ConfigureAwait(false)).Value; // Method expectations string expectedMethodName = "someMethodToInvoke"; int expectedStatus = 222; object expectedRequestPayload = null; // Create module client instance to receive the method invocation string moduleClientConnectionString = $"HostName={GetHostName()};DeviceId={testDeviceId};ModuleId={testModuleId};SharedAccessKey={module.Authentication.SymmetricKey.PrimaryKey}"; moduleClient = ModuleClient.CreateFromConnectionString(moduleClientConnectionString, TransportType.Mqtt_Tcp_Only); // These two methods are part of our track 1 device client. When the test fixture runs when isAsync = true, // these methods work. When isAsync = false, these methods silently don't work. await moduleClient.OpenAsync().ConfigureAwait(false); await moduleClient.SetMethodHandlerAsync( expectedMethodName, (methodRequest, userContext) => { return(Task.FromResult(new MethodResponse(expectedStatus))); }, null).ConfigureAwait(false); // Invoke the method on the module CloudToDeviceMethodRequest methodRequest = new CloudToDeviceMethodRequest() { MethodName = expectedMethodName, Payload = expectedRequestPayload, ConnectTimeoutInSeconds = 5, ResponseTimeoutInSeconds = 5 }; var methodResponse = (await serviceClient.Modules.InvokeMethodAsync(testDeviceId, testModuleId, methodRequest).ConfigureAwait(false)).Value; Assert.AreEqual(expectedStatus, methodResponse.Status); } finally { if (moduleClient != null) { await moduleClient.CloseAsync().ConfigureAwait(false); } await CleanupAsync(serviceClient, device).ConfigureAwait(false); } }
/// <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(); InitLogging(); Logger.Information(@" ███████╗███████╗██████╗ ██╗ █████╗ ██╗ ██████╗ ██████╗ ██████╗ ████████╗ ██╔════╝██╔════╝██╔══██╗██║██╔══██╗██║ ██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ ███████╗█████╗ ██████╔╝██║███████║██║ ██████╔╝██║ ██║██████╔╝ ██║ ╚════██║██╔══╝ ██╔══██╗██║██╔══██║██║ ██╔═══╝ ██║ ██║██╔══██╗ ██║ ███████║███████╗██║ ██║██║██║ ██║███████╗ ██║ ╚██████╔╝██║ ██║ ██║ ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ______ _ _ | ___ \ | | | | | | _ | | ___ _ | |_ _| | ____ | || || |/ _ \ / || | | | | |/ _ ) | || || | |_| ( (_| | |_| | ( (/ / |_||_||_|\___/ \____|\____|_|\____) https://github.com/jantielens/serialportmodules "); Logger.Information("IoT Hub module client initialized."); // Initialize Serial Port string[] ports = SerialPort.GetPortNames(); Logger.Information("The following serial ports were found:"); // Display each port name to the console. foreach (string port in ports) { Logger.Information($" - {port}"); } Logger.Information("End of serial ports."); string serialPortName = "/dev/ttyACM0"; int serialPortSpeed; // try to read configured port env. vars if (Environment.GetEnvironmentVariable("portname") != null) { // found in env variables, use it serialPortName = Environment.GetEnvironmentVariable("portname"); Logger.Information($"Found 'portname' environment variable, using port '{serialPortName}'."); } else { Logger.Warning($"Environment variable 'portname' not found, using default name '{serialPortName}'."); } if (Environment.GetEnvironmentVariable("portspeed") != null) { Logger.Information($"Found 'portspeed' environment variable, value '{Environment.GetEnvironmentVariable("portspeed")}'."); if (int.TryParse(Environment.GetEnvironmentVariable("portspeed"), out serialPortSpeed)) { Logger.Information($"Using serial port speed {serialPortSpeed}"); } else { Logger.Error("Couldn't convert environment variable to a number, using default speed 9600."); serialPortSpeed = 9600; } } else { Logger.Warning("No environment variable 'portspeed' found, using default speed 9600"); serialPortSpeed = 9600; } Logger.Information("Opening port."); try { serialPort = new SerialPort(serialPortName, serialPortSpeed); serialPort.Open(); serialPort.ReadExisting(); // flush what's in there serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceived); Logger.Information($"Port {serialPortName} opened."); } catch (Exception ex) { Logger.Error($"Exception while opening port: { ex.ToString()}"); throw new ApplicationException($"Could not open serial port '{serialPortName}': {ex.ToString()}"); } await ioTHubModuleClient.SetMethodHandlerAsync("sendserial", OnSendSerial, null); }
/// <summary> /// Initializes the DeviceClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { Console.WriteLine("Starting Init process..."); try { Console.WriteLine("Setting transport settings..."); AmqpTransportSettings amqpTransportSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpTransportSetting }; Console.WriteLine("Setting up module client..."); // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); Console.WriteLine("Setting module twin info..."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); Console.WriteLine("Getting module twin desired props..."); var desiredProperties = moduleTwin.Properties.Desired; Console.WriteLine("Starting SQL connection string..."); string sqlConnectionString = desiredProperties["sqlConnectionString"]; DataHelper.ConnectionString = sqlConnectionString; Console.WriteLine($"sqlConnectionString: {sqlConnectionString}"); string json = JsonConvert.SerializeObject(desiredProperties); ModbusLayoutConfig modbusConfig = JsonConvert.DeserializeObject <ModbusLayoutConfig>(json); ModbusMessage.SurfaceLayoutConfig = modbusConfig.SurfaceCardConfiguration; ModbusMessage.PumpLayoutConfig = modbusConfig.PumpCardConfiguration; Console.WriteLine("Setting module twin property handler"); // Attach callback for Twin desired properties updates await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); Console.WriteLine("Setting modbusInput handler"); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("modbusInput", ProcessModbusInput, ioTHubModuleClient); Console.WriteLine("Setting opcInput handler"); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("opcInput", ProcessOPCInput, ioTHubModuleClient); Console.WriteLine("Setting generated telemetry handler"); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("telemetryInput", GeneratedTelemetryInput, ioTHubModuleClient); Console.WriteLine("Setting alertInput handler"); // Register callback to be called when an alert is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("alertInput", ProcessAlert, ioTHubModuleClient); Console.WriteLine("Setting config update direct method handler"); // Register callback to be called when an alert is received by the module await ioTHubModuleClient.SetMethodHandlerAsync("configUpdate", ConfigurationUpdate, ioTHubModuleClient); Console.WriteLine("Done setting inputs"); } catch (Exception ex) { Console.WriteLine($"Exception during Init: {ex.Message}"); Console.WriteLine(ex.StackTrace); } }
async Task InitCallBack() { try { ITransportSettings transportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { transportSettings }; //if running as Edge module if (configuration.RunningAsIoTEdgeModule) { ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); Logger.Init(new LoggerConfiguration { ModuleClient = ioTHubModuleClient, LogLevel = configuration.LogLevel, LogToConsole = configuration.LogToConsole, LogToHub = configuration.LogToHub, LogToUdp = configuration.LogToUdp, LogToUdpPort = configuration.LogToUdpPort, LogToUdpAddress = configuration.LogToUdpAddress, }); if (configuration.IoTEdgeTimeout > 0) { ioTHubModuleClient.OperationTimeoutInMilliseconds = configuration.IoTEdgeTimeout; Logger.Log($"Changing timeout to {ioTHubModuleClient.OperationTimeoutInMilliseconds} ms", Logger.LoggingLevel.Info); } Logger.Log("Getting properties from module twin...", Logger.LoggingLevel.Info); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { this.loraDeviceInfoManager.FacadeServerUrl = moduleTwinCollection["FacadeServerUrl"]; Logger.Log($"Facade function url: {this.loraDeviceInfoManager.FacadeServerUrl}", Logger.LoggingLevel.Always); } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeServerName not exist", Logger.LoggingLevel.Error); throw e; } try { this.loraDeviceInfoManager.FacadeAuthCode = moduleTwinCollection["FacadeAuthCode"]; } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeAuthCode does not exist", Logger.LoggingLevel.Error); throw e; } await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null); await ioTHubModuleClient.SetMethodHandlerAsync("ClearCache", ClearCache, null); } //running as non edge module for test and debugging else { Logger.Init(new LoggerConfiguration { ModuleClient = null, LogLevel = configuration.LogLevel, LogToConsole = configuration.LogToConsole, LogToHub = configuration.LogToHub, LogToUdp = configuration.LogToUdp, LogToUdpPort = configuration.LogToUdpPort, LogToUdpAddress = configuration.LogToUdpAddress, }); this.loraDeviceInfoManager.FacadeServerUrl = configuration.FacadeServerUrl; this.loraDeviceInfoManager.FacadeAuthCode = configuration.FacadeAuthCode; } } catch (Exception ex) { Logger.Log($"Initialization failed with error: {ex.Message}", Logger.LoggingLevel.Error); throw ex; } }
static async Task <int> MainAsync() { Console.WriteLine("SimulatedTemperatureSensor Main() started."); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); messageDelay = configuration.GetValue("MessageDelay", TimeSpan.FromSeconds(5)); int messageCount = configuration.GetValue(MessageCountConfigKey, 500); var simulatorParameters = new SimulatorParameters { MachineTempMin = configuration.GetValue <double>("machineTempMin", 21), MachineTempMax = configuration.GetValue <double>("machineTempMax", 100), MachinePressureMin = configuration.GetValue <double>("machinePressureMin", 1), MachinePressureMax = configuration.GetValue <double>("machinePressureMax", 10), AmbientTemp = configuration.GetValue <double>("ambientTemp", 21), HumidityPercent = configuration.GetValue("ambientHumidity", 25) }; Console.WriteLine( $"Initializing simulated temperature 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)."); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); ModuleClient moduleClient = await CreateModuleClientAsync( transportType, DefaultTimeoutErrorDetectionStrategy, DefaultTransientRetryStrategy); await moduleClient.OpenAsync(); await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); Twin currentTwinProperties = await moduleClient.GetTwinAsync(); if (currentTwinProperties.Properties.Desired.Contains(SendIntervalConfigKey)) { messageDelay = TimeSpan.FromSeconds((int)currentTwinProperties.Properties.Desired[SendIntervalConfigKey]); } if (currentTwinProperties.Properties.Desired.Contains(SendDataConfigKey)) { sendData = (bool)currentTwinProperties.Properties.Desired[SendDataConfigKey]; if (!sendData) { Console.WriteLine("Sending data disabled. Change twin configuration to start sending again."); } } ModuleClient userContext = moduleClient; await moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdated, userContext); await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext); 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); }
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}."); } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { _deviceId = System.Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID"); _moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID"); Console.WriteLine(); Console.WriteLine(" _ _ _ _ _ _ __ _ "); Console.WriteLine(" (_)___| |_ ___ ___ __| |__ _ ___ ___| |__ ___ ___ _ _| (_)/ _| |_ "); Console.WriteLine(" | / _ \\ _|___/ -_) _` / _` / -_)___| '_ \\/ -_) -_) '_| | | _| _|"); Console.WriteLine(" |_\\___/\\__| \\___\\__,_\\__, \\___| |_.__/\\___\\___|_| |_|_|_| \\__|"); Console.WriteLine(" |___/ "); Console.WriteLine(); Console.WriteLine(" Copyright © 2020 - josa josa josa"); Console.WriteLine(" "); 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); Console.WriteLine("Device twin initialized."); await ioTHubModuleClient.OpenAsync(); Console.WriteLine($"Module '{_deviceId}'-'{_moduleId}' initialized."); Console.WriteLine("Attached routing output: output1."); //// Initialize GPIO _controller = new GpioController(); _controller.OpenPin(UpRelayPin, PinMode.Output); _controller.OpenPin(DownRelayPin, PinMode.Output); _controller.OpenPin(FloodedPin, PinMode.Input); _controller.Write(UpRelayPin, PinValue.High); //by default high _controller.Write(DownRelayPin, PinValue.High); //by default high Console.WriteLine("Default GPIO relays Initialized."); //// Direct methods await ioTHubModuleClient.SetMethodHandlerAsync( "Up", UpMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: Up."); await ioTHubModuleClient.SetMethodHandlerAsync( "Down", DownMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: Down."); await ioTHubModuleClient.SetMethodHandlerAsync( "Ambiant", AmbiantValuesMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: Ambiant."); await ioTHubModuleClient.SetMethodHandlerAsync( "Circus", CircusMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: Circus."); await ioTHubModuleClient.SetMethodHandlerAsync( "Advertise", AdvertiseMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: Advertise."); await ioTHubModuleClient.SetMethodHandlerAsync( "FindEmptySlot", FindEmptySlotMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: FindEmptySlot."); await ioTHubModuleClient.SetMethodHandlerAsync( "MarkPosition", MarkPositionMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: MarkPosition."); await ioTHubModuleClient.SetMethodHandlerAsync( "BottleHolders", BottleHoldersMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: BottleHolders."); await ioTHubModuleClient.SetMethodHandlerAsync( "Roulette", RouletteMethodCallBack, ioTHubModuleClient); Console.WriteLine("Attached method handler: Roulette."); SetupI2CRead(); SetupI2CWrite(); //// start reading beer state if (_mcp23xxxRead != null) { var thread = new Thread(() => ThreadBody(ioTHubModuleClient)); thread.Start(); } if (_liftState == LiftState.Unknown) { // move the lift down (initial state) in case of 'unknown' state await DownMethodCallBack(null, ioTHubModuleClient); } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { _deviceId = System.Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID"); _moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID"); Console.WriteLine(" _ ___ _____ ___ _"); Console.WriteLine(" /_\\ ___ _ _ _ _ ___ |_ _| ___|_ _| | __| __| | __ _ ___ "); Console.WriteLine(" / _ \\ |_ /| || || '_|/ -_) | | / _ \\ | | | _| / _` |/ _` |/ -_)"); Console.WriteLine(" /_/ \\_\\/__| \\_,_||_| \\___| |___|\\___/ |_| |___|\\__,_|\\__, |\\___|"); Console.WriteLine(" |___/"); Console.WriteLine(" _____ _ __ _ "); Console.WriteLine(" |_ _| _ () _ __| |/ _|_ _(_) "); Console.WriteLine(" | || '_/ _` / _` | _| '_| | "); Console.WriteLine(" |_||_| \\__,_\\__,_|_| |_| |_| "); Console.WriteLine(" "); Console.WriteLine(" Copyright © 2019-2020 - IoT Edge Foundation"); Console.WriteLine(" "); Console.WriteLine($".Net framework version '{Environment.GetEnvironmentVariable("DOTNET_VERSION")}' in use"); MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); ITransportSettings[] settings = { mqttSetting }; // Open a connection to the Edge runtime _ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); // 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); await _ioTHubModuleClient.OpenAsync(); Console.WriteLine($"Module '{_deviceId}'-'{_moduleId}' initialized"); Console.WriteLine("Attached routing output: output1"); //// assign direct method handlers await _ioTHubModuleClient.SetMethodHandlerAsync( "generateAppSecret", GenerateAppSecretMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: generateAppSecret"); await _ioTHubModuleClient.SetMethodHandlerAsync( "collectInformation", collectInformationMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: collectInformation"); await _ioTHubModuleClient.SetMethodHandlerAsync( "reboot", RebootMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: reboot"); await _ioTHubModuleClient.SetMethodHandlerAsync( "reconnect", ReconnectMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: reconnect"); await _ioTHubModuleClient.SetMethodHandlerAsync( "setLight", SetLightMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: setLight"); await _ioTHubModuleClient.SetMethodHandlerAsync( "setOutlet", SetOutletMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: setOutlet"); await _ioTHubModuleClient.SetMethodHandlerAsync( "setGroup", SetGroupMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: setGroup"); await _ioTHubModuleClient.SetMethodHandlerAsync( "getGatewayInfo", GetGatewayInfoMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: getGatewayInfo"); await _ioTHubModuleClient.SetMethodHandlerAsync( "collectBatteryPower", CollectBatteryPowerMethodCallBack, _ioTHubModuleClient); Console.WriteLine("Attached method handler: collectBatteryPower"); var thread = new Thread(() => ThreadBody(_ioTHubModuleClient)); thread.Start(); }