Sternwarte
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
"""The stacker for the PC at home: opens a Connectivitizer session to the observatory (../pi/observatory.py,
on another network), pulls every new frame of its camera and averages them. With every frame the noise of
the average falls; the current stack is written to a file and one line is printed.
python stacker.py # through Connectivitizer (keys: see README.md)
python stacker.py --local http://127.0.0.1:8161 # straight to an observatory on the same machine
Needs numpy, and the Connectivitizer SDK (``pip install huelake-connectivitizer``) unless --local is used.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import math
import os
import struct
import sys
import urllib.error
import urllib.request
import zlib
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, Optional, Tuple
import numpy as np
HERE = Path(__file__).resolve().parent
Fetch = Callable[[str], Awaitable[Tuple[int, bytes]]] # a path on the observatory's service: (status, body)
def decode_image(data: bytes) -> Tuple[np.ndarray, int, int]:
"""A picture as the observatory sends it: (pixels as (height, width, channels), serial of the stack,
number of the frame). 16 bytes of head, little endian, then the samples."""
magic, width, height, channels, bits, serial, number = struct.unpack("<4sHHBBHI", data[:16])
if magic != b"CZFR" or bits not in (8, 16) or len(data) != 16 + width * height * channels * bits // 8:
raise ValueError("This is not a frame of the observatory.")
pixels = np.frombuffer(data, dtype="<u2" if bits == 16 else np.uint8, offset=16)
return pixels.reshape(height, width, channels), serial, number
def stack_statistics(mean: np.ndarray) -> Tuple[float, float]:
"""(noise, signal to noise) of a stack, estimated as the observatory does it: the noise from the
differences between neighbouring pixels (with the median, so that stars hardly count), the signal as
how far the middle of the frame lies above the background."""
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)
def write_png(path: Path, mean: np.ndarray) -> None:
"""The stack as a picture to look at: the sky taken off each colour, the brightest stars as white, an
asinh stretch to 8 bits. The numbers themselves are in the .npy file next to it."""
level = mean - np.median(mean, axis=(0, 1))
level = level / max(1e-9, float(np.percentile(level, 99.9)))
shown = np.arcsinh((level + 0.015) / 0.05) / math.asinh(1.015 / 0.05)
pixels = np.rint(np.clip(shown[..., :3], 0, 1) * 255).astype(np.uint8)
height, width, _ = pixels.shape
rows = b"".join(b"\x00" + pixels[row].tobytes() for row in range(height))
def chunk(kind: bytes, data: bytes) -> bytes:
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
head = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) # 8 bits, RGB
path.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", head) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b""))
async def stack_frames(fetch: Fetch, out: Path, limit: int) -> None:
"""Asks for the newest frame twice a second and adds every new one to the stack. The observatory starts
a new stack (another serial) when it slews or its settings change; so does this."""
out.mkdir(parents=True, exist_ok=True)
serial, have, frames, total = -1, -1, 0, None
done = 0
while limit <= 0 or done < limit:
status, body = await fetch(f"/frame/latest?after={have}")
if status == 200:
frame, frame_serial, have = decode_image(body)
if frame_serial != serial or total is None or total.shape != frame.shape:
serial, frames, total = frame_serial, 0, np.zeros(frame.shape)
total += frame
frames += 1
done += 1
mean = total / frames
noise, snr = stack_statistics(mean)
np.save(out / f"stack-{serial}.npy", mean.astype(np.float32))
write_png(out / f"stack-{serial}.png", mean)
print(f"stack {serial}: frame {have} added, {frames} stacked, noise {noise:.1f} counts, signal to noise {snr:.1f}", flush=True)
elif status not in (204, 404): # 204: nothing new yet; 404: the stack has no frame yet (slewing, say)
print(f"The observatory answered {status} to /frame/latest.", flush=True)
await asyncio.sleep(0.5)
def local_fetch(base: str) -> Fetch:
"""Without Connectivitizer: plain HTTP to an observatory on the same machine."""
def get(path: str) -> Tuple[int, bytes]:
try:
with urllib.request.urlopen(base.rstrip("/") + path, timeout=10) as answer:
return answer.status, answer.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
async def fetch(path: str) -> Tuple[int, bytes]:
return await asyncio.to_thread(get, path)
return fetch
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():
file = json.loads(path.read_text(encoding="utf-8"))
return {
"api_url": os.environ.get("CZ_API_URL") or str(file.get("apiUrl") or ""),
"api_key": os.environ.get("CZ_API_KEY") or str(file.get("apiKey") 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 main() -> int:
parser = argparse.ArgumentParser(description="Pulls the frames of the remote observatory and stacks them.")
parser.add_argument("--local", metavar="URL", help="plain HTTP to an observatory on this machine, without Connectivitizer")
parser.add_argument("--out", type=Path, default=HERE / "stacks", help="where the stacks are written (default: stacks, next to this file)")
parser.add_argument("--frames", type=int, default=0, help="stop after this many frames (default 0: run until stopped)")
args = parser.parse_args()
if args.local:
print(f"Local: asking {args.local} without Connectivitizer.")
await stack_frames(local_fetch(args.local), args.out, args.frames)
return 0
config = read_config()
if any(not config[name] or "..." in config[name] for name in ("api_key", "shared_key")):
print("No keys: fill in secrets.json, or set CZ_API_KEY and CZ_SHARED_KEY (or use --local).")
return 2
from connectivitizer import Client, ConnectivitizerError # pip install huelake-connectivitizer
try:
api_url = config["api_url"] if config["api_url"] and "..." not in config["api_url"] else None
async with Client(api_url, api_key=config["api_key"], shared_key=config["shared_key"]) as client:
session = await client.connect(config["device_name"], ["api"])
# What this endpoint established itself: 'direct' is peer to peer, 'e2e-relay' goes through the relay.
print(f"Session to '{config['device_name']}': {session.info.mode}, end-to-end encrypted: {session.info.end_to_end_encrypted}")
async def fetch(path: str) -> Tuple[int, bytes]:
response = await session.fetch("api", path)
return response.status, await response.bytes()
await stack_frames(fetch, args.out, args.frames)
except ConnectivitizerError as error: # no session, or the session ended
print(f"Stopped: {error} ({error.code})")
return 1
return 0
if __name__ == "__main__":
try:
sys.exit(asyncio.run(main()))
except KeyboardInterrupt:
pass