serveur-web-capteur.py

Raspberry Pi Compute Module 5 (compute-module-5) · File : serveur-web-capteur.py · Language : Python · Use case : Exposer les mesures de la carte sur un mini serveur web

With no external dependency, the board becomes a web server: an HTML page shows SoC temperature and uptime, a JSON endpoint exposes them to dashboards. The network reflex for monitoring a headless SBC.

Hardware required

A Compute Module 5 (BCM2712 + RP1) on a CM5 IO Board, powered by 5 V USB-C (up to 25 W over PD), running Raspberry Pi OS Bookworm. No component; the board is already on the network (cable or Wi-Fi).

Wiring

No wiring. Open port 8080 if a firewall is active; find the IP with ip addr or avahi (board.local).

How it works

http.server serves a hand-written handler: do_GET picks HTML or JSON by path, reading sysfs/procfs on the fly. serve_forever loops accepting connections. On Bookworm: sudo apt install python3-gpiozero then python3 your_script.py. The connector 28 GPIOs reuse the Pi 5 BCM numbering; the module adds a PWR_BUT button and an RTC (VBAT).

Going further

Add endpoints for sensors (DHT, I2C), or move to Flask (pip install flask) for clean routing.

serveur-web-capteur.py

#!/usr/bin/env python3
# Mini serveur web (bibliotheque standard uniquement) : etat de la carte.
# http://<ip-de-la-carte>:8080/   -> page HTML
# http://<ip-de-la-carte>:8080/api -> mesures en JSON
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

def mesures():
    with open("/sys/class/thermal/thermal_zone0/temp") as f:
        temp = int(f.read()) / 1000.0
    with open("/proc/uptime") as f:
        uptime = float(f.read().split()[0])
    return {"temperature_c": round(temp, 1),
            "uptime_s": int(uptime),
            "horodatage": time.strftime("%Y-%m-%dT%H:%M:%S%z")}

class Gestionnaire(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api":
            corps = json.dumps(mesures()).encode()
            type_ = "application/json"
        else:
            m = mesures()
            corps = (f"<h1>Carte : {m['temperature_c']} C</h1>"
                     f"<p>Uptime : {m['uptime_s']} s</p>").encode()
            type_ = "text/html; charset=utf-8"
        self.send_response(200)
        self.send_header("Content-Type", type_)
        self.end_headers()
        self.wfile.write(corps)

if __name__ == "__main__":
    print("Serveur sur le port 8080 (Ctrl-C pour arreter)")
    HTTPServer(("0.0.0.0", 8080), Gestionnaire).serve_forever()

← Back to the board