Exemplo n.º 1
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);
        }
        public void NotSettingPnpModelIdShouldNotSetModelIdOnConnectPacket()
        {
            // arrange
            string ModelIdParam           = "model-id";
            var    passwordProvider       = new Mock <IAuthorizationProvider>();
            var    mqttIotHubEventHandler = new Mock <IMqttIotHubEventHandler>();
            var    mqttTransportSetting   = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
            var    productInfo            = new ProductInfo();
            var    options = new ClientOptions();
            var    channelHandlerContext = new Mock <IChannelHandlerContext>();
            var    mqttIotHubAdapter     = new MqttIotHubAdapter("deviceId", string.Empty, string.Empty, passwordProvider.Object, mqttTransportSetting, null, mqttIotHubEventHandler.Object, productInfo, options);

            // Save all the messages from the context
            var messages = new List <object>();

            channelHandlerContext.Setup(context => context.WriteAndFlushAsync(It.IsAny <object>())).Callback((object message) => messages.Add(message)).Returns(TaskHelpers.CompletedTask);

            // Act
            channelHandlerContext.SetupGet(context => context.Handler).Returns(mqttIotHubAdapter);
            mqttIotHubAdapter.ChannelActive(channelHandlerContext.Object);

            // Assert: the username should use the GA API version and not have the model ID appended
            ConnectPacket       connectPacket = messages.First().As <ConnectPacket>();
            NameValueCollection queryParams   = ExtractQueryParamsFromConnectUsername(connectPacket.Username);

            Assert.IsFalse(queryParams.AllKeys.Contains(ModelIdParam));
        }
Exemplo n.º 3
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.");
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, 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("DHT Edge module client initialized.");

            var thread = new Thread(() => ThreadBody(ioTHubModuleClient));

            thread.Start();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            _deviceClient = DeviceClient.CreateFromConnectionString(connectionString, settings);
            await _deviceClient.OpenAsync();

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

            _mqttClient.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            _mqttClient.Connect("BC01");

            if (_mqttClient.IsConnected)
            {
                _mqttClient.Subscribe(new string[] { "#" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
                Console.WriteLine("MQTT connected");
            }
        }
Exemplo n.º 6
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();
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 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 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);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, 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);

            timer.Elapsed += new System.Timers.ElapsedEventHandler((s, e) => OnTimedEvent(s, e, ioTHubModuleClient));
            timer.Start();
        }
Exemplo n.º 10
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.º 11
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.º 12
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, 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);
            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            var moduleTwinCollection = moduleTwin.Properties.Desired;
            // 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", PacketForwarderHostMessages, ioTHubModuleClient);

            // Direct method handler to reset (recycle) the packet forwarder
            //await ioTHubModuleClient.SetMethodHandlerAsync("Reset", resetHandler, packetForwarderProcess);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, 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;

            if (moduleTwinCollection["TemperatureThreshold"] != null)
            {
                temperatureThreshold = moduleTwinCollection["TemperatureThreshold"];
            }

            // 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);

            var timer = new System.Timers.Timer(5000);

            timer.Elapsed += async(sender, e) => {
                // read the log file
                try
                {
                    using (StreamReader sr = new StreamReader("/var/log/messages"))
                    {
                        String line = sr.ReadToEnd();
                        moduleTwinCollection["logs"] = line;
                        await ioTHubModuleClient.UpdateReportedPropertiesAsync(moduleTwinCollection);

                        Console.WriteLine(line);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Issue with reading the file");
                    Console.WriteLine(ex.Message);
                }
            };
        }
Exemplo n.º 14
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
        }
        /// <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
            grovePiPlus           = new GrovePiPlus(1);
            ledButtonDevice       = new GrovePiPlusBlueLEDButton(grovePiPlus, 4, 5);
            barometerSensorDevice = new BarometerBME280(1);
            barometerSensorDevice.Initialize();
#if USE_LIGHT_SENSE
            lightSensor = new GrovePiLightSensor(grovePiPlus, 0);
#endif
#if USE_CO2_SENSE
            co2Sensor = new CO2SensorMHZ19B();
#endif
            Console.WriteLine("Sensing Device Initialized");

            iotHubConnector     = new ModuleClientConnector(settings, "command-input", "telemetry-output");
            sensingDeviceClient = new EnvironmentSensingDeviceClient(iotHubConnector, barometerSensorDevice, ledButtonDevice, lightSensor, co2Sensor);

            var tokenSource = new CancellationTokenSource();
            var ct          = tokenSource.Token;
            await sensingDeviceClient.Initialize(ct);

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

            // 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);
        }
        /// <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.º 18
0
        static ITransportSettings[] GetMqttTransportSettings(TransportType type, Option <IWebProxy> proxy)
        {
            var settings = new MqttTransportSettings(type);

            proxy.ForEach(p => settings.Proxy = p);
            return(new ITransportSettings[] { settings });
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings);

            ioTHubModuleClient.ReceiveAsync(TimeSpan.FromSeconds(2)).Wait();
            //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);

            // 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);
        }
Exemplo n.º 20
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.º 21
0
        static public async Task InitDeviceClient()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // DEV only! bypass certs validation
            mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            ITransportSettings[] settings = { mqttSetting };

            deviceClient = DeviceClient.CreateFromConnectionString(iotDeviceConnectionString, settings);
            await deviceClient.OpenAsync();

            Console.WriteLine($"Connected to IoT Hub with connection string [{iotDeviceConnectionString}]");

            //read twin  setting upon first load
            var twin = await deviceClient.GetTwinAsync();

            await onDesiredPropertiesUpdate(twin.Properties.Desired, deviceClient);

            //register for Twin desiredProperties changes
            await deviceClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null);

            //callback for generic direct method calls
            //todo change the callback to actual method name and finalize callback implementation
            deviceClient.SetMethodHandlerAsync("WriteBack", SwitchOff, null).Wait();
        }
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
            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.º 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
            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.º 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);

            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);
        }
        private async Task SendRequestAndAcksInSpecificOrderAsync <T>(T requestPacket, Func <T, PacketWithId> ackFactory, bool receiveResponseBeforeSendingRequestContinues)
        {
            var passwordProvider       = new Mock <IAuthorizationProvider>();
            var mqttIotHubEventHandler = new Mock <IMqttIotHubEventHandler>();
            var productInfo            = new ProductInfo();
            var options = new ClientOptions();
            var mqttTransportSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only)
            {
                HasWill = false
            };
            var channelHandlerContext = new Mock <IChannelHandlerContext>();

            var mqttIotHubAdapter = new MqttIotHubAdapter(
                "deviceId",
                string.Empty,
                string.Empty,
                passwordProvider.Object,
                mqttTransportSetting,
                null,
                mqttIotHubEventHandler.Object,
                productInfo,
                options);

            // Setup internal state to be "Connected". Only then can we manage subscriptions
            // "NotConnected" -> (ChannelActive) -> "Connecting" -> (ChannelRead ConnAck) -> "Connected".
            channelHandlerContext
            .Setup(context => context.Channel.EventLoop.ScheduleAsync(It.IsAny <Action>(), It.IsAny <TimeSpan>()))
            .Returns(TaskHelpers.CompletedTask);
            channelHandlerContext.SetupGet(context => context.Handler).Returns(mqttIotHubAdapter);
            mqttIotHubAdapter.ChannelActive(channelHandlerContext.Object);
            mqttIotHubAdapter.ChannelRead(channelHandlerContext.Object, new ConnAckPacket {
                ReturnCode = ConnectReturnCode.Accepted, SessionPresent = false
            });

            // Setup sending of a Packet so that the matching response is received before sending task is completed.
            var    startRequest = new TaskCompletionSource <T>();
            Action sendResponse = async() =>
            {
                var response = ackFactory(await startRequest.Task.ConfigureAwait(false));
                mqttIotHubAdapter.ChannelRead(channelHandlerContext.Object, response);
            };

            channelHandlerContext.Setup(context => context.WriteAndFlushAsync(It.IsAny <T>()))
            .Callback <object>((packet) => startRequest.SetResult((T)packet))
            .Returns(receiveResponseBeforeSendingRequestContinues
                    ? Task.Run(sendResponse)
                    : TaskHelpers.CompletedTask);

            // Act:
            // Send the request (and response if not done as mocked "sending" task) packets
            var sendRequest = mqttIotHubAdapter.WriteAsync(channelHandlerContext.Object, requestPacket);

            if (!receiveResponseBeforeSendingRequestContinues)
            {
                sendResponse();
            }

            // Assert: No matter the event ordering, sending should be awaitable without errors
            await sendRequest.ConfigureAwait(false);
        }
        public async Task Start()
        {
            try
            {  
              var connectionString = Environment.GetEnvironmentVariable("EdgeHubConnectionString");
              Console.WriteLine("Connection String {0}", connectionString);

              var bypassCertVerification = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

              var mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
              // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
              if (bypassCertVerification)
              {
                  mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
              }
              ITransportSettings[] settings = { mqttSetting };

              // Open a connection to the Edge runtime

              Console.WriteLine("Setting up device client");
              var ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings);
              await ioTHubModuleClient.OpenAsync();

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

              Console.WriteLine("Add device ingestion input");
              await ioTHubModuleClient.SetInputMessageHandlerAsync("DeviceIngestion", MessageReceived, ioTHubModuleClient);

              Console.WriteLine("Add vessel orientation input");
              await ioTHubModuleClient.SetInputMessageHandlerAsync("VesselOrientation", VesselOrientationMessageReceived, ioTHubModuleClient); }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception : {ex.Message} - {ex.StackTrace}");
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task <DeviceClient> Init(string connectionString, Options options, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            TransportType transportProtocol = TransportType.Mqtt_Tcp_Only;

            if (!String.IsNullOrEmpty(options.IoTHubProtocol))
            {
                transportProtocol = (TransportType)Enum.Parse(typeof(TransportType), options.IoTHubProtocol);
            }
            MqttTransportSettings mqttSetting = new MqttTransportSettings(transportProtocol);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings);
            await ioTHubModuleClient.OpenAsync();

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

            return(ioTHubModuleClient);
        }
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.");

            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;
        }
        public void TestAuthenticationChain()
        {
            const string authChain              = "leaf;edge1;edge2";
            var          passwordProvider       = new Mock <IAuthorizationProvider>();
            var          mqttIotHubEventHandler = new Mock <IMqttIotHubEventHandler>();
            var          productInfo            = new ProductInfo();
            var          mqttTransportSetting   = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only)
            {
                HasWill = false
            };
            var channelHandlerContext = new Mock <IChannelHandlerContext>();
            var mqttIotHubAdapter     = new MqttIotHubAdapter("deviceId", string.Empty, string.Empty, passwordProvider.Object, mqttTransportSetting, null, mqttIotHubEventHandler.Object, productInfo);

            // Set an authchain on the transport settings
            mqttTransportSetting.AuthenticationChain = authChain;

            // Save all the messages from the context
            List <object> messages = new List <object>();

            channelHandlerContext.Setup(context => context.WriteAndFlushAsync(It.IsAny <object>())).Callback((object message) => messages.Add(message)).Returns(TaskHelpers.CompletedTask);

            // Act
            channelHandlerContext.Setup(context => context.Channel.EventLoop.ScheduleAsync(It.IsAny <Action>(), It.IsAny <TimeSpan>())).Returns(TaskHelpers.CompletedTask);
            channelHandlerContext.SetupGet(context => context.Handler).Returns(mqttIotHubAdapter);
            mqttIotHubAdapter.ChannelActive(channelHandlerContext.Object);

            // Assert: the auth chain should be part of the username
            ConnectPacket       connectPacket = messages.First().As <ConnectPacket>();
            NameValueCollection queryParams   = System.Web.HttpUtility.ParseQueryString(connectPacket.Username);

            Assert.AreEqual(authChain, queryParams.Get("auth-chain"));
        }
Exemplo n.º 30
0
        private ITransportSettings GetTransportSettings()
        {
            ITransportSettings transportSettings;

            switch (this.deviceRunnerConfiguration.Protocol)
            {
            case "mqtt":
                transportSettings = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
                break;

            default:
            {
                var amqp = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);

                if (this.deviceRunnerConfiguration.AmqpMultiplex)
                {
                    amqp.AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings()
                    {
                        Pooling = true,
                    };
                }
                transportSettings = amqp;
                break;
            }
            }

            return(transportSettings);
        }