2016年8月25日

[Azure]客製化IOT Suite Portal的儀錶板

Azure IOT Suite是一個開源、預先設置好的套件,透過此套件可以讓我們快速的客製化開發IOT的解決方案。關於IOT Suite詳細的資訊可以參考這裡:https://azure.microsoft.com/zh-tw/suites/iot-suite/

在所有的IOT專案中,儀表板幾乎都是需要相當程度客製化的;一般來說,我們可以透過PowerBI來拉好所需的報表,再鑲入IOT Suite的Portal上;或是使用其他第三方廠商或是開源的專案來製作報表(例如Freeboard)

這裡我想展示的是如果我們只是單純地想在IOT Suite介面上增加簡單的欄位,所需的客製化步驟。

在開始進行前,我們需要一個前端模擬器,這個前端模擬器會模擬設備送上數據以及metadata;我已經事先準備好了一個IOT Suite模擬器:https://github.com/michael-chi/Azure-IOTHub/tree/master/device-simulator/iotsuite-simulator/iotsuite-simulator

在這個模擬器中,我們會在Metadata中設定IOT Suite預設的portal儀錶板上Telemetry History圖表上要顯示的欄位;其設定的方式在這裡:https://github.com/michael-chi/Azure-IOTHub/blob/master/device-simulator/iotsuite-simulator/iotsuite-simulator/IOTSuiteClientHelper.cs

此模擬器會產生如下格式的模擬數據:{"DeviceId":"device004","_0101":3,"_0102":0,"_0103":32,"_0104":78,"_0105":0}

而我會在此儀表板上新增一個欄位,用字符的方式將資料展示出來,結果會像下面這樣:

  • 首先,我們依照IOT Suite的架構,在Views/Dashboard下新增一個Partial View (Razor)叫做_KPI.cshtml;程式碼如下,其中名為kpe的Div即是我們要顯示資料的地方。
  • 在程式碼中,我們呼叫IoTApp.Dashboard.KPI.init()將一些初始化資料傳給KPI物件;

@using GlobalResources
    <div>
        <div></div>
        <div type="text" id="kpi" name="kpi" style="font-size:24px"/>
    </div>
    <script src="~/Scripts/Views/Dashboard/KPI.js"></script>
    <script type="text/javascript">
        (function () {
            'use strict';

            var kpiSettings = {
                targetControl: $('#kpi')
            };

            IoTApp.Dashboard.KPI.init(kpiSettings);
        })();
    </script>

  • 接著,要新增KPI物件的定義;在Scripts/Views/Dashboard下新增一個KPI.js

IoTApp.createModule(
    'IoTApp.Dashboard.KPI',
    (function () {

        var targetControl;
   
        'use strict';
        var updateKPI = function (newData, fields) {
           var latest = newData[newData.length - 1]; //最新一筆資料
            $(targetControl).text(latest.values._0101);//將最新一筆資料展示到畫面上
        };
   
        var init = function (settings) {
            targetControl = settings.targetControl;
        };
 

    return {
        updateKPI: updateKPI,
        init: init
    }
}), [jQuery, resources]);

  • 然後將這個KPI控制項展示到畫面上
  • 在_DashboardDevicePane.cshtml中,加入下面的程式

<div class="telemetryhistory">
    @{
        Html.RenderPartial("_TelemetryHistory");
        Html.RenderPartial("_TelemetryHistorySummary");
        Html.RenderPartial("_KPI");
    }
    <div id="loadingElement" class="loader_container loader_container_details">
        <div class="loader_container__loader loader_container__loader--large_top_margin"></div>
    </div>

  • 把控制項畫到畫面上之後,當然我們必須要告訴他的parent control,也就是DashboardDevicePane我們多加了一個控制項,當畫面更新時要一起更新他
  • 在Scripts\Views\Dashboard\DashboardDevicePane.js新增下面程式碼:

  • 在DashboardDevicePane的refreshData方法中,呼叫kpiRefreshData()來更新KPI控制項

  • 完成之後佈署到Azure上,啟動前端模擬器就可以看到結果了!

完整的範例程式碼在此:https://github.com/michael-chi/azure-iot-suite-customization-demo

沒有留言:

Blog Archive

About Me