# Smart Sports Facility Automation Architecture
## 10 Courts × 4 ON/OFF Lights — Reservations, Lighting & QR Access

---

## 1. Investor-Facing Summary

We are building a **fully automated, staff-light sports facility**: players book a court through any of the booking channels they already use (Booksy, Bookero, EasyWeek, CourtsApp, Google, WhatsApp, the website, and more), and everything else happens automatically. Every reservation lands in **one master calendar** (Google Calendar), which is the single source of truth for availability — this eliminates double bookings across all channels.

Minutes before a reservation starts, the **lights on the correct court switch on automatically**; after it ends, they switch off — cutting electricity waste and enabling unmanned evening operation. Each booking generates a **QR code** that opens the entrance door during the reservation's validity window — no keys, no receptionist. Group bookings are fully supported: either every participant gets a personal QR code, or the group shares one master code.

The result: a facility that can operate **24/7 with minimal staff**, lower energy costs, zero scheduling conflicts, and a modern customer experience — built almost entirely on proven, off-the-shelf hardware and open-source software, keeping both CAPEX and vendor lock-in low.

---

## 2. Data Flow (Text Diagram)

```
                          ┌─────────────────────────────────────────────┐
                          │           BOOKING CHANNELS                  │
                          │  Booksy · zarezerwuj.pl · Bookero ·         │
                          │  EasyWeek · CourtsApp · TennisTime ·        │
                          │  Clubiano · tenis4U · TwójTenis ·           │
                          │  Google Reserve · Website form ·            │
                          │  WhatsApp · Email · other apps              │
                          └───────────────┬─────────────────────────────┘
                                          │  API / webhook / polling /
                                          │  email parsing / manual entry
                                          ▼
┌──────────────────────────────────────────────────────────────────────────┐
│              MASTER CALENDAR — Google Calendar (single source of truth)  │
│   • one calendar per court (10 calendars) or one calendar + court tag    │
│   • availability checks BEFORE any booking is confirmed anywhere         │
│   • event metadata: court #, start, end, group size, QR policy, contact  │
└───────────────────────────────┬──────────────────────────────────────────┘
                                │  Google Calendar API (watch / sync)
                                ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                    HERMES — Orchestration & Business Logic               │
│  • normalizes events from all channels into one internal model           │
│  • conflict/double-booking resolution (master calendar wins)             │
│  • issues & revokes QR codes (individual or shared-group mode)           │
│  • schedules lighting jobs (ON at start − lead time, OFF at end + grace) │
│  • sends notifications (confirmation, QR, reminders) via email/WhatsApp  │
│  • monitors health of all integrations, alerting, audit log              │
└──────────────┬───────────────────────────────────┬───────────────────────┘
               │ automation commands (MQTT/REST)   │ QR validation request
               ▼                                   ▼
┌──────────────────────────────┐    ┌──────────────────────────────────────┐
│   HOME ASSISTANT OS          │    │        QR ACCESS LOGIC               │
│   (local automation layer)   │    │  reader at entrance → Hermes checks: │
│  • relays per court/light    │    │  valid code? within time window?     │
│  • schedules + manual wall   │    │  → yes: pulse door relay             │
│    switches as fallback      │    │  → no: deny + log + optional notify  │
│  • runs 100% locally even    │    └───────────────┬──────────────────────┘
│    if internet is down       │                    │ door relay pulse
└──────────────┬───────────────┘                    ▼
               │  relay coil drivers     ┌────────────────────┐
               ▼                         │  ELECTRIC STRIKE / │
┌──────────────────────────┐             │  MAGNETIC LOCK     │
│  RELAY MODULES /          │             └─────────┬──────────┘
│  CONTACTORS (DIN rail)    │                       ▼
│  10 courts × 4 lights =   │                 ENTRANCE OPENS
│  40 switched circuits     │
└──────────────┬───────────┘
               ▼
        COURT LIGHTS (ON/OFF)
```

**Key resilience principle:** the booking/sync layer needs internet, but Home Assistant executes lighting schedules **locally**, and the door controller caches valid QR windows — so the facility keeps working through an internet outage.

---

## 3. Technical Architecture

### 3.1 Booking Channel Integrations
Each channel connects through the best mechanism it offers, in priority order:
1. **Native API / webhooks** (Booksy, EasyWeek, Bookero and similar SaaS platforms typically expose partner APIs or calendar sync) — near-real-time push into the master calendar.
2. **iCal / CalDAV feed sync** — for platforms without webhooks; polled every 1–5 minutes.
3. **Google Reserve / Google Calendar** — writes directly into the master calendar natively.
4. **Website booking form** — talks to the orchestrator's API directly, which writes to the master calendar after an availability check.
5. **WhatsApp / email** — handled via a templated request flow (WhatsApp Business API / structured email parsing) that creates a *pending* reservation, confirmed only after an availability check against the master calendar.

All channels are **normalized to one reservation model**: `{court, start, end, customer, participants, channel, qr_mode, status}`.

### 3.2 Central Calendar — Google Calendar
- Acts as the **single source of truth**: nothing is "booked" until it exists as an event here.
- One calendar per court (recommended) → availability = free/busy query on that court's calendar.
- Every write goes through an **atomic check-then-create** step (query free/busy → create event) so two channels can never confirm the same slot. If a conflict is detected, the later request is rejected with the next available slots offered.
- Extended event properties carry structured metadata (court number, QR mode, group size, channel origin).

### 3.3 Hermes — Orchestration & Business Logic Layer
*(Described at behavior level only.)*
Hermes subscribes to calendar changes and drives everything downstream:
- **Scheduling engine:** computes lighting events per reservation — ON at `start − 10 min` (lead time configurable), OFF at `end + 5 min` grace — and handles back-to-back bookings by merging adjacent light windows so lights don't flicker off between sessions.
- **QR service:** generates cryptographically signed, single-purpose QR tokens with a validity window (e.g., 15 min before start → 15 min after end). Group mode: `individual` (one token per participant, each revocable) or `shared` (one token, configurable max entries). Codes can be revoked instantly if a booking is cancelled.
- **Notification service:** confirmation + QR delivery via email/WhatsApp, reminders, access-denied and anomaly alerts to staff.
- **Supervision:** health checks on every integration, sync-status dashboard, full audit log.

### 3.4 Home Assistant OS — Local Automation Layer
- Runs on a dedicated mini PC on-site; controls relays via local network (MQTT/ESPHome-class relay controllers or DIN-mounted network relay modules).
- Receives lighting schedules from the orchestrator but **executes them autonomously** — if the cloud link drops, lights still follow the day's schedule.
- Wall-mounted manual override switches per court (physical fallback, wired in parallel with relays where code permits).
- Optional later expansion: presence sensors, light-level sensors, energy metering per court, heating/ventilation control.

### 3.5 Light Switching Logic
- 10 courts × 4 lights = **40 switched circuits**, each ON/OFF only.
- Low-power LED fixtures can be switched by 16A relay modules; high-power discharge/flood lighting switches via **contactors** driven by the relays (protects relay contacts, handles inrush current).
- Each circuit individually fused/MCB-protected on the DIN rail.
- Behavior rules: per-reservation ON/OFF, back-to-back merge, grace period after end, manual override with auto-revert to schedule, "all off" schedule after closing time as a safety net.

### 3.6 QR Access Logic
1. Visitor scans QR at the entrance reader.
2. Reader forwards the token to the validation service (with local cache of active windows for offline resilience).
3. On success: short pulse to the door relay → electric strike/maglock releases; entry logged with timestamp and booking reference.
4. On failure: denial shown, attempt logged; repeated failures alert staff.
5. Emergency egress always mechanical (push bar) — access control never blocks exit, per fire code.

---

## 4. Hardware Shopping List

| # | Item | Suggested spec | Qty | Est. unit price (EUR) |
|---|------|----------------|-----|----------------------|
| 1 | Mini PC for Home Assistant OS | Intel N100-class, 16 GB RAM, fanless preferred | 1 | 200–300 |
| 2 | SSD storage | 500 GB NVMe/SATA | 1 | 40–60 |
| 3 | UPS | 1000–1500 VA line-interactive, USB monitoring | 1 | 150–250 |
| 4 | Router | Dual-WAN capable business router | 1 | 120–250 |
| 5 | Managed switch | 16-port Gigabit, PoE budget ≥150 W | 1 | 180–300 |
| 6 | DIN rail enclosure | Metal distribution cabinet, 48–72 modules | 1–2 | 100–250 |
| 7 | Relay modules | 16A DIN rail network relays (MQTT/ESPHome-class), 40 channels total | 3×16-ch | 120–200 ea |
| 8 | Contactors | 25–40A modular contactors (for high-power lighting circuits) | 10–20 | 15–35 ea |
| 9 | Circuit protection | MCBs per circuit (40×), RCDs, surge protector SPD Type 2 | set | 300–600 |
| 10 | QR code reader | Wiegand/RS485 or USB outdoor-rated 2D scanner | 1–2 | 100–250 ea |
| 11 | Door controller / relay board | Network relay for strike pulse (can share relay modules) | 1 | 60–150 |
| 12 | Electric strike or magnetic lock | Fail-safe strike or 280 kg maglock, per fire code | 1–2 | 60–200 ea |
| 13 | Power supplies | 12V DC DIN (locks/reader), 24V DC DIN (contactors/coils), 5V spares | 3–4 | 20–60 ea |
| 14 | Exit button + emergency break-glass | Push-to-exit, green break-glass for maglock | 1 set | 30–80 |
| 15 | Wall override switches | One per court | 10 | 5–15 ea |
| 16 | Wiring & accessories | CYKY/OWY cable, control wire, DIN rails, terminal blocks, cable ducts, connectors, labels | lot | 300–600 |
| 17 | Optional: energy meters | Per-court DIN rail meters (expansion) | 10 | 25–45 ea |

**Rough hardware budget: €2,500–4,500** plus certified electrician labor for the 230/400V panel work (required by law in most jurisdictions).

---

## 5. Recommended MVP (Phase 1, ~4–6 weeks)

Goal: prove the core loop on **2 courts** before scaling to 10.

**In scope:**
- Google Calendar as master calendar (2 court-calendars).
- Integrations: website form + Google Calendar native + **one** external platform (pick the highest-volume channel, e.g. Bookero) + manual entry for WhatsApp/email bookings.
- Double-booking prevention via check-then-create on the master calendar.
- Lighting automation for the 2 pilot courts (8 circuits) via Home Assistant + one 16-channel relay module.
- QR access: shared-group QR mode only (simpler), one reader, one electric strike, UPS, basic monitoring.

**Explicitly out of scope for MVP:** individual per-participant QR codes, remaining booking platforms, energy metering, maglock on second door, native mobile app.

**Success criteria before scaling:** zero double bookings in 30 days, ≥98% correct light automation, QR entry success rate ≥99%, measurable kWh savings vs. manual baseline.

---

## 6. Risks and Limitations

| Risk | Impact | Mitigation |
|------|--------|-----------|
| Booking platforms without open APIs | Sync delays, double-booking window | iCal polling as fallback; conflict resolution rule "master calendar wins"; buffer times |
| Internet outage | New bookings impossible | Local execution of pre-loaded schedules; cached QR windows; LTE/5G backup WAN on router |
| Power outage | Lights/door dead | UPS for control gear; **fail-safe** door hardware (unlocks on power loss per fire code); mechanical key override |
| Google Calendar API limits/outage | Master calendar unavailable | Local shadow copy of schedule in Home Assistant; queued writes on recovery |
| QR code sharing/misuse | Unauthorized entry | Short validity windows, signed tokens, optional entry-count limits, audit log, camera at entrance (optional) |
| Electrical compliance | Legal/safety exposure | All 230/400V work by certified electrician; RCDs, SPD, inspection sign-off |
| GDPR (booking & entry logs) | Legal exposure | Data minimization, retention policy, consent in booking terms, EU-hosted processing where required |
| WhatsApp/email bookings | Unstructured, error-prone | Templated flow creates *pending* reservations only; human or rule-based confirmation before calendar write |
| Vendor lock-in | Long-term cost | Open-source core (Home Assistant), standard protocols (MQTT, iCal, Google Calendar API), commodity hardware |

---

## 7. Implementation Stages

| Stage | Duration | Deliverables |
|-------|----------|--------------|
| **0. Design & procurement** | 2–3 weeks | Final electrical design, API access requests to booking platforms, hardware orders, fire-code consultation for door hardware |
| **1. Core backbone** | 2 weeks | Mini PC + Home Assistant OS, network (router/switch/UPS), master Google Calendar structure, Hermes core with check-then-create booking engine |
| **2. MVP pilot (2 courts)** | 2–3 weeks | Electrical panel build (relays, contactors, protection — certified electrician), 8 lighting circuits live, website form + 1 platform integration, shared QR + electric strike on entrance |
| **3. Pilot validation** | 4 weeks | Live operation against success criteria, tuning lead/grace times, offline-resilience tests |
| **4. Scale to 10 courts** | 2–3 weeks | Remaining 32 circuits, wall overrides, remaining channel integrations (Booksy, EasyWeek, CourtsApp, TennisTime, Clubiano, tenis4U, TwójTenis, zarezerwuj.pl, Google Reserve, WhatsApp/email flows) |
| **5. Advanced access & polish** | 2–3 weeks | Individual per-participant QR codes, revocation flows, staff dashboard, alerting, second door/maglock if needed |
| **6. Optimization (optional)** | ongoing | Energy metering per court, presence-based light trim, dynamic pricing hooks, extended-hours unmanned operation |

**Total to full deployment: roughly 3–4 months**, with revenue-relevant automation (no double bookings, automatic lights, QR entry) already live after the MVP.
