NodeJS -> System Info - Server Remote Monitoring

Let's consider an example script for monitoring a PC, laptop, or server. To collect data, we will need the NodeJS package called systeminformation.

What we will need:

  • Operating System: Any OS, in this example, Debian is used.
  • Programs:
    • Nano — console text editor.
    • cURL — command-line program for working with HTTP.
    • cron — daemon used for periodic task execution.
    • NodeJS — server-side platform for working with JavaScript through the V8 engine.
    • systeminformation — NodeJS package for obtaining data from the PC.

Adding and configuring the device:

  1. Add a new device to VizIoT with the name "VizIoTSystemInfo".
  2. In the "Basic Settings" of the device, copy the Access Key and Access Password.

NodeJS Installation:

Refer to the NodeJS documentation. Standard installation for Ubuntu or Debian:

# Using Ubuntu
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
# Using Debian, as root
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
apt-get install -y nodejs

Creating a NodeJS Program.

The program will retrieve data from the systeminformation package, compile it into a packet, and send it to the VizIoT server every 15 seconds:

Create a directory:

mkdir /var/viziot/
mkdir /var/viziot/VizIoTSystemInfo

Navigate to the directory:

cd /var/viziot/VizIoTSystemInfo

Create a NodeJS project:

npm init

Install packages for operation:

  • systeminformation (https://github.com/sebhildebrandt/systeminformation) - a package for collecting information from PCs, laptops, or servers with operating systems such as Linux, macOS, Windows, FreeBSD, OpenBSD, NetBSD, SunOS;
    npm install systeminformation --save
  • viziot-mqtt-client-nodejs (https://www.npmjs.com/package/viziot-mqtt-client-nodejs) - a module that allows you to send data to the VizIoT server using the MQTT protocol:
    npm install viziot-mqtt-client-nodejs --save

Create a script file:

nano ./index.js

Script content:

'use strict';
//# VizIoT Access Key and Password
let keyDevice = "_______________";
let passDevice = "_____________________";
let idIntervalSend = 0;
let viziotMQTT = require('viziot-mqtt-client-nodejs');
let viziotMQTTClient = new viziotMQTT(keyDevice, passDevice);
viziotMQTTClient.connect(function () {
	clearInterval(idIntervalSend);
	idIntervalSend = setInterval(function () {
		getPacketAndSendToServer();
	}, 15000);
});

//https://github.com/sebhildebrandt/systeminformation
const si = require('systeminformation');
console.log("systeminformation version", si.version());
//TODO Specify the network interface for monitoring network traffic
let networkInterface = "Ethernet 5";
// to view all network interfaces
// si.networkInterfaces(function(data){console.log(data); })

// It's necessary to read the network interface status once when the program starts to establish an initial reference point; failing to do so will result in zero initial data
if(networkInterface != null && networkInterface.length > 0){
	si.networkStats(networkInterface, function(data) {});
}

// Configure which parameters we want to monitor
let listGetData = {
	'currentLoadCPU' : true,
	'currentLoadCPUCore' : false,
	'memRAMTotal_Gb' : false,
	'memRAMUsed_Gb' : true,
	'memRAMFree_Gb' : true,
	'memRAMUsed_Percent' : true,
	'memRAMFree_Percent' : true,
	'logicDiskTotal_Gb' : false,
	'logicDiskUsed_Gb' : true,
	'logicDiskFree_Gb' : true,
	'logicDiskUsed_Percent' : true,
	'logicDiskFree_Percent' : true,
	'countProcesses' : true,
	'mostActiveProcesses' : true, // Specify the minimum CPU load percentage to track applications that heavily load the CPU
	'networkStatsInterface' : true,
	'time' : true,
	'uptimeDays' : true,
	'countUsers' : true,
	'countOnlineUsers' : true,
	'cpuTemperature' : true,
	'battery' : true,
};
let maxCPUUsed = 50; // Allowed range from 10 to 100. Setting 1 will track almost all processes on the PC
let maxMEMUsed = 50; // Allowed range from 10 to 100. Setting 1 will track almost all processes on the PC

// Count how many results are needed from the systeminformation package to send to the VizIoT server.
let countResultsForSendPacket = 0;
for(let key in listGetData){
	if(listGetData[key] == true){
		countResultsForSendPacket++;
	}
}

function getRoundData(data, digits){
	if (data == undefined){
		return undefined;
	}
	if (digits == undefined){
		digits = 2;
	}
	return +(data).toFixed(digits);
}
function sendPacketToServer(packet, countResults) {
	if(countResults == countResultsForSendPacket){
		viziotMQTTClient.sendDataToVizIoT(packet, function (err) {
			if (err) {
				console.log("publish", err);
			}
		});
	}
}
function getPacketAndSendToServer() {
	let packet ={};
	let countResults = 0;
	let timePC = si.time();

	if(listGetData['currentLoadCPU'] || listGetData['currentLoadCPUCore'] ){
		si.currentLoad(function(data) {
			if(listGetData['currentLoadCPU']){
				packet.loadCPU = getRoundData(data.currentload);
				packet.loadUserCPU = getRoundData(data.currentloadUser);
				packet.loadSystemCPU = getRoundData(data.currentloadSystem);
				countResults++;
			}
			if(listGetData['currentLoadCPUCore']){
				for (let jj = 0; jj < data.cpus.length; jj++) {
					let core = data.cpus[jj];
					packet["loadCore" + jj] = getRoundData(core.load);
					packet["loadUserCore" + jj] = getRoundData(core.loadUser);
					packet["loadSystemCore" + jj] = getRoundData(core.loadSystem);
				}
				countResults++;
			}
			sendPacketToServer(packet, countResults);
		});
	}
	if(listGetData['memRAMTotal_Gb'] || listGetData['memRAMUsed_Gb'] || listGetData['memRAMFree_Gb'] || listGetData['memRAMUsed_Percent'] || listGetData['memRAMFree_Percent']){
		si.mem(function(data) {
			if(listGetData['memRAMTotal_Gb']){
				packet.memRAMTotal_Gb = getRoundData(data.total/1073741824);
				countResults++;
			}
			if(listGetData['memRAMUsed_Gb']){
				packet.memRAMUsed_Gb = getRoundData(data.used/1073741824);
				countResults++;
			}
			if(listGetData['memRAMFree_Gb']){
				packet.memRAMFree_Gb = getRoundData(data.free/1073741824);
				countResults++;
			}
			if(listGetData['memRAMUsed_Percent']){
				packet.memRAMUsed_Percent = getRoundData(data.used / data.total * 100);
				countResults++;
			}
			if(listGetData['memRAMFree_Percent']){
				packet.memRAMFree_Percent = getRoundData(data.free / data.total * 100);
				countResults++;
			}
			sendPacketToServer(packet, countResults);
		});
	}
	if(listGetData['logicDiskTotal_Gb'] || listGetData['logicDiskUsed_Gb'] || listGetData['logicDiskFree_Gb'] || listGetData['logicDiskUsed_Percent'] || listGetData['logicDiskFree_Percent']){
		si.fsSize(function(data) {
			if(listGetData['logicDiskTotal_Gb']){
				for (let jj = 0; jj < data.length; jj++) {
					let disc = data[jj];
					if(disc.type != undefined){
						let discName = disc.fs.replace(/\W/g, '');
						packet["logicDisk" + discName + "Total_Gb"] = getRoundData(disc.size/1073741824);
					}
				}
				countResults++;
			}
			if(listGetData['logicDiskUsed_Gb']){
				for (let jj = 0; jj < data.length; jj++) {
					let disc = data[jj];
					if(disc.type != undefined){
						let discName = disc.fs.replace(/\W/g, '');
						packet["logicDisk" + discName + "Used_Gb"] = getRoundData(disc.used/1073741824);
					}
				}
				countResults++;
			}
			if(listGetData['logicDiskFree_Gb']){
				for (let jj = 0; jj < data.length; jj++) {
					let disc = data[jj];
					if(disc.type != undefined){
						let discName = disc.fs.replace(/\W/g, '');
						packet["logicDisk" + discName + "Free_Gb"] = getRoundData((disc.size - disc.used)/1073741824);
					}
				}
				countResults++;
			}
			if(listGetData['logicDiskUsed_Percent']){
				for (let jj = 0; jj < data.length; jj++) {
					let disc = data[jj];
					if(disc.type != undefined){
						let discName = disc.fs.replace(/\W/g, '');
						packet["logicDisk" + discName + "Used_Percent"] = getRoundData(disc.use);
					}
				}
				countResults++;
			}
			if(listGetData['logicDiskFree_Percent']){
				for (let jj = 0; jj < data.length; jj++) {
					let disc = data[jj];
					if(disc.type != undefined){
						let discName = disc.fs.replace(/\W/g, '');
						packet["logicDisk" + discName + "Free_Percent"] = getRoundData(100 - disc.use);
					}
				}
				countResults++;
			}
			sendPacketToServer(packet, countResults);
		});
	}
	if(listGetData['countProcesses'] || listGetData['mostActiveProcesses']){
		si.processes(function(data) {
			if(listGetData['countProcesses']){
				packet.countProceses = data.all;
				countResults++;
			}
			if(listGetData['mostActiveProcesses']){
				for (let jj = 0; jj < data.list.length; jj++) {
					let process = data.list[jj];
					let processName = process.name.replace(/\W/g, '');
					if(process.pcpu >= maxCPUUsed || process.pmem >= maxMEMUsed){
						packet["p_" + processName + "_cpu"] = getRoundData(process.pcpu);
						packet["p_" + processName + "_mem"] = getRoundData(process.pmem);
					}
				}
				countResults++;
			}
			sendPacketToServer(packet, countResults);
		});
	}
	if(listGetData['networkStatsInterface']){
		if(networkInterface != undefined && networkInterface.length > 0){
			si.networkStats(networkInterface, function(data) {
				packet.networkReadSpeed = getRoundData(data[0].rx_sec * 8 / 1024 / 1024);
				packet.networkWriteSpeed = getRoundData(data[0].tx_sec * 8 / 1024 / 1024);
				countResults++;
				sendPacketToServer(packet, countResults);
			});
		}else{
			countResults++;
			sendPacketToServer(packet, countResults);
		}
	}
	if(listGetData['time']) {
		packet.date = parseInt(timePC.current / 1000);
		countResults++;
		sendPacketToServer(packet, countResults);
	}
	if(listGetData['uptimeSeconds']){
		packet.uptimeSeconds = getRoundData(timePC.uptime, 3);
		countResults++;
		sendPacketToServer(packet, countResults);
	}
	if(listGetData['uptimeMinutes']){
		packet.uptimeMinutes = getRoundData(timePC.uptime/60, 3);
		countResults++;
		sendPacketToServer(packet, countResults);
	}
	if(listGetData['uptimeHours']){
		packet.uptimeHours = getRoundData(timePC.uptime/3600, 3);
		countResults++;
		sendPacketToServer(packet, countResults);
	}
	if(listGetData['uptimeDays']){
		packet.uptimeDays = getRoundData(timePC.uptime/86400, 3);
		countResults++;
		sendPacketToServer(packet, countResults);
	}
	if(listGetData['countUsers'] || listGetData['countOnlineUsers']){
		si.users(function(data) {
			if(Array.isArray(data)){
				if(listGetData['countUsers']){
					packet.countUsers = data.length;
					countResults++;
				}
				if(listGetData['countOnlineUsers']){
					packet.countOnlineUsers = data.filter(user => user.tty.length > 0).length;
					countResults++;
				}
			}else{
				packet.countUsers = -1;
				packet.countOnlineUsers = -1;
				countResults++;
			}
			sendPacketToServer(packet, countResults);
		});
	}
	if(listGetData['cpuTemperature']){
		si.cpuTemperature(function(data) {
			packet.temperatureCPU = data.main;
			for (let jj = 0; jj < data.cores.length; jj++) {
				packet["temperatureCore" + jj] = data.cores[jj];
			}
			countResults++;
			sendPacketToServer(packet, countResults);
		});
	}
	if(listGetData['battery']){
		si.battery(function(data) {
			if(data.hasbattery ==  true){
				packet.batIsCharg = (data.ischarging == true) ? 1 : 0;
				packet.batMaxCapacit = data.maxcapacity;
				packet.batCapacit = data.currentcapacity;
				packet.batPercent = data.percent;
				packet.batCycleCount = data.cyclecount;
			}
			countResults++;
			sendPacketToServer(packet, countResults);
		});
	}
}
This script will be executed on system startup. To do this, we will add a record to the cron. Open the cron editor by running:
crontab -e
Add the following line at the end, which will run the script "/var/viziot/VizIoTSystemInfo/index.js":
@reboot node /var/viziot/VizIoTSystemInfo/index.js > /var/viziot/VizIoTSystemInfo/output.txt &
Widget Setup:
  1. Create a new panel named "System Information".
  2. Add "CPU" widget:
    1. Type: "Stacked Area Chart".
    2. Device: "VizIoTSystemInfo".
    3. Parameters: loadUserCPU, loadSystemCPU.
  3. Add "RAM" widget:
    1. Type: "Stacked Area Chart".
    2. Device: "VizIoTSystemInfo".
    3. Parameters: memRAMUsed_Gb, memRAMFree_Gb.
  4. Add "Disk C" widget:
    1. Type: "Stacked Area Chart".
    2. Device: "VizIoTSystemInfo".
    3. Parameters: logicDiskCUsed_Gb, logicDiskCFree_Gb.
  5. Add "Internet Speed" widget:
    1. Type: "Area Chart".
    2. Device: "VizIoTSystemInfo".
    3. Parameters: networkReadSpeed, networkWriteSpeed.
  6. Everything is set up now - you can monitor your system's status.