Azure IoT Edge入門(11)IoT Edge裝置上的函式計算Function,使用Function寫資料庫-Using Azure Function On Edge device save data to Azure SQL Edge
本文介紹:
在IoT Edge邊緣裝置中部署Azure Function;
通過Azure Function或者其他Module 將遙測資料寫入SQL Edge 資料庫中;
本地邊緣裝置上的Function 附加除錯;
視訊:
https://www.51azure.cloud/post/2020/11/17/using-azure-function-on-edge-device-save-data-to-azure-sql-edge
圖文:
在IoT Edge邊緣裝置中部署Azure Function;
在部署檔案上右鍵選擇 Add iot edge module:
選擇Azure Functions:
填寫ACR地址:
FunctionModule建立完成:
刪除上一講中建立的FirstModule和修改路由:
"$edgeHub": {
"properties.desired": {
"schemaVersion": "1.0",
"routes": {
"SensorModuleToFunctionModule": "FROM /messages/modules/SensorModule/outputs/sensorOutput INTO BrokeredEndpoint(\"/modules/FunctionModule/inputs/input1\")",
"FunctionModuleToIoTHub": "FROM /messages/modules/FunctionModule/outputs/* INTO $upstream"
},
"storeAndForwardConfiguration": {
"timeToLiveSecs": 7200
}
}
通過Azure Function或者其他Module 將遙測資料寫入SQL Edge 資料庫中;
使用nuget新增System.Data.SqlClient引用,版本選擇4.5.1(已經經過我們的測試,其他版本未測試):
ctrl+shift+p,輸入NuGet Package Manager:Add Package
輸入或選擇System.Data.SqlClient
版本選擇4.5.1
將程式集新增到FunctionModule上:
修改邏輯程式碼,增加寫資料庫的部分:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EdgeHub;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
namespace Functions.Samples
{
public static class FunctionModule
{
[FunctionName("FunctionModule")]
public static async Task FilterMessageAndSendMessage(
[EdgeHubTrigger("input1")] Message messageReceived,
[EdgeHub(OutputName = "output1")] IAsyncCollector<Message> output,
ILogger logger)
{
byte[] messageBytes = messageReceived.GetBytes();
var messageString = System.Text.Encoding.UTF8.GetString(messageBytes);
if (!string.IsNullOrEmpty(messageString))
{
// write message into sql edge
var dbstring="Data Source=SQLServerModule;Initial Catalog=master;User Id=SA;Password=Strong!Passw0rd;TrustServerCertificate=False;Connection Timeout=30;";
/* string moduleID=messageReceived.ConnectionModuleId;
string clientID=messageReceived.ConnectionDeviceId;
Console.WriteLine(moduleID+"-"+clientID); */
try
{
var sensorData=new SensorData();
try
{
sensorData= JsonConvert.DeserializeObject<SensorData>(messageString);
}
catch(Exception ex)
{
Console.WriteLine($"error{ex.Message}");
}
using (SqlConnection con = new SqlConnection(dbstring))
{
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string strCmd = $"insert into dbo.Telemetry(temperature,humidity,funcsavedt,deviceid) values ({sensorData.Temperature},{sensorData.Humidity},'{System.DateTime.Now}','{messageReceived.ConnectionDeviceId}' )";
SqlCommand sqlcmd = new SqlCommand(strCmd, con);
int n = sqlcmd.ExecuteNonQuery();
if (n > 0)
{
logger.LogInformation("save to sql edge db successfully");
}
else
{
logger.LogError("save to sql edge db error");
}
}
con.Close();
}
}
catch (Exception ex)
{
logger.LogInformation(ex.StackTrace);
}
logger.LogInformation("Info: Received one non-empty message");
using (var pipeMessage = new Message(messageBytes))
{
foreach (KeyValuePair<string, string> prop in messageReceived.Properties)
{
pipeMessage.Properties.Add(prop.Key, prop.Value);
}
await output.AddAsync(pipeMessage);
logger.LogInformation("Info: Piped out the message");
}
}
}
}
class SensorData
{
public double Temperature { get; set; }
public double Humidity { get; set; }
}
}
在Edge裝置上連線到SQL Edge,建立資料庫和表,本例中直接使用了Master資料庫:
建表指令碼參考:
注意:這裡僅做測試,實際應注意sql的相關索引等等要求。
CREATE TABLE [dbo].[telemetry](
[temperature] [numeric](18, 2) NULL,
[humidity] [numeric](18, 2) NULL,
[deviceid] [nvarchar](50) NULL,
[funcsavedt] [datetime] NULL
) ON [PRIMARY]
GO
本地邊緣裝置上的Function 附加除錯;
在debug的部署檔案上右鍵,選擇 build and run iot edge solution in simulator
可以在本地看到包括SQL EDGE在內的容器已經啟動:
選擇 Function 專案的 remote debug,即可啟動除錯。
宣告:
點選可查閱本站文章目錄《文章分類目錄》
本站所有內容僅代表個人觀點,如與官文件衝突,請以官方文件為準。
可在本頁面下方留言或通過下方聯絡方式聯絡我:
微信:wxyusz;郵箱:[email protected]
歡迎關注公眾號“雲端計算實戰”,接收最新文章推送。
本作品由Sean Yu採用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。
歡迎轉載、使用、重新發布,但務必保留文章連結:https://www.51azure.cloud,且不得用於商業目的。