Arcade-Duell
Der Ordner demo-kit/ simuliert das Gerät für die Demo auf der Startseite. Auf dem Gerät wird er nicht benötigt.
Der Ordner demo-kit/ simuliert das Gerät für die Demo auf der Startseite. Auf dem Gerät wird er nicht benötigt.
#!/usr/bin/env python3
"""One arcade cabinet of two that play Rimshock against each other, each in its own home.
python arcade.py --role host # cabinet one: accepts the session and runs the game
python arcade.py --role guest # cabinet two: opens the session to cabinet one and sends its inputs
Both roles serve the companion page (../ui/arcade.html, a device UI) and a small HTTP and WebSocket API on
127.0.0.1. With keys (secrets.json next to this file, or environment variables) the program is a
Connectivitizer device that exposes that server as the service ``api``, and the guest opens its session
to the host as that device; its device key has "Its devices may open sessions to other devices" switched
on in the web app. Without keys it runs "local only": the host plays on its own, and a guest reaches a
host on the same machine with ``--local 127.0.0.1:8141``.
The cabinet's stick, button, screen and lights are behind the class ``Cabinet`` (cabinet.py). Only the
simulator exists: computer players hold the sticks and nothing is drawn. A real cabinet is NOT implemented.
Only the standard library is used here. The Connectivitizer SDK (``pip install huelake-connectivitizer``)
is imported only when keys are there.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import sys
import time
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, List, Optional, Set
from cabinet import Cabinet, HardwareCabinet, SimulatedCabinet
from game import DT, NEUTRAL, Game, Input
from server import Answer, HttpServer, WebSocket, connect_websocket, json_answer, text_answer
HERE = Path(__file__).resolve().parent
UI_FOLDER = HERE.parent / "ui"
PAGE_FILE = UI_FOLDER / "arcade.html"
MANIFEST_FILE = UI_FOLDER / "manifest.json"
SCORES_FILE = HERE / "scores.json" # the host keeps the scoreboard here; not committed
MAX_PAGE_BYTES = 2 * 1024 * 1024 # what the app accepts as a device UI
GAME_NAME = "Rimshock"
HISTORY_LENGTH = 20 # matches the scoreboard remembers
GUEST_STATES_EVERY = 2 # ticks between two snapshots for the other cabinet: 30 a second
PAGE_STATES_EVERY = 3 # ticks between two snapshots for the companion pages: 20 a second
INPUT_FRESH_SECONDS = 0.5 # an input older than this counts as a stick let go
SILENT_SECONDS = 5.0 # another cabinet that says nothing for this long is gone
CONNECT_SECONDS = 30.0 # how long opening the session to the host may take
Log = Callable[[str], None]
def _parse(text: Optional[str]) -> Dict[str, Any]:
"""A message from a socket as an object; anything else as an empty one."""
try:
value = json.loads(text) if text else None
except ValueError:
value = None
return value if isinstance(value, dict) else {}
def _name(value: Any, fallback: Optional[str]) -> Optional[str]:
"""A name another program sent, cut to what a screen can show."""
return value.strip()[:24] if isinstance(value, str) and value.strip() else fallback
# ---------------------------------------------------------------------------------------------------------
# What both roles share: the companion page, GET /state, GET /scores, POST /challenge, WS /match
# ---------------------------------------------------------------------------------------------------------
class Station:
"""One cabinet as its phone sees it. `seat` is 0 for the host and 1 for the guest."""
role = ""
seat = 0
def __init__(self, name: str, home: str, player: str, cabinet: Cabinet, log: Log) -> None:
self._cabinet = cabinet
self._log = log
self._watchers: Set[WebSocket] = set() # the companion pages on /match
nobody = {"cabinet": None, "home": None, "player": None, "present": False, "computer": False}
self.players: List[Dict[str, Any]] = [dict(nobody), dict(nobody)]
self.players[self.seat] = {"cabinet": name, "home": home, "player": player, "present": True, "computer": cabinet.computer}
self.link: Dict[str, Any] = {"connected": False, "path": None, "endToEndEncrypted": None, "rttMs": None}
self.view: Dict[str, Any] = Game().snapshot()
def me(self) -> Dict[str, Any]:
return self.players[self.seat]
# --- what the phone asks ---
def state(self) -> Dict[str, Any]:
return {"game": GAME_NAME, "role": self.role, "seat": self.seat, "players": self.players, "link": self.link, "match": self.view}
def scores(self) -> Dict[str, Any]:
raise NotImplementedError
def send_to_other_cabinet(self, message: Dict[str, Any]) -> bool:
"""Queues a message for the other cabinet. False when it is not connected."""
raise NotImplementedError
def route(self, method: str, path: str, query: Dict[str, List[str]], body: bytes) -> Answer:
if path == "/state" and method == "GET":
return json_answer(200, self.state())
if path == "/scores" and method == "GET":
return json_answer(200, self.scores())
if path == "/challenge":
if method != "POST":
return text_answer(405, "Use POST.", {"Allow": "POST"})
if not self.send_to_other_cabinet({"type": "challenge", "from": self.me["player"]}):
return json_answer(409, {"error": "The other cabinet is not connected."})
other = self.players[1 - self.seat]
return json_answer(200, {"ok": True, "to": {"cabinet": other["cabinet"], "player": other["player"]}})
if path == "/.cz/ui.json" and method == "GET":
return self._file(MANIFEST_FILE, "application/json")
if path == "/.cz/ui.html" and method == "GET":
return self._file(PAGE_FILE, "text/html; charset=utf-8")
if path == "/" and method == "GET":
return 302, "text/plain; charset=utf-8", b"", {"Location": "/.cz/ui.html"}
return text_answer(404, "Not found")
def _file(file: Path, content_type: str) -> Answer:
# Read on every request: the page can be edited while the program runs.
try:
data = file.read_bytes()
except OSError:
return text_answer(404, f"{file.name} is not there.")
if len(data) > MAX_PAGE_BYTES:
return text_answer(500, f"{file.name} is larger than 2 MB.")
return 200, content_type, data, {}
async def match_socket(self, socket: WebSocket) -> None:
"""WS /match: everything the companion page shows, as it happens. Nothing is expected from the page."""
socket.send({"type": "hello", "state": self.state(), "scores": self.scores()})
self._watchers.add(socket)
try:
while await socket.receive() is not None:
pass
finally:
self._watchers.discard(socket)
def tell_pages(self, message: Dict[str, Any]) -> None:
text = json.dumps(message, separators=(",", ":"))
for socket in list(self._watchers):
if socket.is_open:
socket.send(text)
else:
self._watchers.discard(socket)
def tell_pages_info(self) -> None:
self.tell_pages({"type": "info", "players": self.players, "link": self.link})
# --- challenges, the same in both directions ---
def from_other_cabinet(self, message: Dict[str, Any]) -> bool:
"""Handles what both roles receive alike. True when the message was one of those."""
other = 1 - self.seat
if message.get("type") == "challenge":
challenger = _name(message.get("from"), None) or "The other cabinet"
self._cabinet.light_up(challenger)
self.send_to_other_cabinet({"type": "lit"})
self.tell_pages({"type": "event", "event": "challenge", "t": self.view["t"], "seat": other, "player": challenger})
return True
if message.get("type") == "lit": # the other cabinet lit up for this one's challenge
self.tell_pages({"type": "event", "event": "lit", "t": self.view["t"], "seat": other})
return True
return False
# ---------------------------------------------------------------------------------------------------------
# The host: cabinet one runs the game, keeps the scoreboard and accepts the other cabinet on WS /play
# ---------------------------------------------------------------------------------------------------------
class ScoreBook:
"""The scoreboard of the two homes, kept in scores.json on the host."""
def __init__(self, file: Path, log: Log) -> None:
self._file = file
self._log = log
self._wins = [0, 0]
self._history: List[Dict[str, Any]] = []
self._names: List[Dict[str, Any]] = [{"home": None, "player": None}, {"home": None, "player": None}] # as last seen
try:
saved = json.loads(file.read_text(encoding="utf-8"))
wins, history = saved["wins"], saved["history"]
if isinstance(wins, list) and len(wins) == 2 and isinstance(history, list):
self._wins = [int(wins[0]), int(wins[1])]
self._history = [entry for entry in history if isinstance(entry, dict)][:HISTORY_LENGTH]
names = saved.get("names")
if isinstance(names, list) and len(names) == 2 and all(isinstance(entry, dict) for entry in names):
self._names = [{"home": entry.get("home"), "player": entry.get("player")} for entry in names]
except FileNotFoundError:
pass
except (OSError, ValueError, KeyError, TypeError) as error:
log(f"{file.name} could not be read ({error}); the scoreboard starts empty.")
def add(self, entry: Dict[str, Any]) -> None:
self._wins[entry["winner"]] += 1
self._history.insert(0, entry)
del self._history[HISTORY_LENGTH:]
try:
draft = self._file.with_suffix(".tmp")
draft.write_text(json.dumps({"wins": self._wins, "names": self._names, "history": self._history}, indent=1), encoding="utf-8")
draft.replace(self._file)
except OSError as error:
self._log(f"{self._file.name} could not be written ({error}).")
def answer(self, players: List[Dict[str, Any]]) -> Dict[str, Any]:
# A seat that is empty right now keeps the names of whoever sat there last.
for names, player in zip(self._names, players):
if player["present"] and player["cabinet"]:
names["home"], names["player"] = player["home"], player["player"]
return {
"homes": [{"home": names["home"], "player": names["player"], "wins": wins} for names, wins in zip(self._names, self._wins)],
"history": self._history,
}
class Host(Station):
role = "host"
seat = 0
def __init__(self, name: str, home: str, player: str, cabinet: Cabinet, log: Log, simulator: bool) -> None:
super().__init__(name, home, player, cabinet, log)
self._simulator = simulator
self._game = Game()
self._book = ScoreBook(SCORES_FILE, log)
self._guest: Optional[WebSocket] = None
self._guest_input: Input = NEUTRAL
self._guest_input_at = 0.0
# In simulator mode a computer player sits in for the other cabinet while it is not connected.
self._stand_in: Optional[SimulatedCabinet] = SimulatedCabinet(1, lambda line: None) if simulator else None
self._seat_two_empty()
if simulator:
self._game.new_match()
self.view = self._game.snapshot()
def _seat_two_empty(self) -> None:
self.players[1] = {"cabinet": None, "home": None, "player": "Computer" if self._simulator else None, "present": False, "computer": self._simulator}
self.link = {"connected": False, "path": None, "endToEndEncrypted": None, "rttMs": None}
def scores(self) -> Dict[str, Any]:
return self._book.answer(self.players)
def send_to_other_cabinet(self, message: Dict[str, Any]) -> bool:
if self._guest is None or not self._guest.is_open:
return False
self._guest.send(message)
return True
async def play_socket(self, socket: WebSocket) -> None:
"""WS /play: the other cabinet. It says hello, then sends its inputs and gets the game back."""
try:
hello = _parse(await asyncio.wait_for(socket.receive(), 10))
except asyncio.TimeoutError:
hello = {}
if hello.get("type") != "hello":
socket.close(1002)
return
if self._guest is not None and self._guest.is_open:
socket.send({"type": "busy", "error": "Another cabinet is playing."})
socket.close(1013)
return
self._guest = socket
self._guest_input = NEUTRAL
self.players[1] = {
"cabinet": _name(hello.get("cabinet"), "cabinet-two"),
"home": _name(hello.get("home"), None),
"player": _name(hello.get("player"), "Player two"),
"present": True,
"computer": hello.get("computer") is True,
}
# How the session between the cabinets is routed is known to the side that opened it: the guest's SDK.
path = hello.get("path")
encrypted = hello.get("endToEndEncrypted")
self.link = {
"connected": True,
"path": path if path in ("direct", "relayed", "local") else None,
"endToEndEncrypted": encrypted if isinstance(encrypted, bool) else None,
"rttMs": None,
}
self._log(f"{self.players[1]['player']} at {self.players[1]['cabinet']} joined ({self.link['path'] or 'path unknown'}). A new match starts.")
socket.send({"type": "welcome", "cabinet": self.me["cabinet"], "home": self.me["home"], "player": self.me["player"], "computer": self.me["computer"], "scores": self.scores()})
self._game.new_match()
self.tell_pages_info()
self.tell_pages({"type": "scores", **self.scores()})
try:
while True:
text = await asyncio.wait_for(socket.receive(), SILENT_SECONDS)
if text is None:
break
message = _parse(text)
kind = message.get("type")
if kind == "in":
try:
self._guest_input = (float(message.get("x", 0)), float(message.get("y", 0)), message.get("b") is True)
except (TypeError, ValueError):
self._guest_input = NEUTRAL
self._guest_input_at = time.monotonic()
elif kind == "ping":
socket.send({"type": "pong", "n": message.get("n")})
rtt = message.get("rttMs")
if isinstance(rtt, (int, float)) and 0 <= rtt < 60000 and rtt != self.link["rttMs"]:
self.link["rttMs"] = round(rtt, 1)
self.tell_pages_info()
else:
self.from_other_cabinet(message)
except asyncio.TimeoutError:
self._log("The other cabinet went silent.")
finally:
self._guest = None
self._seat_two_empty()
if not self._simulator:
self._game.wait()
self._log("The other cabinet left." + (" A computer player takes its seat." if self._simulator else " Waiting for it."))
self.tell_pages_info()
async def run(self) -> None:
"""The clock of the game: 60 ticks a second, each with the inputs of both seats."""
loop = asyncio.get_running_loop()
due = loop.time()
tick = 0
while True:
due += DT
delay = due - loop.time()
if delay < -0.25: # the machine was busy: do not replay what was missed
due = loop.time()
await asyncio.sleep(max(0.0, delay))
tick += 1
one = self._cabinet.read_input(self.view)
if self._guest is not None:
two = self._guest_input if time.monotonic() - self._guest_input_at <= INPUT_FRESH_SECONDS else NEUTRAL
elif self._stand_in is not None:
two = self._stand_in.read_input(self.view)
else:
two = NEUTRAL
events = self._game.step([one, two])
self.view = self._game.snapshot()
self._cabinet.draw(self.view)
for event in events:
self._cabinet.event(event)
self.send_to_other_cabinet(event)
self.tell_pages(event)
if event["event"] == "match":
self._book.add({
"at": round(time.time()),
"winner": event["winner"],
"score": event["score"],
"rounds": event["rounds"],
"seconds": event["seconds"],
"computer": self.players[0]["computer"] or self.players[1]["computer"],
})
scores = {"type": "scores", **self.scores()}
self.send_to_other_cabinet(scores)
self.tell_pages(scores)
if tick % GUEST_STATES_EVERY == 0:
self.send_to_other_cabinet({"type": "state", **self.view})
if tick % PAGE_STATES_EVERY == 0 and self._watchers:
self.tell_pages({"type": "state", **self.view})
# ---------------------------------------------------------------------------------------------------------
# The guest: cabinet two opens the session to cabinet one, sends its inputs and shows what comes back
# ---------------------------------------------------------------------------------------------------------
class Link:
"""The guest's WebSocket to the host's /play, and how it is routed."""
path = "local" # direct | relayed | local
end_to_end_encrypted = False
async def send(self, message: Dict[str, Any]) -> None:
raise NotImplementedError
async def receive(self) -> Optional[str]:
"""The next message, or None once the connection is over."""
raise NotImplementedError
async def close(self) -> None:
raise NotImplementedError
class LocalLink(Link):
"""Plain TCP to a host on this machine: for trying both roles without Connectivitizer. Not encrypted."""
def __init__(self, socket: WebSocket) -> None:
self._socket = socket
async def send(self, message: Dict[str, Any]) -> None:
if not self._socket.is_open:
raise ConnectionError("The connection to the host is closed.")
self._socket.send(message)
async def receive(self) -> Optional[str]:
return await self._socket.receive()
async def close(self) -> None:
self._socket.close()
await self._socket.wait_closed()
class SessionLink(Link):
"""A WebSocket through a Connectivitizer session to the host cabinet's service `api`."""
def __init__(self, session: Any, socket: Any) -> None:
self._session = session
self._socket = socket
# What the SDK on this cabinet observed of the session, not what anybody claimed.
self.path = "direct" if session.info.mode == "direct" else "relayed"
self.end_to_end_encrypted = session.info.end_to_end_encrypted is True
async def send(self, message: Dict[str, Any]) -> None:
await self._socket.send(json.dumps(message, separators=(",", ":")))
async def receive(self) -> Optional[str]:
message = await self._socket.receive()
return message.decode("utf-8", "replace") if isinstance(message, (bytes, bytearray)) else message
async def close(self) -> None:
try:
await self._socket.close()
finally:
await self._session.close()
class Guest(Station):
role = "guest"
seat = 1
def __init__(self, name: str, home: str, player: str, cabinet: Cabinet, log: Log, open_link: Callable[[], Awaitable[Link]]) -> None:
super().__init__(name, home, player, cabinet, log)
self._open_link = open_link
self._link: Optional[Link] = None
self._outbox: List[Dict[str, Any]] = [] # challenges and their answers, sent with the next input
self._scores: Dict[str, Any] = {"homes": [], "history": []}
self._told_pages_at = 0.0
def scores(self) -> Dict[str, Any]:
"""The host's scoreboard as it last sent it; empty until the first connection."""
return self._scores
def send_to_other_cabinet(self, message: Dict[str, Any]) -> bool:
if self._link is None:
return False
self._outbox.append(message)
return True
async def run(self) -> None:
"""Keeps a connection to the host: opens it, plays until it ends, waits, opens it again."""
wait = 2.0
while True:
try:
link = await self._open_link()
except Exception as error:
self._log(f"The host cabinet could not be reached: {error}. Next try in {wait:.0f} s.")
await asyncio.sleep(wait)
wait = min(30.0, wait * 2)
continue
wait = 2.0
try:
await self._play(link)
except Exception as error:
self._log(f"The connection to the host cabinet ended: {error or type(error).__name__}")
finally:
self._link = None
self._outbox.clear()
try:
await link.close()
except Exception:
pass
self.players[0]["present"] = False
self.link = {"connected": False, "path": None, "endToEndEncrypted": None, "rttMs": None}
self.view = {**self.view, "phase": "waiting"}
self.tell_pages_info()
self.tell_pages({"type": "state", **self.view})
await asyncio.sleep(wait)
async def _play(self, link: Link) -> None:
self.link = {"connected": True, "path": link.path, "endToEndEncrypted": link.end_to_end_encrypted, "rttMs": None}
await link.send({"type": "hello", "cabinet": self.me["cabinet"], "home": self.me["home"], "player": self.me["player"],
"computer": self.me["computer"], "path": link.path, "endToEndEncrypted": link.end_to_end_encrypted})
self._link = link
self._log(f"Connected to the host cabinet ({link.path}).")
async def send_inputs() -> None:
# 30 inputs a second, and once a second a ping that carries the last round-trip time measured.
pinged = 0.0
while True:
x, y, button = self._cabinet.read_input(self.view)
await link.send({"type": "in", "x": round(x, 3), "y": round(y, 3), "b": button})
while self._outbox:
await link.send(self._outbox.pop(0))
now = time.monotonic()
if now - pinged >= 1.0:
pinged = now
await link.send({"type": "ping", "n": now, "rttMs": self.link["rttMs"]})
await asyncio.sleep(1 / 30)
sending = asyncio.ensure_future(send_inputs())
try:
while True:
receiving = asyncio.ensure_future(asyncio.wait_for(link.receive(), SILENT_SECONDS))
await asyncio.wait({receiving, sending}, return_when=asyncio.FIRST_COMPLETED)
if sending.done():
receiving.cancel()
sending.result() # raises what ended the sending
return
text = receiving.result()
if text is None:
self._log("The host cabinet closed the connection.")
return
self._from_host(_parse(text))
finally:
sending.cancel()
def _from_host(self, message: Dict[str, Any]) -> None:
kind = message.get("type")
if kind == "state":
self.view = {key: value for key, value in message.items() if key != "type"}
self._cabinet.draw(self.view)
now = time.monotonic()
if now - self._told_pages_at >= 0.045: # every second snapshot goes on to the pages: 15 a second
self._told_pages_at = now
self.tell_pages(message)
elif kind == "event":
self._cabinet.event(message)
self.tell_pages(message)
elif kind == "pong":
sent = message.get("n")
if isinstance(sent, (int, float)):
self.link["rttMs"] = round((time.monotonic() - sent) * 1000, 1)
self.tell_pages_info()
elif kind == "welcome":
self.players[0] = {
"cabinet": _name(message.get("cabinet"), "cabinet-one"),
"home": _name(message.get("home"), None),
"player": _name(message.get("player"), "Player one"),
"present": True,
"computer": message.get("computer") is True,
}
self._set_scores(message.get("scores"))
self.tell_pages_info()
elif kind == "scores":
self._set_scores(message)
elif kind == "busy":
self._log("The host cabinet already plays with another cabinet.")
else:
self.from_other_cabinet(message)
def _set_scores(self, scores: Any) -> None:
if isinstance(scores, dict) and isinstance(scores.get("homes"), list) and isinstance(scores.get("history"), list):
self._scores = {"homes": scores["homes"], "history": scores["history"]}
self.tell_pages({"type": "scores", **self._scores})
# ---------------------------------------------------------------------------------------------------------
# Configuration and Connectivitizer
# ---------------------------------------------------------------------------------------------------------
def _is_placeholder(value: str) -> bool:
return not value or "..." in value or "…" in value
def read_config() -> Dict[str, str]:
"""The keys and names: environment variables first, then secrets.json next to this file (never committed)."""
file: Dict[str, Any] = {}
path = HERE / "secrets.json"
if path.exists():
try:
file = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as error:
print(f"secrets.json could not be read ({error}); it is ignored.")
def value(variable: str, member: str) -> str:
return os.environ.get(variable) or str(file.get(member) or "")
return {
"role": value("ARCADE_ROLE", "role"),
"home": value("ARCADE_HOME", "home"),
"player": value("ARCADE_PLAYER", "player"),
"api_url": value("CZ_API_URL", "apiUrl"),
"shared_key": value("CZ_SHARED_KEY", "sharedKey"),
"device_key": value("CZ_DEVICE_KEY", "deviceKey"),
"device_name": value("CZ_DEVICE_NAME", "deviceName"),
"host_device": value("CZ_HOST_DEVICE", "hostDevice") or "cabinet-one",
}
def _has(config: Dict[str, str], *names: str) -> bool:
return not any(_is_placeholder(config[name]) for name in names)
class CabinetDevice:
"""This cabinet as a Connectivitizer device with one service, `api`. The guest opens its session to the
host as this device, over the device's own connection to the platform. Needs the SDK."""
def __init__(self, config: Dict[str, str]) -> None:
self._config = config
self._agent: Any = None
def start(self, port: int) -> None:
"""Creates the device once the local port is known."""
from connectivitizer import Agent # only needed with keys: pip install huelake-connectivitizer
self._agent = Agent(
None if _is_placeholder(self._config["api_url"]) else self._config["api_url"],
device_key=self._config["device_key"],
name=self._config["device_name"],
shared_key=self._config["shared_key"],
services={"api": f"127.0.0.1:{port}"}, # nothing else on this Pi is reachable
log=lambda line: print(f"connectivitizer: {line}"),
)
async def run(self) -> None:
print(f"Connectivitizer: connecting as device '{self._config['device_name']}' with the service 'api'.")
try:
await self._agent.run() # reconnects by itself; raises when the device key was revoked
finally:
await self._agent.stop()
async def open_link(self) -> Link:
"""The guest's way to the host through Connectivitizer: a new session for every try."""
# connect() waits for this cabinet's connection to the platform; a try does not wait that long.
if self._agent is None or not self._agent.is_connected:
raise ConnectionError("this cabinet is not connected to Connectivitizer")
try:
session = await asyncio.wait_for(self._agent.connect(self._config["host_device"], ["api"]), CONNECT_SECONDS)
except asyncio.TimeoutError:
raise ConnectionError("opening the session took too long") from None
except Exception as error:
code = getattr(error, "code", None) # the SDK's errors carry a code, such as FORBIDDEN or DEVICE_OFFLINE
if code is None:
raise
raise ConnectionError(f"{error} ({code})") from error
try:
socket = await session.websocket("api", "/play")
except BaseException:
await session.close()
raise
return SessionLink(session, socket)
def local_link_opener(address: str) -> Callable[[], Awaitable[Link]]:
host, _, port = address.rpartition(":")
async def open_link() -> Link:
return LocalLink(await connect_websocket(host or "127.0.0.1", int(port), "/play"))
return open_link
async def main() -> int:
config = read_config()
parser = argparse.ArgumentParser(description="One of two arcade cabinets that play Rimshock against each other through Connectivitizer.")
parser.add_argument("--role", choices=["host", "guest"], default=config["role"] or None, help="host: cabinet one, runs the game. guest: cabinet two, joins it.")
parser.add_argument("--port", type=int, default=None, help="local port on 127.0.0.1 (default 8141 for the host, 8142 for the guest; 0: any free one)")
parser.add_argument("--player", default=config["player"], help="who plays at this cabinet (default: Player one or Player two)")
parser.add_argument("--home", default=config["home"], help="what this cabinet's home is called on the scoreboard (default: Home one or Home two)")
parser.add_argument("--cabinet", default="simulator", help="'simulator' (default): a computer player holds the stick. 'hardware' is NOT implemented.")
parser.add_argument("--local", metavar="HOST:PORT", default=None, help="guest only: reach a host on this machine over plain TCP instead of Connectivitizer")
args = parser.parse_args()
if args.role not in ("host", "guest"):
parser.error("say which cabinet this is: --role host or --role guest (or \"role\" in secrets.json)")
host_role = args.role == "host"
if args.local and host_role:
parser.error("--local is for the guest")
seat = 0 if host_role else 1
if args.cabinet == "simulator":
cabinet: Cabinet = SimulatedCabinet(seat, print)
else:
try:
cabinet = HardwareCabinet()
except NotImplementedError as error:
print(error)
return 2
name = config["device_name"] or ("cabinet-one" if host_role else "cabinet-two")
config["device_name"] = name
home = args.home or ("Home one" if host_role else "Home two")
player = args.player or ("Player one" if host_role else "Player two")
keys_for_device = _has(config, "shared_key", "device_key")
if keys_for_device:
try:
import connectivitizer # noqa: F401
except ImportError:
print("Connectivitizer is NOT started: the keys are there, but the SDK is not installed (pip install -r requirements.txt).")
keys_for_device = False
device = CabinetDevice(config) if keys_for_device else None
station: Station
if host_role:
station = Host(name, home, player, cabinet, print, simulator=args.cabinet == "simulator")
sockets = {"/match": station.match_socket, "/play": station.play_socket}
else:
if args.local:
open_link = local_link_opener(args.local)
elif device is not None:
open_link = device.open_link
else:
print("The guest has no way to the host: fill in deviceKey and sharedKey (secrets.json or CZ_DEVICE_KEY, CZ_SHARED_KEY), "
"or try both roles on one machine with --local 127.0.0.1:8141.")
return 2
station = Guest(name, home, player, cabinet, print, open_link)
sockets = {"/match": station.match_socket}
server = HttpServer(station.route, sockets, print)
port = args.port if args.port is not None else int(os.environ.get("ARCADE_PORT") or (8141 if host_role else 8142))
listener = await asyncio.start_server(server.handle, "127.0.0.1", port) # loopback only: no open port
port = listener.sockets[0].getsockname()[1]
print(f"Arcade cabinet '{name}' ({args.role}, {args.cabinet}): {player} at {home}, on http://127.0.0.1:{port}")
print(f" the companion page: http://127.0.0.1:{port}/.cz/ui.html")
print(f" the match: http://127.0.0.1:{port}/state")
if args.cabinet == "simulator":
print(" SIMULATOR: a computer player holds this cabinet's stick, and nothing is drawn on a screen.")
if not PAGE_FILE.exists() or not MANIFEST_FILE.exists():
print(f" {PAGE_FILE} or {MANIFEST_FILE} is missing; the cabinet has no companion page without them.")
if device is not None:
device.start(port)
tasks = [asyncio.ensure_future(station.run())]
if device is not None:
tasks.append(asyncio.ensure_future(device.run()))
else:
print("Local only: this cabinet is NOT a Connectivitizer device (no keys: fill in secrets.json, or set CZ_DEVICE_KEY and CZ_SHARED_KEY).")
if not host_role:
print(f"The guest reaches the host {'over plain TCP at ' + args.local if args.local else 'through Connectivitizer as device ' + repr(config['host_device'])}.")
if not args.local:
print(' Its device key needs "Its devices may open sessions to other devices"; without it the platform refuses the session (FORBIDDEN).')
try:
async with listener:
# Ends when the game's clock or Connectivitizer ends with an error (a revoked key, say).
done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
for task in done:
if task.exception() is not None:
print(f"Stopped: {task.exception()}")
return 1
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
return 0
if __name__ == "__main__":
try:
sys.exit(asyncio.run(main()))
except KeyboardInterrupt:
pass