Monitoring PC and Server Status with NodeJS and VizIoT

Below is an improved and structured guide for setting up comprehensive monitoring of a computer, laptop, or server. We will use the VizIoT platform for data visualization and the systeminformation package to collect it.


Demonstration

Embedded example of a monitoring dashboard:


What You'll Need

Operating System

Any OS will work. The example uses Debian, but you can use Ubuntu, CentOS, Windows, macOS, etc.

Required Software and Packages

  • nano — a console text editor
  • curl — a utility for working with HTTP
  • cron — a task scheduler
  • NodeJS — a server-side JavaScript runtime environment
  • systeminformation — the main package for collecting information
  • viziot-mqtt-client-nodejs — a library for sending data to VizIoT via MQTT

Adding and Configuring the Device in VizIoT

  1. Create a new device in VizIoT, for example: VizIoTSystemInfo.
  2. In the General Settings section, copy:
    • Access Key
    • Access Password

These will be needed for authorization via MQTT.


Installing NodeJS

Detailed documentation: https://nodejs.org

Installation via NVM (Recommended)

# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

# Activate without restarting the shell
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

# Install Node.js (e.g., LTS version)
nvm install --lts

# Check versions
node -v
npm -v

Creating a NodeJS Project

Create a directory:

mkdir -p /var/viziot/VizIoTSystemInfo
cd /var/viziot/VizIoTSystemInfo

Initialize the project:

npm init -y

Install the required packages:

Package for getting system information:

npm install systeminformation --save

Module for sending data to VizIoT:

npm install viziot-mqtt-client-nodejs --save

Creating the Monitoring Script

Create a file:

nano ./index.js

Script Content

Below is an optimized version (structure preserved, minor errors corrected):

'use strict';

// Specify your VizIoT access key and password
let keyDevice = "_______________";
let passDevice = "_____________________";

const viziotMQTT = require('viziot-mqtt-client-nodejs');
const si = require('systeminformation');

let viziotMQTTClient = new viziotMQTT(keyDevice, passDevice);
let idIntervalSend = 0;

console.log("systeminformation version", si.version());

// Specify your primary network interface. On Windows it might be "Ethernet", on Linux "eth0".
// You can find it by running si.networkInterfaces()
let networkInterface = "eth0"; 

// Pre-read the network interface to start monitoring
if (networkInterface) {
  si.networkStats(networkInterface, () => {});
}

// Connect to the VizIoT MQTT server
viziotMQTTClient.connect(() => {
  console.log('Connected to VizIoT MQTT');
  clearInterval(idIntervalSend);
  idIntervalSend = setInterval(() => {
    getPacketAndSendToServer();
  }, 15000); // Send data every 15 seconds
});


// Helper function to round data
function getRoundData(data, digits = 2) {
    return data === undefined || data === null ? undefined : +(data).toFixed(digits);
}

// Asynchronously collect all system data and send it in one packet
async function getPacketAndSendToServer() {
    try {
        const timeData = si.time();
        const cpuLoad = await si.currentLoad();
        const mem = await si.mem();
        const fs = await si.fsSize();
        const processes = await si.processes();
        const network = await si.networkStats(networkInterface);
        const temp = await si.cpuTemperature();
        const batteryInfo = await si.battery();

        const packet = {};

        // System Time
        packet.uptimeDays = getRoundData(timeData.uptime / 86400);

        // CPU Load
        packet.loadUserCPU = getRoundData(cpuLoad.currentLoadUser);
        packet.loadSystemCPU = getRoundData(cpuLoad.currentLoadSystem);
        packet.loadTotalCPU = getRoundData(cpuLoad.currentLoad);

        // Memory (RAM)
        packet.memRAMUsed_Gb = getRoundData(mem.used / (1024 * 1024 * 1024));
        packet.memRAMFree_Gb = getRoundData(mem.free / (1024 * 1024 * 1024));
        packet.memRAMUsed_Percent = getRoundData((mem.used / mem.total) * 100);
        packet.memRAMFree_Percent = getRoundData((mem.free / mem.total) * 100);

        // Disk Usage (example for the first disk)
        if (fs.length > 0) {
            const mainDisk = fs[0];
            packet.logicDiskUsed_Gb = getRoundData(mainDisk.used / (1024 * 1024 * 1024));
            packet.logicDiskFree_Gb = getRoundData((mainDisk.size - mainDisk.used) / (1024 * 1024 * 1024));
            packet.logicDiskUsed_Percent = getRoundData(mainDisk.use);
            packet.logicDiskFree_Percent = getRoundData(100 - mainDisk.use);
        }

        // Processes
        packet.countProcesses = processes.all;

        // Network Stats
        if (network.length > 0) {
            packet.networkReadSpeed = getRoundData(network[0].rx_sec / (1024 * 1024)); // MB/s
            packet.networkWriteSpeed = getRoundData(network[0].tx_sec / (1024 * 1024)); // MB/s
        }

        // CPU Temperature
        if (temp.main !== null) {
            packet.cpuTemperature = getRoundData(temp.main);
        }

        // Battery
        if (batteryInfo.hasBattery) {
            packet.batteryPercent = getRoundData(batteryInfo.percent);
        }

        // Send the complete packet to VizIoT
        viziotMQTTClient.sendDataToVizIoT(packet, (err) => {
            if (err) {
                console.log("Publish error:", err);
            } else {
                console.log("Data sent successfully:", new Date().toLocaleTimeString());
            }
        });

    } catch (e) {
        console.error('Error getting system info:', e);
    }
}

Autostarting the Script via cron

Open cron:

crontab -e

Add the following line:

@reboot node /var/viziot/VizIoTSystemInfo/index.js > /var/viziot/VizIoTSystemInfo/output.txt &

Configuring the Monitoring Dashboard in VizIoT

  1. Create a dashboard: "PC Information"

  2. Add a CPU widget

    • type: Summing Area Graph
    • device: VizIoTSystemInfo
    • parameters: loadUserCPU, loadSystemCPU
  3. Add a RAM widget

    • type: Summing Area Graph
    • parameters: memRAMUsed_Gb, memRAMFree_Gb
  4. Add a Disk C widget

    • type: Summing Area Graph
    • parameters: logicDiskUsed_Gb, logicDiskFree_Gb
  5. Add an Internet Speed widget

    • type: Area Graph
    • parameters: networkReadSpeed, networkWriteSpeed

After configuring all the widgets, you will have a complete monitoring dashboard that allows you to track the state of your PC in real time.


All Set!

Now your server or PC automatically sends data to VizIoT every 15 seconds, and you get a convenient, live monitoring dashboard.