天天看點

node-red可視化程式設計——自定義動态CPU顯示圖表節點目錄

目錄

  1. node-red介紹
  2. Demo效果圖
  3. node-red自定義節點A–擷取主機CPU使用率os-info
  4. node-red自定義節點B–動态顯示UI圖表panel-node
  5. 節點A、節點B聯合使用Demo效果
  6. github源碼位址

node-red介紹

node-red是IBM開發的一個基于浏覽器、可拖動節點和連接配接的可視化程式設計工具。

該工具基于node.js。

開發者可通過快速拖動節點,連接配接流程開發自己的dashboard界面

或者用于建構物聯網應用程式。具體安裝和介紹見官網(https://nodered.org/)

本文基于ubuntu 16.04 + node-red程式設計工具自定義節點,

實作一個可以動态顯示CPU使用率的一個dashboard界面。

Demo效果圖

如圖,該demo動态地顯示主機CPU,X軸為目前時間,Y軸為CPU使用率。

每一秒鐘自動讀取CPU使用率并動态加載到表格中。

當CPU使用率超過90%的時候折線變為紅色,左上角為目前的CPU使用率。

node-red可視化程式設計——自定義動态CPU顯示圖表節點目錄

上圖的效果使用node-red程式設計工具使用,一共使用了三個節點。第一個節點為node-red自帶的inject節點,設定周期性每秒鐘自動注入時間戳,第二個節點為自己實作的節點并添加到node-red中,該節點能自動讀取主機CPU等資訊,第三個節點為動态圖表,也是自己實作的節點并添加到node-red中,該節點能将os-info節點的資訊呈現給使用者。下面是兩個自定義節點的代碼實作。`

node-red可視化程式設計——自定義動态CPU顯示圖表節點目錄

node-red自定義節點A–擷取主機CPU使用率os-info

建立檔案夾,并且建立三個檔案
 	os-info.html   os-info.js  package.json
	os-info.html,該檔案有三個<script>元素
	第一個<script>用來注冊節點
	第二個<script>為節點的屬性前端頁面
	第三個節點<script>為節點的說明頁面
           
<script type="text/javascript">
    RED.nodes.registerType('os-info',{
        category: 'myNode',
        color: '#a6bbcf',
        defaults: {
            name: {value:""}
        },
        inputs:1,
        outputs:1,
        icon: "file.png",
        label: function() {
            return this.name||"os-info";
        }
    });
</script>

<script type="text/x-red" data-template-name="os-info">
    <div class="form-row">
        <label for="node-input-name"><i class="icon-tag"></i> Name</label>
        <input type="text" id="node-input-name" placeholder="Name">
    </div>
</script>

<script type="text/x-red" data-help-name="os-info">
    <p>A simple node that provides system informations</p>
</script>
           

os-info.js,該檔案用來擷取主機cpu,記憶體,系統負載等值。

當有輸入操作觸發時,調用getInfo()方法,并作為msg發送出去。

module.exports = function(RED) {
    function getOsInfo(config) {
        RED.nodes.createNode(this,config);
        var node = this;
        this.previousTotalTick = []; 
        this.previousTotalIdle = [];
        node.on('input', function(msg) {
        	msg.osInfo = getInfo(this);
            node.send(msg);
        })
    }
    RED.nodes.registerType("os-info",getOsInfo);
}

function getInfo(node) {
    var osInfo = {
        "loadavg": loadAvg(),
        "cpuUsage": cpuUsage(node),
        "memory": memUsage()
    };
    return osInfo;
}

var os = require('os');
function loadAvg() {
    var loadavg = os.loadavg();
    return loadavg;
}

function memUsage() {
    var freemem = os.freemem();
    var totalmem = os.totalmem();
    var memUsage = (totalmem-freemem)/totalmem * 100;
    return memUsage;
}

function cpuUsage(node) {
    var currentTotalTick = [];
    var currentTotalIdle = [];
    var overallUsagePercentage = 0;
                  
    // Calculate the current CPU usage percentage (for each of the 4 CPU cores)
    for(var i = 0, len = os.cpus().length; i < len; i++) {
        currentTotalTick.push(0);
        currentTotalIdle.push(0);
                
        // Current total number of CPU ticks (spent in user, nice, sys, idle, and irq)
        for(var type in os.cpus()[i].times) {
            currentTotalTick[i] += os.cpus()[i].times[type];
        }
                
        // Current total idle time
        currentTotalIdle[i] += os.cpus()[i].times.idle;
                
        // Difference in idle and total time, compared to the previous calculation.
        // I.e. difference since the last time this node has been triggered!
        var totalTickDifference = currentTotalTick[i] - ( node.previousTotalTick[i] || 0 );
        var totalIdleDifference = currentTotalIdle[i] - ( node.previousTotalIdle[i] || 0 );
                
       // Average percentage CPU usage (of the period since the previous trigger of this node)
       var percentageCPU = 100 - ~~(100 * totalIdleDifference / totalTickDifference);
         
                
       overallUsagePercentage += percentageCPU;
    }
            
    // Store the current counters for the next calculation
    node.previousTotalTick = currentTotalTick;
    node.previousTotalIdle = currentTotalIdle;
    return overallUsagePercentage = overallUsagePercentage/os.cpus().length;

}
           

package.json,節點配置檔案,配置版本等資訊。

{
  "name": "os-info",
  "node-red": {
    "nodes": {
      "os-info": "os-info.js"
    }
  },
  "version": "1.0.0",
  "main": "os-info.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": ""
}
           

代碼實作後需要執行cd到node-red的node_modules目錄,

并執行指令ln -s <建立檔案夾的路徑>(window環境下使用npm install …)

此時重新啟動node-red就可以在node-red左側的節點面闆中找到自定義的節點

并拖動使用。

node-red可視化程式設計——自定義動态CPU顯示圖表節點目錄

node-red自定義節點B–動态顯示UI圖表panel-node

該節點一共有4個檔案

public(靜态資源檔案夾),package.json, panel-node.html, panel-node.js

public(靜态資源檔案夾),預設通路頁面為index.html。

該檔案中使用highcharts.js來繪制UI動态圖表。

其他三個檔案與上述自定義節點類似。

<html>
<head>
<meta charset="UTF-8" />
<title>Lenovo Dashboard</title>
<script src="js/jquery.js"></script>
<script src="js/highcharts.js"></script>
</head>
<body>
<input type="text" id="one" value=""></input>
<div id="container" style="width: 550px; height: 400px; margin: 0 auto"></div>
<script language="JavaScript">
function getinfo(){
   $.ajax({url:"/myui",success:function(result){
      cpu = result.cpu;
      document.getElementById("one").value=result.cpu;       
   }});            //擷取rest API "/myui"的值
}
var cpu;
$(document).ready(function() {
   getinfo();  
   var chart = {
      type: 'spline',
      animation: Highcharts.svg, // don't animate in IE < IE 10.
      marginRight: 10,
      events: {
         load: function () {
            // set up the updating of the chart each second
            var series = this.series[0];
            setInterval(function () {
               getinfo();
               var x = (new Date()).getTime(), // current time
                   y = cpu;
               // y = Math.random();
               series.addPoint([x, y], true, true);
            }, 1000);   // 設定定時器,一秒鐘重新整理一次資料
         }
      }
   };
   var title = {
      text: 'CPU Usage'   
   };   
   var xAxis = {
      type: 'datetime',
      tickPixelInterval: 150
   };
   var yAxis = {
      title: {
         text: 'percentage'
      },
      tickPositions: [0, 0.2, 0.4, 0.6, 0.8, 1.0],
      plotLines: [{
         value: 0,
         width: 1,
         color: '#808080'
      }]
   };
   var tooltip = {
      formatter: function () {
      return '<b>' + this.series.name + '</b><br/>' +
         Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
         Highcharts.numberFormat(this.y, 2);
      }
   };
   var plotOptions = {
      area: {
         pointStart: 1940,
         marker: {
            enabled: false,
            symbol: 'circle',
            radius: 2,
            states: {
               hover: {
                 enabled: true
               }
            }
         }
      }
   };
   var legend = {
      enabled: false
   };
   var exporting = {
      enabled: false
   };
   var series= [{
      name: 'CPU details',
      data: (function () {
         // generate an array of random data
         var data = [],time = (new Date()).getTime(),i;
         for (i = -19; i <= 0; i += 1) {
            data.push({
               x: time + i * 1000,
               y: cpu
               // y: Math.random()
            });
         }
         return data;
      }()),
      zones:[
         {
            value:0.9,
            color:'#7cb5ec'
         },
         {
            color:'#FF0000'
         }]    
   }];     
      
   var json = {};   
   json.chart = chart; 
   json.title = title;     
   json.tooltip = tooltip;
   json.xAxis = xAxis;
   json.yAxis = yAxis; 
   json.legend = legend;  
   json.exporting = exporting;   
   json.series = series;
   json.plotOptions = plotOptions;
   
   
   Highcharts.setOptions({
      global: {
         useUTC: false
      }
   });
   $('#container').highcharts(json);
  
});
</script>
</body>
</html>
           

github源碼位址

https://github.com/yangsh12/Node-red

繼續閱讀