Observatoire
demo-kit/ est ce qui simule l’appareil pour la démo sur la page de démarrage. L’appareil lui-même n’en a pas besoin.
demo-kit/ est ce qui simule l’appareil pour la démo sur la page de démarrage. L’appareil lui-même n’en a pas besoin.
#!/usr/bin/env python3
"""A remote observatory on a Raspberry Pi: one program that points a telescope mount, takes exposures, keeps
a live stack of them, and serves all of it as a small HTTP and WebSocket API on 127.0.0.1. Through
Connectivitizer the API is the service ``api``: the phone shows the observatory's own screen
(../ui/observatory.html, a device UI), and a program on another network (../home/stacker.py) pulls every
frame and stacks it there.
python observatory.py # simulator: a pretend mount and a pretend camera
Without keys (secrets.json next to this file, or CZ_DEVICE_KEY and CZ_SHARED_KEY) it runs
"local only": everything is served on 127.0.0.1 and Connectivitizer is not started.
The hardware is behind the classes ``Mount`` and ``Camera``. ``SimulatedMount`` and ``SimulatedCamera`` are
the ones that work: every frame they give is synthetic. ``RealMount`` and ``RealCamera`` mark where a
telescope would be connected; they are NOT implemented and NOT tested.
Needs numpy. The Connectivitizer SDK (``pip install huelake-connectivitizer``) is imported only when keys
are there. The SDK forwards every stream of a session as plain TCP to 127.0.0.1:<port>, so the HTTP and
WebSocket server below is all a session needs.
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import hashlib
import json
import math
import os
import struct
import sys
import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from urllib.parse import parse_qs, urlsplit
import numpy as np
HERE = Path(__file__).resolve().parent
UI_FOLDER = HERE.parent / "ui"
PAGE_FILE = UI_FOLDER / "observatory.html"
MANIFEST_FILE = UI_FOLDER / "manifest.json"
MAX_PAGE_BYTES = 2 * 1024 * 1024 # what the app accepts as a device UI
EXPOSURES = (1, 2, 4, 8) # seconds
GAIN_MAX = 300 # in units of 0.1 dB, as many astronomy cameras count it
# Right ascension in hours, declination in degrees (J2000). The simulator draws a synthetic object of the
# same kind at each of them, not the real one.
TARGETS: List[Dict[str, Any]] = [
{"id": "m51", "name": "M51", "title": "Whirlpool Galaxy", "kind": "spiral", "ra": 13.498, "dec": 47.195},
{"id": "m42", "name": "M42", "title": "Orion Nebula", "kind": "nebula", "ra": 5.588, "dec": -5.391},
{"id": "m13", "name": "M13", "title": "Hercules Cluster", "kind": "cluster", "ra": 16.695, "dec": 36.460},
{"id": "m57", "name": "M57", "title": "Ring Nebula", "kind": "ring", "ra": 18.893, "dec": 33.029},
]
SEEDS = {"m51": 51, "m42": 42, "m13": 13, "m57": 57}
# ---------------------------------------------------------------------------------------------------------
# The hardware: a mount and a camera
# ---------------------------------------------------------------------------------------------------------
class Mount:
"""What the observatory needs from a mount. All of it is called from the event loop."""
def position(self) -> Tuple[float, float]:
"""Where the telescope points: (right ascension in hours, declination in degrees)."""
raise NotImplementedError
def slewing(self) -> bool:
raise NotImplementedError
def slew_to(self, ra: float, dec: float) -> None:
raise NotImplementedError
def tick(self, seconds: float) -> None:
"""Called about four times a second with the time that has passed."""
class Camera:
"""What the observatory needs from a camera. A frame is a numpy array (height, width, 3) of uint16."""
width = 0
height = 0
def point(self, target: Dict[str, Any]) -> None:
"""Called when the mount has arrived at a target. Only the simulator needs to know."""
def expose(self, seconds: float, gain: int) -> np.ndarray:
"""Called when an exposure of `seconds` has run: gives its frame."""
raise NotImplementedError
def white_level(self, seconds: float, gain: int) -> float:
"""The count above the sky background that the live stack shows as white."""
raise NotImplementedError
# --- The simulator. Nothing is connected: every position and every pixel is invented. ---------------------
SKY = 0.06 # the sky background, in the unit of the scene (1 is the core of the galaxy)
ELECTRONS_PER_SECOND = 20.0 # what a scene value of 1 gives the sensor
COUNTS_PER_ELECTRON = 16.0 # at gain 0
OFFSET = 400.0 # the count of a pixel that saw nothing
STAR_SIGMA = 1.15 # the width of a star, in pixels
class Lcg:
"""A small random number generator with the same sequence as the one in ../ui/demo-data.js."""
def __init__(self, seed: int) -> None:
self._state = (seed * 2654435761) & 0xFFFFFFFF
def next(self) -> float:
self._state = (self._state * 1664525 + 1013904223) & 0xFFFFFFFF
return self._state / 4294967296.0
def _smooth(low: float, high: float, value: np.ndarray) -> np.ndarray:
t = np.clip((value - low) / (high - low), 0.0, 1.0)
return t * t * (3 - 2 * t)
def _add_star(image: np.ndarray, x: float, y: float, brightness: float, colour: Tuple[float, float, float]) -> None:
"""A star at (x, y), each from -1 to 1 across the frame."""
height, width = image.shape[:2]
cx, cy = (x + 1) / 2 * width - 0.5, (y + 1) / 2 * height - 0.5
reach = 5
x0, x1 = max(0, int(cx) - reach), min(width, int(cx) + reach + 2)
y0, y1 = max(0, int(cy) - reach), min(height, int(cy) + reach + 2)
if x0 >= x1 or y0 >= y1:
return
px, py = np.meshgrid(np.arange(x0, x1), np.arange(y0, y1))
spot = brightness * np.exp(-((px - cx) ** 2 + (py - cy) ** 2) / (2 * STAR_SIGMA**2))
image[y0:y1, x0:x1] += spot[..., None] * np.array(colour)
def _star_colour(c: float) -> Tuple[float, float, float]:
"""From a warm star (0) to a blue one (1)."""
return (1.0 - 0.25 * c, 0.82 + 0.03 * c, 0.70 + 0.30 * c)
def render_scene(kind: str, seed: int, width: int, height: int) -> np.ndarray:
"""The sky without noise: a synthetic object of one kind with stars around it, as (height, width, 3)
in the unit of the scene. The formulas are the same as in ../ui/demo-data.js."""
xs = (np.arange(width) + 0.5) / width * 2 - 1
ys = (np.arange(height) + 0.5) / height * 2 - 1
x, y = np.meshgrid(xs, ys)
image = np.zeros((height, width, 3))
rng = Lcg(seed)
def add(value: np.ndarray, colour: Tuple[float, float, float]) -> None:
image[...] += value[..., None] * np.array(colour)
field_stars = 36
if kind == "spiral":
# An inclined disc with a bright core, two arms, knots along them and a companion.
u = (x * math.cos(0.6) + y * math.sin(0.6)) / 1.3
v = (-x * math.sin(0.6) + y * math.cos(0.6)) / (1.3 * 0.72)
r, theta = np.hypot(u, v), np.arctan2(v, u)
psi = 2 * theta - 5.2 * np.log(r + 0.02)
arm = (0.5 + 0.5 * np.cos(psi)) ** 3 * np.exp(-r / 0.36) * _smooth(0.06, 0.16, r) * (1 - _smooth(0.62, 0.85, r))
add(1.1 * np.exp(-r / 0.055) + 0.30 * np.exp(-((r / 0.16) ** 2)), (1.0, 0.86, 0.62))
add(0.10 * np.exp(-r / 0.30), (0.9, 0.85, 0.8))
add(0.42 * arm, (0.5, 0.66, 1.0))
add(0.30 * arm**2 * (0.5 + 0.5 * np.sin(9 * theta + 23 * r)) ** 4, (1.0, 0.35, 0.55))
add(0.5 * np.exp(-((x - 0.62) ** 2 + (y + 0.60) ** 2) / (2 * 0.07**2)), (1.0, 0.85, 0.65))
elif kind == "nebula":
# Glowing gas: warped waves under a wide envelope, a bright core, a blue wing and a dark bay.
a = x + 0.25 * np.sin(3.1 * y + 1.3)
b = y + 0.25 * np.sin(2.7 * x - 0.8)
n1 = 0.5 + 0.5 * np.sin(4.2 * a + 1.7 * np.sin(3.3 * b))
n2 = 0.5 + 0.5 * np.sin(5.1 * b - 2.2 * np.sin(2.9 * a) + 1.0)
n3 = 0.5 + 0.5 * np.sin(9 * a + 7 * b + 2 * np.sin(6 * b))
cloud = 0.55 * n1 * n2 + 0.25 * n3 * n1 + 0.2
envelope = np.exp(-((x + 0.05) ** 2 / 0.5 + (y - 0.05) ** 2 / 0.38))
bay = 1 - 0.8 * np.exp(-((x - 0.12) ** 2 / 0.012 + (y - 0.24) ** 2 / 0.05))
core = np.exp(-((x + 0.08) ** 2 + (y - 0.02) ** 2) / (2 * 0.13**2))
add(0.85 * cloud * envelope * bay, (1.0, 0.32, 0.42))
add(0.9 * core * (0.6 + 0.4 * n3) * bay, (0.75, 0.95, 1.0))
add(0.18 * np.exp(-((x - 0.35) ** 2 + (y + 0.45) ** 2) / 0.08), (0.45, 0.6, 1.0))
elif kind == "cluster":
# A globular cluster: a glow and some hundred stars, crowded towards the middle.
r = np.hypot(x, y)
add(0.35 / (1 + (r / 0.12) ** 2) ** 1.3, (1.0, 0.93, 0.8))
for _ in range(520):
radius = min(1.3, 0.09 * math.tan(rng.next() * 1.35))
angle = rng.next() * 2 * math.pi
brightness = 0.08 + 0.9 * rng.next() ** 5
_add_star(image, radius * math.cos(angle), radius * math.sin(angle), brightness, _star_colour(rng.next() ** 2))
field_stars = 18
elif kind == "ring":
# A planetary nebula: a red rim, a green ring inside it, a blue filling and the star in the middle.
u = x * math.cos(0.5) + y * math.sin(0.5)
v = (-x * math.sin(0.5) + y * math.cos(0.5)) / 0.78
r, theta = np.hypot(u, v), np.arctan2(v, u)
add(0.55 * np.exp(-(((r - 0.33) / 0.07) ** 2)) * (1 + 0.25 * np.cos(2 * theta)), (1.0, 0.35, 0.30))
add(0.50 * np.exp(-(((r - 0.27) / 0.06) ** 2)), (0.55, 1.0, 0.6))
add(0.22 * np.exp(-((r / 0.22) ** 2)), (0.3, 0.7, 1.0))
add(0.05 * np.exp(-((r / 0.5) ** 2)), (1.0, 0.4, 0.4))
_add_star(image, 0.0, 0.0, 0.6, (0.8, 0.9, 1.0))
# Any other kind is an empty field: stars only.
for _ in range(field_stars):
sx, sy = rng.next() * 2 - 1, rng.next() * 2 - 1
_add_star(image, sx, sy, 0.2 + 2.2 * rng.next() ** 8, _star_colour(rng.next()))
return image
class SimulatedMount(Mount):
"""Turns both axes towards the goal at `rate` degrees a second, right ascension the short way round."""
def __init__(self, ra: float, dec: float, rate: float = 4.0) -> None:
self._ra, self._dec = ra, dec
self._goal: Optional[Tuple[float, float]] = None
self._rate = max(0.1, rate)
def position(self) -> Tuple[float, float]:
return self._ra, self._dec
def slewing(self) -> bool:
return self._goal is not None
def slew_to(self, ra: float, dec: float) -> None:
self._goal = (ra % 24.0, max(-90.0, min(90.0, dec)))
def tick(self, seconds: float) -> None:
if self._goal is None:
return
step = self._rate * seconds # degrees
ra_left = ((self._goal[0] - self._ra + 12.0) % 24.0 - 12.0) * 15.0 # degrees, the short way
dec_left = self._goal[1] - self._dec
self._ra = (self._ra + max(-step, min(step, ra_left)) / 15.0) % 24.0
self._dec += max(-step, min(step, dec_left))
if abs(ra_left) <= step and abs(dec_left) <= step:
self._ra, self._dec = self._goal
self._goal = None
class SimulatedCamera(Camera):
"""A pretend colour camera of 160 x 160 pixels. A frame is the scene of the target, as many electrons
as the exposure collects, with the noise of the light itself and of reading the sensor, times the gain.
A higher gain lowers the read noise a little, as it does on real sensors."""
width = 160
height = 160
def __init__(self) -> None:
self._random = np.random.default_rng()
self._scene = np.zeros((self.height, self.width, 3))
def point(self, target: Dict[str, Any]) -> None:
seed = SEEDS.get(target["id"], int(target["ra"] * 1000) * 7919 + int((target["dec"] + 90) * 100))
self._scene = render_scene(target["kind"], seed, self.width, self.height) + SKY
def expose(self, seconds: float, gain: int) -> np.ndarray:
electrons = self._scene * seconds * ELECTRONS_PER_SECOND
read_noise = 7.0 - gain / 75.0
electrons = electrons + self._random.standard_normal(electrons.shape) * np.sqrt(electrons + read_noise**2)
counts = electrons * COUNTS_PER_ELECTRON * 10 ** (gain / 200.0) + OFFSET
return np.clip(np.rint(counts), 0, 65535).astype(np.uint16)
def white_level(self, seconds: float, gain: int) -> float:
return 1.4 * seconds * ELECTRONS_PER_SECOND * COUNTS_PER_ELECTRON * 10 ** (gain / 200.0)
# --- A real telescope: NOT IMPLEMENTED, NOT TESTED. -------------------------------------------------------
class RealMount(Mount):
"""Where a real mount would be connected. Nothing in this class works: it has never been run against
a mount, and it is here only to show what would have to be filled in.
Most mounts are driven through an INDI server (``indiserver`` with the mount's driver, on this Pi) or
speak the LX200 protocol on a serial port:
* position(): the mount's ``EQUATORIAL_EOD_COORD`` property (INDI), or ``:GR#`` and ``:GD#`` (LX200).
* slew_to(): set ``ON_COORD_SET`` to ``TRACK`` and write the coordinates (INDI), or ``:Sr``, ``:Sd``
and ``:MS#`` (LX200). A real mount also needs limits, a meridian flip and a way to stop.
* slewing(): the state of the coordinate property (``Busy``), or ``:D#``.
Do the talking in a thread or with asyncio streams and keep the last known values; nothing here may
block tick().
"""
def __init__(self, address: str) -> None:
raise NotImplementedError(
"A real mount is not implemented in this example (see the class RealMount in observatory.py). "
"Run it without --telescope for the simulator."
)
class RealCamera(Camera):
"""Where a real camera would be connected. Nothing in this class works: it has never been run against
a camera.
* A Raspberry Pi camera with picamera2: set ``ExposureTime`` (microseconds) and ``AnalogueGain``,
capture the raw array, debayer it and bin it down to a size that travels well.
* An astronomy camera through INDI: set ``CCD_EXPOSURE`` and read the image the driver sends back.
An exposure takes as long as it takes: start it when the previous one ends, and let expose() hand over
the frame that is ready. white_level() is the count that should look white, 65535 at most.
"""
def __init__(self) -> None:
raise NotImplementedError("A real camera is not implemented in this example (see the class RealCamera in observatory.py).")
# ---------------------------------------------------------------------------------------------------------
# The observatory: pointing, exposures and the live stack. It knows the hardware only as Mount and Camera.
# ---------------------------------------------------------------------------------------------------------
FRAME_MAGIC = b"CZFR"
def encode_image(pixels: np.ndarray, serial: int, number: int) -> bytes:
"""A picture as the device sends it: 16 bytes (the magic 'CZFR'; width and height as uint16; channels
and bits per sample as uint8; the serial of the stack as uint16; a number as uint32; little endian),
then the samples row by row, red, green, blue."""
height, width, channels = pixels.shape
bits = pixels.dtype.itemsize * 8
head = FRAME_MAGIC + struct.pack("<HHBBHI", width, height, channels, bits, serial & 0xFFFF, number)
return head + pixels.astype(pixels.dtype.newbyteorder("<")).tobytes()
def stack_statistics(mean: np.ndarray) -> Tuple[float, float]:
"""(noise, signal to noise) of a stack. The noise is taken from the differences between neighbouring
pixels of the brightness, with the median, so that stars and the object itself hardly count. The signal
is how far the middle of the frame lies above the background. Both are estimates."""
brightness = mean.mean(axis=2)
steps = brightness[:, 1:] - brightness[:, :-1]
noise = 1.4826 * float(np.median(np.abs(steps - np.median(steps)))) / math.sqrt(2)
height, width = brightness.shape
middle = brightness[height // 4 : height - height // 4, width // 4 : width - width // 4]
signal = float(middle.mean() - np.median(brightness))
return noise, (max(0.0, signal) / noise if noise > 0 else 0.0)
class Observatory:
def __init__(self, mount: Mount, camera: Camera, simulated: bool, tour_frames: int = 0) -> None:
self._mount = mount
self._camera = camera
self._simulated = simulated
self._tour_frames = tour_frames
self._target = TARGETS[0]
self._running = True
self._exposure = 2
self._gain = 120
self._elapsed = 0.0 # seconds of the exposure that is running
self._serial = 0 # counts the stacks
self._sequence = 0 # counts the frames since the program started
self._frames = 0 # frames in the stack
self._sum = np.zeros((camera.height, camera.width, 3))
self._noise = 0.0
self._snr = 0.0
self._latest: Optional[bytes] = None
self._preview: Optional[bytes] = None
self._served = 0
self._served_sequence = 0
self._served_at = 0.0
self.on_change: Optional[Callable[[], None]] = None
"""Called when the mount starts or ends a slew, or the capture settings changed."""
self.on_frame: Optional[Callable[[], None]] = None
"""Called when a frame was added to the stack."""
camera.point(self._target)
self._new_stack()
def _new_stack(self) -> None:
self._serial += 1
self._frames = 0
self._sum[...] = 0
self._noise = self._snr = 0.0
self._elapsed = 0.0
self._latest = None
self._preview = None
def _changed(self) -> None:
if self.on_change is not None:
self.on_change()
def tick(self, seconds: float) -> None:
seconds = max(0.0, min(2.0, seconds))
was_slewing = self._mount.slewing()
self._mount.tick(seconds)
if was_slewing and not self._mount.slewing():
self._camera.point(self._target)
self._new_stack()
self._changed()
if self._mount.slewing() or not self._running:
return
self._elapsed += seconds
if self._elapsed >= self._exposure:
self._elapsed = 0.0
self._add(self._camera.expose(self._exposure, self._gain))
if self._tour_frames > 0 and self._frames >= self._tour_frames:
index = next((i for i, target in enumerate(TARGETS) if target["id"] == self._target["id"]), -1)
self.slew(TARGETS[(index + 1) % len(TARGETS)])
def _add(self, frame: np.ndarray) -> None:
self._sequence += 1
self._frames += 1
self._sum += frame
self._latest = encode_image(frame, self._serial, self._sequence)
mean = self._sum / self._frames
self._noise, self._snr = stack_statistics(mean)
# The live stack for the screen: the sky taken off each colour, then a fixed asinh stretch to 8 bits,
# so that the grain is seen to fall as frames are added.
level = (mean - np.median(mean, axis=(0, 1))) / self._camera.white_level(self._exposure, self._gain)
shown = np.arcsinh((level + 0.015) / 0.05) / math.asinh(1.015 / 0.05)
self._preview = encode_image(np.rint(np.clip(shown, 0, 1) * 255).astype(np.uint8), self._serial, self._frames)
if self.on_frame is not None:
self.on_frame()
# --- what the server asks ---
def stack(self) -> Dict[str, Any]:
return {
"serial": self._serial,
"frames": self._frames,
"integrationSeconds": self._frames * self._exposure,
"noise": round(self._noise, 2),
"snr": round(self._snr, 2),
}
def state(self) -> Dict[str, Any]:
ra, dec = self._mount.position()
slewing = self._mount.slewing()
return {
"t": round(time.time()),
"simulated": self._simulated,
"mount": {"state": "slewing" if slewing else "tracking", "ra": round(ra, 4), "dec": round(dec, 3), "target": self._target},
"camera": {"exposureSeconds": self._exposure, "gain": self._gain, "width": self._camera.width, "height": self._camera.height},
"capture": {
"running": self._running,
"exposureProgress": 0.0 if slewing or not self._running else round(min(1.0, self._elapsed / self._exposure), 3),
"sequence": self._sequence,
},
"stack": self.stack(),
"downlink": {
"framesServed": self._served,
"lastSequence": self._served_sequence,
"lastSecondsAgo": round(time.monotonic() - self._served_at, 1) if self._served else None,
},
}
def sequence(self) -> int:
return self._sequence
def latest_frame(self) -> Optional[bytes]:
"""The newest exposure of the stack that is running, 16 bits a sample, or None before the first."""
return self._latest
def frame_served(self) -> None:
self._served += 1
self._served_sequence = self._sequence
self._served_at = time.monotonic()
def preview(self) -> Optional[bytes]:
"""The live stack, 8 bits a sample, or None before the first frame."""
return self._preview
def slew(self, target: Dict[str, Any]) -> None:
ra, dec = self._mount.position()
if not self._mount.slewing() and abs(ra - target["ra"]) < 1e-6 and abs(dec - target["dec"]) < 1e-6:
return # already there
self._target = target
self._mount.slew_to(target["ra"], target["dec"])
self._new_stack() # what was stacked belongs to the place the telescope leaves
self._changed()
def capture(self, running: Optional[bool], exposure: Optional[int], gain: Optional[int]) -> None:
if (exposure is not None and exposure != self._exposure) or (gain is not None and gain != self._gain):
self._exposure = exposure if exposure is not None else self._exposure
self._gain = gain if gain is not None else self._gain
self._new_stack() # frames of different settings are not averaged together
if running is not None and running != self._running:
self._running = running
self._elapsed = 0.0
self._changed()
# ---------------------------------------------------------------------------------------------------------
# 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 = 64 * 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(), {}
def _binary(data: bytes) -> Answer:
return 200, "application/octet-stream", data, {}
class Server:
def __init__(self, observatory: Observatory, log: Callable[[str], None]) -> None:
self._observatory = observatory
self._log = log
self._sockets: Set["asyncio.Queue[Optional[str]]"] = set()
observatory.on_change = self._tell_state
observatory.on_frame = self._tell_frame
# --- events ---
def _tell_state(self) -> None:
self._broadcast({"type": "state", "state": self._observatory.state()})
def _tell_frame(self) -> None:
self._broadcast({"type": "frame", "sequence": self._observatory.sequence, "stack": self._observatory.stack()})
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)
async def run_observatory(self) -> None:
"""The clock of the observatory: ticks four times a second, and tells the sockets once a second,
four times a second while the mount slews."""
last = time.monotonic()
told = last
while True:
await asyncio.sleep(0.25)
now = time.monotonic()
self._observatory.tick(now - last)
last = now
state = self._observatory.state()
if self._sockets and (now - told >= 1.0 or state["mount"]["state"] == "slewing"):
told = now
self._broadcast({"type": "state", "state": state})
# --- routes ---
def _route(self, method: str, path: str, query: Dict[str, List[str]], body: bytes) -> Answer:
observatory = self._observatory
if path == "/state" and method == "GET":
return _json(200, observatory.state())
if path == "/targets" and method == "GET":
return _json(200, TARGETS)
if path == "/frame/latest" and method == "GET":
frame = observatory.latest_frame()
if frame is None:
return _json(404, {"error": "No frame yet."})
try:
after = int(query["after"][0]) if "after" in query else -1
except ValueError:
return _json(400, {"error": "after is a whole number."})
if observatory.sequence == after: # the caller has the newest one
return 204, "application/octet-stream", b"", {}
observatory.frame_served()
return _binary(frame)
if path == "/stack" and method == "GET":
preview = observatory.preview()
return _binary(preview) if preview is not None else _json(404, {"error": "No frame yet."})
if path in ("/slew", "/capture"):
if method != "POST":
return 405, "text/plain; charset=utf-8", b"Use POST.", {"Allow": "POST"}
try:
wanted = json.loads(body.decode("utf-8")) if body else {}
except ValueError:
wanted = None
if not isinstance(wanted, dict):
return _json(400, {"error": "The body is a JSON object."})
error = self._slew(wanted) if path == "/slew" else self._capture(wanted)
return _json(400, {"error": error}) if error else _json(200, observatory.state())
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 _slew(self, wanted: Dict[str, Any]) -> Optional[str]:
"""{ "target": "m42" } or { "ra": hours, "dec": degrees }. Gives the error, or None."""
if "target" in wanted:
target = next((target for target in TARGETS if target["id"] == wanted["target"]), None)
if target is None:
return "There is no such target; GET /targets lists them."
else:
ra, dec = wanted.get("ra"), wanted.get("dec")
numbers = all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in (ra, dec))
if not numbers or not (0 <= ra < 24 and -90 <= dec <= 90):
return "Give target, or ra (0 up to 24 hours) and dec (-90 to 90 degrees)."
target = {"id": "custom", "name": "Field", "title": "Custom position", "kind": "field", "ra": round(float(ra), 4), "dec": round(float(dec), 3)}
self._observatory.slew(target)
return None
def _capture(self, wanted: Dict[str, Any]) -> Optional[str]:
"""{ "running": bool, "exposureSeconds": 1 | 2 | 4 | 8, "gain": 0 to 300 }, each optional."""
running, exposure, gain = wanted.get("running"), wanted.get("exposureSeconds"), wanted.get("gain")
if running is not None and not isinstance(running, bool):
return "running is true or false."
if exposure is not None and (isinstance(exposure, bool) or exposure not in EXPOSURES):
return f"exposureSeconds is one of {', '.join(str(value) for value in EXPOSURES)}."
if gain is not None and (isinstance(gain, bool) or not isinstance(gain, int) or not 0 <= gain <= GAIN_MAX):
return f"gain is a whole number from 0 to {GAIN_MAX}."
self._observatory.capture(running, int(exposure) if exposure is not None else None, gain)
return None
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
url = urlsplit(target)
path, query = url.path or "/", parse_qs(url.query)
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, query, 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._observatory.state()}, separators=(",", ":")))
self._sockets.add(queue)
async def read_frames() -> None:
# Nothing the other side 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_config() -> 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 ""),
"device_name": os.environ.get("CZ_DEVICE_NAME") or str(file.get("deviceName") or "") or "observatory",
}
async def run_connectivitizer(config: Dict[str, str], port: int) -> None:
"""Makes this program a Connectivitizer device with one service, `api`. Needs the SDK."""
try:
from connectivitizer import Agent # 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).")
return
agent = Agent(
None if _is_placeholder(config["api_url"]) else config["api_url"],
device_key=config["device_key"],
name=config["device_name"],
shared_key=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}"),
)
print(f"Connectivitizer: connecting as device '{config['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="Remote observatory: a device UI and API for a telescope, through Connectivitizer.")
parser.add_argument("--port", type=int, default=int(os.environ.get("OBSERVATORY_PORT", "8161")), help="local port on 127.0.0.1 (0: any free one)")
parser.add_argument("--slew-rate", type=float, default=4.0, help="simulator: degrees a second the pretend mount turns (default 4)")
parser.add_argument("--tour-frames", type=int, default=0, help="slew to the next target after this many frames (default 0: stay)")
parser.add_argument("--telescope", default="simulator", help="'simulator' (default), or the address of a real mount (NOT implemented)")
args = parser.parse_args()
simulated = args.telescope == "simulator"
if simulated:
mount: Mount = SimulatedMount(TARGETS[0]["ra"], TARGETS[0]["dec"], args.slew_rate)
camera: Camera = SimulatedCamera()
else:
try:
mount = RealMount(args.telescope)
camera = RealCamera()
except NotImplementedError as error:
print(error)
return 2
server = Server(Observatory(mount, camera, simulated, args.tour_frames), 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"Observatory ({'simulator: every frame is synthetic' if simulated else args.telescope}) on http://127.0.0.1:{port}")
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 = [asyncio.ensure_future(server.run_observatory())]
config = read_config()
missing = [name for name in ("device_key", "shared_key") if _is_placeholder(config[name])]
if missing:
print("Local only: Connectivitizer is NOT started (no keys: fill in secrets.json, or set CZ_DEVICE_KEY and CZ_SHARED_KEY).")
else:
tasks.append(asyncio.ensure_future(run_connectivitizer(config, port)))
try:
async with listener:
# Ends when the observatory'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
# Connectivitizer returned without an error (the SDK is missing): keep serving locally.
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)
return 0
if __name__ == "__main__":
try:
sys.exit(asyncio.run(main()))
except KeyboardInterrupt:
pass