Added setup folder with needed launch files - Update when new version is ready

This commit is contained in:
Jeff Luke committed 2026-10-07 06:06:03 -07:00
1 parent 91b7840535
commit 0dcada4db2
50 files changed
+3753 -11

No files matched your search

@@ -0,0 +1,2 @@
__pycache__/
*.sqlite3*
+167
View File
@@ -0,0 +1,167 @@
# Arcade room controller and browser operator
See the [cabinet setup guide](../../docs/cabinet_setup.md) for the supplied internal token registry and PC-versus-Pi configuration examples.
This controller is independent of Odin. It uses Python's standard library, authenticated HTTP, and SQLite; no Odin services or dependencies are needed.
For supervised startup on Windows or the Pi, use the [stack launch scripts](../launch/README.md). The manual commands below remain available for troubleshooting.
## Available now
- A touch-friendly browser operator for the Mac mini and iPads, served by the controller itself.
- Room boundary, walls, cabinet positions, and reference device positions exported from the existing editor resources.
- Independent cabinet connections, game sessions, readiness, win/loss states, and command history.
- Scenario preparation across multiple cabinets. The entire assignment list is validated before commands are queued. Each cabinet acknowledges separately; this is not an atomic room-wide load.
- Compatible game lists and server-side and cabinet-side hardware checks. Games load from the cabinet's installed export; this does not transfer game binaries.
- Designer event mappings for `game_activated`, `game_started`, `game_won`, and `game_lost`. Other event mappings and nonstandard variants are rejected instead of silently ignored.
- Manual game assignments without scenario hardware rewards.
- Idempotent GPIO commands through the existing local bridge. Accepted commands do not prove a coin was delivered or a physical device changed.
External sensor inputs, detailed designer-defined puzzle steps, room timers/hints, and coordinated finale game variants are future work. The map's device dots are reference positions, not live sensor indicators. Runtime phases and hardware command acknowledgements are live.
## Deployment layout
```text
Mac mini / PC: Python controller :8766 + persistent SQLite database
^ browser operator (Mac / iPad, same controller URL)
^ managed Godot cabinet clients (one identity per Pi)
-> local GPIO bridge 127.0.0.1:8765 -> cabinet hardware
```
Use a trusted isolated room LAN. This HTTP configuration does not encrypt traffic; use TLS termination before using an untrusted network. Do not expose it directly to the internet. The GPIO bridge stays on each Pi's loopback address, not the controller address.
## 1. Export the designer catalog
The source of truth remains the existing Godot resources:
- `data/project_database.tres`: registered cabinets, games, and scenarios.
- `data/rooms/arcade_room.tres`: room layout and cabinet/device placements.
- `data/cabinets/*.tres`: cabinet IDs, capabilities, and hardware actions.
- `data/games/*.tres`: requirements and alternative control sets.
After saving designer changes, run this on the development computer (replace `godot` with your Godot executable):
```sh
godot --headless --path . --script tools/room_controller/export_catalog.gd
```
This writes `tools/room_controller/catalog.json`. Copy **server.py, operator.html, and catalog.json together** onto the controller machine. Restart the controller after updating the catalog. Re-export/redeploy Godot when game, cabinet, or hardware resources change; its own compatibility check uses those packaged resources.
Capabilities describe physical controls; they do not replace the per-device control mapping wizard. Configure both. Common requirements must all be present; when a game has control alternatives, one entire alternative must also be present. Tempest accepts horizontal joystick, spinner, or trackball plus two buttons and Start. Robotron accepts dual 8-way joysticks or one 8-way joystick plus four firing buttons, with Start. Missile Command requires trackball, three fire buttons, and Start.
The sample cabinet profiles are intentionally not expanded to claim hardware they may not have. Cabinet 01/02 currently list one action button; Cabinet 03 has no room placement. Update these resources to match the physical cabinets before expecting all seven games to appear in their compatible lists.
## 2. Start the controller on the Mac mini (or PC)
Python 3 is needed on the controller; Godot is not. Generate a different random token of at least 16 characters for the operator and for each cabinet. The assigned tokens for this internal installation are recorded in the cabinet setup guide.
macOS / Linux:
```sh
export ARCADE_OPERATOR_TOKEN='your-generated-operator-token'
export ARCADE_CABINET_TOKENS='{"cabinet_01":"your-generated-cabinet-one-token","cabinet_02":"your-generated-cabinet-two-token"}'
python3 server.py --bind 0.0.0.0 --database /absolute/path/arcade_room.sqlite3
```
Windows PowerShell, from the project directory:
```powershell
$env:ARCADE_OPERATOR_TOKEN = 'your-generated-operator-token'
$env:ARCADE_CABINET_TOKENS = '{"cabinet_01":"your-generated-cabinet-one-token","cabinet_02":"your-generated-cabinet-two-token"}'
py -3 tools/room_controller/server.py --bind 0.0.0.0 --database arcade_room.sqlite3
```
The existing `ARCADE_CABINET_TOKEN` environment variable still provisions `cabinet_01` if that ID is not already in the JSON object. Cabinets without provisioned tokens cannot connect. Each cabinet token is bound to its ID and cannot control other cabinets or use the operator API.
Keep the database path stable. Allow inbound TCP 8766 on the room LAN. Existing single-cabinet state is migrated into cabinet 01's record; do not delete the database to upgrade. Back it up before deployment. Connectivity always starts offline until a cabinet polls again.
## 3. Start each Pi cabinet
Deploy the updated Godot export: the fleet controller requires protocol 2 (`arcade-cabinet-2`). Old cabinet exports are rejected so they cannot incorrectly load Pac-Man for a different assignment.
First run the normal launcher to map that Pi's physical controls. The managed client uses the saved mappings. Escape still quits.
Configure `user://arcade_network.cfg` on each Pi:
```ini
[network]
url="http://CONTROLLER_IP:8766"
cabinet_id="cabinet_01"
cabinet_token="your-generated-cabinet-one-token"
```
Godot CFG strings use double quotes. The file belongs in the app's user data folder, not beside the executable: normally `~/.local/share/godot/app_userdata/ArcadeEscape/` on Linux and `%APPDATA%/Godot/app_userdata/ArcadeEscape/` on Windows. URL/token environment variables override the file. `--cabinet=cabinet_02` overrides the cabinet ID.
Start the [GPIO bridge](../pi_gpio/README.md) on each Pi with that cabinet's controller ID and configured BCM pin allowlist. For the Cabinet 01 coin-release LED test:
```sh
GPIOZERO_PIN_FACTORY=lgpio python3 pi_gpio_bridge.py --controller cabinet_01_gpio --pins 17
./ArcadeEscape.arm64 -- --managed-cabinet --cabinet=cabinet_01 --gpio=real
```
Run those in separate terminals/services. Additional mapped actions require their actual pins in the bridge's allowlist. Do not use the cabinet 01 bridge identity on cabinet 02. Only run one managed game process per cabinet ID. The GPIO helper uses port **8765 locally**, while the room URL uses **8766**.
For desktop game/network testing, omit `--gpio=real`. Hardware actions report failure in simulation mode; they do not claim physical success.
## 4. Use the operator
Open `http://CONTROLLER_IP:8766/` in the Mac or iPad browser and enter the operator token. No iPad app or Godot installation is needed. The token stays in page memory and is cleared by Lock, reload, or closing the page.
1. Verify the expected cabinets show ONLINE.
2. Select a scenario and **Prepare assigned cabinets**. Each cabinet changes from PREPARING to READY only after its game loads. An offline or incompatible assignment prevents the entire dispatch.
3. Select a cabinet on the map or card, then **Start game**, or use the cabinet's mapped Start button.
4. Watch its runtime phase, hardware command statuses, and activity history. Win outputs follow that scenario's event mappings.
5. **Reset cabinet…** ends its current session. Reset active cabinets before preparing another scenario.
6. For an individual game override, select a compatible game and **Prepare game**. This deliberately removes scenario event mappings for that cabinet; no automatic coin reward is inherited.
The room map uses the saved designer positions. Cabinets without placements remain selectable through their cards. This is an operator view; continue editing layout/scenarios in Godot, then re-export the catalog.
The older exported `--operator` Godot window remains a Cabinet 01 quick-control view. Its Prepare Pac-Man button prepares the `proof_of_concept` scenario and keeps that scenario's reward. Use the browser for multiple cabinets and other game assignments.
## Reconnects and uncertain hardware results
- Cabinets become offline after roughly four seconds without a poll. The browser disables actions when the controller connection is unavailable.
- Commands expire after 15 seconds. Expired commands are not automatically reissued.
- Every command carries its cabinet session and unique ID. Old-session reports are ignored after Reset/Prepare.
- Duplicate command deliveries reuse the agent outcome; the GPIO bridge persists request IDs across helper restarts to prevent replayed pulses.
- A cabinet process restart requires preparation again. A reconnect by the same process can deliver its buffered reports.
- An accepted GPIO command confirms the bridge API call, not physical delivery. A timeout/failure is uncertain; inspect the hardware before trying again. There is no automatic reward retry.
- Keep the GPIO request ledger at its configured path, default `~/.local/state/arcade_gpio/requests.sqlite3`. Do not delete it to replay a command.
- Reset unloads the game and clears the controller session; it is not a physical hardware reset. Existing bridge pulse timers/watchdog still apply.
## Verification
```sh
python3 -m unittest discover -s tests/room_network -v
python3 -m unittest discover -s tests/gpio -v
python3 tests/room_network/check_integration.py /path/to/godot
godot --headless --path . --script tests/room_network/check_capabilities.gd
```
The integration test starts temporary localhost services on 8765/8766 and two actual headless Godot clients. It prepares Pac-Man via a scenario and Galaga via a manual assignment, forces wins only in the test harness, and verifies exactly one fake GPIO activation. Do not run while real services occupy those ports.
Deployment checklist: verify both cabinet IDs/tokens, test physical controls on each Pi, prepare a scenario and confirm both game names, win and check the intended LED/output only, reset, then unplug/reconnect one cabinet and confirm its offline/recovery behavior. Finally test the browser on the actual iPad; desktop browser checks do not replace device testing.
## Two-Pi chain test: Cabinet 1 wins -> Cabinet 2 starts
Select **Cabinet 1 -> Cabinet 2** (`cabinet_chain_test`) in the browser. This separate sample uses Pac-Man on `cabinet_01` followed by Galaga on `cabinet_02`, with no GPIO event mappings required.
1. On Windows, run the controller only: `.\Start-Arcade.ps1 -Mode controller -Browser`. Do not also start a Windows game using either Pi's cabinet identity.
2. Provision distinct cabinet tokens for `cabinet_01` and `cabinet_02` in the controller configuration.
3. On Pi 1 set `[cabinet] id = cabinet_01`; on Pi 2 set `id = cabinet_02`. Use each cabinet's matching token and the Windows controller URL, then run `bash start-arcade.sh cabinet` on both.
4. Confirm both cabinets are ONLINE. Reset any active assignments, select **Cabinet 1 -> Cabinet 2**, and click **Prepare assigned cabinets**.
5. Cabinet 1 becomes READY with Pac-Man. Cabinet 2 unloads any game, then shows WAITING in the operator; the Pi shows its existing waiting-for-operator screen. Its physical Start button cannot bypass the dependency because no game is loaded.
6. Start Cabinet 1 and win its configured Pac-Man objective. Cabinet 2 automatically loads Galaga, waits for the game's readiness acknowledgement, and starts it. No operator click or physical Start on Cabinet 2 is needed.
To repeat, reset Cabinet 1 and Cabinet 2, then prepare the scenario again. Resetting/reassigning/restarting a source cabinet invalidates its dependent sessions, including any running dependent game; prepare the scenario again. A loss does not activate the next cabinet. Duplicate win reports and acknowledgements do not create additional starts. An offline target waits until the same process reconnects; a restarted target or a failed/expired load requires operator preparation again.
The activation field is `activate_after_win` on a `ScenarioAssignment` resource (editable in the Inspector). Set it to another cabinet ID in the same scenario, or leave it empty for normal immediate preparation. Export the catalog after editing it. Missing dependencies and cycles are rejected before dispatch. This activation behavior belongs to the managed network controller; the local editor simulation does not execute this network chain.
For this update, deploy **server.py, catalog.json, and operator.html** together and restart the Windows controller, then refresh the browser. Existing protocol-2 Pi game exports already support the reset/prepare/start commands used here; a Pi game re-export is not required solely for this controller feature.
Automated two-client check (no GPIO; wins forced only by the test harness):
```sh
python3 tests/room_network/check_chain_integration.py /path/to/godot
```
+338
View File
@@ -0,0 +1,338 @@
{
"cabinets": {
"cabinet_01": {
"actions": [
"coin_release",
"start_light"
],
"capabilities": [
"joystick_4way",
"button_1",
"start_button",
"joystick_horizontal",
"button_2",
"button_3",
"button_4",
"button_5",
"button_6",
"select_button",
"trackball",
"joystick_8way",
"joystick_dual"
],
"name": "Master Cabinet",
"position": [
-5.94849967956543,
0.147500038146973
]
},
"cabinet_02": {
"actions": [
"coin_release",
"start_light",
"glitch_code"
],
"capabilities": [
"joystick_4way",
"button_1",
"start_button",
"joystick_horizontal"
],
"name": "Cabinet 02",
"position": [
-3.51539182662964,
0.142745211720467
]
},
"cabinet_03": {
"actions": [
"coin_release"
],
"capabilities": [
"spinner",
"button_1",
"start_button"
],
"name": "Cabinet 03",
"position": null
}
},
"games": {
"frogger": {
"alternatives": [],
"name": "Frogger",
"requirements": [
"joystick_4way",
"start_button"
]
},
"galaga": {
"alternatives": [],
"name": "Galaga",
"requirements": [
"joystick_horizontal",
"button_1",
"start_button"
]
},
"missile_command": {
"alternatives": [],
"name": "Missile Command",
"requirements": [
"trackball",
"button_1",
"button_2",
"button_3",
"start_button"
]
},
"pacman": {
"alternatives": [],
"name": "Pac-Man",
"requirements": [
"joystick_4way",
"start_button"
]
},
"robotron": {
"alternatives": [
[
"dual_joystick_8way"
],
[
"joystick_8way",
"button_1",
"button_2",
"button_3",
"button_4"
]
],
"name": "Robotron 2084",
"requirements": [
"start_button"
]
},
"space_invaders": {
"alternatives": [],
"name": "Space Invaders",
"requirements": [
"joystick_horizontal",
"button_1",
"start_button"
]
},
"tempest": {
"alternatives": [
[
"joystick_horizontal"
],
[
"spinner"
],
[
"trackball"
]
],
"name": "Tempest",
"requirements": [
"button_1",
"button_2",
"start_button"
]
}
},
"layout": {
"boundary": [
[
-7.31519985198975,
-0.609600007534027
],
[
-2.13359999656677,
-0.609600007534027
],
[
-2.13359999656677,
7.61999988555908
],
[
-7.31519985198975,
7.61999988555908
]
],
"devices": [
{
"id": "coin_release_a",
"name": "Coin Release A",
"position": [
-6.0149998664856,
0.555000007152557
]
},
{
"id": "coin_release_b",
"name": "Coin Release B",
"position": [
-3.57996416091919,
0.568386673927307
]
},
{
"id": "light_a",
"name": "Light A",
"position": [
-6.46999979019165,
0.560000002384186
]
},
{
"id": "light_b",
"name": "Light B",
"position": [
-4.0322380065918,
0.576531648635864
]
},
{
"id": "glitch_code",
"name": "Glitch Code",
"position": [
-2.75500297546387,
1.51234555244446
]
}
],
"walls": [
[
[
-7.01039981842041,
-0.304800003767014
],
[
-2.43840003013611,
-0.304800003767014
]
],
[
[
-2.43840003013611,
-0.304800003767014
],
[
-2.43840003013611,
7.31519985198975
]
],
[
[
-2.43840003013611,
7.31519985198975
],
[
-7.01039981842041,
7.31519985198975
]
],
[
[
-7.01039981842041,
7.31519985198975
],
[
-7.01039981842041,
-0.304800003767014
]
]
]
},
"scenarios": {
"cabinet_chain_test": {
"assignments": [
{
"activate_after_win": "",
"cabinet": "cabinet_01",
"game": "pacman",
"mappings": {},
"variant": "standard"
},
{
"activate_after_win": "cabinet_01",
"cabinet": "cabinet_02",
"game": "galaga",
"mappings": {},
"variant": "standard"
}
],
"name": "Cabinet 1 -> Cabinet 2"
},
"galaga_proof_of_concept": {
"assignments": [
{
"activate_after_win": "",
"cabinet": "cabinet_01",
"game": "galaga",
"mappings": {
"game_won": [
"coin_release"
]
},
"variant": "standard"
}
],
"name": "Galaga Proof of Concept"
},
"proof_of_concept": {
"assignments": [
{
"activate_after_win": "",
"cabinet": "cabinet_01",
"game": "pacman",
"mappings": {
"game_won": [
"coin_release"
]
},
"variant": "standard"
}
],
"name": "Proof of Concept"
},
"two_cabinet_test": {
"assignments": [
{
"activate_after_win": "",
"cabinet": "cabinet_01",
"game": "pacman",
"mappings": {
"game_started": [
"start_light"
],
"game_won": [
"coin_release"
]
},
"variant": "standard"
},
{
"activate_after_win": "",
"cabinet": "cabinet_02",
"game": "galaga",
"mappings": {
"game_activated": [
"glitch_code"
],
"game_started": [
"start_light"
],
"game_won": [
"coin_release"
]
},
"variant": "standard"
}
],
"name": "Two Cabinet Test"
}
},
"version": 1
}
@@ -0,0 +1,38 @@
extends SceneTree
## Export designer resources to the controller's deployment catalog.
func _initialize() -> void:
call_deferred("run")
func run() -> void:
var database: ProjectDatabase = load("res://data/project_database.tres")
var room: RoomDefinition = load("res://data/rooms/arcade_room.tres")
var catalog := {"version": 1, "games": {}, "cabinets": {}, "scenarios": {}, "layout": {"boundary": [], "walls": [], "devices": []}}
for game in database.games:
catalog.games[str(game.game_id)] = {"name": game.display_name, "requirements": Array(game.required_capabilities), "alternatives": Array(game.control_alternatives)}
for cabinet in database.cabinets:
var actions: Array = []
if cabinet.hardware_config != null:
for action in cabinet.hardware_config.actions: actions.append(str(action.action_id))
var placement := room.get_cabinet_placement(cabinet.cabinet_id)
catalog.cabinets[str(cabinet.cabinet_id)] = {"name": cabinet.display_name, "capabilities": Array(cabinet.capabilities), "actions": actions, "position": [placement.position.x, placement.position.y] if placement else null}
for scenario in database.scenarios:
var assignments: Array = []
for assignment in scenario.assignments:
if assignment.cabinet == null or assignment.game == null: continue
var mappings := {}
for mapping in assignment.event_mappings:
if not mappings.has(str(mapping.game_event)): mappings[str(mapping.game_event)] = []
mappings[str(mapping.game_event)].append_array(Array(mapping.hardware_actions))
assignments.append({"cabinet": str(assignment.cabinet.cabinet_id), "game": str(assignment.game.game_id), "variant": str(assignment.variant), "activate_after_win": str(assignment.activate_after_win), "mappings": mappings})
catalog.scenarios[str(scenario.scenario_id)] = {"name": scenario.display_name, "assignments": assignments}
for point in room.boundary_points: catalog.layout.boundary.append([point.x, point.y])
for wall in room.walls: catalog.layout.walls.append([[wall.start.x, wall.start.y], [wall.end.x, wall.end.y]])
for device in room.devices:
catalog.layout.devices.append({"id": str(device.device_id), "name": device.display_name, "position": [device.position.x, device.position.y]})
var file := FileAccess.open("res://tools/room_controller/catalog.json", FileAccess.WRITE)
if file == null:
push_error("Cannot write controller catalog")
quit(1)
return
file.store_string(JSON.stringify(catalog, "\t"))
print("Exported controller catalog from editor resources")
quit()
@@ -0,0 +1 @@
uid://bj7g63dhd8r1t
@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Arcade · Room operator</title>
<style>
:root{color-scheme:dark;font:16px system-ui,sans-serif;background:#0b111a;color:#e3ebf5}*{box-sizing:border-box}body{margin:0}header{padding:24px 4vw;border-bottom:1px solid #293749;display:flex;align-items:center;justify-content:space-between;gap:20px}h1{font-size:24px;margin:0}h2{font-size:18px;margin:0 0 16px}p{line-height:1.5}small,.muted{color:#9eb0c6}main{max-width:1500px;margin:auto;padding:28px 4vw}.panel{background:#121c29;border:1px solid #293749;border-radius:14px;padding:22px;margin-bottom:20px}.row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.columns{display:grid;grid-template-columns:1.25fr 1fr;gap:22px}button,input,select{font:inherit;border-radius:7px;border:1px solid #45576c;padding:12px;background:#1c2a3b;color:inherit;min-height:46px}button{cursor:pointer}button.primary{background:#69ddcd;color:#092923;border-color:#69ddcd;font-weight:650}button:disabled{opacity:.4;cursor:default}button:focus-visible,select:focus-visible,input:focus-visible{outline:3px solid #69ddcd;outline-offset:3px}select{max-width:100%}#login{max-width:550px;margin:8vh auto}#login input{width:100%;margin:10px 0}#status{color:#69ddcd}#error{color:#ffce96;white-space:pre-wrap}#error:empty{display:none}#cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px;margin-top:16px}.card{text-align:left;padding:16px;background:#152335}.card[aria-pressed=true]{border-color:#69ddcd;box-shadow:inset 0 0 0 1px #69ddcd}.card span{display:block;margin-top:9px;font-size:14px}svg{width:100%;height:340px;background:#0b131e;border-radius:8px}.steps{display:flex;gap:6px;flex-wrap:wrap;margin:18px 0}.steps span{padding:8px 10px;border-radius:5px;background:#223043;font-size:13px}.steps .current{background:#69ddcd;color:#092923}table{width:100%;border-collapse:collapse;font-size:14px}td,th{text-align:left;padding:10px 6px;border-bottom:1px solid #293749;overflow-wrap:anywhere}#events{max-height:270px;overflow:auto;padding-left:22px;font-size:14px}#events li{padding:6px}#assignment{white-space:pre-line}#scenarioSummary{font-size:14px;color:#b9c8d9}#output{overflow-x:auto}#signout{font-size:14px} [hidden]{display:none!important}@media(max-width:850px){.columns{grid-template-columns:1fr}header{align-items:flex-start}main{padding:18px}svg{height:280px}}
</style></head><body>
<header><div><small>ARCADE ESCAPE / OPERATIONS</small><h1>Room control</h1></div><div class="row"><span id="status" role="status">Not connected</span><button id="signout" hidden>Lock</button></div></header>
<main><div id="error" class="panel" role="alert"></div>
<form id="login" class="panel"><h2>Connect to this room</h2><p class="muted">Use the operator token configured on this controller. It stays in memory until this page closes or locks.</p><label for="token">Operator token</label><input id="token" type="password" autocomplete="off" required><button class="primary">Connect</button></form>
<div id="workspace" hidden>
<section class="panel"><h2>Prepare a scenario</h2><div class="row"><select id="scenario" aria-label="Scenario"></select><button id="prepareScenario" class="primary">Prepare assigned cabinets</button></div><p id="scenarioSummary"></p><small>Preparation loads games and their event-to-hardware mappings. Start each cabinet when ready. Reset active cabinets before changing assignments.</small></section>
<div class="columns"><section class="panel"><h2>Room overview</h2><svg id="map" role="img" aria-label="Room layout and cabinet status"></svg><p class="muted"><small>Cabinet colors show runtime state. Room devices are reference locations; physical sensor feedback is not connected.</small></p><div id="cards"></div></section>
<section class="panel"><h2 id="cabinetTitle">Select a cabinet</h2><p id="connection" class="muted"></p><p id="assignment"></p><div id="steps" class="steps"></div><div class="row"><button id="start" class="primary">Start game</button><button id="reset">Reset cabinet…</button></div><hr style="border:0;border-top:1px solid #293749;margin:24px 0"><h2>Manual game assignment</h2><div class="row"><select id="game" aria-label="Compatible game"></select><button id="prepare">Prepare game</button></div><p><small>Only compatible games are listed. Manual assignments run without scenario hardware rewards.</small></p><h2>Hardware commands</h2><p id="reward" class="muted"></p><div id="output"></div><h2 style="margin-top:24px">Activity</h2><ol id="events"></ol></section></div>
</div></main><script>
'use strict';
const $=id=>document.getElementById(id);let token='',state=null,selected='',pending=false,connected=false,refreshing=false;
const colors={ready:'#69ddcd',playing:'#7bbaff',won:'#b4ec86',lost:'#ffae9e'};
function node(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e}
async function api(path,data={}){const response=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:JSON.stringify(data),signal:AbortSignal.timeout(6000)});const value=await response.json();if(!response.ok)throw Error(value.error||'Controller request failed');return value}
function options(id,entries){const select=$(id),before=select.value;if(select.options.length===entries.length&&entries.every(([value,name],i)=>select.options[i].value===value&&select.options[i].textContent===name))return;select.replaceChildren(...entries.map(([value,name])=>{const o=node('option',name);o.value=value;return o}));if(entries.some(x=>x[0]===before))select.value=before}
function enable(){const c=state?.cabinets[selected],available=connected&&!pending;const queued=c?.commands.some(x=>x.status==='queued');$('start').disabled=!available||!c?.online||c.phase!=='ready'||!!c.gate||queued;$('reset').disabled=!available||!c?.online||['preparing','starting','resetting'].includes(c.phase);$('prepare').disabled=!available||!c?.online||queued||!['idle','won','lost','needs_prepare'].includes(c.phase)||!$('game').value;$('prepareScenario').disabled=!available||!$('scenario').value}
function scenarioSummary(){if(!state)return;const s=state.catalog.scenarios[$('scenario').value];$('scenarioSummary').textContent=s?s.assignments.map(a=>(state.catalog.cabinets[a.cabinet]?.name||a.cabinet)+' → '+(state.catalog.games[a.game]?.name||a.game)).join(' · '):'No scenarios exported'}
function drawMap(){const svg=$('map'),layout=state.catalog.layout,points=[...layout.boundary,...Object.values(state.cabinets).filter(c=>c.definition.position).map(c=>c.definition.position),...layout.walls.flat(),...layout.devices.map(d=>d.position)];svg.replaceChildren();if(!points.length)return;const xs=points.map(p=>p[0]),ys=points.map(p=>p[1]),minX=Math.min(...xs)-1,minY=Math.min(...ys)-1,w=Math.max(...xs)-minX+1,h=Math.max(...ys)-minY+1;svg.setAttribute('viewBox',`${minX} ${minY} ${w} ${h}`);const unit=Math.max(w,h)/18;function shape(tag,attrs,text){const e=document.createElementNS('http://www.w3.org/2000/svg',tag);for(const [k,v]of Object.entries(attrs))e.setAttribute(k,v);if(text)e.textContent=text;svg.append(e);return e}if(layout.boundary.length)shape('polygon',{points:layout.boundary.map(p=>p.join(',')).join(' '),fill:'#152335',stroke:'#435770','stroke-width':unit/14});for(const wall of layout.walls)shape('line',{x1:wall[0][0],y1:wall[0][1],x2:wall[1][0],y2:wall[1][1],stroke:'#647a92','stroke-width':unit/10});for(const d of layout.devices){const e=shape('circle',{cx:d.position[0],cy:d.position[1],r:unit*.18,fill:'#8491a2'});const title=document.createElementNS(svg.namespaceURI,'title');title.textContent=d.name+' — no sensor feedback';e.append(title)}for(const [id,c]of Object.entries(state.cabinets)){const p=c.definition.position;if(!p)continue;const e=shape('circle',{cx:p[0],cy:p[1],r:unit*.5,fill:c.online?colors[c.phase]||'#e5c57b':'#647081',stroke:id===selected?'white':'none','stroke-width':unit/10});e.style.cursor='pointer';e.onclick=()=>{selected=id;render()};shape('text',{x:p[0],y:p[1]-unit*.75,fill:'#e3ebf5','font-size':unit*.6,'text-anchor':'middle'},c.definition.name)}}
function render(){if(!state?.cabinets)throw Error('Update the room controller to use the browser operator');if(!state.cabinets[selected])selected=Object.keys(state.cabinets)[0];options('scenario',Object.entries(state.catalog.scenarios).map(([id,s])=>[id,s.name]));scenarioSummary();$('cards').replaceChildren();for(const[id,c]of Object.entries(state.cabinets)){const b=node('button',c.definition.name,'card');b.setAttribute('aria-pressed',id===selected);b.append(node('span',(c.online?'ONLINE':'OFFLINE')+' · '+c.phase.toUpperCase()));b.append(node('span',state.catalog.games[c.game]?.name||c.game,'muted'));if(!c.definition.position)b.append(node('span','Not placed in room map','muted'));b.onclick=()=>{selected=id;render()};$('cards').append(b)}drawMap();const c=state.cabinets[selected];$('cabinetTitle').textContent=c.definition.name;$('connection').textContent=(c.online?'Online':'Offline')+' · '+c.version+' · GPIO: '+c.gpio;$('assignment').textContent='Game: '+(state.catalog.games[c.game]?.name||c.game)+'\nAssignment: '+(c.scenario||'None prepared')+(c.gate?'\nActivation: after '+c.gate.cabinet+' wins':'');$('steps').replaceChildren(...['idle','waiting','preparing','ready','playing','won','lost'].map(p=>node('span',p.toUpperCase(),c.phase===p?'current':'')));options('game',c.compatible_games.map(id=>[id,state.catalog.games[id].name]));$('reward').textContent='Win output: '+c.reward;const table=node('table'),head=node('tr');for(const name of ['Action','Status'])head.append(node('th',name));table.append(head);for(const command of c.commands.filter(x=>['output','reward'].includes(x.type))){const row=node('tr');row.append(node('td',command.action_id||command.type),node('td',command.status==='accepted'?'Accepted · physical result unconfirmed':command.status));table.append(row)}$('output').replaceChildren(table);$('events').replaceChildren(...c.history.slice().reverse().map(e=>node('li',new Date(e.time*1000).toLocaleTimeString()+' · '+e.message)));enable()}
async function refresh(){if(!token||refreshing||pending)return;refreshing=true;try{state=await api('/operator/state');connected=true;render();$('workspace').hidden=false;$('login').hidden=true;$('signout').hidden=false;$('status').textContent='Controller connected'}catch(e){connected=false;$('status').textContent='Connection unavailable';$('error').textContent=e.message;enable()}finally{refreshing=false}}
async function command(action,extra={}){if(pending||!connected)return;pending=true;enable();$('error').textContent='';try{state=await api('/operator/command',{action,cabinet:selected,...extra});render()}catch(e){$('error').textContent=e.message}finally{pending=false;enable();refresh()}}
$('login').onsubmit=e=>{e.preventDefault();token=$('token').value.trim();$('token').value='';$('error').textContent='';refresh()};$('signout').onclick=()=>location.reload();$('scenario').onchange=scenarioSummary;$('prepareScenario').onclick=()=>command('prepare_scenario',{scenario:$('scenario').value});$('prepare').onclick=()=>command('prepare',{game:$('game').value});$('start').onclick=()=>command('start');$('reset').onclick=()=>{if(confirm('Reset '+state.cabinets[selected].definition.name+'? This ends its current game.'))command('reset')};setInterval(refresh,1000);
</script></body></html>
+388
View File
@@ -0,0 +1,388 @@
#!/usr/bin/env python3
"""Arcade room controller and browser operator; Python standard library only."""
import argparse
import hmac
import json
import os
from pathlib import Path
import sqlite3
import time
import uuid
from urllib.parse import urlparse
from http.server import BaseHTTPRequestHandler, HTTPServer
class Room:
def __init__(self, database, clock=time.time, cabinet_id="cabinet_01"):
self.clock = clock
self.cabinet_id = cabinet_id
self.db = sqlite3.connect(database, check_same_thread=False)
self.db.execute("CREATE TABLE IF NOT EXISTS room (id INTEGER PRIMARY KEY, value TEXT NOT NULL)")
self.db.execute("CREATE TABLE IF NOT EXISTS cabinet_rooms (id TEXT PRIMARY KEY, value TEXT NOT NULL)")
row = self.db.execute("SELECT value FROM cabinet_rooms WHERE id=?", (cabinet_id,)).fetchone()
if row is None and cabinet_id == "cabinet_01":
row = self.db.execute("SELECT value FROM room WHERE id=1").fetchone()
self.state = json.loads(row[0]) if row else dict(
session="", phase="idle", reward="not requested", commands=[], seen=[], history=[])
# Never carry live connectivity across a controller restart.
self.last_seen = 0
self.boot = self.state.get("boot", "")
self.version = "unknown"
self.gpio = "unknown"
self.state.setdefault("game", "pacman")
self.state.setdefault("mappings", {"game_won": ["coin_release"]})
self.save()
def save(self):
with self.db:
self.db.execute("INSERT OR REPLACE INTO cabinet_rooms VALUES (?, ?)", (self.cabinet_id, json.dumps(self.state)))
def log(self, message):
self.state["history"].append(dict(time=self.clock(), message=message))
self.state["history"] = self.state["history"][-100:]
def online(self):
return self.last_seen > 0 and self.clock() - self.last_seen < 4
def snapshot(self):
self.expire()
return dict(self.state, online=self.online(), cabinet=self.cabinet_id,
version=self.version, gpio=self.gpio,
last_seen=self.last_seen, protocol=2)
def expire(self):
for command in self.state["commands"]:
if command["status"] == "queued" and self.clock() > command["expires"]:
command["status"] = "unknown"
if command["type"] in ("reward", "output"):
self.state["reward" if command["type"] == "reward" else "last_output"] = "unknown — inspect hardware; not automatically retried"
else:
self.state["phase"] = "needs_prepare"
self.log(command["type"] + " acknowledgement timed out")
self.save()
def command(self, kind):
command = dict(id=str(uuid.uuid4()), session=self.state["session"], type=kind,
status="queued", expires=self.clock() + 15)
if kind == "prepare":
command.update(game=self.state["game"], variant=self.state.get("variant", "standard"))
self.state["commands"].append(command)
self.log("Queued " + kind)
return command
def operator(self, action):
self.expire()
if not self.online(): raise ValueError("Cabinet is offline; no command sent")
if any(c["status"] == "queued" and c["type"] not in ("output", "reward") for c in self.state["commands"]):
raise ValueError("Wait for the pending command or its timeout")
if action in ("prepare", "reset"):
if action == "prepare" and self.state["phase"] not in ("idle", "won", "lost", "needs_prepare"):
raise ValueError("Reset the active session before preparing again")
self.state.update(session=str(uuid.uuid4()), phase="preparing" if action == "prepare" else "resetting",
reward="not requested", commands=[], seen=[])
self.command(action)
elif action == "start":
if self.state["phase"] != "ready": raise ValueError("Prepare the cabinet first")
self.state["phase"] = "starting"
self.command("start")
else:
raise ValueError("Unknown operator action")
self.save()
return self.snapshot()
def poll(self, data):
if data.get("cabinet") != self.cabinet_id or data.get("protocol") not in (1, 2):
raise ValueError("Wrong cabinet or protocol version")
boot = data.get("boot")
if not isinstance(boot, str) or not 1 <= len(boot) <= 100:
raise ValueError("Missing cabinet boot identity")
if self.boot and boot != self.boot:
self.state.update(session="", phase="needs_prepare", commands=[], seen=[], reward="not requested")
self.log("Cabinet restarted; operator must prepare a new session")
self.boot = boot
self.state["boot"] = boot
self.last_seen = self.clock()
self.version = str(data.get("version", "unknown"))[:80]
self.gpio = str(data.get("gpio", "unknown"))[:100]
self.expire()
reports = data.get("reports", [])
if not isinstance(reports, list) or len(reports) > 50: raise ValueError("Invalid reports")
for report in reports:
if not isinstance(report, dict): raise ValueError("Invalid report")
if report.get("session") != self.state["session"]: continue
if report.get("kind") == "ack":
self.ack(report)
elif report.get("kind") == "event":
self.event(report)
self.save()
return dict(ok=True, session=self.state["session"],
commands=[c for c in self.state["commands"] if c["status"] == "queued"])
def ack(self, report):
command = next((c for c in self.state["commands"] if c["id"] == report.get("id")), None)
if command is None or command["status"] != "queued": return
success = report.get("ok") is True
command["status"] = "accepted" if success else "failed"
self.log("%s: %s" % (command["type"], str(report.get("detail", command["status"]))[:200]))
if command["type"] == "output":
self.state["last_output"] = "accepted (physical state unconfirmed)" if success else "failed or uncertain"
elif command["type"] == "reward":
statuses = [c["status"] for c in self.state["commands"] if c["type"] == "reward"]
if any(s in ("failed", "unknown") for s in statuses):
self.state["reward"] = "failed or uncertain — inspect cabinet"
elif all(s == "accepted" for s in statuses):
self.state["reward"] = "GPIO accepted (physical delivery unconfirmed)"
else:
self.state["reward"] = "requested"
elif success:
self.state["phase"] = {"prepare": "ready", "reset": "waiting" if self.state.get("gate") else "idle", "start": "playing"}[command["type"]]
if command["type"] == "prepare" and self.state.pop("auto_start", False):
self.state["phase"] = "starting"
self.command("start")
if command["type"] == "prepare":
for action in self.state["mappings"].get("game_activated", []):
self.command("output")["action_id"] = action
else:
self.state["phase"] = "needs_prepare"
def event(self, report):
event_id = report.get("id")
if not isinstance(event_id, str) or not 1 <= len(event_id) <= 100: return
if event_id in self.state["seen"]: return
self.state["seen"].append(event_id)
self.state["seen"] = self.state["seen"][-500:]
name = report.get("event")
if name == "started" and self.state["phase"] in ("ready", "starting"):
self.state["phase"] = "playing"
elif name == "won" and self.state["phase"] == "playing":
self.state["phase"] = "won"
if self.state["reward"] == "not requested" and self.state["mappings"].get("game_won"):
self.state["reward"] = "requested"
elif name == "lost" and self.state["phase"] == "playing":
self.state["phase"] = "lost"
else:
return
self.log(self.state["game"] + " " + name)
for action in self.state["mappings"].get("game_" + name, []):
command = self.command("reward" if name == "won" else "output")
command["action_id"] = action
class Fleet:
"""Editor catalog plus independently acknowledged cabinet sessions."""
def __init__(self, database, catalog, clock=time.time):
self.catalog = catalog
self.rooms = {key: Room(database, clock, key) for key in catalog["cabinets"]}
def compatible(self, cabinet, game):
definition = self.catalog["games"][game]
capabilities = set(self.catalog["cabinets"][cabinet]["capabilities"])
alternatives = definition.get("alternatives", [])
return set(definition["requirements"]) <= capabilities and (not alternatives or any(set(a) <= capabilities for a in alternatives))
def snapshot(self):
cabinets = {}
for key, room in self.rooms.items():
cabinets[key] = dict(room.snapshot(), definition=self.catalog["cabinets"][key],
compatible_games=[g for g in self.catalog["games"] if self.compatible(key, g)])
# Retain the single-cabinet desktop UI response while the browser offers the fleet view.
first = cabinets.get("cabinet_01", next(iter(cabinets.values())))
return dict(first, cabinets=cabinets, catalog=self.catalog)
def validate_assignment(self, item):
cabinet, game = item.get("cabinet"), item.get("game")
if cabinet not in self.rooms or game not in self.catalog["games"]:
raise ValueError("Unknown cabinet or game")
if not self.compatible(cabinet, game): raise ValueError(f"{game} cannot run on {cabinet}: hardware requirements not met")
if item.get("variant", "standard") != "standard": raise ValueError("Only standard variants are supported by this runtime")
allowed = set(self.catalog["cabinets"][cabinet]["actions"])
for event, actions in item.get("mappings", {}).items():
if event not in ("game_activated", "game_started", "game_won", "game_lost"):
raise ValueError(f"Scenario event {event} is not implemented in managed runtime")
if not set(actions) <= allowed: raise ValueError("Scenario refers to an unknown hardware action")
room = self.rooms[cabinet]
room.expire()
if not room.online(): raise ValueError(f"{cabinet} is offline")
if room.state["phase"] not in ("idle", "won", "lost", "needs_prepare"):
raise ValueError(f"Reset {cabinet} before preparing a new assignment")
if any(c["status"] == "queued" for c in room.state["commands"]):
raise ValueError(f"{cabinet} has a pending command")
def operator(self, action, data=None):
data = data or {}
if action == "prepare_scenario":
scenario_id = data.get("scenario")
scenario = self.catalog["scenarios"].get(scenario_id)
if not scenario: raise ValueError("Unknown scenario")
assignments = scenario["assignments"]
if not assignments or len({a["cabinet"] for a in assignments}) != len(assignments):
raise ValueError("Scenario must have unique, nonempty cabinet assignments")
# Validate the whole plan before sending anything to any cabinet.
for item in assignments: self.validate_assignment(item)
by_id = {a["cabinet"]: a for a in assignments}
for item in assignments:
visited = {item["cabinet"]}
source = item.get("activate_after_win", "")
while source:
if source not in by_id: raise ValueError("Dependency cabinet must be assigned in the same scenario")
if source in visited: raise ValueError("Cabinet activation dependencies cannot form a cycle")
visited.add(source)
source = by_id[source].get("activate_after_win", "")
for item in assignments: self.prepare(item, scenario_id)
# Bind dependencies to this particular run, never an earlier win.
for item in assignments:
source = item.get("activate_after_win")
if source:
room = self.rooms[item["cabinet"]]
room.state["gate"] = dict(cabinet=source, session=self.rooms[source].state["session"])
room.log("Waiting for " + source + " to win")
room.save()
elif action == "prepare":
cabinet = data.get("cabinet", "cabinet_01")
item = dict(cabinet=cabinet, game=data.get("game", "pacman"), mappings={})
self.validate_assignment(item)
# Manual overrides do not inherit a reward from the previous scenario.
self.prepare(item, "manual override")
else:
cabinet = data.get("cabinet", "cabinet_01")
if cabinet not in self.rooms: raise ValueError("Unknown cabinet")
if action == "start" and self.rooms[cabinet].state.get("gate"):
raise ValueError("This cabinet starts automatically after its dependency wins")
self.rooms[cabinet].operator(action)
if action == "reset":
self.rooms[cabinet].state.pop("gate", None)
self.rooms[cabinet].state.pop("auto_start", None)
self.rooms[cabinet].save()
self.advance()
return self.snapshot()
def prepare(self, item, scenario):
room = self.rooms[item["cabinet"]]
room.state.update(game=item["game"], mappings=item.get("mappings", {}),
variant=item.get("variant", "standard"), scenario=scenario)
room.state.pop("gate", None)
room.state.pop("auto_start", None)
room.operator("reset" if item.get("activate_after_win") else "prepare")
room.log("Assignment from " + scenario)
room.save()
def poll(self, data):
cabinet = data.get("cabinet")
if data.get("protocol") != 2: raise ValueError("Update cabinet export: controller requires protocol 2")
if cabinet not in self.rooms: raise ValueError("Unknown cabinet")
self.rooms[cabinet].poll(data)
self.advance()
room = self.rooms[cabinet]
return dict(ok=True, session=room.state["session"],
commands=[c for c in room.state["commands"] if c["status"] == "queued"])
def advance(self):
# Invalidate descendants when their source is reset/reassigned/restarted.
# Iterate to propagate invalidation through longer chains.
for _ in self.rooms:
for room in self.rooms.values():
gate = room.state.get("gate")
if not gate: continue
source = self.rooms.get(gate["cabinet"])
if source is None or source.state["session"] != gate["session"]:
room.state.update(session=str(uuid.uuid4()), phase="needs_prepare", commands=[], seen=[], gate=None, auto_start=False)
room.log("Dependency session ended; prepare the scenario again")
room.save()
for room in self.rooms.values():
gate = room.state.get("gate")
if not gate or room.state["phase"] != "waiting" or not room.online(): continue
source = self.rooms[gate["cabinet"]]
if source.state["phase"] == "won":
room.state.update(phase="preparing", auto_start=True)
room.command("prepare")
room.log("Activated by " + gate["cabinet"] + " win")
room.save()
def handler_for(room, operator_token, cabinet_token):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path not in ("/", "/index.html"):
self.respond(404, {"error": "Not found"})
return
body = (Path(__file__).parent / "operator.html").read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Frame-Options", "DENY")
self.end_headers()
self.wfile.write(body)
def do_POST(self):
try:
length = int(self.headers.get("Content-Length", "0"))
if not 0 <= length <= 65536: raise ValueError("Request too large")
data = json.loads(self.rfile.read(length) or b"{}")
if not isinstance(data, dict): raise ValueError("Expected object")
expected = operator_token
if self.path == "/cabinet/poll":
expected = cabinet_token.get(data.get("cabinet"), "") if isinstance(cabinet_token, dict) else cabinet_token
if not expected:
self.respond(401, {"error": "Cabinet credentials not provisioned"})
return
if not hmac.compare_digest(self.headers.get("Authorization", ""), "Bearer " + expected):
self.respond(401, {"error": "Unauthorized"})
return
origin = self.headers.get("Origin")
if origin and urlparse(origin).netloc != self.headers.get("Host"):
raise ValueError("Cross-origin requests are disabled")
if self.path == "/cabinet/poll": result = room.poll(data)
elif self.path == "/operator/state": result = room.snapshot()
elif self.path == "/operator/command":
result = room.operator(data.get("action"), data) if isinstance(room, Fleet) else room.operator(data.get("action"))
else: raise ValueError("Unknown endpoint")
self.respond(200, result)
except (ValueError, TypeError, KeyError) as exc:
self.respond(400, {"error": str(exc)})
def setup(self):
super().setup()
self.connection.settimeout(3)
def respond(self, code, data):
body = json.dumps(data).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *_args): pass
return Handler
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--bind", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8766)
parser.add_argument("--database", default="arcade_room.sqlite3")
parser.add_argument("--catalog", default=str(Path(__file__).with_name("catalog.json")))
args = parser.parse_args()
operator = os.environ.get("ARCADE_OPERATOR_TOKEN", "")
cabinet = os.environ.get("ARCADE_CABINET_TOKEN", "")
try:
tokens = json.loads(os.environ.get("ARCADE_CABINET_TOKENS", "{}"))
except ValueError:
parser.error("ARCADE_CABINET_TOKENS must be a JSON object")
if not isinstance(tokens, dict): parser.error("ARCADE_CABINET_TOKENS must be a JSON object")
if cabinet: tokens.setdefault("cabinet_01", cabinet)
if not isinstance(tokens, dict) or not tokens or len(operator) < 16 or any(not isinstance(t, str) or len(t) < 16 or t == operator for t in tokens.values()) or len(set(tokens.values())) != len(tokens):
parser.error("Set an operator token and unique cabinet tokens (16+ characters); use ARCADE_CABINET_TOKEN for cabinet_01 or ARCADE_CABINET_TOKENS JSON for multiple cabinets")
catalog = json.loads(Path(args.catalog).read_text(encoding="utf-8"))
room = Fleet(Path(args.database), catalog)
server = HTTPServer((args.bind, args.port), handler_for(room, operator, tokens))
print(f"Arcade controller ready at http://{args.bind}:{args.port}/ — {len(room.rooms)} cabinets", flush=True)
try: server.serve_forever()
except KeyboardInterrupt: pass
finally:
server.server_close()
for cabinet_room in room.rooms.values(): cabinet_room.db.close()
if __name__ == "__main__": main()