Azure Iot Hub 模块孪生 属性 变化检测

Azure IotHub Module's twin property change detection

我有一个包含一个边缘设备的 Azure IOThub。在这个边缘设备中,我有几个模块 运行,我可以通过 连接来更改任何单个模块的 双胞胎 属性字符串.

现在我希望模块在双胞胎 属性 发生更改时执行某些操作,但模块无法访问它的连接字符串并且它不应该这样做,因为它不需要连接到本身。

模块如何在没有连接字符串的情况下检测到它的孪生 属性 变化?

我已按照本教程进行操作,但它使用连接字符串来检测更改:https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-module-twin-getstarted#create-a-module-identity

这是此模块的代码:

using System;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace DataSyncService
{

    class Program
    {

        private const string ModuleConnectionString = "CONNECTION STRING";
        private static ModuleClient Client = null;
        static void ConnectionStatusChangeHandler(ConnectionStatus status,
                                                  ConnectionStatusChangeReason reason)
        {
            Console.WriteLine("Connection Status Changed to {0}; the reason is {1}",
                status, reason);
        }

        static void Main(string[] args)
        {
            Microsoft.Azure.Devices.Client.TransportType transport =
                Microsoft.Azure.Devices.Client.TransportType.Amqp;

            try
            {
                Client =
                    ModuleClient.CreateFromConnectionString(ModuleConnectionString, transport);
                Client.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler);
                // I want to set this callback but this requires a client and the client requires
                // a connection string.    
                Client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).Wait();

                Console.WriteLine("Retrieving twin");
                var twinTask = Client.GetTwinAsync();
                twinTask.Wait();
                var twin = twinTask.Result;
                Console.WriteLine(JsonConvert.SerializeObject(twin.Properties));

                Console.WriteLine("Sending app start time as reported property");
                TwinCollection reportedProperties = new TwinCollection();
                reportedProperties["DateTimeLastAppLaunch"] = DateTime.Now;

                Client.UpdateReportedPropertiesAsync(reportedProperties);
            }
            catch (AggregateException ex)
            {
                Console.WriteLine("Error in sample: {0}", ex);
            }

            Console.WriteLine("Waiting for Events.  Press enter to exit...");
            Console.ReadLine();
            Client.CloseAsync().Wait();
        }

        private static async Task OnDesiredPropertyChanged(TwinCollection desiredProperties,
                                                           object userContext)
        {
            Console.WriteLine("desired property change:");
            Console.WriteLine(JsonConvert.SerializeObject(desiredProperties));
            Console.WriteLine("Sending current time as reported property");
            TwinCollection reportedProperties = new TwinCollection
                                                    {
                                                        ["DateTimeLastDesiredPropertyChangeReceived"] = DateTime.Now
                                                    };

            await Client.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false);
        }
    }
}

当您在 Visual Studio 代码中创建新模块时,它会为您生成一个模板模块,向您展示它是如何完成的。我将在下面包括重要的一点:

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

之所以如此,是因为 Azure IoT Edge 运行时会将模块创建为 Docker 容器,并将连接设置作为环境变量。当您调用

时,模块客户端使用这些变量连接到 IoT 中心

ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

this Microsoft tutorial 上有一个很好的示例,其中还包括侦听双胞胎更新。