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

            var state = new IoTEdgeModuleState()
            {
                ConnectionString       = connectionString,
                BypassCertVerification = bypassCertVerification,
            };


            // open connection to edge
            var ioTHubModuleClient = await state.CreateAndOpenClient();

            if (ioTHubModuleClient == null)
            {
                Logger.Error($"Could not connect to {state.ConnectionString}. Aborting");
            }
            Logger.Log($"IoT Hub module client initialized.");

            await ioTHubModuleClient.SetMethodHandlerAsync("middlewarestatus", HandleStatusMethod, null);

            Logger.Log($"Setup handing for method 'status'");

            // Attach callback for Twin desired properties updates
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null);

            Logger.Log($"Setup desired property update handler");

            var twin = await ioTHubModuleClient.GetTwinAsync();

            if (twin.Properties?.Desired?.Count > 0)
            {
                Logger.Log($"Twin desired has {twin.Properties?.Desired?.Count ?? 0} properties");
                UpdateThreshold(twin.Properties.Desired);
            }

            // Resolve output name
            outputName = Environment.GetEnvironmentVariable("OutputName");
            if (string.IsNullOrEmpty(outputName))
            {
                outputName = "middlewareoutput";
            }
            ;
            Logger.Log($"IoT Hub module is outputting message '{outputName}'.");

            // Register callback to be called when a message is received by the module
            var inputName = Environment.GetEnvironmentVariable("InputName");

            if (string.IsNullOrEmpty(inputName))
            {
                inputName = "sensor";
            }
            ;
            await ioTHubModuleClient.SetInputMessageHandlerAsync(inputName, HandleInputMessages, ioTHubModuleClient);

            Logger.Log($"IoT Hub module is listening for input messages on '{inputName}'.");



            return(state);
        }