Something went wrong. Try again.
A Zig library for driving Elgato Stream Deck devices over USB HID.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A Stream Deck reached over the network rather than over USB: the//! open socket, which of the two framings it turned out to speak, and//! the buffer partly-arrived frames accumulate in.//!//! This is the half of the TCP transport that touches a socket.//! Everything that turns bytes into a structure and back is in//! `framing.zig`, which needs no socket and is tested and fuzzed//! without one.//!//! ## The caller has to keep reading//!//! A networked device pings every few seconds and disconnects a host//! that has not answered within about five. Answering happens here, but//! only while something is reading: inside `read`, and inside the//! request half of any host command. Nothing runs on its own -- there//! is no background task and no thread -- so a caller that neither//! reads events nor asks the device anything for five seconds will be//! dropped.//!//! That is a real constraint and not an oversight. The alternative is a//! task owning the socket, with a queue and a lock between it and the//! caller, which is a great deal of machinery for a library that//! otherwise has none. An application that is doing anything with a//! Stream Deck is sitting in `Events.read` anyway, which services the//! socket; one that spends five seconds drawing without reading has to//! say so.
const std = @import("std");
const Tcp = @This();
const framing = @import("framing.zig");const Keys = @import("Keys.zig");const StreamDeck = @import("StreamDeck.zig");
/// The port a Stream Deck listens on.pub const default_port: u16 = 5343;
/// How long without a word from the device before it is presumed gone.////// The device's own ping interval is not documented and the sources/// that guess put it between two and a half and four seconds, so five/// is what the reference implementation waits and five is what this/// waits.pub const timeout_ns: u64 = 5 * std.time.ns_per_s;
/// How much of a partly-arrived frame can be held.////// A frame is a header and at most `framing.max_payload`, and there can/// be the tail of one and the head of the next, so this is comfortably/// more than one of the largest frames either side sends.const buffer_size = 2 * (framing.header_size + framing.max_payload);
/// How big an acknowledgement and a host request are made.////// Implementations send 32 bytes and 1024 bytes for these and both are/// reported to work, so the device does not care. 32 is the smaller.const command_size = 32;
/// How many keepalives may go by while a reply is awaited before the/// question is taken to have gone unanswered. One could arrive in the/// instant between asking and being answered, so it takes two: at the/// device's rate of one every few seconds, that is several seconds of/// silence about a question normally answered in a millisecond.const reply_keepalives = 2;
/// What can go wrong that is this transport's own, rather than the/// socket's./// The product id a Stream Deck Network Dock reports over the network.////// It is not a USB id: the dock is not a USB device and was never/// assigned one, so this is Elgato's own stand-in. Recognising it is/// what tells `connect` to go on to the deck behind the dock.pub const network_dock_product: u16 = 0xffff;
pub const Error = error{ /// The device sent something that is neither framing. NotAStreamDeck, /// A Stream Deck Network Dock answered, and has no deck plugged /// into it. NothingBehindDock, /// The connection was closed, by the device or by the network. Disconnected, /// The device did not answer a question it was asked. NoResponse, /// The operation has no known encoding on this transport. `reset` /// is the one: no implementation has ever been seen to perform it /// over the network, so this library will not invent an encoding /// for it. Unsupported,};
alloc: std.mem.Allocator,stream: std.Io.net.Stream,/// Which framing the device speaks, once it has said enough for that/// to be known. Null until then.framing_mode: ?framing.Framing = null,/// Bytes received from the socket and not yet consumed by a frame.buffer: [buffer_size]u8 = undefined,len: usize = 0,/// The payload most recently taken off the wire, copied out of/// `buffer` so that consuming the frame around it cannot disturb it.payload: [framing.max_payload]u8 = undefined,/// Whether this connection answers host commands -- a Studio, or a/// dock itself -- as opposed to being a device behind a dock, which/// answers ordinary USB feature reports instead.primary: bool = false,/// What the device said it is, once `identity` has been asked.vendor: u16 = 0,product: u16 = 0,/// Counts up so that a reply can be matched to its request. The device/// echoes whatever it is sent, so only distinctness matters.next_message_id: u32 = 1,
/// Open a connection to a Stream Deck and bring it up: classify the/// framing it speaks, answer its first keepalive, and ask it what it/// is.////// A **Network Dock** at the address is followed to the deck plugged/// into it. The dock is only a way in: asked, it says what is plugged/// in and which of its ports that deck answers on, and the deck is then/// a connection of its own at the dock's address. The connection to the/// dock is closed before the deck's is opened -- a deck's connection/// was seen to outlive a dock's closed cleanly, and to be dropped along/// with one left open and unanswered -- so what comes back is the/// deck's alone. `error.NothingBehindDock` if nothing is plugged in.////// The caller owns the result and must release it with `close`.pub fn connect(io: std.Io, alloc: std.mem.Allocator, address: std.Io.net.IpAddress) !*Tcp { const self = try open(io, alloc, address); errdefer self.close(io);
try self.identify(io); if (self.product != network_dock_product) return self;
const child = try self.childInfo(io); self.close(io); if (!child.present) return error.NothingBehindDock;
var deck_address = address; deck_address.setPort(child.port); const deck = try open(io, alloc, deck_address); // A deck behind a dock is not asked who it is: it takes ordinary // USB feature reports and knows nothing of host commands, and the // dock has just said. deck.vendor = child.vendor; deck.product = child.product; deck.primary = false; return deck;}
/// Open a connection and bring it as far as knowing its framing, with/// the first keepalive answered.fn open(io: std.Io, alloc: std.mem.Allocator, address: std.Io.net.IpAddress) !*Tcp { // `ConnectOptions` has a `timeout`, and it would be the right thing // here -- the usual way to get an address wrong is to give one with // nothing at it, and waiting for the operating system to give up on // a silently dropped packet takes minutes. It cannot be used on Zig // 0.16.0: `Io.Threaded.netConnectIpPosix` answers any timeout but // `.none` with `@panic("TODO implement netConnectIpPosix with // timeout")`, so asking for one is a crash rather than a wait. // // So this waits as long as the operating system does, and a caller // that needs to bound it has to bound the whole call. Worth // revisiting whenever the toolchain moves. const stream = try address.connect(io, .{ .mode = .stream }); errdefer stream.close(io);
const self = try alloc.create(Tcp); errdefer alloc.destroy(self);
self.* = .{ .alloc = alloc, .stream = stream }; self.setNoDelay();
// The device speaks first, and what it opens with is what says // which framing it uses. Until one whole frame has been taken off // the wire nothing can be sent, because there is no way to know how // to wrap it. const first = try self.receive(io);
// A device opens with a keepalive probe. Answering it is what makes // the connection live, so it is done here rather than left for // whenever the caller first reads. if (framing.isKeepaliveProbe(first)) try self.acknowledge(io, first);
return self;}
/// Ask the device its vendor and product id, and learn from the answer/// whether this is a connection that speaks host commands at all.fn identify(self: *Tcp, io: std.Io) !void { var buf: [command_size]u8 = undefined; // This is the one question every device reached directly answers, // and asking it is how a connection turns into a model. // // A device reached *through* a dock is not asked: `connect` learns // what it is from the dock instead. const reply = self.hostCommand(io, .identity, &buf) catch |err| switch (err) { error.NoResponse => return error.Unsupported, else => |e| return e, };
const id = framing.parseIdentity(reply) orelse return error.NotAStreamDeck;
self.vendor = id.vendor; self.product = id.product; self.primary = true;}
/// Turn off Nagle's algorithm.////// Image data goes out as a run of one kilobyte packets, and coalescing/// them costs a round trip apiece. `std.Io.net` exposes no socket/// options, so this reaches for the handle directly and shrugs if the/// platform will not have it -- it is throughput and not correctness.fn setNoDelay(self: *Tcp) void { std.posix.setsockopt( self.stream.socket.handle, std.posix.IPPROTO.TCP, std.posix.TCP.NODELAY, &std.mem.toBytes(@as(c_int, 1)), ) catch {};}
/// Close the connection and free this `Tcp`. Nothing may be used/// afterwards.pub fn close(self: *Tcp, io: std.Io) void { self.stream.close(io); self.alloc.destroy(self);}
/// Read more bytes from the socket into the buffer.////// The reader is given the free tail of `buffer` as its own buffer, so/// what it reads lands where it is wanted with no second copy.fn fill(self: *Tcp, io: std.Io) !void { if (self.len >= self.buffer.len) { // Nothing legitimate is this big -- `framing.max_payload` // bounds a frame and the buffer holds two of them -- so a full // buffer means the stream holds something that is not a frame. return error.NotAStreamDeck; }
var reader = self.stream.reader(io, self.buffer[self.len..]); reader.interface.fill(1) catch return error.Disconnected; self.len += reader.interface.bufferedLen();}
/// Drop the first `n` bytes of the buffer.fn drop(self: *Tcp, n: usize) void { std.debug.assert(n <= self.len); std.mem.copyForwards(u8, self.buffer[0 .. self.len - n], self.buffer[n..self.len]); self.len -= n;}
/// Take one payload off the wire, whichever framing this device/// speaks, reading more as it takes to get a whole one.////// The result points into `payload` and is good only until the next/// call.fn receive(self: *Tcp, io: std.Io) ![]const u8 { while (true) { if (self.framing_mode) |mode| switch (mode) { .cora => { if (try framing.decode(self.buffer[0..self.len])) |frame| { const n = frame.payload.len; @memcpy(self.payload[0..n], frame.payload); self.drop(frame.consumed); return self.payload[0..n]; } }, .legacy => { // No header: a frame is however many bytes a frame is, // and what it means is decided by its first bytes. if (self.len >= framing.legacy_recv_size) { const n = framing.legacy_recv_size; @memcpy(self.payload[0..n], self.buffer[0..n]); self.drop(n); return self.payload[0..n]; } }, } else { // `classify` says null while what has arrived so far is // still consistent with either framing. if (try framing.classify(self.buffer[0..self.len])) |mode| { self.framing_mode = mode; continue; } }
try self.fill(io); }}
/// Send one payload, wrapped however this device expects.fn send(self: *Tcp, io: std.Io, flags: u16, op: framing.HidOp, payload: []const u8) !void { switch (self.framing_mode orelse return error.NotAStreamDeck) { .cora => { var buf: [framing.header_size + framing.max_payload]u8 = undefined; const message_id = self.next_message_id; self.next_message_id +%= 1; const bytes = try framing.encode(&buf, flags, op, message_id, payload); try self.writeAll(io, bytes); }, .legacy => { // No header, and every frame is the same size whatever it // carries, so a short payload is padded out. if (payload.len > framing.legacy_send_size) return error.BufferTooSmall; var buf = std.mem.zeroes([framing.legacy_send_size]u8); @memcpy(buf[0..payload.len], payload); try self.writeAll(io, &buf); }, }}
fn writeAll(self: *Tcp, io: std.Io, bytes: []const u8) !void { var buf: [64]u8 = undefined; var writer = self.stream.writer(io, &buf); writer.interface.writeAll(bytes) catch return error.Disconnected; writer.interface.flush() catch return error.Disconnected;}
/// Answer a keepalive probe, quoting back the connection number it/// carried. A device serves several clients at once and tells them/// apart by that number.fn acknowledge(self: *Tcp, io: std.Io, probe: []const u8) !void { var buf: [command_size]u8 = undefined; const ack = try framing.keepaliveAck(&buf, probe); // `ack_nak` echoes nothing useful in legacy framing, where there is // no header to carry it, and is ignored there. try self.send(io, framing.Flags.ack_nak, .write, ack);}
/// Take payloads off the wire until one is something the caller wants,/// answering keepalives and discarding notifications on the way.////// Without this filter a keepalive would reach `Events.decode`, which/// would read its `0x01` as an input report and its `0x0a` as a control/// type it has never heard of, several times a second.////// Waiting for a reply is bounded, and waiting for input is not. A/// device answers a question it understands within a millisecond or/// so, and one it does not understand it ignores -- while going on/// sending keepalives, so the connection never goes quiet and nothing/// else would ever end the wait. A Studio does exactly that with a/// verbatim `get_report`. So a keepalive arriving while a reply is/// awaited is counted, and once `reply_keepalives` of them have gone by/// the question is taken to have gone unanswered.fn pump(self: *Tcp, io: std.Io, want: enum { input, reply, child }) ![]const u8 { var keepalives: usize = 0; while (true) { const payload = try self.receive(io);
if (framing.isKeepaliveProbe(payload)) { try self.acknowledge(io, payload); if (want != .input) { keepalives += 1; if (keepalives >= reply_keepalives) return error.NoResponse; } continue; }
// A dock saying what is plugged into it: the answer to // `childInfo`, or, when nothing asked, the dock announcing a // deck plugged in or pulled out. `connect` closes the dock's // connection once it has its answer, so there is nobody to tell // about the second -- but it must not be mistaken for an input // report. if (framing.isChildNotification(payload)) { if (want == .child) return payload; continue; }
switch (want) { .input => if (framing.isInputReport(payload)) return payload, // Anything that is not an input report is an answer to // something that was asked. This is deliberately not "a // payload beginning 0x03": that is the shape of a host // command reply, but a verbatim `get_report` -- what a // device behind a dock answers -- comes back as a raw HID // feature report whose first byte is the report id. Waiting // for 0x03 would wait forever for one of those. .reply => if (payload.len > 0 and !framing.isInputReport(payload)) return payload, .child => {}, } }}
/// Ask a Network Dock what is plugged into it.pub fn childInfo(self: *Tcp, io: std.Io) !framing.ChildInfo { var buf: [command_size]u8 = undefined; const request = try framing.hostRequest(&buf, .child); try self.send(io, framing.Flags.none, .get_report, request); const payload = try self.pump(io, .child); return framing.parseChildInfo(payload) orelse error.NoResponse;}
/// Ask the device a host command and return its reply payload.////// The reply points into this `Tcp`'s buffer and is good only until the/// next read.pub fn hostCommand(self: *Tcp, io: std.Io, command: framing.HostCommand, buf: []u8) ![]const u8 { const request = try framing.hostRequest(buf, command); try self.send(io, framing.Flags.none, .get_report, request);
// A device answers the question it was asked; anything else on the // wire in the meantime is somebody else's business and is handled // by `pump`. A reply to a different command means this one went // unanswered. const payload = try self.pump(io, .reply); if (payload.len < 2 or payload[1] != @intFromEnum(command)) return error.NoResponse; return payload;}
/// Read a string-valued host command into `buf` and return the part of/// it that holds the string.fn hostString(self: *Tcp, io: std.Io, command: framing.HostCommand, buf: []u8) ![]const u8 { var request: [command_size]u8 = undefined; const payload = try self.hostCommand(io, command, &request); const reply = framing.HostReply.parse(payload) orelse return error.NoResponse; const string = framing.replyString(reply);
if (buf.len < string.len) return error.BufferTooSmall; @memcpy(buf[0..string.len], string); return buf[0..string.len];}
/// The device's serial number.////// Over USB this is a feature report; here it is a host command, which/// is the one place the two transports genuinely disagree about how to/// ask the same question.pub fn serialNumber(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { return self.hostString(io, .serial, buf);}
/// The device's firmware version.////// Not `hostString`: this reply declares a length of zero and carries/// its string at a fixed offset instead. See `framing.parseFirmware`.pub fn firmwareVersion(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { var request: [command_size]u8 = undefined; const payload = try self.hostCommand(io, .firmware, &request); const string = framing.parseFirmware(payload) orelse return error.NoResponse;
if (buf.len < string.len) return error.BufferTooSmall; @memcpy(buf[0..string.len], string); return buf[0..string.len];}
/// Write an output report: a page of a key image, or a command that/// takes no answer.////// The bytes are exactly what would go to a USB device, and they are/// not re-chunked on the way -- the same kilobyte packets with the same/// headers cross the network unchanged, which is what lets `Keys` and/// `Touchscreen` stay entirely unaware of which transport they are/// driving.pub fn write(self: *Tcp, io: std.Io, buf: []const u8) !usize { try self.send(io, framing.Flags.verbatim, .write, buf); return buf.len;}
/// Send a feature report. Verbatim, so brightness and touch key colour/// go out as the very same bytes a USB device would be sent.pub fn sendFeatureReport(self: *Tcp, io: std.Io, data: []const u8) !usize { try self.send(io, framing.Flags.verbatim, .send_report, data); return data.len;}
/// Read a feature report. `buf[0]` names the report wanted, as it does/// over USB.////// This is the verbatim path, which is right for a device behind a dock/// and wrong for one reached directly -- a Studio answers questions/// about itself through host commands instead. `StreamDeck` is what/// knows the difference; see `serialNumber` above.////// So a connection that answers host commands refuses it with/// `error.Unsupported` rather than sending it. A Studio in legacy/// framing has seen what that would send -- the report id alone, padded/// out, with no header to say it is a question -- and ignores it.pub fn getFeatureReport(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { if (buf.len == 0) return error.BufferTooSmall; if (self.primary) return error.Unsupported; try self.send(io, framing.Flags.verbatim, .get_report, buf[0..1]);
const payload = try self.pump(io, .reply); const n = @min(buf.len, payload.len); @memcpy(buf[0..n], payload[0..n]); return buf[0..n];}
/// Wait for an input report and copy it into `buf`.////// Keepalives are answered while waiting, which is what keeps the/// connection alive at all; see the note at the top of this file about/// what that asks of the caller.pub fn read(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { const payload = try self.pump(io, .input); const n = @min(buf.len, payload.len); @memcpy(buf[0..n], payload[0..n]); return buf[0..n];}
test { std.testing.refAllDecls(@This());}
/// A Stream Deck Studio, played by a socket on the loopback interface.////// This is enough of a device to bring a connection up and take an/// image: it opens with a keepalive probe as a real one does, answers/// the two questions `connect` asks, and records every verbatim write/// it is sent so that the test can check what actually crossed the/// wire.const FakeDeck = struct { server: std.Io.net.Server, /// What the client wrote, concatenated. Image pages land here. written: std.ArrayList(u8) = .empty, /// Whether the keepalive probe was acknowledged, and with the right /// connection number. acknowledged: bool = false, alloc: std.mem.Allocator,
/// The connection number the probe carries. Quoting back something /// else would be answering on another client's behalf, so the test /// checks for this exact value. const connection: u8 = 0x2a;
fn address(self: *const FakeDeck) std.Io.net.IpAddress { return self.server.socket.address; }
/// Wrap a payload in a `cora` frame and send it. fn sendFrame(stream: std.Io.net.Stream, io: std.Io, flags: u16, payload: []const u8) !void { var frame: [framing.header_size + 256]u8 = undefined; const bytes = try framing.encode(&frame, flags, .get_report, 1, payload);
var buf: [64]u8 = undefined; var writer = stream.writer(io, &buf); try writer.interface.writeAll(bytes); try writer.interface.flush(); }
/// Take one whole frame off the wire. fn recv(stream: std.Io.net.Stream, io: std.Io, buf: []u8, len: *usize) !framing.Frame { while (true) { if (try framing.decode(buf[0..len.*])) |frame| return frame;
var reader = stream.reader(io, buf[len.*..]); try reader.interface.fill(1); len.* += reader.interface.bufferedLen(); } }
/// Run the device until the client hangs up. fn run(self: *FakeDeck, io: std.Io) void { self.serve(io) catch {}; }
fn serve(self: *FakeDeck, io: std.Io) !void { const stream = try self.server.accept(io); defer stream.close(io);
// A real device speaks first, and what it opens with is what // tells the client which framing to use. var probe = std.mem.zeroes([8]u8); probe[0] = 0x01; probe[1] = 0x0a; probe[5] = connection; try sendFrame(stream, io, framing.Flags.none, &probe);
var buf: [4096]u8 = undefined; var len: usize = 0;
while (true) { const frame = recv(stream, io, &buf, &len) catch return; const payload = frame.payload;
if (payload.len >= 3 and payload[0] == 0x03 and payload[1] == 0x1a) { self.acknowledged = payload[2] == connection; } else if (frame.header.flags & framing.Flags.verbatim != 0) { if (frame.header.hid_op == @intFromEnum(framing.HidOp.write)) { try self.written.appendSlice(self.alloc, payload); } } else if (payload.len >= 2 and payload[0] == 0x03) { try self.answer(stream, io, payload[1]); }
// `recv` leaves the rest of the buffer behind it. const rest = buf[frame.consumed..len]; std.mem.copyForwards(u8, buf[0..rest.len], rest); len = rest.len; } }
fn answer(self: *FakeDeck, stream: std.Io.net.Stream, io: std.Io, command: u8) !void { _ = self; switch (command) { // Identity: a Studio's vendor and product id, at the fixed // offsets the reply carries them at. 0x80 => { var reply = std.mem.zeroes([16]u8); reply[0] = 0x03; reply[1] = 0x80; std.mem.writeInt(u16, reply[12..14], 0x0fd9, .little); std.mem.writeInt(u16, reply[14..16], 0x00aa, .little); try sendFrame(stream, io, framing.Flags.result, &reply); }, // Serial number, whose length is big-endian. 0x84 => { var reply = std.mem.zeroes([16]u8); reply[0] = 0x03; reply[1] = 0x84; std.mem.writeInt(u16, reply[2..4], 4, .big); @memcpy(reply[4..8], "CL12"); try sendFrame(stream, io, framing.Flags.result, &reply); }, else => {}, } }};
test "a deck is brought up, identified and driven over a socket" { const alloc = std.testing.allocator;
// `std.testing.io` does not promise the concurrency this needs -- // the device and the client both have to be making progress, or // each waits for the other forever. `Io.Threaded` leaves // `concurrent_limit` unlimited. var threaded: std.Io.Threaded = .init(alloc, .{}); defer threaded.deinit(); const io = threaded.io();
const loopback: std.Io.net.IpAddress = .{ .ip4 = .loopback(0) }; var deck: FakeDeck = .{ // Port zero, so the kernel picks one nothing else is using. .server = try loopback.listen(io, .{ .mode = .stream }), .alloc = alloc, }; defer deck.server.deinit(io); defer deck.written.deinit(alloc);
var group: std.Io.Group = .init; defer group.cancel(io); try group.concurrent(io, FakeDeck.run, .{ &deck, io });
// Connecting classifies the framing, answers the first keepalive // and asks the device what it is -- so a deck coming back at all // means the whole handshake worked. // Closed explicitly further down rather than with a `defer`: // `close` frees the connection, so closing twice is a use after // free, and the device has to be let go before what it recorded is // read. const sd = try StreamDeck.connect(io, alloc, deck.address());
try std.testing.expectEqual(StreamDeck.Type.ElgatoStreamDeckStudio, sd.type);
// The serial number comes from a host command rather than the USB // feature report, and its length is the one big-endian field in the // protocol. var serial_buf: [32]u8 = undefined; try std.testing.expectEqualStrings("CL12", try sd.getSerialNumber(io, &serial_buf));
// Resetting has no known encoding here, and is refused rather than // guessed at. try std.testing.expectError(error.Unsupported, sd.reset(io));
// Now the claim this whole design rests on: an image sent over the // network is byte for byte the one that would have gone over USB. const key = 0; var surface = (try sd.keys.blankImage(alloc, key)).?; defer surface.deinit(alloc);
// Noise, so that the JPEG of it is too big for one packet and the // image is actually paged. A blank key encodes to a few hundred // bytes and would cross in a single write, which would leave the // paging untested -- and paging is where a transport that // re-chunked would show itself. var prng: std.Random.DefaultPrng = .init(0x5715_dec4); const random = prng.random(); for (0..@intCast(surface.getHeight())) |y| { for (0..@intCast(surface.getWidth())) |x| { surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = random.int(u8), .g = random.int(u8), .b = random.int(u8), } }); } }
try sd.keys.setImage(io, alloc, key, surface);
// Let the device finish reading before looking at what it got. sd.close(io, alloc); group.await(io) catch {};
const feature = sd.keys.getImageFeature(key).?; const encoded = try Keys.encodeImage(alloc, surface, feature); defer alloc.free(encoded);
const report = sd.type.imageReport(); const max = report.size - feature.header_format.headerSize(); const pages = (encoded.len + max - 1) / max;
// Every page is a whole report, padded, exactly as the USB path // writes them -- not re-chunked to fit the network. A single page // would make the rest of this vacuous, so check there were several. try std.testing.expect(pages > 1); try std.testing.expectEqual(pages * report.size, deck.written.items.len);
// Take the pages apart again and reassemble the image out of them. // If anything had been re-chunked, re-headered or dropped on the // way across, this is what would not come back. const header_len = feature.header_format.headerSize(); var rebuilt: std.ArrayList(u8) = .empty; defer rebuilt.deinit(alloc);
for (0..pages) |page| { const packet = deck.written.items[page * report.size ..][0..report.size];
// The v2 key image header, with this key's index and this // page's number on it. try std.testing.expectEqual(@as(u8, 0x02), packet[0]); try std.testing.expectEqual(@as(u8, 0x07), packet[1]); try std.testing.expectEqual(@as(u8, key), packet[2]); try std.testing.expectEqual( @as(u16, @intCast(page)), std.mem.readInt(u16, packet[6..8], .little), );
// Only the last page is marked last. const last = packet[3] == 1; try std.testing.expectEqual(page == pages - 1, last);
const page_len = std.mem.readInt(u16, packet[4..6], .little); try std.testing.expect(page_len <= max); try rebuilt.appendSlice(alloc, packet[header_len..][0..page_len]); }
try std.testing.expectEqualSlices(u8, encoded, rebuilt.items);
// The keepalive was answered, quoting the right connection number. try std.testing.expect(deck.acknowledged);}