Raspberry Pi 5 + FastAPI + MariaDB で工場ダッシュボードを構築する方法(2025版)
はじめに
この記事では Raspberry Pi 5・FastAPI・MariaDB
を使って工場向けリアルタイムダッシュボードを構築する方法を紹介します。
システム構成
[設備 / PLC] → Raspberry Pi 5 → MariaDB → FastAPI → Webブラウザ
Raspberry Pi 5 初期セットアップ
sudo apt update
sudo apt upgrade -y
sudo apt install python3 python3-pip python3-venv mariadb-server -y
MariaDB セットアップ
sudo mysql_secure_installation
DB作成
CREATE DATABASE log;
CREATE USER 'piuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON log.* TO 'piuser'@'localhost';
FLUSH PRIVILEGES;
テーブル定義
CREATE TABLE factory_log (
id INT AUTO_INCREMENT PRIMARY KEY,
ts DATETIME NOT NULL,
station INT NOT NULL,
prod_count INT DEFAULT 0,
ng_count INT DEFAULT 0,
ct FLOAT DEFAULT 0
);
FastAPI の実装(api_server.py)
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
import pymysql
from datetime import datetime
app = FastAPI()
def get_db():
return pymysql.connect(
host="localhost",
user="piuser",
password="password",
database="log",
cursorclass=pymysql.cursors.DictCursor
)
@app.get("/api/log/latest")
def get_latest():
conn = get_db()
with conn.cursor() as cur:
cur.execute("SELECT * FROM factory_log ORDER BY id DESC LIMIT 20")
rows = cur.fetchall()
conn.close()
return rows
@app.post("/api/log/add")
def add_log(station: int, prod: int, ng: int, ct: float):
conn = get_db()
with conn.cursor() as cur:
cur.execute(
"INSERT INTO factory_log(ts, station, prod_count, ng_count, ct) VALUES (%s, %s, %s, %s, %s)",
(datetime.now(), station, prod, ng, ct)
)
conn.commit()
conn.close()
return {"status": "ok"}
@app.get("/dashboard", response_class=HTMLResponse)
def dashboard(request: Request):
html = '''<html>
<head><title>Factory Dashboard</title></head>
<body>
<h2>Factory Dashboard</h2>
<table border="1">
<tr><th>ID</th><th>TS</th><th>Station</th><th>Prod</th><th>NG</th><th>CT</th></tr>
{rows}
</table>
</body>
</html>'''
conn = get_db()
with conn.cursor() as cur:
cur.execute("SELECT * FROM factory_log ORDER BY id DESC LIMIT 20")
rows = cur.fetchall()
conn.close()
row_html = ""
for r in rows:
row_html += f"<tr><td>{r['id']}</td><td>{r['ts']}</td><td>{r['station']}</td><td>{r['prod_count']}</td><td>{r['ng_count']}</td><td>{r['ct']}</td></tr>"
return HTMLResponse(html.format(rows=row_html))
起動
uvicorn api_server:app --host 0.0.0.0 --port 8000
ダッシュボード表示
- http://Raspi_IP:8000/dashboard