Exemplo n.º 1
0
        static async Task <Tuple <ModuleClient, ModuleConfig> > InitModuleClient(TransportType transportType)
        {
            ITransportSettings[] GetTransportSettings()
            {
                switch (transportType)
                {
                case TransportType.Mqtt:
                case TransportType.Mqtt_Tcp_Only:
                case TransportType.Mqtt_WebSocket_Only:
                    return(new ITransportSettings[] { new MqttTransportSettings(transportType) });

                default:
                    return(new ITransportSettings[] { new AmqpTransportSettings(transportType) });
                }
            }

            ITransportSettings[] settings = GetTransportSettings();

            ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings).ConfigureAwait(false);

            await moduleClient.OpenAsync().ConfigureAwait(false);

            Console.WriteLine("TemperatureFilter - Opened module client connection");

            ModuleConfig moduleConfig = await GetConfiguration(moduleClient).ConfigureAwait(false);

            Console.WriteLine($"Using TemperatureThreshold value of {moduleConfig.TemperatureThreshold}");

            Console.WriteLine("Successfully initialized module client.");
            return(new Tuple <ModuleClient, ModuleConfig>(moduleClient, moduleConfig));
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (LogContext.PushProperty("FunctionId", nameof(StartAsync)))
            {
                Log.Information("Opening Edge Module Connection");
                await ModuleClient.OpenAsync();

                Log.Information("Initializing InfluxDBRecorder");
                await TimeSeriesRecorder.InitializeAsync();

                Log.Information("Beginning to Process Messages");
                await ModuleClient.SetInputMessageHandlerAsync("telemetry", new MessageHandler(
                                                                   async(message, e) =>
                {
                    Log.Information("Processing message..");
                    var telemetryJson = Encoding.UTF8.GetString(message.GetBytes());
                    try
                    {
                        await TimeSeriesRecorder.RecordMessageAsync(telemetryJson);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, $"Error for message {telemetryJson}");
                    }
                    return(await Task.FromResult(MessageResponse.Completed));
                }
                                                                   ), ModuleClient);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            // create client instance
            try{
                MqttClient client = new MqttClient("localhost");
                // register to message received
                client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

                string clientId = Guid.NewGuid().ToString();
                client.Connect(clientId);
                // subscribe to the topic "/home/temperature" with QoS 2
                client.Subscribe(new string[] { "/messages" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot connect to MQTT broker");
                Console.WriteLine("Exception: " + ex.Message + ex);
            }


            //init module client
            AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);

            ITransportSettings[] settings = { amqpSetting };
            moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await moduleClient.OpenAsync();
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(bool debug = false)
        {
#if DEBUG
            while (debug && !Debugger.IsAttached)
            {
                Console.WriteLine("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();

            Console.WriteLine("IoT Hub module client initialized.");

            // Register callback to be called when a message is received by the module
            await ioTHubModuleClient.SetInputMessageHandlerAsync("compressMessage", CompressMessage, ioTHubModuleClient);

            await ioTHubModuleClient.SetInputMessageHandlerAsync("decompressMessage", DecompressMessage, ioTHubModuleClient);
        }
Exemplo n.º 5
0
        static async Task InitModuleClient(TransportType transportType)
        {
            ITransportSettings[] GetTransportSettings()
            {
                switch (transportType)
                {
                case TransportType.Mqtt:
                case TransportType.Mqtt_Tcp_Only:
                case TransportType.Mqtt_WebSocket_Only:
                    return(new ITransportSettings[] { new MqttTransportSettings(transportType) });

                default:
                    return(new ITransportSettings[] { new AmqpTransportSettings(transportType) });
                }
            }

            ITransportSettings[] settings = GetTransportSettings();

            ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings).ConfigureAwait(false);

            await moduleClient.OpenAsync().ConfigureAwait(false);

            await moduleClient.SetMethodHandlerAsync("HelloWorldMethod", HelloWorldMethod, null).ConfigureAwait(false);

            Console.WriteLine("Successfully initialized module client.");
        }
Exemplo n.º 6
0
        /// <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("IoT Hub module client initialized.");

            // Get environment variables scoped for this module
            _edgeDeviceId    = Environment.GetEnvironmentVariable(DeviceIdVariableName);
            _edgeModuleId    = Environment.GetEnvironmentVariable(ModuleIdVariableName);
            _iothubHostName  = Environment.GetEnvironmentVariable(IotHubHostnameVariableName);
            _gatewayHostName = Environment.GetEnvironmentVariable(GatewayHostnameVariableName);

            // Initialize leaf device cache
            _leafDevices = new MemoryDeviceRepository();

            // Register callback to be called when a message is received by the module
            await ioTHubModuleClient.SetMethodHandlerAsync(ItmCallbackMethodName, DeviceRegistered, ioTHubModuleClient);

            await ioTHubModuleClient.SetInputMessageHandlerAsync(ItmMessageInputName, PipeMessage, ioTHubModuleClient);
        }
Exemplo n.º 8
0
        private void InitializeClient()
        {
            // If the client reports Connected status, it is already in operational state.
            if (s_connectionStatus != ConnectionStatus.Connected &&
                _moduleConnectionStrings.Any())
            {
                lock (_initLock)
                {
                    _logger.LogDebug($"Attempting to initialize the client instance, current status={s_connectionStatus}");

                    // If the module client instance has been previously initialized, then dispose it.
                    // The s_wasEverConnected variable is required to store if the client ever reported Connected status.
                    if (s_wasEverConnected && s_connectionStatus == ConnectionStatus.Disconnected)
                    {
                        s_moduleClient?.Dispose();
                        s_wasEverConnected = false;
                    }

                    s_moduleClient = ModuleClient.CreateFromConnectionString(_moduleConnectionStrings.First(), _transportType);
                    s_moduleClient.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler);
                    s_moduleClient.OperationTimeoutInMilliseconds = (uint)s_operationTimeout.TotalMilliseconds;
                }

                try
                {
                    // Force connection now
                    s_moduleClient.OpenAsync().GetAwaiter().GetResult();
                    _logger.LogDebug($"Initialized the client instance.");
                }
                catch (UnauthorizedException)
                {
                    // Handled by the ConnectionStatusChangeHandler
                }
            }
        }
Exemplo n.º 9
0
        /// <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);
        }
Exemplo n.º 10
0
        static async Task CallDirectMethodAsync()
        {
            try
            {
                var varEnvs = System.Environment.GetEnvironmentVariables();
                foreach (System.Collections.DictionaryEntry varEnv in varEnvs)
                {
                    Console.WriteLine($"Variable: key '{varEnv.Key}', value '{varEnv.Value}'");
                }

                var deviceId = System.Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
                Console.WriteLine($"deviceId: {deviceId}");

                // MethodRequest request = new MethodRequest("MethodA", Encoding.UTF8.GetBytes("{ \"Message\": \"Hello\" }"));
                string        message = "{ \"TimeOut_mns\": " + timeOut_mns.ToString() + " }";
                MethodRequest request = new MethodRequest("NotifyTimeOut", Encoding.UTF8.GetBytes(message));

                MqttTransportSettings mqttSetting        = new MqttTransportSettings(Microsoft.Azure.Devices.Client.TransportType.Mqtt_Tcp_Only);
                ITransportSettings[]  settings           = { mqttSetting };
                ModuleClient          ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

                await ioTHubModuleClient.OpenAsync();

                var response = await ioTHubModuleClient.InvokeMethodAsync(deviceId, "MQTTClientModule", request).ConfigureAwait(false);

                Console.WriteLine($"Received response with status {response.Status}");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine($"Error : {ex.Message}");
            }
        }
Exemplo n.º 11
0
        /// <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);
        }
Exemplo n.º 12
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);

            httpClient = new HttpClient
            {
                BaseAddress = new Uri(Environment.GetEnvironmentVariable("LOCAL_EVENT_GRID_URI"))
            };

            httpClient.DefaultRequestHeaders.Add("aeg-sas-key", Environment.GetEnvironmentVariable("EVENT_GRID_SAS_KEY"));

            topicName            = Environment.GetEnvironmentVariable("TOPIC_NAME");
            enpointUrl           = Environment.GetEnvironmentVariable("WEBHOOK_URL");
            edgeHubOutputName    = Environment.GetEnvironmentVariable("EDGEHUB_OUTPUT_NAME");
            cloudEventGridSasKey = Environment.GetEnvironmentVariable("CLOUD_EVENTGRID_SAS_KEY");
            //cloudEventGridTopicName = Environment.GetEnvironmentVariable("CLOUD_EVENTGRID_TOPIC");
            cloudEventGridEnpointUrl = Environment.GetEnvironmentVariable("CLOUD_EVENTGRID_ENDPOINT");

            await CreateEventGridWebHookSubscriptionAsync();
            await CreateEventGridEdgeHubSubscriptionAsync();
            await CreateCloudEventGridSubscriptionAsync();
        }
Exemplo n.º 13
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.SetImputMessageHandlerAsync("input1", PipeMessage, iotHubModuleClient);

            // Read TemperatureThreshold from Module Twin 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 callback for Twin desired properties updates
            //await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null);

            // Register callback to be called when a message is received by the module
            await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterMessages, ioTHubModuleClient);

            Console.WriteLine("Done setting up callbacks.");
        }
Exemplo n.º 14
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.");

            // 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.");
        }
Exemplo n.º 15
0
        static async Task <int> MainAsync()
        {
            Logger.LogInformation("DirectMethodReceiver Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("config/appsettings.json", optional: true)
                                           .AddEnvironmentVariables()
                                           .Build();

            TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);
            ModuleClient  moduleClient  = await ModuleUtil.CreateModuleClientAsync(
                transportType,
                ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                ModuleUtil.DefaultTransientRetryStrategy,
                Logger);

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null);

            await moduleClient.OpenAsync();

            await moduleClient.SetMethodHandlerAsync("HelloWorldMethod", HelloWorldMethodAsync, null, cts.Token);

            await cts.Token.WhenCanceled();

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("DirectMethodReceiver Main() finished.");
            return(0);
        }
        /// <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.");
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes the ModuleClient
        /// </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);

            // as this runs in a loop we don't await
            await SendData(ioTHubModuleClient);
        }
Exemplo n.º 18
0
        /// <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()
        {
            // the module client is in charge of sending messages in the context of this module (VehicleTelemetry)
            ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(TransportType.Mqtt);

            await ioTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            // Register callback to be called when a message is received by this module
            await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient);

            //the device client is responsible for managing device twin information at the device level
            //obtaining the device connection string is currently not supported by DeviceClient
            //TODO: 7 - set device connection string for the device client
            //ioTHubDeviceClient = DeviceClient.CreateFromConnectionString("<connectionstring>");
            await ioTHubDeviceClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdateAsync, null);

            var twin = await ioTHubDeviceClient.GetTwinAsync();

            var desired = twin.Properties.Desired;

            await UpdateReportedPropertiesFromDesired(desired);

            await GenerateMessage(ioTHubModuleClient);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

            Console.WriteLine($"{connectionString}");
            ContainerClient = new BlobContainerClient(connectionString, "samplecontainer");
            try
            {
                await ContainerClient.CreateIfNotExistsAsync();
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"{ex}");
            }

            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.");

#pragma warning disable 4014
            MainLoop(ioTHubModuleClient);
#pragma warning restore 4014
        }
Exemplo n.º 21
0
        public static async Task <TestModule> CreateAndConnect(string connectionString, ITransportSettings[] settings)
        {
            ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(connectionString, settings);
            await moduleClient.OpenAsync();

            return(new TestModule(moduleClient));
        }
Exemplo n.º 22
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.");

            // 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);
        }
Exemplo n.º 23
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
            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);

            //initialize Raspberry
            _raspberryPins = new Pins();
            _raspberryPins.ConnectGpio();
            _raspberryPins.LoopGpioPins();

            _paradox1738 = new Paradox1738();
            _paradox1738.ParadoxSecurity();
            _paradox1738.IRSensorsReading();

            //Receive Netatmo data
            _receiveNetatmoData = new ReceiveNetatmoData();
            _receiveNetatmoData.ReceiveData();

            //read from ome temperature sensors
            _homeTemperature = new HomeTemperature();
            _homeTemperature.ReadTemperature();

            //Starting schedulers
            _co2Scheduler = new Co2();
            _co2Scheduler.CheckCo2Async();

            _saunaHeating = new SaunaHeating();
            _saunaHeating.CheckHeatingTime();

            _heatingScheduler = new Heating();
            _heatingScheduler.ReduceHeatingSchedulerAsync();

            //Receive IoTHub commands
            _receiveData = new ReceiveData();
            _receiveData.ReceiveCommandsAsync();

            //query WiFiProbes
            _wiFiProbes = new WiFiProbes();
            _wiFiProbes.QueryWiFiProbes();

            //shelly's
            TelemetryDataClass.isOutsideLightsOn = await Shelly.GetShellyState(Shelly.OutsideLight);

            SomeoneAtHome.CheckLightStatuses();

            //Send data to IoTHub
            _sendData = new SendTelemetryData();
            _sendData.SendTelemetryEventsAsync();
        }
Exemplo n.º 24
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);

            // 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();
        }
Exemplo n.º 25
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("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);
        }
Exemplo n.º 26
0
        static async Task <ModuleClient> InitModuleClient(TransportType transportType)
        {
            ITransportSettings[] GetTransportSettings()
            {
                switch (transportType)
                {
                case TransportType.Mqtt:
                case TransportType.Mqtt_Tcp_Only:
                    return(new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) });

                case TransportType.Mqtt_WebSocket_Only:
                    return(new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_WebSocket_Only) });

                case TransportType.Amqp_WebSocket_Only:
                    return(new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_WebSocket_Only) });

                default:
                    return(new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) });
                }
            }

            ITransportSettings[] settings = GetTransportSettings();

            ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings).ConfigureAwait(false);

            await moduleClient.OpenAsync().ConfigureAwait(false);

            Log.Information("Successfully initialized module client.");
            return(moduleClient);
        }
Exemplo n.º 27
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.");

            var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");
            var containerName    = Environment.GetEnvironmentVariable("RESULT_CONTAINER_NAME");
            var storageAccount   = CloudStorageAccount.Parse(connectionString);
            var cloudBlobClient  = storageAccount.CreateCloudBlobClient();

            cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);
            await cloudBlobContainer.CreateIfNotExistsAsync();

            http = new HttpRouter(new string[] { "http://+:80/" });
            http.Register("/caption", SetCaption);
            http.Register("/video/start", StartRecording);
            http.Register("/video/end", EndRecording);
            http.Register("/photo", TakePhoto);
            http.Start();

            await Task.CompletedTask;
        }
Exemplo n.º 28
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.");


            // 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
            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.");
        }
Exemplo n.º 30
0
        /// <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);
        }