Zwei Lampen
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
"""A long-distance lamp for a Raspberry Pi: two lamps in two homes, each run by this one program. Touch one
lamp and the other one glows in your colour for a while.
python lamp.py # simulator: no LEDs, no touch sensor; Enter stands in for a touch
Each lamp is one Connectivitizer device that is called and calls:
* it serves a small HTTP and WebSocket API on 127.0.0.1 and exposes it as the service ``api``, together
with the lamp's own screen (../ui/lamps.html, a device UI). The owner's phone and the other lamp open
sessions to it.
* when it is touched (or the phone asks), it opens a session to the other lamp over its own connection to
the platform and posts a glow to that lamp's ``/glow``. For that its device key has "Its devices may
open sessions to other devices" switched on in the web app.
Who this lamp is and who the other one is comes from lamp.json (see lamp.example.json). The keys come
from secrets.json next to this file, or from CZ_DEVICE_KEY and CZ_SHARED_KEY.
Without keys it runs "local only": everything is served on 127.0.0.1 and Connectivitizer is not started.
The hardware is behind the class ``Lamp``. ``SimulatedLamp`` needs no hardware and is the one that has
been run. ``GpioLamp`` drives a WS2812 ring and reads a touch sensor; it is written from the libraries'
documentation and has NOT been run on a Raspberry Pi.
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 base64
import hashlib
import json
import math
import os
import re
import struct
import sys
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, List, Optional, Set, Tuple
from urllib.parse import urlsplit
HERE = Path(__file__).resolve().parent
UI_FOLDER = HERE.parent / "ui"
PAGE_FILE = UI_FOLDER / "lamps.html"
MANIFEST_FILE = UI_FOLDER / "manifest.json"
MAX_PAGE_BYTES = 2 * 1024 * 1024 # what the app accepts as a device UI
PATTERNS = ["glow", "pulse", "heartbeat", "wave"]
COLOUR = re.compile(r"^#[0-9a-fA-F]{6}$")
HISTORY_LENGTH = 200 # entries kept on the device
HISTORY_ANSWER = 30 # entries in one answer of GET /history
REACHABLE_EVERY = 20.0 # seconds between two looks at whether the other lamp is online
SESSION_IDLE = 120.0 # an unused session to the other lamp is closed after this long
CONNECT_SECONDS = 30.0 # how long opening a session to the other lamp may take
DEFAULT_CONFIG: Dict[str, Any] = {
"here": {"name": "lamp-north", "label": "Alex", "place": "Northhaven", "latitude": 54.0, "longitude": 10.0, "color": "#ffb45e"},
"other": {"name": "lamp-south", "label": "Sam", "place": "Southbrook", "latitude": 48.5, "longitude": 11.5, "color": "#8fb8ff"},
"glowSeconds": 60,
}
def brightness(pattern: str, seconds: float, total: float) -> float:
"""How bright a glow is, 0 to 1, `seconds` after it started (the same formulas as in ../ui/lamps.html)."""
if seconds < 0 or seconds >= total:
return 0.0
fade = max(0.0, min(1.0, seconds / 1.5, (total - seconds) / 3.0))
if pattern == "pulse":
shape = 0.25 + 0.75 * (0.5 - 0.5 * math.cos(2 * math.pi * seconds / 1.6))
elif pattern == "heartbeat":
phase = seconds % 1.4
shape = 0.35 + 0.65 * max(math.exp(-(((phase - 0.12) / 0.07) ** 2)), 0.75 * math.exp(-(((phase - 0.42) / 0.09) ** 2)))
elif pattern == "wave":
shape = 0.35 + 0.65 * (0.5 - 0.5 * math.cos(2 * math.pi * seconds / 5.0))
else:
shape = 0.92 + 0.08 * math.sin(2 * math.pi * seconds / 6.0)
return fade * shape
def distance_km(a: Dict[str, Any], b: Dict[str, Any]) -> Optional[int]:
"""The great-circle distance between two places with latitude and longitude, or None without them."""
try:
lat1, lon1, lat2, lon2 = (math.radians(float(v)) for v in (a["latitude"], a["longitude"], b["latitude"], b["longitude"]))
except (KeyError, TypeError, ValueError):
return None
h = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
return round(2 * 6371.0 * math.asin(math.sqrt(h)))
# ---------------------------------------------------------------------------------------------------------
# The hardware: the light and the touch sensor
# ---------------------------------------------------------------------------------------------------------
class Lamp:
"""What the program needs from the hardware."""
kind = "none"
on_touch: Optional[Callable[[], None]] = None
"""Called on the event loop when the lamp is touched."""
def start(self, loop: asyncio.AbstractEventLoop) -> None:
"""Called once, when the event loop runs."""
def show(self, color: str, pattern: str, seconds: float) -> None:
"""Glow in `color` ("#rrggbb") with `pattern` for `seconds`, replacing what is shown."""
raise NotImplementedError
def close(self) -> None:
"""Switch the light off and let go of the hardware."""
# --- The simulator: NO HARDWARE. The light is a line on the console, a touch is the Enter key. ------------
class SimulatedLamp(Lamp):
"""Stands in for the LEDs and the touch sensor. Nothing is connected: a glow is printed, and a touch is
the Enter key in the terminal the program runs in, or happens by itself every `touch_every` seconds."""
kind = "simulator"
def __init__(self, touch_every: float = 0.0) -> None:
self._touch_every = touch_every
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._dark: Optional[asyncio.TimerHandle] = None
def start(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
if sys.stdin is not None and sys.stdin.isatty():
threading.Thread(target=self._read_enter, daemon=True).start()
print("[simulator] press Enter to touch the lamp.")
if self._touch_every > 0:
loop.call_later(self._touch_every, self._touch_again)
def _read_enter(self) -> None:
for _ in sys.stdin:
self._loop.call_soon_threadsafe(self._touched)
def _touch_again(self) -> None:
self._touched()
self._loop.call_later(self._touch_every, self._touch_again)
def _touched(self) -> None:
print("[simulator] the lamp is touched.")
if self.on_touch is not None:
self.on_touch()
def show(self, color: str, pattern: str, seconds: float) -> None:
print(f"[simulator] the lamp glows {color} ({pattern}) for {seconds:g} s.")
if self._dark is not None:
self._dark.cancel()
self._dark = self._loop.call_later(seconds, lambda: print("[simulator] the lamp is dark."))
def close(self) -> None:
if self._dark is not None:
self._dark.cancel()
# --- Real hardware: written from the libraries' documentation, NOT RUN ON A RASPBERRY PI. -----------------
class GpioLamp(Lamp):
"""A WS2812 ring or strip and a touch sensor on the GPIO pins. This class has never been run: no
Raspberry Pi with LEDs was at hand when the example was written. Treat it as a starting point.
* The LEDs: ``rpi_ws281x`` (``pip install rpi_ws281x``), data line on GPIO 18 by default. The library
needs root for that pin (``sudo``), and 5 V LEDs want a level shifter on the data line.
* The touch sensor: ``gpiozero`` (part of Raspberry Pi OS), a module such as the TTP223 whose output
goes high while it is touched, on GPIO 17 by default. A push button to 3.3 V works the same way.
The light is drawn 30 times a second in a thread of its own, with the same brightness formulas as the
page."""
kind = "gpio"
def __init__(self, led_pin: int, led_count: int, touch_pin: int) -> None:
from gpiozero import Button # raises ImportError off a Raspberry Pi
from rpi_ws281x import Color, PixelStrip
self._color_of = Color
self._count = led_count
self._strip = PixelStrip(led_count, led_pin)
self._strip.begin()
self._button = Button(touch_pin, pull_up=False, bounce_time=0.05)
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._glow: Optional[Tuple[Tuple[int, int, int], str, float, float]] = None # rgb, pattern, started, seconds
self._lock = threading.Lock()
self._stop = threading.Event()
def start(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._button.when_pressed = lambda: loop.call_soon_threadsafe(self._touched) # gpiozero calls from its own thread
threading.Thread(target=self._draw, daemon=True).start()
def _touched(self) -> None:
if self.on_touch is not None:
self.on_touch()
def show(self, color: str, pattern: str, seconds: float) -> None:
rgb = (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
with self._lock:
self._glow = (rgb, pattern, time.monotonic(), seconds)
def _draw(self) -> None:
while not self._stop.wait(1 / 30):
with self._lock:
glow = self._glow
level = 0.0
rgb = (0, 0, 0)
if glow is not None:
rgb, pattern, started, seconds = glow
level = brightness(pattern, time.monotonic() - started, seconds)
value = self._color_of(*(round(part * level) for part in rgb))
for index in range(self._count):
self._strip.setPixelColor(index, value)
self._strip.show()
def close(self) -> None:
self._stop.set()
for index in range(self._count):
self._strip.setPixelColor(index, self._color_of(0, 0, 0))
self._strip.show()
self._button.close()
# ---------------------------------------------------------------------------------------------------------
# The way to the other lamp
# ---------------------------------------------------------------------------------------------------------
class LinkError(Exception):
"""A glow did not arrive. `code` is an error code of the SDK where there is one."""
def __init__(self, code: str, message: str) -> None:
super().__init__(message)
self.code = code
class Link:
"""What the program needs to reach the other lamp."""
kind = "none"
async def reachable(self) -> Optional[bool]:
"""Whether the other lamp can be reached right now; None when that is not known."""
raise NotImplementedError
async def post_glow(self, body: Dict[str, Any]) -> Tuple[Dict[str, Any], Optional[str]]:
"""Posts a glow to the other lamp's /glow. Returns its answer and how it got there ("direct" or
"relayed"; None when that does not apply). Raises LinkError."""
raise NotImplementedError
async def close(self) -> None:
pass
class SessionLink(Link):
"""Through Connectivitizer: a session from this lamp to the other one, opened when a glow is sent and
kept for the next ones while it is in use. The lamp opens it as the device it is (`agent`), so its
device key has to allow that."""
kind = "connectivitizer"
def __init__(self, agent: Any, other: str) -> None:
from connectivitizer import ConnectivitizerError # raises ImportError without the SDK
self._error = ConnectivitizerError
self._other = other
self._agent = agent
self._session: Any = None
self._used = 0.0
self._lock = asyncio.Lock()
async def reachable(self) -> Optional[bool]:
async with self._lock:
if self._session is not None and time.monotonic() - self._used > SESSION_IDLE:
session, self._session = self._session, None
await session.close()
try:
devices = await self._agent.list_devices()
except self._error:
return None # the platform did not answer, or the device key may not open sessions: not known
for device in devices:
if self._other in (device.name, device.slug):
return device.online
return False # this lamp's device key may not reach a device of that name
async def post_glow(self, body: Dict[str, Any]) -> Tuple[Dict[str, Any], Optional[str]]:
async with self._lock:
try:
if self._session is None or self._session.is_ended:
# connect() waits for the lamp's connection to the platform; a glow does not wait that long.
if not self._agent.is_connected:
raise LinkError("NOT_CONNECTED", "This lamp is not connected to Connectivitizer.")
try:
self._session = await asyncio.wait_for(self._agent.connect(self._other, ["api"]), CONNECT_SECONDS)
except asyncio.TimeoutError:
raise LinkError("NOT_CONNECTED", "Opening the session to the other lamp took too long.") from None
session = self._session
self._used = time.monotonic()
response = await session.fetch(
"api", "/glow", method="POST", headers={"Content-Type": "application/json"}, body=json.dumps(body), timeout=15.0
)
if response.status != 200:
raise LinkError("REFUSED", f"The other lamp answered {response.status}.")
answer = await response.json()
except self._error as error:
self._session = None
raise LinkError(error.code, str(error)) from error
# What this endpoint observed of the session, not what anybody claimed.
return answer, "direct" if session.info.mode == "direct" else "relayed"
async def close(self) -> None:
session, self._session = self._session, None
if session is not None:
await session.close()
class LocalLink(Link):
"""For trying two programs on one machine: the glow goes by plain HTTP to the other program's port on
the loopback address. No session, no encryption, nothing of Connectivitizer."""
kind = "local"
def __init__(self, url: str) -> None:
parts = urlsplit(url)
if parts.scheme != "http" or parts.hostname not in ("127.0.0.1", "localhost", "::1"):
raise ValueError("--local-peer takes an address on this machine, such as http://127.0.0.1:8152")
self._url = url.rstrip("/")
def _request(self, path: str, body: Optional[Dict[str, Any]]) -> Dict[str, Any]:
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(self._url + path, data=data, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode())
async def reachable(self) -> Optional[bool]:
try:
await asyncio.to_thread(self._request, "/state", None)
return True
except (OSError, ValueError):
return False
async def post_glow(self, body: Dict[str, Any]) -> Tuple[Dict[str, Any], Optional[str]]:
try:
return await asyncio.to_thread(self._request, "/glow", body), None
except urllib.error.HTTPError as error:
raise LinkError("REFUSED", f"The other lamp answered {error.code}.") from error
except (OSError, ValueError) as error:
raise LinkError("TARGET_UNREACHABLE", str(error)) from error
# ---------------------------------------------------------------------------------------------------------
# The lamp: what glows, what was sent and received
# ---------------------------------------------------------------------------------------------------------
class LampProgram:
def __init__(self, config: Dict[str, Any], lamp: Lamp, history_file: Optional[Path], log: Callable[[str], None]) -> None:
self.here: Dict[str, Any] = config["here"]
self.other: Dict[str, Any] = config["other"]
self.glow_seconds = float(config.get("glowSeconds") or 60)
self.lamp = lamp
self.link: Optional[Link] = None
self.on_event: Optional[Callable[[Dict[str, Any]], None]] = None
self._log = log
self._history_file = history_file
self._entries: List[Dict[str, Any]] = self._read_history()
self._next_id = max((int(entry.get("id", 0)) for entry in self._entries), default=0) + 1
self._here_glow: Optional[Dict[str, Any]] = None # what this lamp shows
self._other_glow: Optional[Dict[str, Any]] = None # what the other lamp shows, as far as this one knows
self._reachable: Optional[bool] = None
self._path: Optional[str] = None
self._tasks: Set["asyncio.Task[None]"] = set()
lamp.on_touch = lambda: self.send(self.here["color"], "glow", "touch")
# --- history: kept in a small file, so that it is still there after a restart ---
def _read_history(self) -> List[Dict[str, Any]]:
if self._history_file is None or not self._history_file.exists():
return []
try:
entries = json.loads(self._history_file.read_text(encoding="utf-8"))
return [entry for entry in entries if isinstance(entry, dict)][-HISTORY_LENGTH:]
except (OSError, ValueError) as error:
self._log(f"{self._history_file.name} could not be read ({error}); the history starts empty.")
return []
def _write_history(self) -> None:
if self._history_file is None:
return
try:
self._history_file.write_text(json.dumps(self._entries, separators=(",", ":")), encoding="utf-8")
except OSError as error:
self._log(f"{self._history_file.name} could not be written ({error}).")
def _add(self, direction: str, color: str, pattern: str, via: str, delivered: Optional[bool]) -> Dict[str, Any]:
entry = {"id": self._next_id, "t": round(time.time()), "direction": direction, "color": color.lower(), "pattern": pattern, "via": via, "delivered": delivered}
self._next_id += 1
self._entries.append(entry)
del self._entries[:-HISTORY_LENGTH]
self._write_history()
return entry
def history(self) -> Dict[str, Any]:
"""{ today: { received, sent, lastReceived, lastSent }, entries: [ newest first ] }. A day is the
device's own day, from its local midnight on. A glow that did not arrive is not counted as sent."""
now = time.localtime()
midnight = time.mktime((now.tm_year, now.tm_mon, now.tm_mday, 0, 0, 0, 0, 0, -1))
today = {"received": 0, "sent": 0, "lastReceived": None, "lastSent": None}
for entry in self._entries:
if entry["direction"] == "sent" and entry["delivered"] is not True:
continue
key = "Received" if entry["direction"] == "received" else "Sent"
if entry["t"] >= midnight:
today[key.lower()] += 1
today["last" + key] = entry["t"]
return {"today": today, "entries": list(reversed(self._entries[-HISTORY_ANSWER:]))}
# --- state ---
def _glow_now(glow: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
if glow is None:
return None
remaining = glow["ends"] - time.monotonic()
if remaining <= 0:
return None
return {"color": glow["color"], "pattern": glow["pattern"], "seconds": glow["seconds"], "remainingSeconds": round(remaining, 1)}
def state(self) -> Dict[str, Any]:
def lamp(about: Dict[str, Any]) -> Dict[str, Any]:
return {"name": about["name"], "label": about.get("label") or about["name"], "place": about.get("place") or "", "color": about["color"]}
here = lamp(self.here)
here["glow"] = self._glow_now(self._here_glow)
other = lamp(self.other)
other["glow"] = self._glow_now(self._other_glow)
other["reachable"] = self._reachable
other["path"] = self._path
return {
"t": round(time.time()),
"here": here,
"other": other,
"distanceKm": distance_km(self.here, self.other),
"glowSeconds": self.glow_seconds,
"patterns": PATTERNS,
"hardware": self.lamp.kind,
"link": self.link.kind if self.link is not None else "none",
}
def _tell(self, kind: str, entry: Optional[Dict[str, Any]] = None, error: Optional[str] = None) -> None:
if self.on_event is None:
return
message: Dict[str, Any] = {"type": kind}
if entry is not None:
message["entry"] = entry
if error is not None:
message["error"] = error
message["state"] = self.state()
self.on_event(message)
def _spawn(self, work: Awaitable[None]) -> None:
task = asyncio.ensure_future(work)
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
# --- glows ---
def receive(self, color: str, pattern: str, via: str) -> Dict[str, Any]:
"""The other lamp sent a glow: this lamp shows it."""
entry = self._add("received", color, pattern, via, True)
self._here_glow = {"color": entry["color"], "pattern": pattern, "seconds": self.glow_seconds, "ends": time.monotonic() + self.glow_seconds}
self.lamp.show(entry["color"], pattern, self.glow_seconds)
self._tell("glow", entry)
return entry
def send(self, color: str, pattern: str, via: str) -> Dict[str, Any]:
"""A touch or the phone: send a glow to the other lamp. Answers at once; whether it arrived follows
as the event `delivered`."""
entry = self._add("sent", color, pattern, via, None)
self._tell("glow", entry)
self._spawn(self._deliver(entry))
return entry
async def _deliver(self, entry: Dict[str, Any]) -> None:
error: Optional[str] = None
if self.link is None:
error = "NO_LINK" # local only: there is no way to the other lamp
else:
try:
body = {"from": self.here["name"], "color": entry["color"], "pattern": entry["pattern"], "via": entry["via"]}
answer, path = await self.link.post_glow(body)
seconds = float(answer.get("glowSeconds") or self.glow_seconds)
self._other_glow = {"color": entry["color"], "pattern": entry["pattern"], "seconds": seconds, "ends": time.monotonic() + seconds}
self._path = path
self._reachable = True
except LinkError as failure:
error = failure.code
self._log(f"The glow {entry['id']} did not arrive: {failure} ({failure.code})")
except Exception as failure: # nothing that goes wrong on the way may leave the entry undecided
error = "FAILED"
self._log(f"The glow {entry['id']} did not arrive: {failure!r}")
entry["delivered"] = error is None
self._write_history()
self._tell("delivered", entry, error)
async def run(self) -> None:
"""Tells the page when a glow has ended, and looks now and then whether the other lamp is online."""
looked = -REACHABLE_EVERY
shown = (False, False)
while True:
now = time.monotonic()
if self.link is not None and now - looked >= REACHABLE_EVERY:
looked = now
self._spawn(self._look())
glowing = (self._glow_now(self._here_glow) is not None, self._glow_now(self._other_glow) is not None)
if glowing != shown:
if (shown[0] and not glowing[0]) or (shown[1] and not glowing[1]):
self._tell("state")
shown = glowing
await asyncio.sleep(0.5)
async def _look(self) -> None:
try:
reachable = await self.link.reachable()
except Exception as error:
self._log(f"Looking for the other lamp failed: {error!r}")
reachable = None
if reachable != self._reachable:
self._reachable = reachable
self._tell("state")
# ---------------------------------------------------------------------------------------------------------
# The web server: HTTP/1.1 and WebSocket on asyncio streams, standard library only
# ---------------------------------------------------------------------------------------------------------
WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
REASONS = {200: "OK", 204: "No Content", 302: "Found", 400: "Bad Request", 404: "Not Found", 405: "Method Not Allowed",
413: "Payload Too Large", 426: "Upgrade Required", 500: "Internal Server Error"}
MAX_BODY = 16 * 1024
IDLE_SECONDS = 75.0
Answer = Tuple[int, str, bytes, Dict[str, str]] # status, content type, body, extra headers
def _json(status: int, value: Any) -> Answer:
return status, "application/json", json.dumps(value, separators=(",", ":")).encode(), {}
def _text(status: int, text: str) -> Answer:
return status, "text/plain; charset=utf-8", text.encode(), {}
class Server:
def __init__(self, program: LampProgram, log: Callable[[str], None]) -> None:
self._program = program
self._log = log
self._sockets: Set["asyncio.Queue[Optional[str]]"] = set()
program.on_event = self._broadcast
def _broadcast(self, message: Dict[str, Any]) -> None:
text = json.dumps(message, separators=(",", ":"))
for queue in list(self._sockets):
if queue.qsize() > 32: # a reader that does not keep up: let it go rather than pile up
self._sockets.discard(queue)
queue.put_nowait(None)
else:
queue.put_nowait(text)
# --- routes ---
def _glow(self, body: bytes) -> Answer:
program = self._program
try:
asked = json.loads(body.decode("utf-8")) if body else {}
except ValueError:
asked = None
if not isinstance(asked, dict):
return _json(400, {"error": "The body is a JSON object."})
sender = asked.get("from")
color = asked.get("color") or (program.other["color"] if sender else program.here["color"])
pattern = asked.get("pattern") or "glow"
if not isinstance(color, str) or not COLOUR.match(color):
return _json(400, {"error": "color is #rrggbb."})
if pattern not in PATTERNS:
return _json(400, {"error": f"pattern is one of {', '.join(PATTERNS)}."})
if sender is None:
# No sender: the owner's phone. The glow goes to the other lamp.
return _json(200, {"ok": True, "entry": program.send(color, pattern, "phone")})
if sender != program.other["name"]:
return _json(400, {"error": "from is not the lamp this one belongs with."})
via = "phone" if asked.get("via") == "phone" else "touch"
return _json(200, {"ok": True, "entry": program.receive(color, pattern, via), "glowSeconds": program.glow_seconds})
def _route(self, method: str, path: str, body: bytes) -> Answer:
if path == "/state" and method == "GET":
return _json(200, self._program.state())
if path == "/history" and method == "GET":
return _json(200, self._program.history())
if path == "/glow":
if method != "POST":
return 405, "text/plain; charset=utf-8", b"Use POST.", {"Allow": "POST"}
return self._glow(body)
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"}
if path == "/events":
return 426, "text/plain; charset=utf-8", b"/events is a WebSocket.", {"Upgrade": "websocket"}
return _text(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(404, f"{file.name} is not there.")
if len(data) > MAX_PAGE_BYTES:
return _text(500, f"{file.name} is larger than 2 MB.")
return 200, content_type, data, {}
# --- one connection ---
async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
try:
while True:
try:
head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), IDLE_SECONDS)
except (asyncio.IncompleteReadError, asyncio.TimeoutError, ConnectionError):
return
except asyncio.LimitOverrunError:
await self._send(writer, _text(400, "The request head is too long."), close=True)
return
lines = head.decode("latin-1").split("\r\n")
parts = lines[0].split(" ")
if len(parts) != 3 or not parts[2].startswith("HTTP/1."):
await self._send(writer, _text(400, "Not an HTTP/1.1 request."), close=True)
return
method, target, version = parts[0].upper(), parts[1], parts[2]
headers: Dict[str, str] = {}
for line in lines[1:]:
name, colon, value = line.partition(":")
if colon:
headers[name.strip().lower()] = value.strip()
if "chunked" in headers.get("transfer-encoding", "").lower():
await self._send(writer, _text(400, "Send the body with Content-Length."), close=True)
return
try:
length = int(headers.get("content-length", "0") or "0")
except ValueError:
length = -1
if length < 0 or length > MAX_BODY:
await self._send(writer, _text(413 if length > 0 else 400, "The body is too large."), close=True)
return
body = b""
if length:
try:
body = await asyncio.wait_for(reader.readexactly(length), IDLE_SECONDS)
except (asyncio.IncompleteReadError, asyncio.TimeoutError, ConnectionError):
return
path = urlsplit(target).path or "/"
tokens = [token.strip().lower() for token in headers.get("connection", "").split(",")]
if path == "/events" and method == "GET" and headers.get("upgrade", "").lower() == "websocket" and "upgrade" in tokens:
await self._websocket(reader, writer, headers)
return
try:
answer = self._route(method if method != "HEAD" else "GET", path, body)
except Exception as error: # a bug in a route must not take the server down
self._log(f"{method} {path} failed: {error!r}")
answer = _text(500, "Internal error")
close = "close" in tokens or (version == "HTTP/1.0" and "keep-alive" not in tokens)
await self._send(writer, answer, close=close, head_only=method == "HEAD")
if close:
return
except (ConnectionError, asyncio.CancelledError):
pass
finally:
try:
writer.close()
await writer.wait_closed()
except Exception:
pass
async def _send(writer: asyncio.StreamWriter, answer: Answer, close: bool, head_only: bool = False) -> None:
status, content_type, body, extra = answer
lines = [
f"HTTP/1.1 {status} {REASONS.get(status, 'OK')}",
f"Content-Type: {content_type}",
f"Content-Length: {len(body)}",
"Cache-Control: no-store",
f"Connection: {'close' if close else 'keep-alive'}",
]
lines.extend(f"{name}: {value}" for name, value in extra.items())
writer.write(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1") + (b"" if head_only else body))
await writer.drain()
# --- WebSocket (RFC 6455): the handshake, text frames out, control frames in ---
def _frame(opcode: int, payload: bytes) -> bytes:
length = len(payload)
if length < 126:
return bytes([0x80 | opcode, length]) + payload
if length < 65536:
return bytes([0x80 | opcode, 126]) + struct.pack("!H", length) + payload
return bytes([0x80 | opcode, 127]) + struct.pack("!Q", length) + payload
async def _websocket(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, headers: Dict[str, str]) -> None:
key = headers.get("sec-websocket-key", "")
if not key or headers.get("sec-websocket-version", "13") != "13":
await self._send(writer, (426, "text/plain; charset=utf-8", b"WebSocket version 13 only.", {"Sec-WebSocket-Version": "13"}), close=True)
return
accept = base64.b64encode(hashlib.sha1((key + WEBSOCKET_GUID).encode()).digest()).decode()
writer.write(
("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" f"Sec-WebSocket-Accept: {accept}\r\n\r\n").encode()
)
await writer.drain()
queue: "asyncio.Queue[Optional[str]]" = asyncio.Queue()
queue.put_nowait(json.dumps({"type": "state", "state": self._program.state()}, separators=(",", ":")))
self._sockets.add(queue)
async def read_frames() -> None:
# Nothing the page sends matters; pings are answered and a close ends it.
while True:
first, second = await reader.readexactly(2)
opcode, masked, length = first & 0x0F, second & 0x80, second & 0x7F
if length == 126:
(length,) = struct.unpack("!H", await reader.readexactly(2))
elif length == 127:
(length,) = struct.unpack("!Q", await reader.readexactly(8))
if length > MAX_BODY or not masked: # a client has to mask (RFC 6455, 5.1)
return
mask = await reader.readexactly(4)
payload = bytes(byte ^ mask[i % 4] for i, byte in enumerate(await reader.readexactly(length)))
if opcode == 0x8: # close: answer with the same status
writer.write(self._frame(0x8, payload[:2]))
await writer.drain()
return
if opcode == 0x9: # ping
writer.write(self._frame(0xA, payload))
await writer.drain()
reading = asyncio.ensure_future(read_frames())
try:
while True:
waiting = asyncio.ensure_future(queue.get())
done, _ = await asyncio.wait({waiting, reading}, return_when=asyncio.FIRST_COMPLETED)
if waiting not in done:
waiting.cancel()
return
text = waiting.result()
if text is None:
writer.write(self._frame(0x8, struct.pack("!H", 1008)))
await writer.drain()
return
writer.write(self._frame(0x1, text.encode()))
await writer.drain()
if reading.done():
return
except (ConnectionError, asyncio.IncompleteReadError):
pass
finally:
self._sockets.discard(queue)
reading.cancel()
try:
await reading
except BaseException:
pass
# ---------------------------------------------------------------------------------------------------------
# Configuration and Connectivitizer
# ---------------------------------------------------------------------------------------------------------
def _is_placeholder(value: str) -> bool:
return not value or "..." in value or "…" in value
def read_lamps(path: Path, explicit: bool) -> Dict[str, Any]:
"""Who this lamp is and who the other one is: lamp.json, or the example's two lamps without it."""
if not path.exists():
if explicit:
raise ValueError(f"{path} is not there.")
return DEFAULT_CONFIG
try:
config = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as error:
raise ValueError(f"{path.name} could not be read ({error}).") from error
for side in ("here", "other"):
about = config.get(side) if isinstance(config, dict) else None
if not isinstance(about, dict) or not isinstance(about.get("name"), str) or not about["name"]:
raise ValueError(f'{path.name}: "{side}" needs a "name", the device name of that lamp.')
if not isinstance(about.get("color"), str) or not COLOUR.match(about["color"]):
raise ValueError(f'{path.name}: "{side}" needs a "color" as #rrggbb.')
if config["here"]["name"] == config["other"]["name"]:
raise ValueError(f"{path.name}: the two lamps need different names.")
return config
def read_keys() -> Dict[str, str]:
"""The keys: 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.")
return {
"api_url": os.environ.get("CZ_API_URL") or str(file.get("apiUrl") or ""),
"device_key": os.environ.get("CZ_DEVICE_KEY") or str(file.get("deviceKey") or ""),
"shared_key": os.environ.get("CZ_SHARED_KEY") or str(file.get("sharedKey") or ""),
}
def make_device(keys: Dict[str, str], name: str, port: int) -> Any:
"""This program as a Connectivitizer device with one service, `api`. The same device opens the sessions
to the other lamp."""
from connectivitizer import Agent
return Agent(
None if _is_placeholder(keys["api_url"]) else keys["api_url"],
device_key=keys["device_key"],
name=name,
shared_key=keys["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_device(agent: Any, name: str) -> None:
"""Keeps the device connected until the program ends."""
print(f"Connectivitizer: connecting as device '{name}' with the service 'api'.")
try:
await agent.run() # reconnects by itself; raises when the device key was revoked
finally:
await agent.stop()
async def main() -> int:
parser = argparse.ArgumentParser(description="A long-distance lamp: touch it and the other lamp glows, through Connectivitizer.")
parser.add_argument("--config", default=None, help="who this lamp and the other lamp are (default: lamp.json next to this file)")
parser.add_argument("--port", type=int, default=int(os.environ.get("LAMP_PORT", "8151")), help="local port on 127.0.0.1 (0: any free one)")
parser.add_argument("--lamp", default="simulator", choices=["simulator", "gpio"], help="'simulator' (default, no hardware) or 'gpio' (WS2812 and touch sensor; NOT tested)")
parser.add_argument("--touch-every", type=float, default=0.0, help="simulator: touch the lamp by itself every so many seconds (default: never)")
parser.add_argument("--led-pin", type=int, default=18, help="gpio: the data pin of the LEDs (default 18)")
parser.add_argument("--led-count", type=int, default=16, help="gpio: how many LEDs (default 16)")
parser.add_argument("--touch-pin", type=int, default=17, help="gpio: the pin of the touch sensor (default 17)")
parser.add_argument("--local-peer", default=None, help="for two programs on one machine: the other one's address, such as http://127.0.0.1:8152 (plain HTTP, no Connectivitizer)")
args = parser.parse_args()
try:
config = read_lamps(Path(args.config) if args.config else HERE / "lamp.json", explicit=args.config is not None)
except ValueError as error:
print(error)
return 2
if args.lamp == "simulator":
lamp: Lamp = SimulatedLamp(args.touch_every)
else:
try:
lamp = GpioLamp(args.led_pin, args.led_count, args.touch_pin)
except ImportError as error:
print(f"--lamp gpio needs gpiozero and rpi_ws281x on a Raspberry Pi ({error}). Run it without --lamp for the simulator.")
return 2
name = config["here"]["name"]
program = LampProgram(config, lamp, HERE / f"history-{name}.json", print)
server = Server(program, print)
listener = await asyncio.start_server(server.handle, "127.0.0.1", args.port) # loopback only: no open port
port = listener.sockets[0].getsockname()[1]
print(f"Lamp '{name}' ({lamp.kind}) on http://127.0.0.1:{port}, belongs with '{config['other']['name']}'")
print(f" the screen: http://127.0.0.1:{port}/.cz/ui.html")
print(f" the state: http://127.0.0.1:{port}/state")
if not PAGE_FILE.exists() or not MANIFEST_FILE.exists():
print(f" {PAGE_FILE} or {MANIFEST_FILE} is missing; the device has no screen without them.")
tasks: List["asyncio.Future[None]"] = []
keys = read_keys()
have = {key: not _is_placeholder(value) for key, value in keys.items()}
try:
if args.local_peer:
program.link = LocalLink(args.local_peer)
print(f"Local only: glows go by plain HTTP to {args.local_peer}. Connectivitizer is NOT started.")
elif not (have["shared_key"] and have["device_key"]):
print("Local only: Connectivitizer is NOT started (no keys: fill in secrets.json, or set CZ_DEVICE_KEY and CZ_SHARED_KEY).")
print(" Glows sent from here do not arrive anywhere.")
else:
try:
import connectivitizer # noqa: F401 (only needed with keys: pip install huelake-connectivitizer)
except ImportError:
print("Connectivitizer is NOT started: the keys are there, but the SDK is not installed (pip install -r requirements.txt).")
else:
agent = make_device(keys, name, port)
tasks.append(asyncio.ensure_future(run_device(agent, name)))
program.link = SessionLink(agent, config["other"]["name"])
print(f"Connectivitizer: glows go through a session to the device '{config['other']['name']}'.")
print(' The device key needs "Its devices may open sessions to other devices"; without it glows end as FORBIDDEN.')
except ValueError as error:
print(error)
listener.close()
return 2
lamp.start(asyncio.get_running_loop())
tasks.append(asyncio.ensure_future(program.run()))
try:
async with listener:
# Ends when the lamp's own loop 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
await asyncio.gather(*[task for task in tasks if not task.done()])
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
if program.link is not None:
await program.link.close()
lamp.close()
return 0
if __name__ == "__main__":
try:
sys.exit(asyncio.run(main()))
except KeyboardInterrupt:
pass