{
  "id": "mattytrentini/framebuf_canvas",
  "name": "framebuf_canvas",
  "prettyName": "framebuf_canvas",
  "description": "Native MicroPython framebuffer publishing to reusable browser canvases over WebSocket",
  "version": "",
  "author": "mattytrentini",
  "license": "MIT",
  "tags": [],
  "status": "VALID",
  "official": false,
  "source": "https://github.com/mattytrentini/framebuf_canvas",
  "updatedAt": "2026-11-21T21:32:32.101Z",
  "page": "https://checkmim.com/packages/mattytrentini+framebuf_canvas",
  "createdAt": "2026-11-21T21:32:27.797Z",
  "submittedBy": "Matt",
  "install": {
    "mpremote": "mpremote mip install github:mattytrentini/framebuf_canvas",
    "mip": "import mip; mip.install(\"github:mattytrentini/framebuf_canvas\")"
  },
  "readme": "# framebuf_canvas\n\nPublish native framebuffer buffers to browser canvases over binary WebSocket.\nUse the real MicroPython `framebuf` drawing implementation; no replacement\nrasterizer, fonts, machine mocks or board models are required.\n\nThe Python publisher also runs on CPython when the pixels come from another\nsource. Drawing with `FrameBuffer` requires MicroPython's native `framebuf`.\n\n## Install\n\n```python\nimport mip\nmip.install(\"github:mattytrentini/framebuf_canvas\")\n```\n\nThe manifest installs the Python modules, both browser bundles, HTML and licenses.\nMicrodot 2.7.0's required modules are pinned to upstream commit\n`7742db9ff9f49635de3387145fafe56bf2377a97`. Nothing installs or overwrites\n`main.py`; assets live inside `framebuf_canvas/static`, independent of the\napplication's working directory. For reproducibility, pass `version=\"<commit>\"`\nto `mip.install`.\n\nFor a CPython source checkout, `pip install .` installs the server dependency and\npackaged assets. The native drawing convenience class is not available there.\n\n## Publish an existing buffer\n\n```python\nimport framebuf\nfrom framebuf_canvas import DisplayServer, buffer_size\n\nwidth, height = 128, 64\npixels = bytearray(buffer_size(width, height, framebuf.MONO_VLSB))\nfb = framebuf.FrameBuffer(pixels, width, height, framebuf.MONO_VLSB)\nserver = DisplayServer()\ndisplay = server.register(pixels, width, height, framebuf.MONO_VLSB, name=\"OLED\")\nfb.text(\"MicroPython\", 0, 0, 1)\ndisplay.publish()\nserver.run()\n```\n\nOpen <http://localhost:8080/>. Register a driver's actual backing buffer and\ncall `publish()` from its `show()`/`flush()` boundary; drawing and hardware\ndrivers remain unchanged. No RGBA conversion runs on the producer.\n\n`publish()` synchronously captures an immutable snapshot and returns its sequence\nnumber. Later changes to the original buffer do not change that snapshot.\nOnly the latest snapshot is retained, even without viewers. Each viewer has an\nindependent writer; stalled viewers time out rather than blocking publishers or\nother viewers. Slow viewers may skip intermediate frames.\n\n## Native drawing convenience\n\n```python\nfrom framebuf_canvas import FrameBuffer, DisplayServer, RGB565, buffer_size\n\npixels = bytearray(buffer_size(320, 240, RGB565))\nfb = FrameBuffer(pixels, 320, 240, RGB565)\nserver = DisplayServer()\ndisplay = server.register(fb)\nfb.fill(0)\nfb.text(\"Hello!\", 20, 25, 0xF800)\nfb.flush()\nserver.run()\n```\n\n`FrameBuffer(buffer, width, height, format, stride=None)` is a real native\n`framebuf.FrameBuffer` subclass. Its drawing methods, fonts and pixel format\nconstants are native, not reimplemented. `flush()` publishes to its registered\nserver; flushing before registration or after removal raises an error. There is\nno default/global server. `register(fb)` returns the same kind of display handle\nas raw-buffer registration.\n\n## API and layouts\n\n`DisplayServer(host=\"127.0.0.1\", port=8080, static_path=None, *,\napp=None, url_prefix=\"\", send_timeout=2)` exposes its Microdot application as\n`server.app`. `run()` blocks; `await server.start()` runs until stopped or\ncancelled. Use `asyncio.gather` with application tasks.\n\n`server.register(buffer, width, height, format, stride=None, byteorder=None,\nname=None)` returns a display handle. The initial snapshot is immediately\navailable to late/reconnecting viewers. `server.unregister(display)` (or the\nregistered convenience framebuffer) removes it from all viewers and invalidates\nfurther publishing. Descriptors cannot be changed after registration.\n\n`buffer_size(width, height, format, stride=None)` returns the minimum compatible\nnative allocation. Stride is in **pixels**, not bytes. Native horizontal packing\nrounds it up to 8 pixels for horizontal mono, 4 for GS2 and 2 for GS4. Row/page\npadding is preserved; surplus data after the minimum allocation is never sent.\nTyped buffers such as `array(\"H\")` are supported.\n\n| Native constant | Value |\n| --- | ---: |\n| `MONO_VLSB` | 0 |\n| `RGB565` | 1 |\n| `GS4_HMSB` | 2 |\n| `MONO_HLSB` | 3 |\n| `MONO_HMSB` | 4 |\n| `GS2_HMSB` | 5 |\n| `GS8` | 6 |\n\nRGB565 defaults to the producer's native byte order; specify `byteorder=\"big\"`\nor `\"little\"` for an externally encoded buffer. Other formats are byte-based.\nDimensions and normalized stride must fit unsigned 16-bit fields. The viewer\nrejects malformed packets and canvases larger than 16,777,216 pixels.\n\n**Migration from 0.1:** the old numeric format IDs, 8-byte RGBA wire protocol,\npure-Python drawing fallback, `to_rgba()` overrides and singleton server have\nbeen removed. Use native constants and update every client to FBC1.\n\n## Embed in an application\n\nPass an existing Microdot app and `url_prefix=\"/display\"`. The viewer is served\nat `/display/`, its WebSocket at `/display/ws`; existing root/API routes remain\nowned by the application. The prefix without its trailing slash redirects.\n`static_path` may replace the standalone viewer's asset directory.\n\nThe side-effect-free ES module at `/display/static/framebuf-canvas.js` exports\n`CanvasRenderer`, `WebSocketClient` and protocol helpers:\n\n```html\n<div id=\"screen\"></div>\n<script type=\"module\">\n  import { CanvasRenderer, WebSocketClient } from \"/display/static/framebuf-canvas.js\";\n  const renderer = new CanvasRenderer(\"screen\");\n  const url = new URL(\"/display/ws\", location.href);\n  url.protocol = location.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n  const client = new WebSocketClient(url.href);\n  client.onConnect(() => renderer.reset());\n  client.onMessage(message => renderer.handleMessage(message));\n  client.onError(error => console.error(error));\n  client.connect();\n</script>\n```\n\nCall `client.disconnect()` and `renderer.destroy()` when disposing the view.\nThe ready-made `app.js` bootstraps the standalone HTML; importing the ES module\ndoes not create a socket or manipulate the page.\n\nThe server has no authentication or IO-control API. Keep the default loopback\nbinding, or provide application authentication/TLS before exposing it beyond a\ntrusted network. `wss` is selected automatically when the page uses HTTPS.\n\n## Examples and published Unix image\n\n- `examples/basic_drawing.py`: native convenience framebuffer.\n- `examples/animation.py`: application task alongside the server.\n- `examples/raw_buffer.py`: native buffer publishing with padded stride.\n\nNo custom MicroPython build is needed. From this checkout on Linux:\n\n```sh\ndocker run --rm -it --entrypoint /bin/sh -p 127.0.0.1:8080:8080 \\\n  -v \"$PWD:/work:ro\" -w /work micropython/unix:v1.29.0 \\\n  -c 'micropython -c \"import mip; mip.install(\\\"github:mattytrentini/framebuf_canvas\\\", target=\\\"/tmp/lib\\\")\" && MICROPYPATH=/tmp/lib:.frozen micropython -X heapsize=8M examples/basic_drawing.py 0.0.0.0'\n```\n\nThe example's optional first argument selects the bind address. Inside Docker,\nbind to `0.0.0.0`; the published port above is still restricted to host loopback.\nThe image's existing native `framebuf`, asyncio and sockets are sufficient.\nFor an unpublished checkout, serve its unchanged manifest over HTTP and use that\nURL with mip; relative file URLs work with both HTTP and GitHub installs.\n\n## Build the browser bundles\n\nGenerated assets are checked in so mip users need no Node tooling:\n\n```sh\ndocker run --rm --user \"$(id -u):$(id -g)\" -e HOME=/tmp \\\n  -v \"$PWD:/work\" -w /work/client node:22-alpine \\\n  sh -c 'npm ci && npm run build'\n```\n\n`npm run watch` rebuilds while editing. Both bundles target ES2020; there are no\nruntime JavaScript dependencies.\n\n## Verification\n\n`tests/native_roundtrip.py` runs native C drawing reference scenes under\nMicroPython with an 8 MiB heap. Point `tests/test_protocol.mjs` (Node 22+) at\nthat running fixture to check all seven formats, padding, minimum allocations,\nRGB565 endianness and typed buffers, snapshots, large frames, bounded bursts,\nstalled viewers and malformed packets.\n\nThe protocol check defaults to `http://127.0.0.1:8766`; set\n`FRAMEBUF_PROOF_URL` when mapping a different host port. Put the mip-installed\npackage and its dependencies on `MICROPYPATH`. The test fixture binds all\ncontainer interfaces, so publish its port only on host loopback.\n\nBrowser acceptance additionally checks actual Canvas pixels, display removal,\nsequence wrap, mobile layout and reconnection into a changed display session.\n\n## FBC1 protocol\n\nEach binary WebSocket message starts with a 20-byte network-order header,\n`>4sBBBBHHHHI`:\n\n| Offset | Field |\n| --- | --- |\n| 0–3 | ASCII `FBC1` |\n| 4 | Kind: INIT=1, FRAME=2, REMOVE=3 |\n| 5 | Native pixel format ID |\n| 6 | Flags: bit 0 means big-endian RGB565; other bits reserved |\n| 7 | Reserved zero |\n| 8–9 | Display ID |\n| 10–11 | Width |\n| 12–13 | Height |\n| 14–15 | Normalized stride in pixels |\n| 16–19 | Sequence, unsigned 32-bit; wraps naturally |\n\nINIT appends an optional UTF-8 name (maximum 255 bytes). FRAME appends exactly\nthe minimum native buffer bytes; REMOVE has no payload. Reconnection starts a\nfresh display session. There is no base64, PNG, producer-side RGBA conversion or\ndelta-frame protocol.\n\n## License\n\n[MIT](LICENSE). Installed Microdot files retain their upstream MIT license.\nThe [Microdot notice](licenses/Microdot.txt) also covers the vendored copies\npresent in this repository's early history; current installs fetch pinned\nupstream modules instead.\n"
}