🍓 Raspberry Pi Backend — Infrastructure Plan

Dedicated backend on RPi for Amfor-Cast: compute, data storage, API endpoints • Aug 2026

1. Concept

Core idea: Raspberry Pi runs all backend logic (cron jobs, data storage, evaluation, API endpoints). Static frontend deployed to tarhely.com. GitLab remains the code repository and development platform.

Three-tier separation:

LayerWhereResponsibility
Code & DevelopmentGitLabSource repo, CI, dev preview (Pages), code review
Backend & DataRaspberry Pi (home)Cron, API calls, scoring, ranking, route log API, data storage
Frontend & Servingtarhely.comStatic HTML/JS/CSS, public-facing, fast CDN

2. Architecture

┌─────────────────────────────────────────────────────────────────────────────┐ │ GitLab (gitlab.com/demogun1/misc_scripts) │ │ │ │ • Source code (Python, HTML, JS) │ │ • CI pipeline (lint, test) │ │ • GitLab Pages = dev/preview version │ │ • Webhook → notifies Pi on push (optional) │ └──────────────────────────────────┬──────────────────────────────────────────┘ │ git pull (Pi cron, every 15min or webhook) ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Raspberry Pi 4/5 (home network, dynamic DNS) │ │ │ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ │ /opt/amfor-cast/ │ │ │ │ ├── repo/ (git clone — auto-pulled) │ │ │ │ ├── data/ (persistent: forecasts, scores, stations) │ │ │ │ │ ├── forecasts/*.json │ │ │ │ │ ├── scores.json │ │ │ │ │ ├── stations.json │ │ │ │ │ ├── model-rankings.json │ │ │ │ │ └── route-logs/*.json │ │ │ │ ├── output/ (generated HTML, synced to frontend) │ │ │ │ └── venv/ (Python 3.12 virtualenv) │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ Services: │ │ ├── Cron: hourly forecast + daily validator │ │ ├── Flask/FastAPI: /api/log-route (receives route feedback POSTs) │ │ ├── rsync: syncs output/ → tarhely.com (after each generation) │ │ └── Nginx (optional): local preview + API reverse proxy │ └──────────────────────────────────┬──────────────────────────────────────────┘ │ rsync/scp (SSH key) ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ tarhely.com (we050.tarhely.com) │ │ │ │ /home/amforcas/public_html/ │ │ ├── index.html │ │ ├── route-weather.html + .js │ │ ├── i18n.js │ │ ├── model-rankings.json (for client-side adaptive selection) │ │ ├── weather-forecast-*.html │ │ ├── weather-history-*.html │ │ ├── model-rankings.html │ │ ├── headache-analysis.html │ │ └── user-guide.html, dev-docs.html │ │ │ │ Pure static serving — no compute, no Python, no cron. │ │ The route-weather.js POSTs to Pi's API endpoint for route logging. │ └─────────────────────────────────────────────────────────────────────────────┘

3. Hardware Recommendation

ComponentPi 4 (budget)Pi 5 (recommended)
CPU4× Cortex-A72 @ 1.8GHz4× Cortex-A76 @ 2.4GHz
RAM4GB sufficient4GB sufficient (8GB future-proof)
Storage32GB microSD + USB SSD recommended32GB microSD + NVMe via HAT
Power~5W idle~7W idle
OSRaspberry Pi OS Lite (64-bit)Raspberry Pi OS Lite (64-bit)
Cost~€50-60~€70-90

Storage recommendation: Use a USB SSD (even 128GB is fine) instead of only microSD. SD cards wear out with frequent writes (JSON files, logs). Boot from SD, store data on SSD.

4. Network Setup

The challenge: reaching the Pi from the internet

The Pi sits behind your home router. For tarhely.com's route-weather.js to POST route logs to the Pi, the Pi needs to be reachable. Options:

MethodComplexityBest for
Dynamic DNS + port forwardEasyIf your ISP gives you a public IP. Forward port 443 to Pi.
Cloudflare TunnelMediumNo port forwarding needed. Free. Pi connects outbound to Cloudflare.
Tailscale/WireGuardMediumIf only YOU need to reach the Pi (not public users).
Pi pushes to tarhely.comSimplestNo inbound needed — Pi just rsyncs output. Route logs handled differently.

Recommended: Cloudflare Tunnel (free)

Alternative: Pi as output-only (no inbound)

If you don't want to expose the Pi publicly:

5. Software Stack on Pi

# OS
Raspberry Pi OS Lite 64-bit (Debian Bookworm based)

# System packages
sudo apt install python3 python3-venv git nginx rsync

# Python environment
python3 -m venv /opt/amfor-cast/venv
source /opt/amfor-cast/venv/bin/activate
/opt/amfor-cast/venv/bin/python3 -m pip install flask gunicorn markdown

# Git identity (needed for pull --rebase and any commits)
git config --global user.email "demogun@gmail.com"
git config --global user.name "Attila Vigh"

# Clone repo
git clone https://gitlab.com/demogun1/misc_scripts.git /opt/amfor-cast/repo

# Symlink data dir (on SSD)
ln -s /mnt/ssd/amfor-data /opt/amfor-cast/data

# Cloudflare tunnel (for public API)
curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64.deb -o cloudflared.deb
sudo dpkg -i cloudflared.deb
cloudflared tunnel login
cloudflared tunnel create amfor-cast

6. Cron Jobs on Pi

# Pull latest code from GitLab (every 15 min)
*/15 * * * * cd /opt/amfor-cast/repo && git pull -r --quiet origin main

# Hourly: pull + generate forecasts + history (skip scoring)
0 * * * * cd /opt/amfor-cast/repo && git pull -r && /opt/amfor-cast/venv/bin/python3 run-and-publish.py --skip-validator --output-dir /opt/amfor-cast/output --data-dir /opt/amfor-cast/data

# Daily 07:00 CEST: save snapshot + evaluate + score
0 5 * * * cd /opt/amfor-cast/repo && git pull -r && /opt/amfor-cast/venv/bin/python3 run-and-publish.py --only-validator --force --data-dir /opt/amfor-cast/data

# After each generation: sync output to tarhely.com
5 * * * * rsync -az --delete -e ssh /opt/amfor-cast/output/ amforcas@we050.tarhely.com:/home/amforcas/public_html/

# Weekly: prune old route logs (keep 90 days)
0 3 * * 0 find /opt/amfor-cast/data/route-logs -name "*.json" -mtime +90 -delete

7. Route Log API (Flask)

# /opt/amfor-cast/api/app.py
from flask import Flask, request, jsonify
from pathlib import Path
from datetime import datetime
import json, uuid

app = Flask(__name__)
ROUTE_LOGS_DIR = Path("/opt/amfor-cast/data/route-logs")

@app.route("/api/log-route", methods=["POST"])
def log_route():
    """Receive route forecast data from client-side route planner."""
    data = request.get_json()
    if not data or "waypoints" not in data:
        return jsonify({"error": "Invalid payload"}), 400

    filename = f"{datetime.now().strftime('%Y-%m-%d')}_route_{uuid.uuid4().hex[:8]}.json"
    ROUTE_LOGS_DIR.mkdir(parents=True, exist_ok=True)
    (ROUTE_LOGS_DIR / filename).write_text(json.dumps(data, indent=2))

    return jsonify({"status": "ok", "id": filename}), 201

@app.route("/api/health", methods=["GET"])
def health():
    return jsonify({"status": "ok", "timestamp": datetime.now().isoformat()})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

Systemd service:

# /etc/systemd/system/amfor-api.service
[Unit]
Description=Amfor-Cast Route Log API
After=network.target

[Service]
Type=simple
User=pi
WorkingDirectory=/opt/amfor-cast/api
ExecStart=/opt/amfor-cast/venv/bin/gunicorn -w 2 -b 127.0.0.1:5000 app:app
Restart=always

[Install]
WantedBy=multi-user.target

Nginx reverse proxy (if using Cloudflare Tunnel):

# /etc/nginx/sites-available/amfor-api
server {
    listen 8080;
    server_name localhost;

    location /api/ {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location / {
        root /opt/amfor-cast/output;
        index index.html;
    }
}

8. Deployment Flow

Developer (you) Raspberry Pi tarhely.com │ │ │ │ git push to GitLab │ │ │──────────────────────────────▶ │ │ │ │ │ │ git pull (cron/webhook)│ │ │ │◀─── pulls every 15 min │ │ │ │ │ cron: run-and-publish │ │ │ │──── generates HTML ──────▶ │ │ │ (rsync output/) │ │ │ │ │ │ │ │ User visits website │ │ │ │ │◀── serves HTML │ │ │ │ User plans a route │ │ │ │◀── POST /api/log-route ──────│ │ │ (via Cloudflare Tunnel) │ │ │ │ │ cron: evaluate-routes │ │ │ │──── scores route logs │ │ │──── updates rankings │ │ │──── rsyncs new rankings ──▶ │ │ │ │

9. Code Changes Required

ChangeWhy
Add --output-dir flag to run-and-publish.pyOutput goes to /opt/amfor-cast/output/ not public_html/
Add --data-dir flag to all scriptsData lives on SSD, not in repo
Update route-weather.js API URLPOST to https://api.yourdomain.com/log-route
Remove scp deploy from run-and-publish.pyReplaced by rsync cron
Remove git push deployPi pushes via rsync, not git
Add .gitignore for data/ and output/Data stays on Pi, not in repo

10. Security

Checklist before exposing Pi to internet:

11. Monitoring & Reliability

WhatHow
Pi alive?UptimeRobot (free) pings /api/health every 5 min
Cron ran?Check output file timestamps; alert if >2h stale
Disk spaceCron: df -h → alert if >80%
Temperaturevcgencmd measure_temp → log + alert if >70°C
Auto-restartSystemd restart-on-failure for API service
Power failureUPS (optional, €30) or accept ~1h data gap on rare outages

12. Cost Comparison

ItemPi setup (one-time)Monthly
Raspberry Pi 5 (4GB)€70—
microSD 32GB + USB SSD 128GB€35—
Power supply + case€25—
Electricity (~7W)—~€1.50
tarhely.com hosting—~€3-5
Cloudflare Tunnel—Free
Domain (optional)—~€1/month
Total~€130~€5-7/month

13. Implementation Phases

Phase 1 Pi Basic Setup

Phase 2 Deploy Pipeline

Phase 3 Route Log API

Phase 4 Hardening & Monitoring

14. Migration Path from Current Setup

No big-bang migration needed. Run both in parallel, cut over gradually:

  1. Week 1: Pi runs alongside build server cron. Both generate output. Compare results.
  2. Week 2: Pi's output goes to tarhely.com. Build server still pushes to GitLab Pages (backup).
  3. Week 3: Disable build server cron. Pi is primary. GitLab Pages becomes dev preview only.
  4. Future: Route log API goes live. Feedback loop closed.

15. What I Need From You

  1. Which Pi? — Pi 4 (4GB) or Pi 5? Do you already have one?
  2. Home internet — do you have a static IP or dynamic? Is your ISP behind CG-NAT?
  3. Domain — do you have or want a custom domain for the API endpoint?
  4. tarhely.com SSH — once active, confirm rsync works from your home network
  5. Go-ahead to start? — I can prepare the code changes (--output-dir, --data-dir) now