aerodynamics
Published © GPL3+

MONITORING RASPBERRY PIs

A simple interface to monitor my raspberry pis (headless) and my laptop thanks to MQTT and Node Red

BeginnerShowcase (no instructions)2 hours707
MONITORING RASPBERRY PIs

Things used in this project

Hardware components

Raspberry Pi 4 Model B
Raspberry Pi 4 Model B
×1

Software apps and online services

Node-RED
Node-RED
MQTT
MQTT

Story

Read more

Code

Python code - Client Side

Python
#! /usr/bin/env python3

import psutil
import time
import datetime
import json
import paho.mqtt.client as mqttClient
name = ""

broker = ""
port = 1883
user = ""
password = ""


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to broker")
        global Connected  # Use global variable
        Connected = True  # Signal connection
    else:
        print("Connection failed")


client = mqttClient.Client()  # create new instance
client.username_pw_set(user, password=password)  # set username and password
client.on_connect = on_connect  # attach function to callback
client.connect(broker, port=port)  # connect to broker

client.loop_start()  # start the loop
i = 0
while 1:
    temperature_main = psutil.sensors_temperatures()["asus"][0][1]
    du = psutil.disk_usage("/")[3]
    virtual_memory = psutil.virtual_memory().percent
    cpu_percent = psutil.cpu_percent(percpu=True)
    cpu_load_avg = psutil.getloadavg()
    uptime = str(datetime.datetime.now().replace(microsecond=0) - datetime.datetime.fromtimestamp(
        psutil.boot_time()).replace(microsecond=0))
    messageToSend = {"name": name, "du": du, "virtual_memory": virtual_memory, "temperature_main": temperature_main, "cpu_percent": cpu_percent, "cpu_load_avg": cpu_load_avg, "uptime": uptime}
    messageToSend_JSON = json.dumps(messageToSend)
    client.publish("topic", messageToSend_JSON)
    print("Message #", i, "published to", broker)
    i+=1
    time.sleep(1)

Credits

aerodynamics

aerodynamics

4 projects • 18 followers

Comments