Azure IotHub模块的双属性更改检测

时间:2019-09-04 23:32:07

标签: c# azure azure-iot-hub

我有一个 Azure IOThub ,其中包含一个边缘设备。在此边缘设备中,我有多个模块正在运行,并且可以通过使用其连接字符串连接到任何单个模块来更改其孪生属性

现在,我希望模块在更改其twin属性时执行某些操作,但是该模块无权访问其连接字符串,并且不应该访问该模块,因为它不需要连接至自身。

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

我已按照本教程进行操作,但这使用连接字符串来检测更改: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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在Visual Studio Code中创建新模块时,它将为您生成一个模板模块,该模板模块将向您展示其完成方式。我将在下面添加重要的内容:

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 =等待   ModuleClient.CreateFromEnvironmentAsync(settings);

this Microsoft tutorial上有一个很好的示例,该示例还涵盖了监听Twin更新。