// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A single Stream Deck: the open device, the model it is, and the //! whole-device operations that do not belong to any one control, such //! as resetting it or reading its serial number. //! //! The controls themselves live in the `keys`, `touchscreen`, `encoders` //! and `events` fields. Each of those finds its way back here with //! `@fieldParentPtr`, so they must always be reached through a //! `StreamDeck` that stays where it is rather than through a copy. const std = @import("std"); const StreamDeck = @This(); const hidapi = @import("hidapi"); const devices = @import("devices.zig"); const Tcp = @import("Tcp.zig"); const Transport = @import("Transport.zig"); const Keys = @import("Keys.zig"); const Touchscreen = @import("Touchscreen.zig"); const Panel = @import("Panel.zig"); const Encoders = @import("Encoders.zig"); const Events = @import("Events.zig"); /// The models this library knows about. The value of each is the USB /// vendor id in the upper sixteen bits and the product id in the lower /// sixteen, which makes a device easy to identify in one comparison. pub const Type = enum(u32) { /// The only device here that is not Elgato's: a Corsair keyboard /// with a Stream Deck panel built into it, reporting Corsair's /// vendor id. CorsairGalleonK100 = 0x1b1c2b18, ElgatoStreamDeckMK2 = 0x0fd90080, ElgatoStreamDeckMK2Scissor = 0x0fd900a5, ElgatoStreamDeckMini = 0x0fd90063, ElgatoStreamDeckMiniDiscord = 0x0fd900b3, ElgatoStreamDeckMiniMK2 = 0x0fd90090, ElgatoStreamDeckModule15 = 0x0fd900b9, ElgatoStreamDeckModule32 = 0x0fd900ba, ElgatoStreamDeckModule6 = 0x0fd900b8, ElgatoStreamDeckNeo = 0x0fd9009a, ElgatoStreamDeckOriginal = 0x0fd90060, ElgatoStreamDeckOriginalV2 = 0x0fd9006d, ElgatoStreamDeckPedal = 0x0fd90086, ElgatoStreamDeckPlus = 0x0fd90084, ElgatoStreamDeckPlusXL = 0x0fd900c6, ElgatoStreamDeckStudio = 0x0fd900aa, ElgatoStreamDeckXL = 0x0fd9006c, ElgatoStreamDeckXLV2 = 0x0fd9008f, // MiraboxStreamDock293S = 0x55486670, /// The model with the given USB vendor and product ids, or /// `error.NotAStreamDeck` if the pair belongs to something else. pub fn init(v: u16, p: u16) error{NotAStreamDeck}!Type { return std.enums.fromInt(Type, (@as(u32, v) << 16) + p) orelse error.NotAStreamDeck; } /// The USB vendor id of this model. pub fn vendor(self: Type) u16 { return @intCast(@intFromEnum(self) >> 16); } /// The USB product id of this model. pub fn product(self: Type) u16 { return @intCast(@intFromEnum(self) & 0xffff); } /// Which generation of the control protocol a model speaks. The /// original and the six key models use one set of feature reports /// and a one byte input report header; everything since the /// Original V2 uses another. /// /// This is deliberately written out one model at a time with no /// `else`, and it is the only place the split is decided. It used /// to be decided again in each of nine switches, which is how the /// tables came to disagree with each other. pub const Generation = enum { gen1, gen2 }; /// Which generation this model belongs to. pub fn generation(self: Type) Generation { return switch (self) { .ElgatoStreamDeckMini, .ElgatoStreamDeckMiniDiscord, .ElgatoStreamDeckMiniMK2, .ElgatoStreamDeckModule6, .ElgatoStreamDeckOriginal, => .gen1, .CorsairGalleonK100, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckModule15, .ElgatoStreamDeckModule32, .ElgatoStreamDeckNeo, .ElgatoStreamDeckOriginalV2, .ElgatoStreamDeckPedal, .ElgatoStreamDeckPlus, .ElgatoStreamDeckPlusXL, .ElgatoStreamDeckStudio, .ElgatoStreamDeckXL, .ElgatoStreamDeckXLV2, => .gen2, }; } /// Where a string like the serial number or the firmware version is /// to be found: which feature report carries it, how long that /// report is, and how far into it the string starts. pub const StringReport = struct { id: u8, len: usize, offset: usize, }; /// The feature report that carries this model's serial number. pub fn serialReport(self: Type) StringReport { return switch (self.generation()) { // The six key models answer a longer report than the // Original does, but put the string in the same place. .gen1 => .{ .id = 0x03, .len = switch (self) { .ElgatoStreamDeckMiniMK2, .ElgatoStreamDeckModule6 => 32, else => 17, }, .offset = 5, }, .gen2 => .{ .id = 0x06, .len = 32, .offset = 2 }, }; } /// How a model's key images are split into reports. pub const ImageReport = struct { /// The exact size of each report written to the device. Every /// page is padded out to this. size: usize, /// What the first page is numbered. first_page: u16, }; /// How to split a key image into reports for this model. The /// Original is the odd one out on both counts: it takes reports /// eight times the size of everything else's and numbers its pages /// from one rather than from zero. pub fn imageReport(self: Type) ImageReport { return switch (self) { .ElgatoStreamDeckOriginal => .{ .size = 8191, .first_page = 1 }, .CorsairGalleonK100, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckMini, .ElgatoStreamDeckMiniDiscord, .ElgatoStreamDeckMiniMK2, .ElgatoStreamDeckModule15, .ElgatoStreamDeckModule32, .ElgatoStreamDeckModule6, .ElgatoStreamDeckNeo, .ElgatoStreamDeckOriginalV2, .ElgatoStreamDeckPedal, .ElgatoStreamDeckPlus, .ElgatoStreamDeckPlusXL, .ElgatoStreamDeckStudio, .ElgatoStreamDeckXL, .ElgatoStreamDeckXLV2, => .{ .size = MAX_PACKET_SIZE, .first_page = 0 }, }; } /// The length of an input report, for a model known to send a /// fixed-size one bigger than the sum of its controls. Null means /// no such length is known, and `Events.readSize` then works it out /// from the controls. /// /// Unlike the switches above this one has an `else`, and on purpose: /// a missing entry here is "nothing known", which degrades to a /// computed size, rather than a fact about the model that has to be /// got right. pub fn inputReportSize(self: Type) ?usize { return switch (self) { // 36 keys, six dials and a touchscreen come to 40 bytes, // but the device sends 64 regardless. .ElgatoStreamDeckPlusXL => 64, else => null, }; } /// Whether this model stops being a Stream Deck when it is left /// alone, and so has to be told the host is still there. /// /// Only the Galleon does. Left without a write for about two /// seconds it hands the panel back to the keyboard's own firmware /// and its input reports stop being Stream Deck reports, so a host /// that goes quiet loses the display and the events together. See /// `keepAlive`, and the README for what was measured. /// /// Written out one model at a time with no `else` on purpose: a /// model missing from here is a model asserted not to need this, /// which is a fact about it rather than something unknown. pub fn needsKeepAlive(self: Type) bool { return switch (self) { .CorsairGalleonK100 => true, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckMini, .ElgatoStreamDeckMiniDiscord, .ElgatoStreamDeckMiniMK2, .ElgatoStreamDeckModule15, .ElgatoStreamDeckModule32, .ElgatoStreamDeckModule6, .ElgatoStreamDeckNeo, .ElgatoStreamDeckOriginal, .ElgatoStreamDeckOriginalV2, .ElgatoStreamDeckPedal, .ElgatoStreamDeckPlus, .ElgatoStreamDeckPlusXL, .ElgatoStreamDeckStudio, .ElgatoStreamDeckXL, .ElgatoStreamDeckXLV2, => false, }; } /// Whether this model answers `Get Unit Information`, the feature /// report through which a device describes its own geometry. /// /// Only the newer protocol has it. Elgato's documentation lists the /// getter feature reports for the Mini family separately and this /// is not among them, so asking a Mini would be asking for a report /// it has never heard of. pub fn hasUnitInfo(self: Type) bool { return self.generation() == .gen2; } /// The feature report that carries this model's firmware version. pub fn firmwareReport(self: Type) StringReport { return switch (self.generation()) { .gen1 => .{ .id = 0x04, .len = 17, .offset = 5 }, .gen2 => .{ .id = 0x05, .len = 32, .offset = 6 }, }; } }; test "needsKeepAlive" { // The Galleon is the only model that stops being a Stream Deck when // it is left alone, and the only one this is true of. try std.testing.expect(Type.CorsairGalleonK100.needsKeepAlive()); inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); if (t != .CorsairGalleonK100) try std.testing.expect(!t.needsKeepAlive()); } } test Type { inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); const device = @field(devices, f.name); try std.testing.expectEqual(device.vendor, t.vendor()); try std.testing.expectEqual(device.product, t.product()); } } /// Which model this device is. Nearly everything else about the device /// is decided by this. type: Type, /// How this device is reached: a HID device, or a TCP connection to a /// Studio or a Network Dock. Valid until `close`. device: Transport, /// The keys, and the images shown on them. keys: Keys = .init, /// The touchscreen, on the models that have one. touchscreen: Touchscreen = .init, /// The whole screen behind the keys, on the models that will let it be /// written. panel: Panel = .init, /// The rotary encoders, on the models that have them. encoders: Encoders = .init, /// Decoding of the input reports the device sends when something on it /// is pressed, touched or turned. events: Events = .init, /// Open the device an enumeration reported and build a `StreamDeck` /// around it. /// /// `info` is what `Enumerator.next` handed back. Its vendor and product /// ids say which model this is before the device is opened at all, so a /// device this library does not know is refused with /// `error.NotAStreamDeck` without being touched. /// /// Opening needs permission where enumerating does not: `/dev/hidraw*` /// is root-only until a udev rule says otherwise, and until then this /// answers `error.AccessDenied`. The README has a rule to copy. /// /// The caller owns the result and must release it with `close`. pub fn open(io: std.Io, alloc: std.mem.Allocator, info: *const hidapi.DeviceInfo) !StreamDeck { const t: Type = try .init(info.vendor_id, info.product_id); // The device is held by pointer because `hidapi` opens one in place // and every operation on it takes a mutable pointer, so it cannot // be moved once opened. const device = try alloc.create(hidapi.Device); errdefer alloc.destroy(device); try device.open(io, info.id, .{}); return .{ .type = t, .device = .fromHid(device) }; } /// Open a device by the id an enumeration reported, asking it which /// model it is once it is open. /// /// `open` is the better way round when the `DeviceInfo` is still to /// hand: it knows the model before it touches the device. This is for a /// caller that kept only the id, which is the part with no lifetime of /// its own. pub fn openId(io: std.Io, alloc: std.mem.Allocator, id: hidapi.DeviceId) !StreamDeck { const device = try alloc.create(hidapi.Device); errdefer alloc.destroy(device); try device.open(io, id, .{}); errdefer device.close(io); var info: hidapi.DeviceInfo = .empty; try device.getInfo(io, &info); return .{ .type = try .init(info.vendor_id, info.product_id), .device = .fromHid(device), }; } /// Open a connection to a Stream Deck reached over the network -- a /// Studio, or a Network Dock -- and build a `StreamDeck` around it. /// /// `address` is where the device is; there is no discovery here, and /// `std.Io.net` has no name resolver, so a caller with a host name has /// to turn it into an address itself. `Tcp.default_port` is the port /// these devices listen on. /// /// The device is asked what it is as part of connecting, and the /// connection is closed again if the answer is not a model this library /// knows. The caller owns the result and must release it with `close`. /// /// Note what driving one of these asks of the caller: the device pings /// every few seconds and hangs up on a host that has not answered /// within five, and answering happens only while something is reading. /// See the note at the top of `Tcp.zig`. pub fn connect(io: std.Io, alloc: std.mem.Allocator, address: std.Io.net.IpAddress) !StreamDeck { const connection = try Tcp.connect(io, alloc, address); errdefer connection.close(io); return .{ .type = try .init(connection.vendor, connection.product), .device = .fromTcp(connection), }; } /// Release the underlying device, closing the HID node or the network /// connection and freeing what was allocated for it. Nothing else on /// this `StreamDeck` may be used afterwards. pub fn close(self: *const StreamDeck, io: std.Io, alloc: std.mem.Allocator) void { self.device.close(io, alloc); } /// The report size every model but the Original takes, and the size of /// a touchscreen image report on every model that has one. pub const MAX_PACKET_SIZE = 1024; /// The largest image report any model takes, which is the Original's. /// A page of image data is assembled in a buffer of this size and then /// only `Type.imageReport().size` bytes of it are written. pub const MAX_IMAGE_REPORT_SIZE = 8191; /// Abandon any partly written key image, so that the next image starts /// from a known state. Does nothing on the Pedal, which has no display /// to write to. pub fn resetKeyStream(self: *const StreamDeck, io: std.Io) !void { if (self.type == .ElgatoStreamDeckPedal) return; // The report is the size of an image report, since that is the // stream it abandons. const size = self.type.imageReport().size; var buffer = std.mem.zeroes([MAX_IMAGE_REPORT_SIZE]u8); buffer[0] = 0x02; _ = try self.device.write(io, buffer[0..size]); } /// Tell the device that the host is still driving it. /// /// Only the Galleon needs this, and it needs it about twice a second. /// That model leaves Stream Deck mode roughly two seconds after the /// last write, handing the panel back to the keyboard's own firmware /// and switching its input reports to something `Events.decode` will /// not accept -- so a host that goes quiet loses the display and the /// events in the same moment. Does nothing at all on every other /// model, so it is safe to call on whatever is attached. /// /// **This library will not do it for you.** There is no timer here and /// no thread; a caller that drives a Galleon has to call this on a /// cadence of its own, and 500ms is a comfortable one inside a two /// second window. /// /// What it sends is feature report `0x03` with command `0x27`, which /// both implementations that drive this device agree on: /// node-elgato-stream-deck sends exactly those two bytes on a 500ms /// interval and calls it a ping, and rust-elgato-streamdeck sends the /// same command padded to thirty-two bytes and calls it refreshing /// software mode. It is padded here, because every other feature report /// this library sends to a gen2 device is thirty-two bytes. /// /// Measurement here agrees on the interval and adds what else works, /// which is worth knowing because `0x03 0x27` was not found by /// experiment: writes on the **image output report** hold the device /// too -- a key image, a whole panel image, or `resetKeyStream` -- while /// reads of feature reports do not, and nor does `setBrightness`, which /// is a feature report write. So it is not that the device counts any /// traffic, and not that it counts only the image stream; this /// particular command is what it is listening for, and the image writes /// evidently refresh the same state as a side effect. pub fn keepAlive(self: *const StreamDeck, io: std.Io) !void { if (!self.type.needsKeepAlive()) return; const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x27, padding: [30]u8 = std.mem.zeroes([30]u8), } = .{}; std.debug.assert(@sizeOf(@TypeOf(packet)) == 32); _ = try self.device.sendFeatureReport(io, std.mem.asBytes(&packet)); } /// Return the device to the state it powers up in, clearing the keys /// back to the manufacturer's logo. The older models want a different /// feature report for this than the newer ones. /// Clear the device and put it back to its logo. /// /// **Do not call this before painting the panel.** It leaves an Original V2 /// able to accept only a short panel image: a solid colour, which encodes to /// two packets, arrives and displays, while a picture taking six comes out as /// a flat wash of its average colour. Bisected on the hardware one call at a /// time; `resetKeyStream` immediately before the write does not clear it, so /// it is not a stuck image stream in the sense that call was written for. /// /// A program that paints the panel loses little by leaving this out. /// `resetKeyStream` and `setBrightness` between them still prove a device /// answers on both the output and the feature-report channels, and painting /// the panel and then every key clears the glass more thoroughly than this /// does. See the README. pub fn reset(self: *const StreamDeck, io: std.Io) !void { // No implementation of the network protocol has ever been seen to // perform this, and there is nothing to copy: the reference client // refuses it outright rather than sending something. Inventing an // encoding for a command that clears the device would be guessing // with the device's state, so this says so instead. if (self.device.kind() == .tcp) return error.Unsupported; var buf: [32]u8 = undefined; var writer = std.Io.Writer.fixed(&buf); switch (self.type.generation()) { .gen1 => { const packet: extern struct { byte0: u8 = 0x0b, byte1: u8 = 0x63, padding: [15]u8 = std.mem.zeroes([15]u8), } = .{}; std.debug.assert(@sizeOf(@TypeOf(packet)) == 17); try writer.writeStruct(packet, .little); }, .gen2 => { const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x02, padding: [30]u8 = std.mem.zeroes([30]u8), } = .{}; std.debug.assert(@sizeOf(@TypeOf(packet)) == 32); try writer.writeStruct(packet, .little); }, } _ = try self.device.sendFeatureReport(io, writer.buffered()); } /// Set the brightness of the backlight, from 0-100. Values larger than /// 100 will be clipped to 100. Does nothing on the Pedal, which has no /// backlight. pub fn setBrightness(self: *const StreamDeck, io: std.Io, percent: u8) !void { var buf: [32]u8 = undefined; var writer = std.Io.Writer.fixed(&buf); if (self.type == .ElgatoStreamDeckPedal) return; switch (self.type.generation()) { .gen1 => { const packet: extern struct { byte0: u8 = 0x05, byte1: u8 = 0x55, byte2: u8 = 0xaa, byte3: u8 = 0xd1, byte4: u8 = 0x01, brightness: u8, padding: [11]u8 = std.mem.zeroes([11]u8), } = .{ .brightness = @min(percent, 100), }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 17); try writer.writeStruct(packet, .little); }, .gen2 => { const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x08, brightness: u8, } = .{ .brightness = @min(percent, 100), }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 3); try writer.writeStruct(packet, .little); }, } _ = try self.device.sendFeatureReport(io, writer.buffered()); } /// What a device says about itself when asked. /// /// This is the answer to `Get Unit Information`, feature report `0x08`, /// and it is worth more than its size suggests: it is the device /// reporting its own key grid and its own pixel dimensions, rather than /// this library looking them up in a table somebody wrote down. Where /// the two disagree, the device is right. /// /// Elgato's HID documentation describes the layout; see the README's /// references. pub const UnitInfo = struct { /// Rows in the key grid, as the device counts them. rows: u8, /// Columns in the key grid. cols: u8, /// The pixel size of one key's display. key_width: u16, key_height: u16, /// The pixel size of the whole panel behind the keys. Every model /// with displays has one, including the ones with no touchscreen. lcd_width: u16, lcd_height: u16, /// Bits per pixel of the images the device takes. image_bpp: u8, /// Which colour scheme those images are in. Elgato documents the /// field but not its values, so this is passed through as a number. image_color_scheme: u8, /// How many key images and screen images the device says it can /// hold in its own gallery, and how many frames its demo runs for. /// /// Do **not** read `lcd_gallery` as the number of background slots. /// A Stream Deck Neo reports four and does not implement the /// background commands at all -- it was sent one and asked to show /// it, accepted both, and displayed nothing. What the gallery /// actually counts is not documented and has not been worked out. key_gallery: u8, lcd_gallery: u8, demo_frames: u8, /// The pixel size of the device's screen strip -- the touchscreen on /// a Plus or a Plus XL, the info strip on a Neo, the screen above a /// Galleon's keys -- or null on a device whose report stops before /// these bytes. /// /// Elgato's documentation describes the report as far as /// `demo_frames` and stops. These two are past the end of it, and /// they were worked out by reading the bytes four devices sent and /// noticing what they already matched: a Neo answers 248 by 58 and /// carries a 248x58 strip, a Plus 800 by 100, a Galleon 720 by 384, /// each exactly what this library's tables claim from other /// sources. That is four independent agreements, which is what /// makes it a reading rather than a guess. /// /// **The fourth is the interesting one.** A Plus XL answers 100 by /// 1200 where its touchscreen is 1200x100 -- transposed, on the one /// model whose glass is mounted a quarter turn round. The device /// reports the panel as it is built rather than as it is looked at, /// so this is the rotation showing up in the geometry, and an /// independent check on a table that rested on documentation alone. /// /// Note what that means for using this field: it is the screen's /// size **before** the rotation `Touchscreen.getFeature` applies, /// so on the Plus XL it is the transpose of the size an image /// handed to `setImage` has to be. touch_width: ?u16, touch_height: ?u16, /// The total number of keys the device says it has. pub fn count(self: UnitInfo) u16 { return @as(u16, self.rows) * self.cols; } }; /// Ask the device to describe itself. /// /// Returns `error.Unsupported` on a model whose protocol has no such /// report -- the Mini family -- and `error.ShortReport` if the device /// answered with less than the layout requires. /// /// This is the one call that can check the device tables against the /// hardware instead of against another implementation, so it is worth /// reaching for when a model's numbers are in doubt. /// /// Confirmed against a Neo and a Plus, which answered with exactly the /// key and panel sizes Elgato's documentation gives for them. /// /// Note that `rows` and `cols` describe the **keypad matrix** and not /// the number of keys: a Neo answers four by three, twelve positions, /// where it has eight keys and two touch buttons and the rest of the /// bottom row is taken up by its info strip. So this confirms pixel /// sizes outright and grid shapes only with judgement. pub fn getUnitInfo(self: *const StreamDeck, io: std.Io) !UnitInfo { if (!self.type.hasUnitInfo()) return error.Unsupported; var buffer = std.mem.zeroes([32]u8); buffer[0] = 0x08; return parseUnitInfo(try self.device.getFeatureReport(io, &buffer)); } /// Read a `Get Unit Information` answer, with the device taken out of /// it. `getUnitInfo` is this plus the feature report that fetches the /// bytes; splitting the two is what lets real answers from real /// hardware be kept as tests. pub fn parseUnitInfo(result: []const u8) !UnitInfo { // The fields run from +0x01 to +0x0f, so anything shorter than // sixteen bytes is an answer this cannot be read out of. if (result.len < 16) return error.ShortReport; return .{ .rows = result[1], .cols = result[2], .key_width = std.mem.readInt(u16, result[3..5], .little), .key_height = std.mem.readInt(u16, result[5..7], .little), .lcd_width = std.mem.readInt(u16, result[7..9], .little), .lcd_height = std.mem.readInt(u16, result[9..11], .little), .image_bpp = result[11], .image_color_scheme = result[12], .key_gallery = result[13], .lcd_gallery = result[14], .demo_frames = result[15], // Past the end of what Elgato documents, so a device that // answers a shorter report is not a device that has failed. // Byte +0x10 sits between these and `demo_frames` and is not // read: every device answers something different there -- 0x95, // 0x42, 0x06, 0x00 -- and nothing has made sense of it. .touch_width = if (result.len >= 19) std.mem.readInt(u16, result[17..19], .little) else null, .touch_height = if (result.len >= 21) std.mem.readInt(u16, result[19..21], .little) else null, }; } test parseUnitInfo { // Four `Get Unit Information` answers, captured from four devices // with `probe`. Every number below is the device describing itself; // where this library's tables say the same thing, they were written // from documentation or from another implementation and are being // checked rather than repeated. const Case = struct { name: []const u8, raw: []const u8, rows: u8, cols: u8, key: [2]u16, lcd: [2]u16, bpp: u8, touch: [2]u16, }; for ([_]Case{ .{ .name = "Stream Deck + XL", .raw = &.{ 0x08, 0x04, 0x09, 0x70, 0x00, 0x70, 0x00, 0x00, 0x05, 0x20, 0x03, 0x02, 0x05, 0x00, 0x00, 0x04, 0x06, 0x64, 0x00, 0xb0, 0x04, 0x03, }, .rows = 4, .cols = 9, .key = .{ 112, 112 }, .lcd = .{ 1280, 800 }, .bpp = 2, // Transposed against the 1200x100 the table carries, which // is this model's quarter turn showing up in its geometry. .touch = .{ 100, 1200 }, }, .{ .name = "Stream Deck Plus", .raw = &.{ 0x08, 0x02, 0x04, 0x78, 0x00, 0x78, 0x00, 0x20, 0x03, 0xe0, 0x01, 0x04, 0x05, 0x00, 0x00, 0x04, 0x42, 0x20, 0x03, 0x64, 0x00, 0x00, }, .rows = 2, .cols = 4, .key = .{ 120, 120 }, .lcd = .{ 800, 480 }, .bpp = 4, .touch = .{ 800, 100 }, }, .{ .name = "Stream Deck Neo", .raw = &.{ 0x08, 0x03, 0x04, 0x60, 0x00, 0x60, 0x00, 0xe0, 0x01, 0x40, 0x01, 0x04, 0x05, 0x01, 0x04, 0x04, 0x95, 0xf8, 0x00, 0x3a, 0x00, 0x00, }, // Four by three is the keypad matrix, not the keys: this // model has eight keys and two touch keys, and the rest of // the bottom row is its info strip. .rows = 3, .cols = 4, .key = .{ 96, 96 }, .lcd = .{ 480, 320 }, .bpp = 4, .touch = .{ 248, 58 }, }, .{ .name = "Corsair Galleon K100", .raw = &.{ 0x08, 0x04, 0x03, 0xa0, 0x00, 0xa0, 0x00, 0xd0, 0x02, 0x00, 0x05, 0x02, 0x05, 0x00, 0x00, 0x04, 0x00, 0xd0, 0x02, 0x80, 0x01, 0x00, }, .rows = 4, .cols = 3, .key = .{ 160, 160 }, .lcd = .{ 720, 1280 }, .bpp = 2, .touch = .{ 720, 384 }, }, }) |c| { errdefer std.debug.print("while reading {s}\n", .{c.name}); const info = try parseUnitInfo(c.raw); try std.testing.expectEqual(c.rows, info.rows); try std.testing.expectEqual(c.cols, info.cols); try std.testing.expectEqual(c.key[0], info.key_width); try std.testing.expectEqual(c.key[1], info.key_height); try std.testing.expectEqual(c.lcd[0], info.lcd_width); try std.testing.expectEqual(c.lcd[1], info.lcd_height); try std.testing.expectEqual(c.bpp, info.image_bpp); try std.testing.expectEqual(c.touch[0], info.touch_width.?); try std.testing.expectEqual(c.touch[1], info.touch_height.?); } } test "a unit info answer that stops early is read as far as it goes" { // The screen size is past the end of what Elgato documents, so a // device that answers only the documented fields is answering // correctly rather than failing. const short = [_]u8{ 0x08, 0x02, 0x04, 0x78, 0x00, 0x78, 0x00, 0x20, 0x03, 0xe0, 0x01, 0x04, 0x05, 0x00, 0x00, 0x04 }; const info = try parseUnitInfo(&short); try std.testing.expectEqual(120, info.key_width); try std.testing.expectEqual(null, info.touch_width); try std.testing.expectEqual(null, info.touch_height); try std.testing.expectError(error.ShortReport, parseUnitInfo(short[0..15])); } /// Which firmware version to ask a device for. /// /// A Stream Deck carries more than one processor and reports a version /// for each. `ap2` is the one a user means by "the firmware version", /// and is what `getFirmwareVersion` reads; the others are here because /// Elgato's documentation names them and because a device that is /// misbehaving is a device whose other versions are worth seeing. pub const Firmware = enum { /// The primary application firmware. ap2, /// The bootloader. ld, /// The backup application firmware. ap1, /// The primary application firmware of the encoder module, on a /// model whose encoders are a board of their own. encoder_ap2, /// That module's bootloader. encoder_ld, /// Every version this library knows how to ask for, for a caller /// that wants to print the lot. pub const all = [_]Firmware{ .ap2, .ld, .ap1, .encoder_ap2, .encoder_ld }; }; /// Whether this model's encoders carry firmware of their own. /// /// Only the Studio does, as far as anything says. Its encoders are a /// separate board with a separate bootloader, and Elgato publishes no /// HID documentation for that model at all -- the two report ids come /// from node-elgato-stream-deck, whose Studio driver asks for exactly /// these three versions where every other model gets the generic set. /// /// The Plus and the Plus XL have encoders and do **not** have this: a /// Stream Deck Plus was asked for both reports and answered with the /// same empty stub it gives any report it does not implement, and /// Elgato's Plus XL page lists its getters as `0x04` through `0x08` /// and `0x0a` and nothing else. pub fn hasEncoderFirmware(t: Type) bool { return t == .ElgatoStreamDeckStudio; } /// The feature report carrying one of a model's firmware versions, or /// null if this model does not report that one. pub fn firmwareReportFor(t: Type, which: Firmware) ?Type.StringReport { switch (which) { .encoder_ap2, .encoder_ld => { if (!hasEncoderFirmware(t)) return null; // Assumed to be laid out like the other newer-protocol // firmware reports -- a length, a word, then the string at // +0x06 -- because that is what the report they sit beside // does. Nothing has run a Studio to check it. return .{ .id = switch (which) { .encoder_ap2 => 0x11, .encoder_ld => 0x13, else => unreachable, }, .len = 32, .offset = 6, }; }, .ap2, .ld, .ap1 => {}, } return switch (t.generation()) { // The older protocol numbers these quite differently, and the // report this library has always used for the Mini family -- // 0x04 -- is not in Elgato's list for them at all. It answers // anyway, with the same string 0xa1 gives; that was checked // against a Stream Deck Mini. Both are kept: the documented one // is what `ap2` asks for, and the other is left working. .gen1 => switch (which) { .ld => .{ .id = 0xa0, .len = 17, .offset = 5 }, .ap2 => .{ .id = 0xa1, .len = 17, .offset = 5 }, .ap1 => .{ .id = 0xa2, .len = 17, .offset = 5 }, .encoder_ap2, .encoder_ld => unreachable, }, .gen2 => switch (which) { .ld => .{ .id = 0x04, .len = 32, .offset = 6 }, .ap2 => .{ .id = 0x05, .len = 32, .offset = 6 }, .ap1 => .{ .id = 0x07, .len = 32, .offset = 6 }, .encoder_ap2, .encoder_ld => unreachable, }, }; } /// A firmware report in full: the version string, and the thirty-two /// bits the device puts in front of it. pub const FirmwareReport = struct { /// The version string. Points into the buffer it was read into. version: []const u8, /// The four bytes between the report's length and its version /// string, read little-endian. /// /// Elgato's documentation calls this a **checksum** on the newer /// protocol and says nothing else about it: not what it covers, /// not the algorithm, not the endianness. On the Mini family the /// same four bytes are listed as "N/A". /// /// What it is a checksum *of* is almost certainly the firmware /// image, which means this library cannot verify it -- see /// `checksum_is_not_of_the_version_string` for the evidence and /// for what was ruled out. It is exposed rather than hidden /// because it is still good for something: it changes when the /// firmware changes, so two reads that disagree mean the device /// was reflashed under you, and a value recorded here is evidence /// for whoever next tries to identify it. checksum: u32, }; /// Why this library does not check the firmware checksum. /// /// Elgato documents the field and not the algorithm, so it was /// attacked with what hardware was to hand: three devices, six /// firmware reports, and a search over 41 checksum algorithms -- the /// RevEng catalogue of 32-bit CRCs, eight 16-bit ones, Adler-32, /// Fletcher-32, FNV-1 and 1a, djb2, sdbm, byte and word sums, MD5, /// SHA-1 and SHA-256 prefixes -- crossed with 23 ways of deriving an /// input from the report and all 24 byte orders of the stored value. /// That is a little over twenty-two thousand combinations, required to /// agree on all six observations at once. None did. /// /// The reason is visible in the older protocol. Those same four bytes, /// which Elgato's Mini page declines to describe, read as a byte count /// on a Stream Deck Mini: 329,560 for the bootloader and 3,397,852 and /// 3,354,892 for the two application slots, which is a bootloader of /// 322 KiB and two firmware images of about 3.28 MiB differing by /// 42,960 bytes. All three are under 2^24, which a random 32-bit /// checksum would manage about once in sixteen million times. /// /// So the four bytes in that slot describe the firmware image rather /// than the eight ASCII characters beside them, and the newer /// protocol's checksum is therefore a checksum of an image this /// library never sees. Checking it from the host is not possible, and /// no amount of further searching over the version string will help. /// /// The observed values are kept as a test below, so that the next /// person to try has real data to work from. pub const checksum_is_not_of_the_version_string = {}; /// Parse a firmware report: the string, and the word in front of it. /// /// Split out from the read so that it can be checked against bytes a /// real device sent without needing the device, which is what the test /// below does. pub fn parseFirmwareReport(report: Type.StringReport, data: []const u8) !FirmwareReport { // The word sits in the four bytes immediately before the string, // which is true of both protocols: the older puts the string at // +0x05 and the word at +0x01, the newer at +0x06 and +0x02. if (report.offset < 4) return error.ShortReport; const word_at = report.offset - 4; if (data.len < report.offset) return error.ShortReport; const string = data[report.offset..]; return .{ .version = if (std.mem.findScalar(u8, string, 0)) |end| string[0..end] else string, .checksum = std.mem.readInt(u32, data[word_at..][0..4], .little), }; } /// Read one of the device's firmware versions in full: the string and /// the word in front of it. /// /// `getFirmwareVersion` is this with the word thrown away, which is /// what nearly every caller wants. pub fn getFirmwareReport( self: *const StreamDeck, io: std.Io, which: Firmware, buffer: []u8, ) !FirmwareReport { const report = firmwareReportFor(self.type, which) orelse return error.Unsupported; if (buffer.len < report.len) return error.BufferTooSmall; @memset(buffer, 0); buffer[0] = report.id; const result = try self.device.getFeatureReport(io, buffer[0..report.len]); return parseFirmwareReport(report, result); } /// Read one of the device's firmware versions into `buffer`. /// /// `getFirmwareVersion` is this with `.ap2`, which is the one worth /// printing; the others are for telling apart two devices that claim /// the same primary version. pub fn getFirmwareVersionOf( self: *const StreamDeck, io: std.Io, which: Firmware, buffer: []u8, ) ![]const u8 { const report = firmwareReportFor(self.type, which) orelse return error.Unsupported; return self.readStringReport(io, buffer, report); } /// Fill one key with a solid colour, instead of sending it an image. /// /// This is far cheaper than encoding a JPEG for a key that only needs /// to be one colour, and it is the only way to light the touch keys on /// a Neo, which have a backlight rather than a display. Elgato's /// documentation describes it for every key on the newer protocol, not /// only those. /// /// Returns `error.Unsupported` on the older protocol, which has no such /// command, and on the Pedal, which has nothing to light. /// /// Confirmed against a Neo and a Plus. /// /// **Over the network it wipes a panel image.** On a Studio, and on a /// Neo behind a Network Dock, a key filled after `Panel.setImage` left /// that key lit and the rest of the panel dark; over USB the rest of the /// panel stays. pub fn fillKey(self: *const StreamDeck, io: std.Io, key: u8, r: u8, g: u8, b: u8) !void { if (self.type.generation() != .gen2) return error.Unsupported; if (self.type == .ElgatoStreamDeckPedal) return error.Unsupported; const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x06, key: u8, r: u8, g: u8, b: u8, } = .{ .key = key, .r = r, .g = g, .b = b }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 6); _ = try self.device.sendFeatureReport(io, std.mem.asBytes(&packet)); } /// Fill the whole panel behind the keys with a solid colour. /// /// Every model with displays has one screen behind all of them, which /// is what the keys are windows onto; this paints the lot in one /// command. Returns `error.Unsupported` where there is no such screen /// or no such command. /// /// Confirmed against a Neo and a Plus: the keys and, on the Neo, the /// info strip all take the colour together. On a Studio, whose panel is /// two screens, both are filled. Note that it is a fill and /// not a mode -- the next image written to a key or to the panel /// covers it, which is easy to mistake for the fill not having worked. pub fn fillScreen(self: *const StreamDeck, io: std.Io, r: u8, g: u8, b: u8) !void { if (self.type.generation() != .gen2) return error.Unsupported; if (self.type == .ElgatoStreamDeckPedal) return error.Unsupported; // A panel of several screens is filled a screen at a time, and the // command then carries the screen's index in front of the colour. // The Studio's two halves went red and green from `03 05 00 ff 00 // 00` and `03 05 01 00 ff 00`, where the single-screen layout would // have read those bytes as green and blue. if (self.panel.getFeature()) |feature| { if (feature.screens > 1) { for (0..feature.screens) |screen| { const packet = [_]u8{ 0x03, 0x05, @intCast(screen), r, g, b }; _ = try self.device.sendFeatureReport(io, &packet); } return; } } const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x05, r: u8, g: u8, b: u8, } = .{ .r = r, .g = g, .b = b }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 5); _ = try self.device.sendFeatureReport(io, std.mem.asBytes(&packet)); } /// The feature report that sets the sleep timeout, built into `buf`. /// /// Split out from `setSleepTimeout` so that the bytes can be checked /// without a device, which is how everything else here that turns a /// decision into a packet is arranged. /// /// The two protocols disagree about everything but the field: the older /// one carries it in report `0x0b` behind command `0xa2`, the newer in /// `0x03` behind `0x0d`. Both take a little-endian signed thirty-two /// bit count of seconds, and both read zero as "do not sleep". pub fn sleepTimeoutReport(t: Type, seconds: u31, buf: []u8) ![]const u8 { var writer = std.Io.Writer.fixed(buf); switch (t.generation()) { .gen1 => { const packet: extern struct { byte0: u8 = 0x0b, byte1: u8 = 0xa2, seconds: i32 align(1), } = .{ .seconds = seconds }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 6); try writer.writeStruct(packet, .little); }, .gen2 => { const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x0d, seconds: i32 align(1), } = .{ .seconds = seconds }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 6); try writer.writeStruct(packet, .little); }, } return writer.buffered(); } /// The feature report a model answers its sleep timeout on. pub fn sleepTimeoutQuery(t: Type) u8 { return switch (t.generation()) { .gen1 => 0xa3, .gen2 => 0x0a, }; } /// How long the device sits idle before blanking itself, in seconds. /// Zero disables it, so the device stays lit until told otherwise. /// /// **A device does not apply this before it answers the next question.** /// Reading it straight back reports the value it held a moment ago, /// which looks exactly like the write having failed. A Mini, a Neo and /// a Plus all wanted somewhere between nothing and ten milliseconds; /// none of them needed fifty. Nothing here waits on your behalf -- /// there is no timer in this library -- so a caller that wants to /// confirm the write has to leave a gap before `getSleepTimeout`. /// /// Confirmed on all three of those devices, which round-tripped two /// different values and restored the original. pub fn setSleepTimeout(self: *const StreamDeck, io: std.Io, seconds: u31) !void { var buf: [32]u8 = undefined; const report = try sleepTimeoutReport(self.type, seconds, &buf); _ = try self.device.sendFeatureReport(io, report); } /// How long the device is currently set to wait before blanking, in /// seconds. Zero means it does not. /// /// See `setSleepTimeout` about reading this immediately after writing /// it: the answer lags the write. pub fn getSleepTimeout(self: *const StreamDeck, io: std.Io) !u31 { var buffer = std.mem.zeroes([32]u8); buffer[0] = sleepTimeoutQuery(self.type); const result = try self.device.getFeatureReport(io, &buffer); // A report id, a length byte, then the duration. Anything shorter // than the three of them together is not an answer. if (result.len < 6) return error.ShortReport; const seconds = std.mem.readInt(i32, result[2..6], .little); // A device has no business reporting a negative idle time, and // narrowing one into a `u31` would be a panic rather than an error. if (seconds < 0) return error.ShortReport; return @intCast(seconds); } test hasEncoderFirmware { // Only the Studio, and the two reports exist only there. inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); const expected = t == .ElgatoStreamDeckStudio; try std.testing.expectEqual(expected, hasEncoderFirmware(t)); for ([_]Firmware{ .encoder_ap2, .encoder_ld }) |which| { const report = firmwareReportFor(t, which); try std.testing.expectEqual(expected, report != null); } // The three every model answers are always there, whatever the // protocol. for ([_]Firmware{ .ap2, .ld, .ap1 }) |which| { try std.testing.expect(firmwareReportFor(t, which) != null); } } try std.testing.expectEqual( @as(u8, 0x11), firmwareReportFor(.ElgatoStreamDeckStudio, .encoder_ap2).?.id, ); try std.testing.expectEqual( @as(u8, 0x13), firmwareReportFor(.ElgatoStreamDeckStudio, .encoder_ld).?.id, ); } test "no two firmware reports on one model share a report id" { // Asking for the encoder's version and getting the panel's would be // silent and wrong, so the ids have to be distinct per model -- and // distinct from the serial number's, which sits in the same range. inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); for (Firmware.all) |a| { const ra = firmwareReportFor(t, a) orelse continue; try std.testing.expect(ra.id != t.serialReport().id); for (Firmware.all) |b| { if (a == b) continue; const rb = firmwareReportFor(t, b) orelse continue; try std.testing.expect(ra.id != rb.id); } } } } test parseFirmwareReport { // Bytes a real Stream Deck Neo and a real Stream Deck Plus sent, // recorded so that the parse is checked against hardware rather // than against a reading of the documentation -- and so that the // checksum values survive for whoever next tries to identify them. const Case = struct { model: Type, which: Firmware, raw: []const u8, version: []const u8, checksum: u32, }; for ([_]Case{ // Stream Deck Neo, firmware 1.00.013. .{ .model = .ElgatoStreamDeckNeo, .which = .ld, .raw = &.{ 0x04, 0x0c, 0x1a, 0xa8, 0xc8, 0x01, '1', '.', '0', '0', '.', '0', '0', '3' }, .version = "1.00.003", .checksum = 0x01c8a81a, }, .{ .model = .ElgatoStreamDeckNeo, .which = .ap2, .raw = &.{ 0x05, 0x0c, 0xd5, 0x27, 0x93, 0xe1, '1', '.', '0', '0', '.', '0', '1', '3' }, .version = "1.00.013", .checksum = 0xe19327d5, }, .{ .model = .ElgatoStreamDeckNeo, .which = .ap1, .raw = &.{ 0x07, 0x0c, 0xe2, 0x63, 0xaa, 0x63, '1', '.', '0', '0', '.', '0', '1', '1' }, .version = "1.00.011", .checksum = 0x63aa63e2, }, // Stream Deck Plus, firmware 2.0.3.1. Its strings are seven // characters and a terminator where the Neo's fill the field, // so this is also the test that the cut is made at the NUL. .{ .model = .ElgatoStreamDeckPlus, .which = .ld, .raw = &.{ 0x04, 0x0c, 0xb1, 0xb0, 0x5d, 0x32, '2', '.', '0', '.', '0', '.', '0', 0x00 }, .version = "2.0.0.0", .checksum = 0x325db0b1, }, .{ .model = .ElgatoStreamDeckPlus, .which = .ap2, .raw = &.{ 0x05, 0x0c, 0x1e, 0x08, 0xa0, 0x20, '2', '.', '0', '.', '3', '.', '1', 0x00 }, .version = "2.0.3.1", .checksum = 0x20a0081e, }, }) |case| { const report = firmwareReportFor(case.model, case.which).?; const parsed = try parseFirmwareReport(report, case.raw); try std.testing.expectEqualStrings(case.version, parsed.version); try std.testing.expectEqual(case.checksum, parsed.checksum); } } test "the Plus reports the same firmware in both application slots" { // Its AP1 and AP2 reports are byte for byte identical -- same // version, same checksum -- which is what the two slots holding // the same image looks like, and is why one device alone cannot // say whether the checksum covers the image or the string. const ap2 = [_]u8{ 0x05, 0x0c, 0x1e, 0x08, 0xa0, 0x20, '2', '.', '0', '.', '3', '.', '1', 0x00 }; const ap1 = [_]u8{ 0x07, 0x0c, 0x1e, 0x08, 0xa0, 0x20, '2', '.', '0', '.', '3', '.', '1', 0x00 }; const a = try parseFirmwareReport( firmwareReportFor(.ElgatoStreamDeckPlus, .ap2).?, &ap2, ); const b = try parseFirmwareReport( firmwareReportFor(.ElgatoStreamDeckPlus, .ap1).?, &ap1, ); try std.testing.expectEqualStrings(a.version, b.version); try std.testing.expectEqual(a.checksum, b.checksum); } test "a firmware report shorter than its own layout is refused" { const report = firmwareReportFor(.ElgatoStreamDeckPlus, .ap2).?; // Nothing at all, and a report cut off inside the checksum. try std.testing.expectError(error.ShortReport, parseFirmwareReport(report, &.{})); try std.testing.expectError( error.ShortReport, parseFirmwareReport(report, &.{ 0x05, 0x0c, 0x1e, 0x08 }), ); } test sleepTimeoutReport { var buf: [32]u8 = undefined; // The newer protocol: report 0x03, command 0x0d, then the seconds // little-endian. 3600 is 0x00000e10. try std.testing.expectEqualSlices( u8, &.{ 0x03, 0x0d, 0x10, 0x0e, 0x00, 0x00 }, try sleepTimeoutReport(.ElgatoStreamDeckPlus, 3600, &buf), ); // Zero is what disables it, and is not a special encoding. try std.testing.expectEqualSlices( u8, &.{ 0x03, 0x0d, 0x00, 0x00, 0x00, 0x00 }, try sleepTimeoutReport(.ElgatoStreamDeckNeo, 0, &buf), ); // The older protocol carries the same field behind a different // report and command. try std.testing.expectEqualSlices( u8, &.{ 0x0b, 0xa2, 0x78, 0x00, 0x00, 0x00 }, try sleepTimeoutReport(.ElgatoStreamDeckMini, 120, &buf), ); // The largest a `u31` can ask for still fits the field without // becoming negative, which is what makes the narrowing in // `getSleepTimeout` safe. const most = try sleepTimeoutReport(.ElgatoStreamDeckPlus, std.math.maxInt(u31), &buf); try std.testing.expectEqual( @as(i32, std.math.maxInt(u31)), std.mem.readInt(i32, most[2..6], .little), ); } test sleepTimeoutQuery { // The two protocols answer on different reports, and the newer // one's number would be a firmware version on the older. try std.testing.expectEqual(0x0a, sleepTimeoutQuery(.ElgatoStreamDeckPlus)); try std.testing.expectEqual(0xa3, sleepTimeoutQuery(.ElgatoStreamDeckMini)); inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); const query = sleepTimeoutQuery(t); // Whatever it is, it has to be a report this library does not // use for something else. try std.testing.expect(query != t.serialReport().id); try std.testing.expect(query != t.firmwareReport().id); } } /// Read a string-valued feature report into `buffer` and return the /// part of it that holds the string. `buffer` is used for the report /// itself, so it has to be at least `report.len` bytes; anything /// smaller gives `error.BufferTooSmall`. The result points into /// `buffer` and is only good until it is next written to. fn readStringReport(self: *const StreamDeck, io: std.Io, buffer: []u8, report: Type.StringReport) ![]const u8 { if (buffer.len < report.len) return error.BufferTooSmall; @memset(buffer, 0); buffer[0] = report.id; const result = try self.device.getFeatureReport(io, buffer[0..report.len]); // A device that answered with less than the string's offset has // told us nothing, and slicing past the end of what it did say // would be a panic rather than an empty answer. if (result.len <= report.offset) return result[result.len..]; const string = result[report.offset..]; if (std.mem.findScalar(u8, string, 0)) |end| return string[0..end]; return string; } /// Read the serial number into `buffer` and return the part of it that /// holds the number, under the rules of `readStringReport`. pub fn getSerialNumber(self: *const StreamDeck, io: std.Io, buffer: []u8) ![]const u8 { if (self.device.tcp()) |connection| { if (connection.primary) return connection.serialNumber(io, buffer); } return self.readStringReport(io, buffer, self.type.serialReport()); } /// Read the serial number and return a copy of it. The caller owns the /// result and must free it with `alloc`. pub fn getSerialNumberAlloc(self: *const StreamDeck, io: std.Io, alloc: std.mem.Allocator) ![]const u8 { var buffer: [32]u8 = undefined; return try alloc.dupe(u8, try self.getSerialNumber(io, &buffer)); } /// Read the firmware version into `buffer` and return the part of it /// that holds the version, under the rules of `readStringReport`. pub fn getFirmwareVersion(self: *const StreamDeck, io: std.Io, buffer: []u8) ![]const u8 { if (self.device.tcp()) |connection| { if (connection.primary) return connection.firmwareVersion(io, buffer); } return self.readStringReport(io, buffer, self.type.firmwareReport()); } /// Read the firmware version and return a copy of it. The caller owns /// the result and must free it with `alloc`. pub fn getFirmwareVersionAlloc(self: *const StreamDeck, io: std.Io, alloc: std.mem.Allocator) ![]const u8 { var buffer: [32]u8 = undefined; return try alloc.dupe(u8, try self.getFirmwareVersion(io, &buffer)); } test "the vendor and product ids round-trip through the enum value" { // `Type` packs the two ids into its value, so the accessors have to // take them back out again unchanged -- and they have to narrow to // `u16` without a cast that could trap. inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); try std.testing.expectEqual(f.value, (@as(u32, t.vendor()) << 16) + t.product()); try std.testing.expectEqual(try Type.init(t.vendor(), t.product()), t); } } test "every model is Elgato's but one, and no two share a product id" { // Corsair owns Elgato and builds a Stream Deck panel into one of // its keyboards, which reports Corsair's vendor id. Everything else // is Elgato's own. inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); const expected: u16 = switch (t) { .CorsairGalleonK100 => 0x1b1c, else => 0x0fd9, }; try std.testing.expectEqual(expected, t.vendor()); } // The enum value is the vendor and product together, so Zig has // already rejected a duplicate pair at compile time. This says so // out loud, and checks the product ids alone for good measure. // // Every model is compared with every other, so the work here grows // as the square of the table and the default comptime budget does // not cover it. @setEvalBranchQuota(10_000); inline for (std.meta.fields(Type)) |a| { inline for (std.meta.fields(Type)) |b| { if (comptime std.mem.eql(u8, a.name, b.name)) continue; const ta: Type = @enumFromInt(a.value); const tb: Type = @enumFromInt(b.value); try std.testing.expect(ta.product() != tb.product()); } } } test "a device that is not a Stream Deck is refused" { const saved = std.testing.log_level; std.testing.log_level = .err; defer std.testing.log_level = saved; try std.testing.expectError(error.NotAStreamDeck, Type.init(0x0000, 0x0000)); // Elgato's vendor id with a product id that is not one of theirs. try std.testing.expectError(error.NotAStreamDeck, Type.init(0x0fd9, 0xffff)); } test "the generation split follows the feature reports a model uses" { // The six key models and the Original speak the older protocol. try std.testing.expectEqual(Type.Generation.gen1, Type.ElgatoStreamDeckOriginal.generation()); try std.testing.expectEqual(Type.Generation.gen1, Type.ElgatoStreamDeckMini.generation()); try std.testing.expectEqual(Type.Generation.gen1, Type.ElgatoStreamDeckMiniMK2.generation()); try std.testing.expectEqual(Type.Generation.gen1, Type.ElgatoStreamDeckModule6.generation()); try std.testing.expectEqual(Type.Generation.gen2, Type.ElgatoStreamDeckMK2.generation()); try std.testing.expectEqual(Type.Generation.gen2, Type.ElgatoStreamDeckXL.generation()); try std.testing.expectEqual(Type.Generation.gen2, Type.ElgatoStreamDeckPedal.generation()); try std.testing.expectEqual(Type.Generation.gen2, Type.ElgatoStreamDeckStudio.generation()); } test "a module speaks the same protocol as the model it is built from" { // The bare panels are the same electronics in a different shell, so // anything that differed here would be a mistake in the tables. const pairs = .{ .{ Type.ElgatoStreamDeckModule6, Type.ElgatoStreamDeckMini }, .{ Type.ElgatoStreamDeckModule15, Type.ElgatoStreamDeckMK2 }, .{ Type.ElgatoStreamDeckModule32, Type.ElgatoStreamDeckXL }, .{ Type.ElgatoStreamDeckMK2Scissor, Type.ElgatoStreamDeckMK2 }, .{ Type.ElgatoStreamDeckMiniDiscord, Type.ElgatoStreamDeckMini }, }; inline for (pairs) |pair| { const module, const base = pair; try std.testing.expectEqual(base.generation(), module.generation()); try std.testing.expectEqual(base.firmwareReport(), module.firmwareReport()); var m: StreamDeck = .{ .type = module, .device = .none }; var b: StreamDeck = .{ .type = base, .device = .none }; try std.testing.expectEqual(b.keys.count(), m.keys.count()); try std.testing.expectEqual(b.keys.getFeature(0), m.keys.getFeature(0)); try std.testing.expectEqual(b.events.readSize(), m.events.readSize()); } } test "the serial and firmware reports fit the buffer they are read into" { // Both strings come out of a report the model's generation picks, // and the buffer has to be big enough for the report itself. inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); for ([_]Type.StringReport{ t.serialReport(), t.firmwareReport() }) |report| { try std.testing.expect(report.len <= 32); try std.testing.expect(report.offset < report.len); } } try std.testing.expectEqual( Type.StringReport{ .id = 0x03, .len = 17, .offset = 5 }, Type.ElgatoStreamDeckOriginal.serialReport(), ); try std.testing.expectEqual( Type.StringReport{ .id = 0x06, .len = 32, .offset = 2 }, Type.ElgatoStreamDeckMK2.serialReport(), ); try std.testing.expectEqual( Type.StringReport{ .id = 0x04, .len = 17, .offset = 5 }, Type.ElgatoStreamDeckOriginal.firmwareReport(), ); try std.testing.expectEqual( Type.StringReport{ .id = 0x05, .len = 32, .offset = 6 }, Type.ElgatoStreamDeckXL.firmwareReport(), ); } test "only the Original takes an oversized image report" { inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); const report = t.imageReport(); // Whatever the size, a page has to be assembled in the buffer // `Keys.setImage` puts on the stack. try std.testing.expect(report.size <= MAX_IMAGE_REPORT_SIZE); if (t == .ElgatoStreamDeckOriginal) { try std.testing.expectEqual(8191, report.size); try std.testing.expectEqual(1, report.first_page); } else { try std.testing.expectEqual(MAX_PACKET_SIZE, report.size); try std.testing.expectEqual(0, report.first_page); } } } test "a report leaves room for the header of every key it has" { inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); var sd: StreamDeck = .{ .type = t, .device = .none }; for (0..sd.keys.count()) |key| { const feature = sd.keys.getImageFeature(@intCast(key)) orelse continue; const header = feature.header_format.headerSize(); try std.testing.expect(header < t.imageReport().size); // And a page has to be able to carry something. try std.testing.expect(t.imageReport().size - header > 0); } } } test { // Everything else here needs an open device, so it can only be // compiled rather than run. std.testing.refAllDecls(@This()); std.testing.refAllDecls(Type); }