1. 程式人生 > 實用技巧 >Azure IoT Edge入門(8)邊緣裝置到雲的訊息 及 在本地開發除錯 debug Edge Module

Azure IoT Edge入門(8)邊緣裝置到雲的訊息 及 在本地開發除錯 debug Edge Module

本文介紹:

1. 利用Module Client 傳送Module 到雲的訊息;

2. 如何在本地VS code中除錯 Azure IoT Edge Module;

3. 使用路由 在多個模組之間控制訊息流向;

本文參考:

開發除錯 edge module:https://docs.microsoft.com/zh-cn/azure/iot-edge/how-to-vs-code-develop-module

edge hub dev tool:https://github.com/Azure/iotedgehubdev

視訊:

https://www.51azure.cloud/post/2020/11/12/azure-iot-edge8-debug-edge-module

圖文:

Azure IoT Edge 的Module 如果要傳送模組到雲的訊息,需要使用Module Client 客戶端,有關 ModuleClient 類及其通訊方法的更多資訊,請參閱首選 SDK 語言的 API 參考:C#CPythonJavaNode.js

本文在《Azure IoT Edge入門(7)體驗Edge Module開發》的基礎上,將模版中的微軟提前預置的“SimulatedTemperatureSensor”替換成自己寫的“SensorModule”,在SensorModule中我們使用了Module Client 類傳送資料,資料格式也比價簡單,每5秒鐘傳送一次模擬的溫溼度值。

1. 利用Module Client 傳送Module 到雲的訊息;

ctrl+shift+p,輸入Azure IoT Edge:Add IoT Edge Module,為解決方案建立一個新的module

選擇一個部署模版,本例中選擇debug,那麼deployment.template.json則需要在專案除錯結束後,手動修改

一個edge中的多個module可以採用不同的開發語言,本例中,我們繼續使用C#語言。

輸入一個Module的命成,本文設定為“SensorModule”。

可以在Azure portal找到 容器登錄檔的 登入伺服器地址,拷貝到 vs code中

保留/sensormodule的路徑

module建立完成後,可以在左側列表中看到如下圖所示的SensorModule,還有上一講中建立好的MyFirstModule

修改Programs.cs中的原始碼,原始碼可參照:

或直接將下文中的原始碼覆蓋掉:

namespace SensorModule
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Devices.Client;
    using Microsoft.Azure.Devices.Client.Transport.Mqtt;
    using Microsoft.Azure.Devices.Shared;
    using Microsoft.Extensions.Configuration;
    using Newtonsoft.Json;


    class Program
    {
        static readonly Random Rnd = new Random();
        static TimeSpan messageDelay;
               

        public static int Main() => MainAsync().Result;

        static async Task<int> MainAsync()
        {
            Console.WriteLine("Sensor Module Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("config/appsettings.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

            messageDelay = configuration.GetValue("MessageDelay", TimeSpan.FromSeconds(5));
                            
            ModuleClient client =  await ModuleClient.CreateFromEnvironmentAsync(new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only)});
            await client.OpenAsync();

            await SendCustomMsg(client,"Sensor Module Start");
            
            await SendEvents(client);
            Console.WriteLine("SimulatedSensor Main() finished.");
            return 0;
        }
  
        static async Task SendCustomMsg( ModuleClient moduleClient,string Msg)
        {                  
                    string sensorDtaBuffer = JsonConvert.SerializeObject(Msg);
                    var sensorEventMessage = new Message(Encoding.UTF8.GetBytes(sensorDtaBuffer));
                    sensorEventMessage.Properties.Add("MsgType", "CustomMsg");

                    await moduleClient.SendEventAsync("sensorOutput", sensorEventMessage);                 
                    
                    Console.WriteLine($"message sent:{sensorDtaBuffer}");              
           

        }
        
        static async Task SendEvents( ModuleClient moduleClient)
        {                   

            while (true)
            {       
                    var sensorData = new SensorData
                                        {
                                            Temperature=Rnd.Next(20,35),
                                            Humidity=Rnd.Next(55,80)
                                        };

                    string sensorDtaBuffer = JsonConvert.SerializeObject(sensorData);
                    var sensorEventMessage = new Message(Encoding.UTF8.GetBytes(sensorDtaBuffer));
                    sensorEventMessage.Properties.Add("MsgType", "Telemetry");
                    if(sensorData.Temperature>30)
                    {
                         sensorEventMessage.Properties.Add("Alert", "TemperatureAlert");
                    }

                    await moduleClient.SendEventAsync("sensorOutput", sensorEventMessage);                 
                    
                     Console.WriteLine($"message sent:{sensorDtaBuffer}");

                await Task.Delay(messageDelay);
            }

           
        }

      
     
     
        class SensorData
        {
            public double Temperature { get; set; }

            public double Humidity { get; set; }            
        }
    }
}

新增一個配置檔案(此步驟僅針對本文案例,不是module開發的必備步驟):

修改 deployment.debug.template.json中模組的資訊:

刪除 預設的 SimulatedTemperatureSensor 模組。

修改路由:

對如下路由進行修改:

修改為:

"routes": {
          "MyFirstModuleToIoTHub": "FROM /messages/modules/MyFirstModule/outputs/* INTO $upstream",

          "SensorModuleToMyFirstModule": "FROM /messages/modules/SensorModule/outputs/sensorOutput INTO BrokeredEndpoint(\"/modules/MyFirstModule/inputs/input1\")"
        },

編譯專案並推送到ACR:

向單個iot edge裝置發起遠端部署:

選擇config資料夾下生成的部署配置檔案:

部署完成後,可以看到四個模組:

開始監控Edge Module傳送到雲端的訊息:

溫溼度值已經可以收到:

2. 如何在本地VS code中除錯 Azure IoT Edge Module;

多個module在本地進行除錯:

在Edge裝置上建立本地除錯用的模擬器,在IoTEdge裝置上右鍵選擇“Setup IoT Edge Simulator”

在VS Code中的TERMINAL視窗中,根據作業系統可能需要輸入管理員密碼,直到看到“Setup iot edge simulator successfully”

在deployment.debug.template.json檔案上右鍵Build and run iot solution in simulator。

在VS Code中的TERMINAL視窗中可以看到 edgehubdev 工具已經開始執行。

同時在vs code docker擴充套件中可以看到本地的三個容器已經開始運行了,注意,三個容器中又一個 edge-hub是Azure IOT Edge系統module,且系統module中本地除錯過程中,沒有edge-agent module。

在要除錯的程式碼出新增斷點:

開始啟動除錯,注意,專案選則帶有remote 字樣的。

斷點被中斷,可以進行除錯:





宣告:

點選可查閱本站文章目錄《文章分類目錄》

本站所有內容僅代表個人觀點,如與官文件衝突,請以官方文件為準。

可在本頁面下方留言或通過下方聯絡方式聯絡我:

微信:wxyusz;郵箱:[email protected]

歡迎關注公眾號“雲端計算實戰”,接收最新文章推送。





本作品由Sean Yu採用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。
歡迎轉載、使用、重新發布,但務必保留文章連結:https://www.51azure.cloud,且不得用於商業目的。