# 使用 Azure SignalR 透過 Functions 即時響應遠端遙測資料於前端 ### 本教學需要以下五個東西 1. Resource Group 2. Azure Functions Service 3. Azure SignalR service 4. Iothub Service 5. Web App ## 一、建立 IoT Hub(Event Hub) Trigger Function 帳戶訂閱下有IoT Hub可直接下拉選單選取,即可連線至 IoT 中樞  ## 二、設定 Function 輸出繫結   我們會需要到連線至 SignalR 的連接字串。  SignalR service connection 的預設並沒有給正確的預設值(?)  所以點選右邊藍字"新增" 自行設定 key : AzureSignalRConnectionString,value : <signalR-connction-string> 儲存。 ## 三、在 Function 的 index.js 貼上以下 code ``` module.exports = async function (context, IoTHubMessages) { context.log(`JavaScript eventhub trigger function called for message array: ${IoTHubMessages}`); context.bindings.signalRMessages = null IoTHubMessages.forEach(message => { context.log(`Processed message: ${JSON.stringify(message)}`); context.bindings.signalRMessages = [{ target: "newMessage", arguments: [ JSON.parse(message) ] }]; }); context.done(); }; ``` SignalR 的繫結接受指定的參數 (之後會使用到),如果使用其他的值將無法傳送至 SignalR 中心 ## 四、開始測試遙測資料的傳送是否成功 我這邊使用微軟提供的 [Raspberry Pi Simulator](https://azure-samples.github.io/raspberry-pi-web-simulator/#Getstarted) 模擬設備傳送資料到 IoT 中樞 Function 按下執行,以及 Run Raspberry Pi Simulator,可以看到資料 log 出來了  接著就是看看 IoT Hub 中心是否有接受到資料  OK! 看來是很即時的資料~~ ## 五、新增 negotiate Http Trigger * 在前端連線到 SignalR 需要 AccessToken 跟指定 URL。最簡單的做法就是使用 Azure Function Http Trigger。 * Function 名稱必須是 "negotiate" * Function 的輸入繫結必須是 SignalR Connection Info,其 SignalR Service connection 作法與上述的相同。輸出則直接使用 res 即可 * 觸發程序請勾選 GET、POST。 執行方能取得 url 跟 accessToken ## 六、前端連接 SignalR 中心 ``` // 使用 cdn 方式 // index.html <script src="https://cdn.jsdelivr.net/npm/@aspnet/signalr@1.1.2/dist/browser/signalr.js"></script> // App.vue const sigR = new window.signalR.HubConnectionBuilder().withUrl('negotiate-function-api-url').configureLogging(window.signalR.LogLevel.Information).build() sigR.on('newMessage', signalMessage => console.log(signalMessage)) sigR.onclose(() => console.log('disconnected')) sigR.start() .then(() => console.log('started ...')) ``` 這邊的 withUrl 直接帶入上面的 Http Trigger Url 即可。但需去掉 negotiate,因為 withUrl 內建會帶入 negotiate。 連上後會看到 console 顯示 started ... , 接著 Run Raspberry Pi Simulator,就可以看到資料傳到前端了哦 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up