// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Ask every attached Stream Deck what it says about itself, and print //! the raw bytes of the answers beside what they were decoded as. //! //! This exists to check the device tables against hardware rather than //! against another implementation. Reading it is the point: a table //! that disagrees with what the device says here is wrong. //! //! Every action applies to every attached deck unless `--only=NAME` //! narrows it to the models whose name contains `NAME`. const std = @import("std"); const streamdeck = @import("streamdeck"); const z2d = @import("z2d"); pub fn main(init: std.process.Init) !void { const io = init.io; const alloc = init.gpa; var buf: [4096]u8 = undefined; const locked = std.debug.lockStderr(&buf); defer std.debug.unlockStderr(); const out = &locked.file_writer.interface; // `--orient` puts the same figure on the first four keys of every // deck, each under a different correction, so that one look says // which correction a model's table is missing. The figure is "12" // with a rule under it: asymmetric every way round, so a mirror and // a half turn cannot be confused for each other the way a lone // digit can. var orient = false; var paint = false; var fill = false; var sleep = false; var scan = false; var background = false; var logo = false; var diff = false; var idle = false; var wake = false; var transparent = false; var composite = false; var after_reset = false; var inset = false; var keepalive = false; var events = false; var screens = false; var panel_only = false; var studio_rings = false; var rings = false; var ring_encoder: ?u8 = null; // Which deck to act on, when more than one is attached. Most of // what follows paints or resets, and with three decks on the bus an // action meant for the one under test should not disturb the two // being used. Matched as a case-insensitive substring of the model // name, so `--only=galleon` is enough. var only: ?[]const u8 = null; // How long to stay connected after acting. A Studio goes back to its // own demo screen the moment its host hangs up, so without this // nothing drawn on one lasts long enough to be looked at. var hold_seconds: u32 = 0; // Networked decks -- a Studio, or a Network Dock -- are never // enumerated, so each one has to be named: `--connect=1.2.3.4`, or // with `:port` to override the default. They are probed first, and // then whatever is attached over USB. var addresses: std.ArrayList(std.Io.net.IpAddress) = .empty; defer addresses.deinit(alloc); var args = init.minimal.args.iterate(); _ = args.next(); while (args.next()) |arg| { if (std.mem.startsWith(u8, arg, "--only=")) only = arg["--only=".len..]; if (std.mem.startsWith(u8, arg, "--hold=")) { hold_seconds = std.fmt.parseInt(u32, arg["--hold=".len..], 10) catch 0; } if (std.mem.startsWith(u8, arg, "--connect=")) { const text = arg["--connect=".len..]; const address = parseAddress(text) catch |err| { try out.print("{s}: not an address: {t}\n", .{ text, err }); continue; }; try addresses.append(alloc, address); } if (std.mem.eql(u8, arg, "--orient")) orient = true; if (std.mem.eql(u8, arg, "--paint")) paint = true; if (std.mem.eql(u8, arg, "--fill")) fill = true; if (std.mem.eql(u8, arg, "--sleep")) sleep = true; if (std.mem.eql(u8, arg, "--scan")) scan = true; if (std.mem.eql(u8, arg, "--background")) background = true; if (std.mem.eql(u8, arg, "--logo")) logo = true; if (std.mem.eql(u8, arg, "--diff")) diff = true; if (std.mem.eql(u8, arg, "--idle")) idle = true; if (std.mem.eql(u8, arg, "--wake")) wake = true; if (std.mem.eql(u8, arg, "--transparent")) transparent = true; if (std.mem.eql(u8, arg, "--composite")) composite = true; if (std.mem.eql(u8, arg, "--after-reset")) { composite = true; after_reset = true; } if (std.mem.eql(u8, arg, "--inset")) inset = true; if (std.mem.eql(u8, arg, "--keepalive")) keepalive = true; if (std.mem.eql(u8, arg, "--events")) events = true; if (std.mem.eql(u8, arg, "--screens")) screens = true; if (std.mem.eql(u8, arg, "--panel")) panel_only = true; if (std.mem.eql(u8, arg, "--studio-rings")) studio_rings = true; if (std.mem.eql(u8, arg, "--rings")) rings = true; if (std.mem.startsWith(u8, arg, "--rings=")) { rings = true; ring_encoder = std.fmt.parseInt(u8, arg["--rings=".len..], 10) catch null; } } var decks: streamdeck.Enumerator = undefined; try decks.init(io, alloc); defer decks.deinit(io, alloc); var next_address: usize = 0; while (true) { const found: streamdeck.StreamDeckInfo = if (next_address < addresses.items.len) found: { const address = addresses.items[next_address]; next_address += 1; const deck = streamdeck.connect(io, alloc, address) catch |err| { try out.print("\n=== {f} ===\n connect: {t}\n", .{ address, err }); continue; }; // Nothing described a networked deck beforehand, so the // info is empty rather than invented. break :found .{ .deck = deck, .info = .empty }; } else (try decks.next(io, alloc)) orelse break; defer found.deinit(io, alloc); const sd = found.deck; if (only) |want| { if (std.ascii.findIgnoreCase(@tagName(sd.type), want) == null) continue; } // Registered after `found.deinit`, so it runs first: the deck is // held before it is closed, whichever action ran. And after // `--only`, so that a deck passed over is not held as well. defer holdConnection(io, &sd, hold_seconds); try out.print("\n=== {t} ===\n", .{sd.type}); // Paint the panel a bright flat colour and then cover every key // with a flat black key image. // // Both a Neo and an Original V2 have shown panel content at the // edges of a key that had an image written to it. If the key // image does not quite fill the aperture the key looks onto, // every key here keeps a bright border. If it fills it exactly, // every key goes black and what was seen before was light // bleeding between the physical key caps. if (rings) { try showRings(io, &sd, out, ring_encoder); continue; } if (studio_rings) { try tryStudioRings(io, &sd, out); continue; } if (screens) { try tryScreens(io, alloc, &sd, out); continue; } if (events) { try dumpEvents(io, alloc, &sd, out); continue; } if (keepalive) { try holdPanel(io, alloc, &sd, out); continue; } if (inset) { try tryInset(io, alloc, &sd, out); continue; } // What Elgato's application calls a background, done with the // commands this library already has: paint the panel, then draw // key images over only the keys that want one. A key left alone // goes on showing the panel, which is exactly "the background // shows where the foreground is transparent" -- with the // transparency being the absence of a write rather than a // property of the image. if (composite) { try tryComposite(io, alloc, &sd, out, after_reset); continue; } // Store a background, then put flat colours on the first few // keys. If a background shows where the foreground is // "transparent", and the key images are JPEG -- which has no // alpha channel at all -- then transparency has to mean some // particular colour being treated as see-through. This tries // the likely candidates one key at a time. if (transparent) { try tryTransparency(io, alloc, &sd, out); continue; } // Put back what `--idle` changed. if (wake) { sd.setSleepTimeout(io, 0) catch {}; sd.setBrightness(io, 50) catch {}; try out.print(" sleep disabled, brightness restored\n", .{}); continue; } // Store a background and then let the device go idle. If a // "background" is simply what a device shows when it has // nothing else to show, that would explain why the Classic // family has a command to store one and none to display it. if (idle) { try tryBackgroundQuiet(io, alloc, &sd); if (sd.setSleepTimeout(io, 5)) { try out.print(" background stored, sleep timeout set to 5s\n", .{}); } else |err| { try out.print(" sleep timeout : {t}\n", .{err}); } continue; } // Snapshot every feature report, store a background, and // snapshot again. If storing one changes anything the device // will admit to, it shows up here -- which distinguishes "it // stored it and nothing displays it" from "it accepted the // write and threw it away", without anyone having to look at // the hardware. if (diff) { try diffAcrossBackground(io, alloc, &sd, out); continue; } // Show Logo, on its own. If Update Background replaces what a // device shows when it has nothing else to show, then this is // the command that puts a stored background up -- which would // explain how the Classic family uses a background it has no // Show Background command for. if (logo) { if (sd.reset(io)) { try out.print(" show logo (0x03 0x02) : sent\n", .{}); } else |err| { try out.print(" show logo (0x03 0x02) : {t}\n", .{err}); } continue; } if (background) { try tryBackground(io, alloc, &sd, out); continue; } // Ask every possible feature report id and print the ones that // answer with something. Reading a feature report is a // Get_Report control request and changes nothing, so this is // safe to point at whatever is attached -- and it finds the // reports Elgato has not documented as well as the ones it has. if (scan) { try scanReports(io, &sd, out); try out.print(" -- stability over 5 reads --\n", .{}); try checkStability(io, &sd, out); continue; } // Round-trip the sleep timeout: read what it is, write // something else, read it back, and put the original value // returned. Reading alone proves nothing about the write, which // is the half that had never been exercised. if (sleep) { try roundTripSleep(io, &sd, out); continue; } // `--paint` writes an image over the fill a moment later, which // makes the fill impossible to see. This does the fill and // nothing else, and leaves it up. if (fill) { try sd.setBrightness(io, 70); if (sd.fillScreen(io, 0, 90, 0)) { try out.print(" fillScreen green : ok -- left up\n", .{}); } else |err| { try out.print(" fillScreen green : {t}\n", .{err}); } continue; } if (paint or panel_only) { try paintPanel(io, alloc, &sd, out, panel_only); continue; } if (orient) { try out.print(" key 0 = as the table has it key 1 = + flip left/right\n", .{}); try out.print(" key 2 = + flip top/bottom key 3 = + half turn\n", .{}); try showCorrections(io, alloc, &sd); continue; } var serial: [32]u8 = undefined; try out.print("serial : {s}\n", .{sd.getSerialNumber(io, &serial) catch "?"}); if (found.info.serial_number.slice()) |from_system| { // The device and the system should agree about this. Where // they do not, the device is the one that matters and the // difference is worth seeing. if (!std.mem.eql(u8, from_system, sd.getSerialNumber(io, &serial) catch "")) { try out.print("serial (system) : {s}\n", .{from_system}); } } // A deck reached directly over the network answers for its // firmware through a host command, and has none of the feature // reports the loop below asks for. One behind a dock answers // those feature reports like a USB deck. if (if (sd.device.tcp()) |t| t.primary else false) { var version: [32]u8 = undefined; try out.print("firmware (host) : {s}\n", .{sd.getFirmwareVersion(io, &version) catch |err| @errorName(err)}); } inline for (streamdeck.StreamDeck.Firmware.all) |which| { var version: [32]u8 = undefined; if (sd.getFirmwareReport(io, which, &version)) |fw| { // The word in front of the string: a checksum on the // newer protocol, and what looks like an image byte // count on the older. Printed both ways because which // it is depends on the model. try out.print("firmware {s:<11}: {s:<12} word=0x{x:0>8} ({d})\n", .{ @tagName(which), fw.version, fw.checksum, fw.checksum, }); } else |err| switch (err) { // A model without an encoder board has no such report, // which is not worth a line of output. error.Unsupported => {}, else => try out.print("firmware {s:<11}: {t}\n", .{ @tagName(which), err }), } } if (sd.getSleepTimeout(io)) |seconds| { try out.print("sleep timeout : {d}s\n", .{seconds}); } else |err| { try out.print("sleep timeout : {t}\n", .{err}); } // What this library believes, out of its tables. try out.print("table grid : {d} x {d} ({d} keys)\n", .{ sd.keys.cols(), sd.keys.rows(), sd.keys.count(), }); if (sd.keys.getImageFeature(0)) |f| { try out.print("table key image : {d}x{d} {t}, rotation {?t}, flip lr={} tb={}\n", .{ f.width, f.height, f.image_format, f.rotation, f.flip_left_right, f.flip_top_bottom, }); } // What the device says, if it answers at all. if (sd.getUnitInfo(io)) |unit| { try out.print("device grid : {d} x {d} ({d} keys)\n", .{ unit.cols, unit.rows, unit.count(), }); try out.print("device key image : {d}x{d}\n", .{ unit.key_width, unit.key_height }); try out.print("device lcd : {d}x{d}\n", .{ unit.lcd_width, unit.lcd_height }); try out.print("device bpp/scheme : {d} / {d}\n", .{ unit.image_bpp, unit.image_color_scheme }); try out.print("device gallery : {d} key, {d} lcd, {d} demo frames\n", .{ unit.key_gallery, unit.lcd_gallery, unit.demo_frames, }); // The screen size, which is past the end of what Elgato // documents and is printed beside what this library's own // table claims so that the two can be compared at a glance. // On the Plus XL they are transposed, which is that model's // quarter turn showing up in the geometry. if (unit.touch_width) |tw| { if (unit.touch_height) |th| { try out.print("device screen : {d}x{d}", .{ tw, th }); if (sd.touchscreen.getFeature()) |f| { const same = f.width == tw and f.height == th; try out.print(" (table {d}x{d}{s})\n", .{ f.width, f.height, if (same) "" else if (f.width == th and f.height == tw) ", transposed -- this model's rotation" else ", DISAGREES", }); } else { try out.print(" (table has no screen for this model)\n", .{}); } } } } else |err| { try out.print("device unit info : {t}\n", .{err}); } // And the raw bytes of every getter, so that a layout this // library has wrong is visible rather than merely wrong. for ([_]u8{ 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0a, 0xa0, 0xa1, 0xa2, 0xa3 }) |report| { var raw = std.mem.zeroes([32]u8); raw[0] = report; const answer = sd.device.getFeatureReport(io, &raw) catch continue; if (answer.len == 0) continue; // `printable` writes into its scratch, so that scratch must // not be the buffer `answer` points into -- the arguments // are all evaluated before any of them is formatted, so // sharing one buffer prints the dotted copy twice. var text: [32]u8 = undefined; try out.print(" report 0x{x:0>2} [{d:>2}] : {x} |{s}|\n", .{ report, answer.len, answer, printable(answer, &text), }); } } try out.flush(); } /// Panel bright, every key flat black. fn tryInset( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer, ) !void { const panel = sd.panel.getFeature() orelse { try out.print(" no writable panel\n", .{}); return; }; try sd.setBrightness(io, 80); var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); for (0..panel.height) |y| { for (0..panel.width) |x| { surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = 0, .g = 255, .b = 0, } }); } } try sd.panel.setImage(io, alloc, surface); const feature = sd.keys.getImageFeature(0) orelse return; var black = try image_blank(alloc, feature.width, feature.height); defer black.deinit(alloc); // `blankImage` is already black; say so rather than relying on it. for (0..feature.height) |y| { for (0..feature.width) |x| { black.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = 0, .g = 0, .b = 0 } }); } } var drawn: usize = 0; for (0..sd.keys.count()) |i| { const key: u8 = @intCast(i); if (sd.keys.getImageFeature(key) == null) continue; sd.keys.setImage(io, alloc, key, black) catch continue; drawn += 1; } try out.print(" panel green {d}x{d}, {d} key(s) filled black {d}x{d}\n", .{ panel.width, panel.height, drawn, feature.width, feature.height, }); } /// Paint the panel, then draw over every other key. /// /// With `after_reset`, `reset` is sent first -- which is the whole point of /// that flag. An Original V2 then accepts only a short panel image: the /// stripes below encode to more than two packets and come back as a flat wash /// of their average colour, while the same device paints them correctly when /// nothing reset it. Run it both ways on one device and the difference is the /// finding. fn tryComposite( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer, after_reset: bool, ) !void { const feature = sd.panel.getFeature() orelse { try out.print(" no writable panel\n", .{}); return; }; if (after_reset) { sd.reset(io) catch |err| { try out.print(" reset : {t}\n", .{err}); }; try out.print(" reset : sent, and the panel below should now be wrong\n", .{}); } try sd.setBrightness(io, 70); var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); for (0..feature.height) |y| { for (0..feature.width) |x| { const on = ((x + y) / 24) % 2 == 0; surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = if (on) 180 else 0, .g = 0, .b = if (on) 0 else 180, } }); } } sd.panel.setImage(io, alloc, surface) catch |err| { try out.print(" panel : {t}\n", .{err}); return; }; try out.print(" panel : {d}x{d} diagonal stripes\n", .{ feature.width, feature.height }); // Now a foreground over the even keys only. var drawn: usize = 0; for (0..sd.keys.count()) |i| { if (i % 2 == 1) continue; const key: u8 = @intCast(i); var figure = (try sd.keys.indexImage(alloc, key, .yellow_on_black)) orelse continue; defer figure.deinit(alloc); sd.keys.setImage(io, alloc, key, figure) catch continue; drawn += 1; } try out.print(" foreground : {d} key(s) drawn; the odd-numbered keys left alone\n", .{drawn}); } /// The colours worth trying as a transparency key, one per key. const Candidate = struct { name: []const u8, r: u8, g: u8, b: u8, }; const candidates = [_]Candidate{ .{ .name = "black 0,0,0", .r = 0, .g = 0, .b = 0 }, .{ .name = "white 255,255,255", .r = 255, .g = 255, .b = 255 }, .{ .name = "magenta 255,0,255", .r = 255, .g = 0, .b = 255 }, .{ .name = "green 0,255,0", .r = 0, .g = 255, .b = 0 }, .{ .name = "grey 128,128,128", .r = 128, .g = 128, .b = 128 }, .{ .name = "near-black 1,1,1", .r = 1, .g = 1, .b = 1 }, }; /// Store a background and then paint each of the first few keys a flat /// candidate colour, so that one look says which colour -- if any -- /// lets the background through. fn tryTransparency( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer, ) !void { try sd.setBrightness(io, 70); try tryBackgroundQuiet(io, alloc, sd); const feature = sd.keys.getImageFeature(0) orelse { try out.print(" no key displays\n", .{}); return; }; for (candidates, 0..) |candidate, i| { const key: u8 = @intCast(i); if (sd.keys.getImageFeature(key) == null) break; var surface = try image_blank(alloc, feature.width, feature.height); defer surface.deinit(alloc); // A flat fill, except for a thin marker stripe down the right // edge in a colour nothing else uses, so that a key which went // fully transparent can still be told from one that failed to // draw at all. for (0..feature.height) |y| { for (0..feature.width) |x| { const marker = x >= feature.width - 6; surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = if (marker) 255 else candidate.r, .g = if (marker) 200 else candidate.g, .b = if (marker) 0 else candidate.b, } }); } } sd.keys.setImage(io, alloc, key, surface) catch |err| { try out.print(" key {d} {s:<20}: {t}\n", .{ key, candidate.name, err }); continue; }; try out.print(" key {d} {s:<20}: drawn (amber stripe on its right edge)\n", .{ key, candidate.name, }); } } /// A black surface of the given size. `image.blankImage` is not public, /// so this is the same thing through the public surface type. fn image_blank(alloc: std.mem.Allocator, width: usize, height: usize) !z2d.Surface { return try z2d.Surface.init(.image_surface_rgb, alloc, @intCast(width), @intCast(height)); } /// Read all 256 feature reports into `into`. fn snapshot(io: std.Io, sd: *const streamdeck.StreamDeck, into: *[256][32]u8) void { for (0..256) |id| { var raw = std.mem.zeroes([32]u8); raw[0] = @intCast(id); const answer = sd.device.getFeatureReport(io, &raw) catch { into[id] = std.mem.zeroes([32]u8); continue; }; into[id] = std.mem.zeroes([32]u8); @memcpy(into[id][0..answer.len], answer); } } fn diffAcrossBackground( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer, ) !void { if (sd.panel.getFeature() == null) { try out.print(" no panel -- nothing to store\n", .{}); return; } var before = try alloc.create([256][32]u8); defer alloc.destroy(before); var after = try alloc.create([256][32]u8); defer alloc.destroy(after); snapshot(io, sd, before); try tryBackgroundQuiet(io, alloc, sd); snapshot(io, sd, after); var changed: usize = 0; for (0..256) |id| { if (std.mem.eql(u8, &before[id], &after[id])) continue; changed += 1; try out.print(" 0x{x:0>2} before : {x}\n", .{ id, before[id] }); try out.print(" after : {x}\n", .{after[id]}); } try out.print(" {d} report(s) changed across the upload\n", .{changed}); } /// The upload half of `tryBackground`, without the printing, so that /// the differential scan can run it between snapshots. fn tryBackgroundQuiet( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, ) !void { const feature = sd.panel.getFeature() orelse return; var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); for (0..feature.height) |y| { for (0..feature.width) |x| { const on = ((x + y) / 30) % 2 == 0; surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = if (on) 200 else 0, .g = 0, .b = if (on) 0 else 200, } }); } } const data = streamdeck.Panel.encodeImage(alloc, surface, feature) catch return; defer alloc.free(data); const header = 8; const max = 1024 - header; var iter = std.mem.window(u8, data, max, max); var page_number: u16 = 0; while (iter.next()) |page| : (page_number += 1) { var packet = std.mem.zeroes([1024]u8); packet[0] = 0x02; packet[1] = 0x0d; packet[2] = 0; packet[3] = if (page.len < max) 1 else 0; std.mem.writeInt(u16, packet[4..6], page_number, .little); std.mem.writeInt(u16, packet[6..8], @intCast(page.len), .little); @memcpy(packet[header..][0..page.len], page); _ = sd.device.write(io, &packet) catch return; } } /// Try the background commands **whether or not** the tables say this /// model has them. /// /// Elgato documents Update Background for the Classic and XL families /// only, but `Get Unit Information` reports a gallery of LCD images on /// a Neo, which is what a background slot is. The two cannot both be /// right, and the device is the one worth asking -- so this writes the /// packets itself rather than going through `Panel`, which would /// refuse. fn tryBackground( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer, ) !void { const caps = sd.panel.backgrounds(); try out.print(" table says : store={} show={}\n", .{ caps.can_store, caps.can_show }); if (sd.getUnitInfo(io)) |unit| { try out.print(" device gallery : {d} key image(s), {d} lcd image(s)\n", .{ unit.key_gallery, unit.lcd_gallery, }); } else |_| { try out.print(" device gallery : not reported\n", .{}); } const feature = sd.panel.getFeature() orelse { try out.print(" no panel -- nothing to store\n", .{}); return; }; // Broad diagonal stripes, which no ordinary key image resembles, so // that a background actually appearing is unmistakable. var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); for (0..feature.height) |y| { for (0..feature.width) |x| { const on = ((x + y) / 30) % 2 == 0; surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = if (on) 200 else 0, .g = 0, .b = if (on) 0 else 200, } }); } } const data = streamdeck.Panel.encodeImage(alloc, surface, feature) catch |err| { try out.print(" encode : {t}\n", .{err}); return; }; defer alloc.free(data); // The background header, written here rather than by the library so // that a model the library refuses can still be tried. const header = 8; const max = 1024 - header; var iter = std.mem.window(u8, data, max, max); var page_number: u16 = 0; var wrote: usize = 0; var failed: ?anyerror = null; while (iter.next()) |page| : (page_number += 1) { var packet = std.mem.zeroes([1024]u8); packet[0] = 0x02; packet[1] = 0x0d; packet[2] = 0; // slot 0 packet[3] = if (page.len < max) 1 else 0; std.mem.writeInt(u16, packet[4..6], page_number, .little); // page, then std.mem.writeInt(u16, packet[6..8], @intCast(page.len), .little); // length @memcpy(packet[header..][0..page.len], page); _ = sd.device.write(io, &packet) catch |err| { failed = err; break; }; wrote += 1; } if (failed) |err| { try out.print(" upload slot 0 : refused after {d} page(s): {t}\n", .{ wrote, err }); } else { try out.print(" upload slot 0 : {d} page(s) accepted\n", .{wrote}); } // And ask for it to be shown, again bypassing the table. const show: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x13, index: u8 = 0, } = .{}; if (sd.device.sendFeatureReport(io, std.mem.asBytes(&show))) |_| { try out.print(" show slot 0 : accepted\n", .{}); } else |err| { try out.print(" show slot 0 : {t}\n", .{err}); } } /// Try every feature report id and report the ones that answer with /// something the device does not say to everything. /// /// A device answers *every* id rather than refusing the ones it does /// not implement, so "it answered" means nothing on its own. What /// separates a real report from a stub is that the stub is the same /// whatever you ask for, so this works out the stub from ids nothing /// could plausibly use and reports only what differs from it. fn scanReports(io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { // Derive the stub from a few high ids. If they disagree with each // other there is no stub to subtract and everything gets printed. var stub = std.mem.zeroes([32]u8); var have_stub = false; for ([_]u8{ 0xf0, 0xf7, 0xfe }) |id| { var raw = std.mem.zeroes([32]u8); raw[0] = id; const answer = sd.device.getFeatureReport(io, &raw) catch continue; if (answer.len < 32) continue; if (!have_stub) { @memcpy(&stub, answer[0..32]); have_stub = true; } else if (!std.mem.eql(u8, stub[1..], answer[1..32])) { have_stub = false; break; } } if (have_stub) { var text: [32]u8 = undefined; try out.print(" stub (0xf0/f7/fe) : {x} |{s}|\n", .{ stub[1..], printable(stub[1..], &text), }); } else { try out.print(" no consistent stub -- printing everything\n", .{}); } var found: usize = 0; for (0..256) |id| { var raw = std.mem.zeroes([32]u8); raw[0] = @intCast(id); const answer = sd.device.getFeatureReport(io, &raw) catch continue; if (answer.len == 0) continue; // Everything past the echoed id, compared with the stub. if (have_stub and answer.len == 32 and std.mem.eql(u8, stub[1..], answer[1..32])) continue; var content = false; for (answer[1..]) |b| if (b != 0) { content = true; break; }; if (!content) continue; found += 1; var text: [32]u8 = undefined; try out.print(" 0x{x:0>2} [{d:>2}] : {x} |{s}|\n", .{ id, answer.len, answer, printable(answer, &text), }); } try out.print(" {d} report(s) differ from the stub\n", .{found}); } /// Read the firmware reports several times over and say whether the /// word in front of the version string holds still. /// /// This matters because a value that drifts between reads is not a /// checksum of anything, and one read cannot tell the difference. fn checkStability(io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { const ids = [_]u8{ 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0b, 0x0c, 0x11, 0x13, 0xa0, 0xa1, 0xa2 }; const passes = 5; for (ids) |id| { var words: [passes]u32 = undefined; var strings: [passes][8]u8 = undefined; var ok = true; for (0..passes) |pass| { var raw = std.mem.zeroes([32]u8); raw[0] = id; const answer = sd.device.getFeatureReport(io, &raw) catch { ok = false; break; }; if (answer.len < 16) { ok = false; break; } words[pass] = std.mem.readInt(u32, answer[1..5], .little); @memcpy(&strings[pass], answer[5..13]); } if (!ok) continue; var stable = true; for (words[1..]) |w| if (w != words[0]) { stable = false; }; var text_stable = true; for (strings[1..]) |t| if (!std.mem.eql(u8, &strings[0], &t)) { text_stable = false; }; // Only worth printing for ids that said something at all. if (words[0] == 0 and strings[0][0] == 0) continue; try out.print(" 0x{x:0>2} word[1..5]", .{id}); for (words) |w| try out.print(" {x:0>8}", .{w}); try out.print(" {s}{s}\n", .{ if (stable) "STABLE" else "DRIFTS", if (text_stable) "" else " (string drifts too!)", }); } } /// Set the sleep timeout to something, read it back/// Set the sleep timeout to something, read it back, and restore /// whatever it was. fn roundTripSleep(io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { const before = sd.getSleepTimeout(io) catch |err| { try out.print(" sleep: cannot read: {t}\n", .{err}); return; }; try out.print(" sleep before : {d}s\n", .{before}); // Two values, so that a device that merely echoes the last thing // written cannot pass by accident, and one of them is not the // value it already had. for ([_]u31{ 120, 3600 }) |wanted| { sd.setSleepTimeout(io, wanted) catch |err| { try out.print(" sleep set {d:<6} : {t}\n", .{ wanted, err }); continue; }; // The device does not apply the setting before it answers the // next question: read straight back and it reports the value it // held a moment ago. This waits instead of reporting a lag as // a mismatch. try io.sleep(.{ .nanoseconds = 1050 * std.time.ns_per_ms }, .awake); const got = sd.getSleepTimeout(io) catch |err| { try out.print(" sleep set {d:<6} : wrote, cannot read back: {t}\n", .{ wanted, err }); continue; }; try out.print(" sleep set {d:<6} : read back {d}s {s}\n", .{ wanted, got, if (got == wanted) "OK" else "MISMATCH", }); } sd.setSleepTimeout(io, before) catch |err| { try out.print(" sleep restore : {t}\n", .{err}); return; }; try io.sleep(.{ .nanoseconds = 1050 * std.time.ns_per_ms }, .awake); const after = sd.getSleepTimeout(io) catch 0; try out.print(" sleep after : {d}s {s}\n", .{ after, if (after == before) "(restored)" else "(NOT restored)", }); } /// Exercise the commands that came out of Elgato's own documentation /// and had nothing in this library before: painting the whole screen /// behind the keys, and filling a key with a colour instead of sending /// it an image. fn paintPanel( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer, // `--panel`: the checkerboard and nothing else, with no fill before // it and no key fill after, so that whatever becomes of it is the // panel image's own doing. panel_only: bool, ) !void { try sd.setBrightness(io, 70); // A solid fill of the whole panel, which takes one feature report // rather than an image. if (panel_only) {} else if (sd.fillScreen(io, 0, 0, 80)) { try out.print(" fillScreen : ok (dark blue)\n", .{}); } else |err| { try out.print(" fillScreen : {t}\n", .{err}); } // Then an actual image over the whole panel: a coarse checkerboard, // so that a panel written in the wrong order or the wrong place is // obvious rather than plausible. if (sd.panel.getFeature()) |feature| { var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); for (0..feature.height) |y| { for (0..feature.width) |x| { const on = ((x / 40) + (y / 40)) % 2 == 0; // One corner is marked, so that a panel written // upside down cannot look like one written correctly. const corner = x < 80 and y < 80; surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = if (corner) 255 else if (on) 90 else 0, .g = if (corner) 0 else if (on) 90 else 0, .b = if (corner) 0 else if (on) 90 else 0, } }); } } if (sd.panel.setImage(io, alloc, surface)) { try out.print(" panel image : ok ({d}x{d}, red square at top-left)\n", .{ feature.width, feature.height, }); } else |err| { try out.print(" panel image : {t}\n", .{err}); } } else { try out.print(" panel image : no writable panel\n", .{}); } // And one key filled with a colour rather than an image. // // The **last** key rather than the first, because the first is // where the checkerboard's corner marker is and filling over it // throws away the one part of this test that says which way up the // panel went on. That cost an afternoon: an amber key 0 in a // photograph was taken for something the device was doing, on two // models, when it was this line all along. if (panel_only) return; const last_key = sd.keys.count() - 1; if (sd.fillKey(io, last_key, 255, 200, 0)) { try out.print(" fillKey {d:<9} : ok (amber)\n", .{last_key}); } else |err| { try out.print(" fillKey {d:<9} : {t}\n", .{ last_key, err }); } } /// One of the four corrections that a table can be wrong by, once the /// rotation itself is right. Each is its own inverse, which is why /// trying all four settles the matter rather than narrowing it. const Correction = enum { none, flip_left_right, flip_top_bottom, half_turn }; /// Draw the same figure on the first four keys, each corrected /// differently. Whichever key reads correctly names the correction the /// model's table is missing. /// Light every segment of an encoder ring a different colour at once, /// and hold it, so that the numbering can be read off a photograph. /// /// `Encoders.ledIndex` gets two things from the two implementations /// that drive this device: that the rings are numbered from the /// right-hand encoder, and that each ring's segment zero sits at a /// different angle. The first was confirmed by lighting one ring and /// seeing which knob lit. The second needs to know *where* a segment /// lands, and that is harder than it sounds. /// /// Walking the segments one at a time, flashing or steady, does not /// answer it. The ring is a diffuser rather than four lamps, so a lit /// segment is a bright arc rather than a dot; the knob is polished /// metal, so it throws a highlight that moves with the camera; and the /// far side of a ring is hidden by the knob from anything but a lens /// directly overhead. Measuring the ring's brightness by angle across a /// recording of such a walk recovers the glare, not the segment. /// /// Colour is the way through. All four segments lit at once in four /// different colours can be read from a single still photograph, with /// no timing to line up and nothing moving -- and a red arc stays red /// under a highlight that would wash a bright one out. So this sets /// them and then sits there keeping the device awake. fn showRings( io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer, only: ?u8, ) !void { const steps = sd.encoders.ledRingSteps(); if (steps == 0) { try out.print(" no encoder rings on this model\n", .{}); return; } // One colour per segment, in segment order. Red, green and blue are // each a single channel, so no highlight can turn one into another; // white is all three and is unmistakable beside them. const wheel = [_][3]u8{ .{ 255, 0, 0 }, .{ 0, 255, 0 }, .{ 0, 0, 255 }, .{ 255, 255, 255 }, }; const first: u8 = only orelse 0; const last: u8 = only orelse sd.encoders.count() - 1; if (first >= sd.encoders.count()) { try out.print(" no encoder {d} on this model\n", .{first}); return; } try sd.keepAlive(io); var colours: [24][3]u8 = undefined; for (0..steps) |i| colours[i] = wheel[i % wheel.len]; // A networked deck: a ring of twenty-four, which the four colour // wheel would only repeat round, and a device that has to have its // keepalives answered -- which the redraw loop below does not do. // So it gets the marker `--studio-rings` put on the device's own // numbering, segment 0 white and 1 to 3 green, drawn once, with // `--hold` to keep it up. If this library's numbering is right both // knobs show white at the top and green running clockwise. if (sd.device.tcp() != null) { for (0..steps) |i| colours[i] = switch (i) { 0 => .{ 255, 255, 255 }, 1...3 => .{ 0, 255, 0 }, else => .{ 40, 0, 40 }, }; var encoder = first; while (encoder <= last) : (encoder += 1) { sd.encoders.setRingColors(io, encoder, colours[0..steps]) catch |err| { try out.print(" encoder {d}: {t}\n", .{ encoder, err }); return; }; if (sd.encoders.hasLed()) try sd.encoders.setColor(io, encoder, 255, 160, 0); try out.print(" encoder {d}: segment 0 white, 1-3 green, knob amber\n", .{encoder}); } return; } { var encoder = first; while (encoder <= last) : (encoder += 1) { sd.encoders.setRingColors(io, encoder, colours[0..steps]) catch |err| { try out.print(" encoder {d}: {t}\n", .{ encoder, err }); return; }; try out.print(" encoder {d}: segment 0 red, 1 green, 2 blue, 3 white, running clockwise from the top\n", .{encoder}); } } // **The colours do not latch.** Set once and left alone they go out // again too quickly to photograph, which is a thing about this // device worth knowing on its own: the keyboard's own lighting // engine owns these rings and paints over anything the host puts // there. So the hold is not a wait, it is a redraw -- ten times a // second, which is comfortably faster than whatever is reclaiming // them, with a `keepAlive` every fifth pass as usual. try out.print(" holding for 120s -- photograph each knob from directly above\n", .{}); for (0..1200) |tick| { if (tick % 5 == 0) sd.keepAlive(io) catch {}; var encoder = first; while (encoder <= last) : (encoder += 1) { sd.encoders.setRingColors(io, encoder, colours[0..steps]) catch {}; } try io.sleep(.fromMilliseconds(100), .awake); } for (0..sd.encoders.count()) |e| { sd.encoders.setRingColor(io, @intCast(e), 0, 0, 0) catch {}; } try out.print(" done\n", .{}); } /// Print the raw bytes of whatever input reports arrive. /// /// `Events.decode` classifies a report by its second byte -- 0 for the /// keys, 2 for the touchscreen, 3 for the encoders -- and a Galleon /// answers with something else, so every press on one comes back as /// `error.UnknownControlType`. That error carries no bytes with it, and /// the bytes are the whole of what is needed, which is what this is /// for. /// /// It reads the report whole rather than at `Events.readSize`, since /// the point is to see what the device sent rather than what this /// library expected, and a hidraw read truncates silently to the buffer /// it is given. Each line is annotated with what `decode` would make of /// the first two bytes. /// /// On a model that needs one it sends a `keepAlive` around every read, /// because otherwise the device leaves Stream Deck mode two seconds in /// and everything recorded after that is the firmware talking rather /// than the deck. fn dumpEvents(io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { // A Galleon reports as a Stream Deck only while it is being written // to, so on that model this has to hold the device open or it // records nothing but the firmware's own reports. Entering the mode // takes a panel write; staying in it takes `keepAlive` inside every // two seconds, which the 400ms read timeout below guarantees. if (sd.type.needsKeepAlive()) { if (try sd.panel.blankImage(alloc)) |blank| { var surface = blank; defer surface.deinit(alloc); sd.panel.setImage(io, alloc, surface) catch {}; } try out.print(" holding the device in Stream Deck mode\n", .{}); } try out.print(" press keys and turn anything that turns; ends after 45s\n", .{}); var seen: usize = 0; var idle: usize = 0; while (seen < 60 and idle < 112) { try sd.keepAlive(io); var buf: [512]u8 = undefined; // A networked deck has no timed read, so this blocks until the // next report and only the count of reports ends it. Each line // is flushed as it comes, so that a run cut short still says // what it saw. const report = if (sd.device.tcp() != null) sd.device.read(io, &buf) catch |err| { try out.print(" read: {t}\n", .{err}); return; } else sd.device.readTimeout(io, &buf, .{ .duration = .{ .raw = .fromMilliseconds(400), .clock = .awake }, }) catch |err| { try out.print(" read: {t}\n", .{err}); return; } orelse { idle += 1; continue; }; seen += 1; // Trailing zeros are most of a 512 byte report and say nothing. var len = report.len; while (len > 2 and report[len - 1] == 0) len -= 1; try out.print(" [{d:>3}] {x}\n", .{ report.len, report[0..@min(len, 40)] }); defer out.flush() catch {}; if (report.len >= 2) { const kind: []const u8 = switch (report[1]) { 0 => "keys", 2 => "touchscreen", 3 => "encoders", else => "UNKNOWN to Events.ControlType", }; try out.print(" report_type={d} control_type={d} ({s})\n", .{ report[0], report[1], kind, }); } } } /// What it takes to stop a Galleon's own firmware from taking the panel /// back. /// /// That keyboard reclaims its panel about two seconds after a /// whole-panel **image** is written to it: a painted checkerboard was /// filmed reverting to Corsair's wallpaper and icons, unprompted, with /// nothing sent in between. It is the concrete thing behind the claim /// that this model "stops listening if it is left alone". /// /// It is specifically the image. The first version of this experiment /// used `fillScreen`, and its control phase -- five seconds with /// nothing sent at all -- held the panel perfectly well, as did every /// other phase; a fill then stayed up for the whole of the device's 180 /// second sleep timeout. So a fill is not reclaimed and a panel image /// is, and only the second is worth an experiment. Each phase here /// therefore writes a flat-coloured panel *image*. /// /// Something has to be sent to hold one and nothing documents what, so /// this tries the candidates in turn: a phase writes its colour and /// then does one thing every 500ms for five seconds. A colour still up /// at the end of its phase is a candidate that holds the panel; one /// that flips back to Corsair's interface part way through is not, and /// the control phase says what happens with no help at all. /// /// Two earlier rounds narrowed it by experiment. Reads of `0x05`, /// `0x14` and `0x15` all behaved like a control that sent nothing, /// reverting after about two seconds; `setBrightness`, a feature report /// write, did too; and writes on the image output report -- a key /// image, a panel image, `resetKeyStream` -- all held it. /// /// What the experiment could not find is the command the device is /// actually listening for, since nothing would have guessed it: both /// node-elgato-stream-deck and rust-elgato-streamdeck send feature /// report `0x03 0x27` every 500ms, which is what `StreamDeck.keepAlive` /// now sends. This round is that claim put on the hardware, with the /// two known answers either side of it. fn holdPanel(io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { const Action = enum { nothing, ping, brightness, reset_key_stream, refill }; const Phase = struct { colour: []const u8, rgb: [3]u8, action: Action, note: []const u8, }; const phases = [_]Phase{ .{ .colour = "red", .rgb = .{ 180, 0, 0 }, .action = .nothing, .note = "control -- nothing sent" }, .{ .colour = "green", .rgb = .{ 0, 140, 0 }, .action = .ping, .note = "keepAlive -- feature 0x03 0x27" }, .{ .colour = "blue", .rgb = .{ 0, 0, 200 }, .action = .brightness, .note = "setBrightness, unchanged" }, .{ .colour = "yellow", .rgb = .{ 190, 150, 0 }, .action = .reset_key_stream, .note = "resetKeyStream" }, .{ .colour = "magenta", .rgb = .{ 170, 0, 170 }, .action = .refill, .note = "re-send the whole panel image" }, }; try sd.setBrightness(io, 70); try out.print(" Watch the panel. Each phase lasts five seconds.\n", .{}); try out.print(" A colour that survives its whole phase is a candidate that works.\n", .{}); if (sd.panel.getFeature() == null) { try out.print(" no writable panel on this model\n", .{}); return; } for (phases) |phase| { var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); const w: usize = @intCast(surface.getWidth()); const h: usize = @intCast(surface.getHeight()); for (0..h) |y| { for (0..w) |x| { surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = phase.rgb[0], .g = phase.rgb[1], .b = phase.rgb[2], } }); } } if (sd.panel.setImage(io, alloc, surface)) { try out.print(" {s:<8} : {s}\n", .{ phase.colour, phase.note }); } else |err| { try out.print(" {s:<8} : panel image {t} -- skipped\n", .{ phase.colour, err }); continue; } for (0..10) |_| { try io.sleep(.fromMilliseconds(500), .awake); switch (phase.action) { .nothing => {}, .ping => { sd.keepAlive(io) catch {}; }, .brightness => { // The cheapest write there is: one feature report, // and setting the brightness to what it already is // changes nothing visible. sd.setBrightness(io, 70) catch {}; }, .reset_key_stream => { sd.resetKeyStream(io) catch {}; }, .refill => { sd.panel.setImage(io, alloc, surface) catch {}; }, } } } try out.print(" done -- which colours lasted the full five seconds?\n", .{}); } fn showCorrections(io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck) !void { // A networked deck has no reset to offer; the key stream reset // below is enough for this. sd.reset(io) catch |err| switch (err) { error.Unsupported => {}, else => |e| return e, }; try sd.resetKeyStream(io); try sd.setBrightness(io, 60); for ([_]Correction{ .none, .flip_left_right, .flip_top_bottom, .half_turn }, 0..) |correction, key| { const feature = sd.keys.getImageFeature(@intCast(key)) orelse continue; var figure = try streamdeck.diagnostic.keyIndexImage( alloc, feature.width, feature.height, 12, .yellow_on_black, ); defer figure.deinit(alloc); var corrected = try apply(alloc, figure, correction); defer corrected.deinit(alloc); try sd.keys.setImage(io, alloc, @intCast(key), corrected); } } /// A copy of `surface` with `correction` applied. fn apply(alloc: std.mem.Allocator, surface: z2d.Surface, correction: Correction) !z2d.Surface { const width: usize = @intCast(surface.getWidth()); const height: usize = @intCast(surface.getHeight()); var out: z2d.Surface = try .init(.image_surface_rgb, alloc, @intCast(width), @intCast(height)); errdefer out.deinit(alloc); for (0..height) |y| { for (0..width) |x| { const sx = switch (correction) { .none, .flip_top_bottom => x, .flip_left_right, .half_turn => width - 1 - x, }; const sy = switch (correction) { .none, .flip_left_right => y, .flip_top_bottom, .half_turn => height - 1 - y, }; out.putPixel(@intCast(x), @intCast(y), surface.getPixel(@intCast(sx), @intCast(sy)).?); } } return out; } /// The report with anything unprintable replaced by a dot, so that a /// string inside it can be seen at a glance. fn printable(data: []const u8, scratch: []u8) []const u8 { for (data, 0..) |c, i| scratch[i] = if (c >= 0x20 and c < 0x7f) c else '.'; return scratch[0..data.len]; } /// An address with an optional port, defaulting to the one networked /// decks listen on. `std.Io.net` parses a literal with a port and a /// literal without one, but not either, so this tries both. fn parseAddress(text: []const u8) !std.Io.net.IpAddress { if (std.Io.net.IpAddress.parseLiteral(text)) |address| { const port = switch (address) { .ip4 => |a| a.port, .ip6 => |a| a.port, }; // A literal with no port parses with a port of zero, which is // not something to connect to. if (port != 0) return address; } else |_| {} return std.Io.net.IpAddress.parse(text, streamdeck.Tcp.default_port); } /// Stay connected for `seconds`, asking the deck something once a /// second. The asking is what answers a networked deck's keepalives -- /// nothing else would read the socket -- and it is harmless over USB. fn holdConnection(io: std.Io, sd: *const streamdeck.StreamDeck, seconds: u32) void { for (0..seconds) |_| { io.sleep(.fromSeconds(1), .awake) catch return; var serial: [32]u8 = undefined; _ = sd.getSerialNumber(io, &serial) catch return; } } /// Address a Studio's panel as two screens rather than one. /// /// node-elgato-stream-deck gives the Studio two full-screen panels, and /// clears them with `03 05 r g b` -- a screen index in front /// of the colour, where this library's `fillScreen` has none. Its sixteen /// by two keys at 144x112 cannot fit the 1424x280 the device reports, /// but eight by two of them can, which is what two screens side by side /// would be. So this tries both halves of that reading, a few seconds /// apart, each in a colour of its own so a photograph says which step /// did what: /// /// 1. fill screen 0 red and screen 1 green, the way node does; /// 2. a panel image with header byte 2 -- the key index, on a key /// image -- set to 0: blue, a white block top-left, yellow /// bottom-right; /// 3. the same with byte 2 set to 1, in magenta. fn tryScreens(io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { try sd.setBrightness(io, 80); const fills = [_][3]u8{ .{ 255, 0, 0 }, .{ 0, 255, 0 } }; for (fills, 0..) |rgb, screen| { const report = [_]u8{ 0x03, 0x05, @intCast(screen), rgb[0], rgb[1], rgb[2] }; if (sd.device.sendFeatureReport(io, &report)) |_| { try out.print(" fill screen {d} : ok ({d},{d},{d})\n", .{ screen, rgb[0], rgb[1], rgb[2] }); } else |err| { try out.print(" fill screen {d} : {t}\n", .{ screen, err }); } } try out.flush(); try waitAnswering(io, sd, 5); const feature = sd.panel.getFeature() orelse { try out.print(" no panel in the table\n", .{}); return; }; const backgrounds = [_][3]u8{ .{ 0, 0, 255 }, .{ 255, 0, 255 } }; for (backgrounds, 0..) |bg, screen| { var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); for (0..feature.height) |y| { for (0..feature.width) |x| { const rgb: [3]u8 = if (x < 300 and y < 120) .{ 255, 255, 255 } else if (x >= feature.width - 300 and y >= feature.height - 120) .{ 255, 255, 0 } else bg; surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] } }); } } const data = try streamdeck.Panel.encodeImage(alloc, surface, feature); defer alloc.free(data); const header_size = 8; const max = 1024 - header_size; var iter = std.mem.window(u8, data, max, max); var page: u16 = 0; var failed: ?anyerror = null; while (iter.next()) |chunk| : (page += 1) { var packet = std.mem.zeroes([1024]u8); packet[0] = 0x02; packet[1] = 0x08; packet[2] = @intCast(screen); packet[3] = @intFromBool(chunk.len < max or iter.index == null); std.mem.writeInt(u16, packet[4..6], @intCast(chunk.len), .little); std.mem.writeInt(u16, packet[6..8], page, .little); @memcpy(packet[header_size..][0..chunk.len], chunk); _ = sd.device.write(io, &packet) catch |err| { failed = err; break; }; } if (failed) |err| { try out.print(" image screen {d} : {t}\n", .{ screen, err }); } else { try out.print(" image screen {d} : ok ({d} bytes, {d} pages)\n", .{ screen, data.len, page }); } try out.flush(); try waitAnswering(io, sd, 5); } } /// Wait `seconds`, asking the deck something once a second so that a /// networked one's keepalives are answered in the meantime. fn waitAnswering(io: std.Io, sd: *const streamdeck.StreamDeck, seconds: u32) !void { for (0..seconds) |_| { try io.sleep(.fromSeconds(1), .awake); var serial: [32]u8 = undefined; _ = try sd.getSerialNumber(io, &serial); } } /// Light a Studio's encoder LEDs the way node-elgato-stream-deck does, /// by hand, to see where each ring starts and which way it runs. /// /// Each encoder has a single LED of its own, `02 10 r g b`, /// and a ring of twenty-four written whole in one output report, /// `02 0f ` and then a colour per LED. node rotates the right /// ring by twelve before sending it; this sends both unrotated, so what /// lights is the device's own numbering: /// /// - the single LEDs: encoder 0 red, encoder 1 blue; /// - each ring: LED 0 white, LEDs 1 to 3 green, the rest dim purple. fn tryStudioRings(io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { const singles = [_][3]u8{ .{ 255, 0, 0 }, .{ 0, 0, 255 } }; for (singles, 0..) |rgb, encoder| { var packet = std.mem.zeroes([1024]u8); packet[0] = 0x02; packet[1] = 0x10; packet[2] = @intCast(encoder); @memcpy(packet[3..6], &rgb); if (sd.device.write(io, &packet)) |_| { try out.print(" encoder {d} LED : ok ({d},{d},{d})\n", .{ encoder, rgb[0], rgb[1], rgb[2] }); } else |err| { try out.print(" encoder {d} LED : {t}\n", .{ encoder, err }); } } for (0..2) |encoder| { var packet = std.mem.zeroes([1024]u8); packet[0] = 0x02; packet[1] = 0x0f; packet[2] = @intCast(encoder); for (0..24) |led| { const rgb: [3]u8 = switch (led) { 0 => .{ 255, 255, 255 }, 1...3 => .{ 0, 255, 0 }, else => .{ 40, 0, 40 }, }; @memcpy(packet[3 + led * 3 ..][0..3], &rgb); } if (sd.device.write(io, &packet)) |_| { try out.print(" encoder {d} ring : ok (0 white, 1-3 green)\n", .{encoder}); } else |err| { try out.print(" encoder {d} ring : {t}\n", .{ encoder, err }); } } }