/// <summary>
        /// Initializes the ModuleClient.
        /// </summary>
        static void Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only)
            {
                RemoteCertificateValidationCallback =
                    (sender, certificate, chain, sslPolicyErrors) => true
            };

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            var mcTask = ModuleClient.CreateFromEnvironmentAsync(settings);

            mcTask.Wait();
            s_moduleClient = mcTask.Result;
            s_moduleClient.OpenAsync().Wait();


            // Read configuration from Module Twin
            Task <Twin> twinTask = s_moduleClient.GetTwinAsync();

            twinTask.Wait();
            Twin twin = twinTask.Result;

            OnDesiredPropertiesUpdate(twin.Properties.Desired, null);
            s_moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

            Console.WriteLine("IoT Hub module client initialized.");
        }
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await ioTHubModuleClient.OpenAsync();

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

            // Read the TemperatureThreshold value from the module twin's desired properties
            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient);

            // Attach a callback for updates to the module twin's desired properties.
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

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

            InitFileWatcher();

            DisplayImage(logoImagePath);

            Console.WriteLine("Successfully initialized ScreenshotWatcher module.");
        }
Example #3
0
        static async Task <ModuleClient> InitializeModuleClientAsync(TransportType transportType, ILogger logger)
        {
            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();
            WriteLog(logger, LogLevel.Information, $"Trying to initialize module client using transport type [{transportType}].");
            ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await moduleClient.OpenAsync();

            WriteLog(logger, LogLevel.Information, $"Successfully initialized module client of transport type [{transportType}].");
            return(moduleClient);
        }
Example #4
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task  InitEdgeModule()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            /*  AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);
             * ITransportSettings[] settings = { amqpSetting };*/

            // Open a connection to the Edge runtime
            ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await ioTHubModuleClient.OpenAsync();

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

            // Read Module Twin Desired Properties
            Console.WriteLine("Reading module Twin from IoT Hub.");
            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            // Parse Twin Json and initialize gateway
            Console.WriteLine("Starting Gateway controller handler process.");
            ServiceBusClientModel gatewayConfigModel = ServiceBusClientModel.InitClientModel(moduleTwin.Properties.Desired);

            serviceBusClient = ServiceBusClient.Init(gatewayConfigModel, ioTHubModuleClient);


            // Attach callback for Twin desired properties updates
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);
        }
Example #5
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.");

            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            var moduleTwinCollection = moduleTwin.Properties.Desired;

            desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection);

            // callback for updating desired properties through the portal or rest api
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

            // this direct method will allow to reset the temperature sensor values back to their initial state
            //await ioTHubModuleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

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

            // as this runs in a loop we don't await
            await SendSimulationData(ioTHubModuleClient);

            Console.WriteLine("Simulating data...");
        }
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings).ConfigureAwait(false);

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

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

            // Read the TemperatureThreshold value from the module twin's desired properties
            var moduleTwin = await ioTHubModuleClient.GetTwinAsync().ConfigureAwait(false);

            await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient);

            // Attach a callback for updates to the module twin's desired properties.
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null).ConfigureAwait(false);

            // Register a callback for messages that are received by the module.
            await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterMessagesAsync, ioTHubModuleClient).ConfigureAwait(false);

            await ioTHubModuleClient.SetMethodHandlerAsync(heartbeat, HeartbeatAsync, null).ConfigureAwait(false);

            Console.WriteLine("Set Heartbeat Method Handler:HeartbeatAsync.");
        }
Example #7
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);
        }
Example #8
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);
        }
        /// <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();
        }
Example #10
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
        }
Example #11
0
        async Task <ModuleClient> CreateModuleClient()
        {
            ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(TransportType.Mqtt_Tcp_Only);

            moduleClient.ProductInfo = "Microsoft.Azure.WebJobs.Extensions.EdgeHub";
            return(moduleClient);
        }
Example #12
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task InitAsync()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            var ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

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

            Logger.LogInfo("IoT Hub module client initialized.");

            alertProcessor = new AlertProcessor(new ModuleClientWrapper(ioTHubModuleClient));

            // Register callback to be called when a message is received by the module
            await ioTHubModuleClient.SetInputMessageHandlerAsync("opc-ua", HandleMessage, ioTHubModuleClient).ConfigureAwait(false);

            var moduleTwin = await ioTHubModuleClient.GetTwinAsync().ConfigureAwait(false);

            await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient).ConfigureAwait(false);

            // Attach a callback for updates to the module twin's desired properties.
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null).ConfigureAwait(false);
        }
Example #13
0
        async Task <ModuleClient> CreateModuleClient()
        {
            ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync().ConfigureAwait(false);

            moduleClient.ProductInfo = "Microsoft.Azure.Devices.Edge.Functions.Binding";
            return(moduleClient);
        }
Example #14
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();
        }
Example #15
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;
        }
Example #16
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);
        }
Example #17
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();
        }
Example #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 };

            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);
        }
Example #19
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");
            await CreateEventGridTopicAsync();
        }
        /// <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);
        }
Example #21
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));
        }
        /// <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);
        }
Example #23
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.");

            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            var moduleTwinCollection = moduleTwin.Properties.Desired;

            Console.WriteLine("Got Device Twin configuration.");
            desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection);

            // callback for updating desired properties through the portal or rest api
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

            await ioTHubModuleClient.SetMethodHandlerAsync("capture", CaptureMethod, ioTHubModuleClient);
        }
Example #24
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);
        }
Example #25
0
        public async Task <EdgeGatewayConfiguration> GetModuleConfigAsync()
        {
            ModuleClient client = await ModuleClient.CreateFromEnvironmentAsync();

            await client.OpenAsync();

            Twin twin = await client.GetTwinAsync();

            TwinCollection collection = twin.Properties.Desired;

            if (!collection.Contains("luss") || !collection.Contains("serviceUrl"))
            {
                Console.WriteLine("Twin has no luss property");
                return(null);
            }

            string luss       = collection["luss"];
            string serviceUrl = collection["serviceUrl"];

            if (string.IsNullOrEmpty(luss) || string.IsNullOrEmpty(serviceUrl))
            {
                Console.WriteLine("Twin has empty luss");
                return(null);
            }

            return(await GetConfigurationAsync(luss, serviceUrl));
        }
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            IoTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await IoTHubModuleClient.OpenAsync();

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

            // 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();
        }
Example #27
0
        static async Task <ModuleClient> 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);

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

            await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

            Console.WriteLine("Successfully initialized module client.");
            return(moduleClient);
        }
Example #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("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);
        }
Example #29
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 };

            // Retrieve storage account from connection string.
            var storageAccountName      = Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_NAME");
            var storageAccountKey       = Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_KEY");
            var storageConnectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}";

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            // Create the blob client.
            Console.WriteLine("Creating blob client");
            blobClient = storageAccount.CreateCloudBlobClient();

            // Open a connection to the Edge runtime
            ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await ioTHubModuleClient.OpenAsync();

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

            await ioTHubModuleClient.SetInputMessageHandlerAsync("messagesToUpload", UploadMessage, ioTHubModuleClient);

            await ioTHubModuleClient.SetMethodHandlerAsync("HearBeat", HeartBeat, null);

            Console.WriteLine("Set Heartbeat Method Handler:HeartBeat.");
        }
Example #30
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);
        }