serveur-web-capteur.py

Orange Pi PC (Allwinner H3) · 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

An Orange Pi PC (Allwinner H3 quad Cortex-A7, 1 GB) running Armbian or the Orange Pi image, connected over Ethernet. 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.

Running it

On Armbian: apt install gpiod python3-gpiod, identify the chip with gpiodetect and pins with gpioinfo, then run the script (possibly with sudo the first time).

Variants

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