低程式碼開發物聯網app(4.1)-將Azure IoT Service SDK 整合到 Azure Function併發布
技術標籤:公開課教程azurefunctioniotazurewindows azure物聯網
本文介紹:
將IoT Hub Service SDK 呼叫Direct Method 封裝為Azure Functions Http Trigger(C#)
視訊介紹:
圖文介紹:
本文內容比較簡單,不做圖文介紹了,直接建立functions,採用http 觸發,新增如下程式碼,釋出後即可通過呼叫http請求的方式,向iot hub 傳送 direct method 呼叫。
注意:
1.引用包:using Microsoft.Azure.Devices;
2.本例呼叫的客戶端案例為\azure-iot-samples-node-master\iot-hub\Quickstarts\simulated-device-2
3. 其中iot hub 連線字串寫入functions 配置檔案,deviceid 和payload 通過query string 傳遞
例如,http://localhost:7071/api/CallDierctMethod?deviceId=device-0001&payload=10
表示將名稱為device-0001的裝置的上報資料頻率改為10秒
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Microsoft.Azure.Devices; namespace Company.Function { public static class CallDierctMethod { private static ServiceClient s_serviceClient; // The function will called like : // http://localhost:7071/api/CallDierctMethod?deviceId=device-0001&payload=1 [FunctionName("CallDierctMethod")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string deviceId = req.Query["deviceId"]; string payload = req.Query["payload"]; log.LogInformation($"parameter deviceId:{deviceId},payload:{payload}"); string s_connectionString = System.Environment.GetEnvironmentVariable("IoTHubConnectionString"); s_serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString); var cloudToDeviceMethodResult= InvokeMethod(deviceId,payload).GetAwaiter().GetResult(); log.LogInformation($"Functions Result:{cloudToDeviceMethodResult.GetPayloadAsJson()}"); return new OkObjectResult(cloudToDeviceMethodResult); } private static async Task<CloudToDeviceMethodResult> InvokeMethod(string deviceId,string payload) { var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval") { ResponseTimeout = TimeSpan.FromSeconds(30) }; methodInvocation.SetPayloadJson(payload); // Invoke the direct method asynchronously and get the response from the simulated device. var response = await s_serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation); return response; } } }
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"IoTHubConnectionString":"{your iot hub connection string}"
}
}
宣告:
點選可查閱本站文章目錄《文章分類目錄》
本站所有內容僅代表個人觀點,如與官文件衝突,請以官方文件為準。
可在本頁面下方留言或通過下方聯絡方式聯絡我:
微信:wxyusz;郵箱:[email protected]
歡迎關注公眾號“雲端計算實戰”,接收最新文章推送。
本作品由Sean Yu採用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。
歡迎轉載、使用、重新發布,但務必保留文章連結:https://www.51azure.cloud,且不得用於商業目的。