Impressora 3D
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
#!/usr/bin/env python3
"""A 3D-printer companion for a Raspberry Pi: one program that serves a small HTTP and WebSocket API on
127.0.0.1 and exposes it as the service ``api`` through Connectivitizer, together with the printer's own
screen (../ui/printer.html, a device UI).
python printer_companion.py # simulator: a pretend print that advances in real time
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 printer itself is behind the class ``Printer``. ``SimulatedPrinter`` is the one that works.
``SerialPrinter`` marks where a real printer would be connected; it is NOT implemented and NOT tested.
Only the standard library is used here. 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 random
import struct
import sys
import time
from collections import deque
from pathlib import Path
from typing import Any, Callable, Deque, Dict, List, Optional, Set, Tuple
from urllib.parse import parse_qs, urlsplit
HERE = Path(__file__).resolve().parent
UI_FOLDER = HERE.parent / "ui"
PAGE_FILE = UI_FOLDER / "printer.html"
MANIFEST_FILE = UI_FOLDER / "manifest.json"
MAX_PAGE_BYTES = 2 * 1024 * 1024 # what the app accepts as a device UI
AMBIENT = 23.0
HISTORY_STEP = 5.0 # seconds between two entries of the temperature history
HISTORY_LENGTH = 120 # ten minutes
# ---------------------------------------------------------------------------------------------------------
# The printer
# ---------------------------------------------------------------------------------------------------------
class Printer:
"""What the web server needs from a printer. All of it is called from the event loop."""
on_state: Optional[Callable[[], None]] = None
"""Called by the printer whenever the state of the job changed (the server tells the open sockets)."""
def tick(self, seconds: float) -> None:
"""Called about four times a second with the time that has passed."""
def job(self) -> Dict[str, Any]:
"""{ state, file, progress, layer, layers, elapsedSeconds, remainingSeconds, filamentUsedMm, speedPercent }"""
raise NotImplementedError
def temps(self) -> Dict[str, Any]:
"""{ t, nozzle: { actual, target }, bed: { actual, target } }, without the history."""
raise NotImplementedError
def history(self) -> List[Dict[str, float]]:
"""[ { t, nozzle, bed } ... ] of the last ten minutes, oldest first."""
raise NotImplementedError
def toolpath(self, layer: int) -> Optional[Dict[str, Any]]:
"""{ layer, layers, z, polylines } of one layer (1 is the first), or None when there is no such layer."""
raise NotImplementedError
def pause(self) -> bool:
raise NotImplementedError
def resume(self) -> bool:
raise NotImplementedError
def cancel(self) -> bool:
raise NotImplementedError
# --- The simulator: a pretend print job that advances in real time. --------------------------------------
PARTS = [
{"file": "twisted-vase.gcode", "shape": "vase", "layers": 96, "height": 1.25, "filamentMm": 14200, "nozzle": 215, "bed": 60},
{"file": "spiral-tower.gcode", "shape": "tower", "layers": 110, "height": 1.4, "filamentMm": 17800, "nozzle": 215, "bed": 60},
{"file": "drive-gear.gcode", "shape": "gear", "layers": 44, "height": 0.42, "filamentMm": 9600, "nozzle": 240, "bed": 80},
]
def _clamp(value: float, low: float, high: float) -> float:
return max(low, min(high, value))
def _loop(count: int, radius_at: Callable[[float], float], cx: float = 0.5, cy: float = 0.5) -> List[float]:
"""A closed line around (cx, cy) as [x0, y0, x1, y1, ...]: `count` points, the radius for each angle from `radius_at`."""
points: List[float] = []
for i in range(count + 1):
angle = ((i % count) / count) * 2 * math.pi
radius = radius_at(angle)
points.append(round(cx + radius * math.cos(angle), 3))
points.append(round(cy + radius * math.sin(angle), 3))
return points
def outline(part: Dict[str, Any], layer: int) -> List[List[float]]:
"""The outline of one layer of a part, from a formula (the same ones as in ../ui/demo-data.js)."""
u = (layer - 1) / (part["layers"] - 1) if part["layers"] > 1 else 0.0 # 0 at the bed, 1 at the top
if part["shape"] == "vase":
belly = 0.3 + 0.11 * math.sin(u * 5.2 + 0.6) - 0.05 * u
return [_loop(60, lambda a: belly * (1 + 0.09 * math.cos(5 * a + u * 3.2)))]
if part["shape"] == "tower":
side = 0.3 - 0.11 * u + 0.015 * math.sin(u * 9.4)
def rounded_square(a: float) -> float:
phi = a - u * 2.6
return side / (abs(math.cos(phi)) ** 4 + abs(math.sin(phi)) ** 4) ** 0.25
return [_loop(64, rounded_square)]
# The gear: a toothed disc with a bore and five holes, and a plain hub on top of it.
bore = _loop(20, lambda a: 0.085)
if u >= 0.62:
return [_loop(28, lambda a: 0.16), bore]
lines = [_loop(140, lambda a: 0.37 + 0.045 * _clamp(2.4 * math.cos(14 * a), -1, 1)), bore]
for hole in range(5):
at = (hole / 5) * 2 * math.pi + 0.3
lines.append(_loop(14, lambda a: 0.055, 0.5 + 0.215 * math.cos(at), 0.5 + 0.215 * math.sin(at)))
return lines
class _Heater:
def __init__(self, heat_tau: float, cool_tau: float, swing: float) -> None:
self.actual = AMBIENT
self.target = 0.0
self._heat_tau = heat_tau
self._cool_tau = cool_tau
self._swing = swing
def approach(self, seconds: float) -> None:
goal = self.target if self.target > 0 else AMBIENT
tau = self._heat_tau if goal > self.actual else self._cool_tau
self.actual += (goal - self.actual) * (1 - math.exp(-seconds / tau))
def reading(self, clock: float) -> Dict[str, float]:
actual = self.actual
if self.target > 0: # a heater that regulates never stands still
actual += self._swing * (math.sin(clock / 3.1) + 0.45 * math.sin(clock / 0.9 + 1) + (random.random() - 0.5) * 0.5)
return {"actual": round(actual, 1), "target": self.target}
class SimulatedPrinter(Printer):
"""Prints the parts above one after the other. Nothing is connected: every number is invented.
A print takes `print_seconds`; `restart_seconds` after it is done or cancelled the next one starts, so
that the example keeps showing something. The heaters start cold, and the pretend print does not wait
for them (a real printer would)."""
def __init__(self, print_seconds: float = 900.0, restart_seconds: float = 20.0) -> None:
self._print_seconds = max(10.0, print_seconds)
self._restart_seconds = restart_seconds
self._index = 0
self._state = "printing"
self._printed = 0.0 # seconds of printing done
self._clock = 0.0
self._ended_at = 0.0
self._sampled_at = -HISTORY_STEP
self._nozzle = _Heater(heat_tau=25.0, cool_tau=110.0, swing=1.1)
self._bed = _Heater(heat_tau=60.0, cool_tau=240.0, swing=0.3)
self._history: Deque[Dict[str, float]] = deque(maxlen=HISTORY_LENGTH)
self._set_state("printing")
def _part(self) -> Dict[str, Any]:
return PARTS[self._index]
def _set_state(self, state: str) -> None:
self._state = state
heating = state in ("printing", "paused")
self._nozzle.target = float(self._part["nozzle"]) if heating else 0.0
self._bed.target = float(self._part["bed"]) if heating else 0.0
if state in ("done", "cancelled"):
self._ended_at = self._clock
if self.on_state is not None:
self.on_state()
def tick(self, seconds: float) -> None:
seconds = _clamp(seconds, 0.0, 2.0)
self._clock += seconds
if self._state == "printing":
self._printed += seconds
if self._printed >= self._print_seconds:
self._printed = self._print_seconds
self._set_state("done")
elif self._state in ("done", "cancelled") and self._clock - self._ended_at >= self._restart_seconds:
self._index = (self._index + 1) % len(PARTS)
self._printed = 0.0
self._set_state("printing")
self._nozzle.approach(seconds)
self._bed.approach(seconds)
if self._clock - self._sampled_at >= HISTORY_STEP:
self._sampled_at = self._clock
now = self.temps()
self._history.append({"t": now["t"], "nozzle": now["nozzle"]["actual"], "bed": now["bed"]["actual"]})
def job(self) -> Dict[str, Any]:
part = self._part
progress = 1.0 if self._state == "done" else _clamp(self._printed / self._print_seconds, 0.0, 1.0)
layer = min(part["layers"], int(progress * part["layers"]) + 1)
return {
"state": self._state,
"file": part["file"],
"progress": round(progress, 4),
"layer": layer,
"layers": part["layers"],
"elapsedSeconds": round(self._printed),
"remainingSeconds": max(0, round(self._print_seconds - self._printed)),
"filamentUsedMm": round(progress * part["filamentMm"], 1),
"speedPercent": 50 if layer <= 2 else 100, # the first layers go down slowly
}
def temps(self) -> Dict[str, Any]:
return {"t": round(time.time()), "nozzle": self._nozzle.reading(self._clock), "bed": self._bed.reading(self._clock)}
def history(self) -> List[Dict[str, float]]:
return list(self._history)
def toolpath(self, layer: int) -> Optional[Dict[str, Any]]:
part = self._part
if layer < 1 or layer > part["layers"]:
return None
return {"layer": layer, "layers": part["layers"], "z": round(layer / part["layers"] * part["height"], 3), "polylines": outline(part, layer)}
def _change(self, allowed: Tuple[str, ...], to: str) -> bool:
if self._state not in allowed:
return False
self._set_state(to)
return True
def pause(self) -> bool:
return self._change(("printing",), "paused")
def resume(self) -> bool:
return self._change(("paused",), "printing")
def cancel(self) -> bool:
return self._change(("printing", "paused"), "cancelled")
# --- A real printer: NOT IMPLEMENTED, NOT TESTED. ---------------------------------------------------------
class SerialPrinter(Printer):
"""Where a real printer would be connected. Nothing in this class works: it has never been run against
a printer, and it is here only to show what would have to be filled in.
Two ways to do it:
* Serial G-code with pyserial (``pip install pyserial``, port such as /dev/ttyUSB0 or /dev/ttyACM0).
This program would then be the one that sends the file to the printer, line by line, waiting for
``ok`` after each. Reading alone is not enough: a printer that prints from its own SD card answers
only a few questions on the serial port. Roughly:
- temps(): ``M105`` answers like ``ok T:214.8 /215.0 B:60.1 /60.0``; parse both pairs, and keep
one sample every 5 s for history().
- job(): progress is the share of the file's lines (or bytes) sent; ``layer`` from the
``;LAYER:n`` comments most slicers write, ``layers`` from ``;LAYER_COUNT:n``;
remainingSeconds from the slicer's ``;TIME:`` comment and the share done;
speedPercent from ``M220``.
- toolpath(): parse the file once when the job starts: for every layer the ``G1 X.. Y..`` moves
that extrude (E grows), scaled into 0..1 by the bed size, thinned out to a few
hundred points, kept in memory.
- pause()/resume(): stop/continue sending lines, and park/unpark the head (for example
``G91``, ``G1 Z5``, ``G90`` and back), or ``M25``/``M24`` when printing from SD.
- cancel(): stop sending, then heaters off (``M104 S0``, ``M140 S0``), fan off (``M107``).
Do the serial reading and writing in a thread (pyserial blocks) and hand the results to the event
loop; nothing here may block tick().
* A printer host that already runs next to the printer and has a local HTTP API: ask it for the job
and the temperatures, and send it pause, resume and cancel. Then job(), temps() and the three
commands are one request each, and toolpath() comes from the G-code file it gives out.
"""
def __init__(self, port: str, baud: int = 115200) -> None:
raise NotImplementedError(
"A real printer is not implemented in this example (see the class SerialPrinter in printer_companion.py). "
"Run it without --printer for the simulator."
)
# ---------------------------------------------------------------------------------------------------------
# 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",
409: "Conflict", 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(), {}
class Server:
def __init__(self, printer: Printer, log: Callable[[str], None]) -> None:
self._printer = printer
self._log = log
self._sockets: Set["asyncio.Queue[Optional[str]]"] = set()
printer.on_state = self._state_changed
# --- events ---
def _state_changed(self) -> None:
job = self._printer.job()
self._broadcast({"type": "state", "state": job["state"], "job": job})
def _progress(self) -> Dict[str, Any]:
now = self._printer.temps()
return {"type": "progress", "t": now["t"], "job": self._printer.job(), "temps": {"nozzle": now["nozzle"], "bed": now["bed"]}}
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_printer(self) -> None:
"""The clock of the printer: ticks four times a second, and tells the sockets once a second."""
last = time.monotonic()
told = last
while True:
await asyncio.sleep(0.25)
now = time.monotonic()
self._printer.tick(now - last)
last = now
if now - told >= 1.0:
told = now
if self._sockets:
self._broadcast(self._progress())
# --- routes ---
def _route(self, method: str, path: str, query: Dict[str, List[str]]) -> Answer:
printer = self._printer
if path == "/job" and method == "GET":
return _json(200, printer.job())
if path == "/temps" and method == "GET":
now = printer.temps()
return _json(200, {"t": now["t"], "nozzle": now["nozzle"], "bed": now["bed"], "history": printer.history()})
if path == "/toolpath" and method == "GET":
job = printer.job()
try:
layer = int(query["layer"][0]) if "layer" in query else int(job["layer"])
except ValueError:
return _json(400, {"error": "layer is a whole number."})
answer = printer.toolpath(layer)
if answer is None:
return _json(404, {"error": f"This job has the layers 1 to {job['layers']}."})
return _json(200, answer)
if path in ("/job/pause", "/job/resume", "/job/cancel"):
if method != "POST":
return 405, "text/plain; charset=utf-8", b"Use POST.", {"Allow": "POST"}
done = {"/job/pause": printer.pause, "/job/resume": printer.resume, "/job/cancel": printer.cancel}[path]()
job = printer.job()
if not done:
return _json(409, {"error": f"The job is {job['state']}.", "job": job})
return _json(200, job)
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
if length:
try:
await asyncio.wait_for(reader.readexactly(length), IDLE_SECONDS) # no route reads a body
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)
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()
job = self._printer.job()
queue.put_nowait(json.dumps({"type": "state", "state": job["state"], "job": job}, 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_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.")
config = {
"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 "printer-pi",
}
return config
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="3D-printer companion: a device UI and API for a printer, through Connectivitizer.")
parser.add_argument("--port", type=int, default=int(os.environ.get("PRINTER_PORT", "8137")), help="local port on 127.0.0.1 (0: any free one)")
parser.add_argument("--print-seconds", type=float, default=900.0, help="simulator: how long one pretend print takes (default 900)")
parser.add_argument("--restart-seconds", type=float, default=20.0, help="simulator: pause before the next pretend print (default 20)")
parser.add_argument("--printer", default="simulator", help="'simulator' (default), or a serial port such as /dev/ttyUSB0 (NOT implemented)")
args = parser.parse_args()
if args.printer == "simulator":
printer: Printer = SimulatedPrinter(args.print_seconds, args.restart_seconds)
else:
try:
printer = SerialPrinter(args.printer)
except NotImplementedError as error:
print(error)
return 2
server = Server(printer, 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"Printer companion ({'simulator' if args.printer == 'simulator' else args.printer}) on http://127.0.0.1:{port}")
print(f" the screen: http://127.0.0.1:{port}/.cz/ui.html")
print(f" the job: http://127.0.0.1:{port}/job")
if not PAGE_FILE.exists() or not MANIFEST_FILE.exists():
print(f" note: {PAGE_FILE} or {MANIFEST_FILE} is missing; the device has no screen without them.")
tasks = [asyncio.ensure_future(server.run_printer())]
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 printer'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