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