本案例適用於開發者入門理解Azure Functions/ IoT Hub / Service Bus / Power BI等幾款產品。
主要實戰的內容爲:
將設備遙測數據上傳到物聯網中心,
將遙測數據路由到消息中間件的Topic中,
使用Azure Function解析消息中間件Topic中的消息並推送到大屏 。
先了解下Azure Functions的基本概念:
https://v.qq.com/x/page/j3031z2zlns.html
在Azure Portal 創建Functions 並體驗:
https://v.qq.com/x/page/v3031m1g9vv.html
IoT Hub 和Service Bus的準備工作,請參考:
設備數據通過Azure Functions 推送到 Power BI 數據大屏進行展示(1.準備工作)
使用Visual studio 2019 創建併發布Functions:
https://v.qq.com/x/page/a3031iu2d4q.html
本示例中的示例代碼:
using System;using System.IO;using System.Net;using System.Text;using Microsoft.Azure.WebJobs;using Microsoft.Azure.WebJobs.Host;using Microsoft.Extensions.Logging;using Newtonsoft.Json;namespace FunctionApp2{ public static class Function1 { [FunctionName("Function1")] public static void Run([ServiceBusTrigger("fromiothubtopic", "sub", Connection = "sbconn")]string mySbMsg, ILogger log) { log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}"); string url = "https://api.powerbi.cn/beta/請替換成您自己的URL"; IoTDeviceMsg msg = JsonConvert.DeserializeObject<IoTDeviceMsg>(mySbMsg); // Create JSON message var telemetryDataPoint = new { temperature = msg.temperature, humidity = msg.humidity, time = DateTime.Now }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Timeout = 8000;//設置請求超時時間,單位爲毫秒 req.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes("[" + messageString + "]"); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //獲取響應內容 if (resp.StatusCode == HttpStatusCode.OK) { log.LogInformation($"OK: {messageString}"); } } } public class IoTDeviceMsg { public decimal temperature { get; set; } public decimal humidity { get; set; } }}
針對開發人員入門,需關注如下基本概念:
1.Azure Functions Trigger
AzureFunctions 提供了幾種模板,模板支持如下的觸發:
HTTPTrigger - 使用 HTTP 請求觸發執行代碼。
TimerTrigger - 按預定義的計劃執行清除或其他批處理任務。
CosmosDBTrigger - 在 NoSQL 數據庫中以集合形式添加或更新Azure CosmosDB 文檔時,對這些文檔進行處理。
QueueTrigger - 當消息到達 Azure 存儲隊列時,響應這些消息。
BlobTrigger - Azure 存儲 blob 添加到容器時,處理這些 blob。 可以使用此函數調整圖像大小。
EventHubTrigger - 響應傳送到 Azure 事件中心的事件。
ServiceBusQueueTrigger - 通過偵聽消息隊列將代碼連接到其他Azure 服務或本地服務。
ServiceBusTopicTrigger - 通過訂閱主題將代碼連接到其他Azure 服務或本地服務。
2. Azure Functions 集成
AzureFunctions 可與各種 Azure 和第三方服務集成。 這些服務可以觸發函數開始執行,或者可用作代碼的輸入和輸出。 AzureFunctions 支持以下服務集成:
Azure CosmosDB
Azure 事件中心
Azure 通知中心
Azure 服務總線(隊列和主題)
Azure 存儲(blob、隊列和表)
本地(使用服務總線)
兩種計費方式:
使用計劃(Consumptionplan):只爲代碼運行時間付費
應用服務計劃(App Serviceplan):將函數像 Web 應用一樣運行。 如果已對其他應用程序使用應用服務,可以按相同的計劃運行自己的函數,而不用另外付費。
具體的計費請參考:
https://www.azure.cn/zh-cn/pricing/details/azure-functions/