// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The rotary encoders (knobs) of a Stream Deck. Only some models have //! them; on the rest every query here reports zero encoders. //! //! An `Encoders` lives as the `encoders` field of a `StreamDeck` and //! carries no state of its own. It recovers the device it belongs to //! with `@fieldParentPtr`, so the answers below depend on the model of //! that device. const std = @import("std"); const Encoders = @This(); const StreamDeck = @import("StreamDeck.zig"); /// The value to initialize the `encoders` field of a `StreamDeck` with. pub const init: Encoders = .{}; /// The number of rotary encoders the device has: the Stream Deck Plus /// has four, the Plus XL six, and the Studio two, one at either end of /// its key row. pub fn count(self: *const Encoders) u8 { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); return switch (sd.type) { .CorsairGalleonK100 => 2, .ElgatoStreamDeckMini => 0, .ElgatoStreamDeckMiniDiscord => 0, .ElgatoStreamDeckMiniMK2 => 0, .ElgatoStreamDeckMK2 => 0, .ElgatoStreamDeckMK2Scissor => 0, .ElgatoStreamDeckModule15 => 0, .ElgatoStreamDeckModule32 => 0, .ElgatoStreamDeckModule6 => 0, .ElgatoStreamDeckNeo => 0, .ElgatoStreamDeckOriginal => 0, .ElgatoStreamDeckOriginalV2 => 0, .ElgatoStreamDeckPedal => 0, .ElgatoStreamDeckPlus => 4, .ElgatoStreamDeckPlusXL => 6, .ElgatoStreamDeckStudio => 2, .ElgatoStreamDeckXL => 0, .ElgatoStreamDeckXLV2 => 0, }; } /// The number of bytes an encoder report occupies in the body of an /// input report: an event type, and then one byte per encoder. /// `Events.bodySize` takes the largest of these across all of the /// control groups to size its read buffer, and `Events.decode` uses it /// to give the parser exactly this control's bytes and no more. /// /// The event type is counted here, which the key equivalent has no need /// to do: a key report is nothing but states. pub fn readSize(self: *const Encoders) usize { const n = self.count(); return if (n == 0) 0 else 1 + @as(usize, n); } /// The number of LEDs in the ring around each encoder, or zero on a /// model whose encoders have no ring. /// /// Two models have one. The Galleon's is four to a ring -- quadrants /// rather than an arc smooth enough to draw a level on -- and the /// Studio's is twenty-four. Written out one model at a time with no /// `else`, because a model missing from here is one asserted to have no /// ring rather than one nothing is known about. pub fn ledRingSteps(self: *const Encoders) u8 { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); return switch (sd.type) { .CorsairGalleonK100 => 4, .ElgatoStreamDeckStudio => 24, .ElgatoStreamDeckMini, .ElgatoStreamDeckMiniDiscord, .ElgatoStreamDeckMiniMK2, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckModule15, .ElgatoStreamDeckModule32, .ElgatoStreamDeckModule6, .ElgatoStreamDeckNeo, .ElgatoStreamDeckOriginal, .ElgatoStreamDeckOriginalV2, .ElgatoStreamDeckPedal, .ElgatoStreamDeckPlus, .ElgatoStreamDeckPlusXL, .ElgatoStreamDeckXL, .ElgatoStreamDeckXLV2, => 0, }; } /// Where one ring's `segment` sits in the flat numbering the device /// addresses its LEDs by. /// /// Two things stop this being the identity. The rings are numbered from /// the **right-hand** encoder, so encoder 1 owns 0 through 3 and /// encoder 0 owns 4 through 7. And each ring's own numbering starts at /// a different angle, so a segment has to be rotated into place first: /// three quarter turns for the left ring and one for the right. Both /// implementations that drive this device carry the same two rotations, /// arrived at separately, which is the only reason to believe them. /// /// All of it is confirmed against a Galleon. Walking encoder 0 lights the /// left knob and encoder 1 the right, which is what indices running from /// the right-hand encoder predicts. Lighting all four segments at once /// in four colours then showed the rotations putting **the ring's zero /// at the top, with the ring advancing anticlockwise** -- 1 at nine /// o'clock, 2 at six, 3 at three -- and showed both rings presenting /// that same arrangement, which is the thing the two rotations exist to /// do. A wrong rotation would have left one ring turned against the /// other. /// /// This library numbers segments **clockwise** from the top, on every /// model, because that is the way a level is read round a dial. So a /// segment is reversed into that anticlockwise order before it is /// rotated: segment 1 is at three o'clock and 3 at nine, which a Galleon /// lit red, green, blue and white showed on both knobs. fn ledIndex(self: *const Encoders, encoder: u8, segment: u8) u8 { const steps = self.ledRingSteps(); const rotation: u8 = if (encoder == 0) 3 else 1; const anticlockwise = (steps - segment) % steps; const hardware = (anticlockwise + steps - rotation) % steps; return (self.count() - 1 - encoder) * steps + hardware; } /// Light one LED of one encoder's ring. /// /// The report is `0x03 0x24` then the LED's index and its three colour /// bytes, six bytes in all -- which is what both implementations send, /// unpadded, so it is what this sends rather than the thirty-two bytes /// a gen2 feature report usually runs to. Confirmed against a Galleon: /// the rings take the colours they are given. /// /// **They do not keep them.** See `setRingColor`. fn setRingLed(self: *const Encoders, io: std.Io, index: u8, red: u8, green: u8, blue: u8) !void { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x24, index: u8, red: u8, green: u8, blue: u8, } = .{ .index = index, .red = red, .green = green, .blue = blue }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 6); _ = try sd.device.sendFeatureReport(io, std.mem.asBytes(&packet)); } /// Light the whole of one encoder's ring a single colour. /// /// **A ring does not hold its colour, and this is not a write-and-forget /// call.** On a Galleon the keyboard's own lighting engine owns these /// LEDs and paints back over whatever the host puts there, within about /// a second -- set once and left alone, a ring is dark again too soon to /// photograph. Holding a colour means re-sending it; ten times a second /// is comfortably enough and is what `probe --rings` does. Note that /// `StreamDeck.keepAlive` does **not** cover this: it keeps the device /// in Stream Deck mode, where the panel and the input reports live, and /// the rings are a separate argument with the firmware. A Studio's /// rings are the exception: drawn once, they stay lit for as long as /// the connection is held. /// /// `error.Unsupported` on a model whose encoders have no ring, and /// `error.NoSuchEncoder` if the device has no such encoder. On a /// Galleon each LED takes a report of its own, so this sends /// `ledRingSteps` of them; a Studio takes a whole ring in one. pub fn setRingColor( self: *const Encoders, io: std.Io, encoder: u8, red: u8, green: u8, blue: u8, ) !void { const steps = self.ledRingSteps(); if (steps == 0) return error.Unsupported; if (encoder >= self.count()) return error.NoSuchEncoder; // A Studio takes a whole ring in one report, so a single colour is // just every entry of it the same. const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); if (sd.type == .ElgatoStreamDeckStudio) { var colors: [studio_ring_steps][3]u8 = undefined; @memset(&colors, .{ red, green, blue }); return self.setRingColors(io, encoder, &colors); } // A single colour needs no rotation -- every segment is the same -- // but it goes through `ledIndex` anyway so that there is one place // where the numbering is decided. for (0..steps) |segment| { try self.setRingLed(io, self.ledIndex(encoder, @intCast(segment)), red, green, blue); } } /// Light each LED of one encoder's ring separately, `colors` running /// round the ring from its segment zero. /// /// Segment 0 is at the **top** of the ring and they advance /// **clockwise**, so `colors` reads round the ring the way a clock does /// and a level can be drawn as a run from the start of the slice. Each /// model's own numbering is turned into that; both confirmed on /// hardware. /// /// `colors` has to hold exactly `ledRingSteps` entries, each a red, /// green and blue byte; anything else is `error.WrongNumberOfColors`. /// Otherwise as `setRingColor`, including that a ring does not keep /// what it is given. pub fn setRingColors( self: *const Encoders, io: std.Io, encoder: u8, colors: []const [3]u8, ) !void { const steps = self.ledRingSteps(); if (steps == 0) return error.Unsupported; if (encoder >= self.count()) return error.NoSuchEncoder; if (colors.len != steps) return error.WrongNumberOfColors; const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); if (sd.type == .ElgatoStreamDeckStudio) { var packet: [StreamDeck.MAX_PACKET_SIZE]u8 = undefined; _ = try sd.device.write(io, studioRingReport(&packet, encoder, colors)); return; } for (colors, 0..) |colour, segment| { try self.setRingLed( io, self.ledIndex(encoder, @intCast(segment)), colour[0], colour[1], colour[2], ); } } const studio_ring_steps = 24; /// A Studio's ring report: `02 0f ` and then a colour for each /// of its twenty-four LEDs, in one output report where a Galleon takes a /// feature report per LED. node-elgato-stream-deck sends the same. /// /// The device numbers each ring **clockwise**, and not from the top: on /// encoder 0 its LED 0 is one step clockwise of twelve o'clock, so the /// LED at the top is its 23, and encoder 1's ring is mounted a half /// turn round, so its top is 11 -- node's offset of twelve between /// them. Both were read off a Studio lit with LED 0 white and 1 to 3 /// green, and the step at the top from the same marker sent through /// this function, which first put white one LED clockwise of the top. /// `colors` arrives in this library's own order, segment 0 at the top /// running clockwise, the device's own direction, so each ring needs /// only turning. fn studioRingReport(packet: *[StreamDeck.MAX_PACKET_SIZE]u8, encoder: u8, colors: []const [3]u8) []const u8 { std.debug.assert(colors.len == studio_ring_steps); @memset(packet, 0); packet[0] = 0x02; packet[1] = 0x0f; packet[2] = encoder; // The device's LED at twelve o'clock. const start: usize = if (encoder == 0) studio_ring_steps - 1 else studio_ring_steps / 2 - 1; for (colors, 0..) |colour, segment| { const led = (start + segment) % studio_ring_steps; @memcpy(packet[3 + led * 3 ..][0..3], &colour); } return packet; } /// Whether an encoder has a light of its own, apart from any ring /// around it. /// /// Only the Studio's do: the top of each knob is ringed with an LED of /// a single colour, which `setColor` sets. pub fn hasLed(self: *const Encoders) bool { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); return sd.type == .ElgatoStreamDeckStudio; } /// Light an encoder's own LED -- on a Studio, the ring of light on top /// of the knob -- a single colour. /// /// The report is `02 10 r g b`, an output report, as /// node-elgato-stream-deck sends it. Confirmed against a Studio: /// encoder 0 is the left knob and 1 the right, and each takes the colour /// it is given. /// /// `error.Unsupported` on a model whose encoders have no such LED, and /// `error.NoSuchEncoder` if the device has no such encoder. pub fn setColor(self: *const Encoders, io: std.Io, encoder: u8, red: u8, green: u8, blue: u8) !void { if (!self.hasLed()) return error.Unsupported; if (encoder >= self.count()) return error.NoSuchEncoder; const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); var packet = std.mem.zeroes([StreamDeck.MAX_PACKET_SIZE]u8); packet[0] = 0x02; packet[1] = 0x10; packet[2] = encoder; packet[3] = red; packet[4] = green; packet[5] = blue; _ = try sd.device.write(io, &packet); } /// Whether an encoder is currently pressed in. pub const State = enum(u8) { up = 0, down = 1, }; /// The kind of encoder event, taken from the first byte of the encoder /// portion of an input report. pub const EventType = enum(u8) { push = 0, turn = 1, }; /// A single report of encoder activity. Both variants describe every /// encoder on the device at once rather than just the one that moved, /// so `states` always holds `count()` entries: for a `push` the up or /// down state of each encoder, and for a `turn` the number of detents /// each was rotated by, negative for counterclockwise. pub const Event = struct { timestamp: std.Io.Timestamp, event: union(EventType) { push: struct { states: []State, }, turn: struct { states: []i8, }, }, /// Parse the encoder portion of an input report, which `data` must /// point at: an event type, then one byte per encoder. Fails with /// `ReportError.ShortReport` if there is not even a type byte, and /// `ReportError.UnknownEventType` if that byte is not one this /// library knows. The caller owns the result and must release it /// with `deinit`. pub fn init(alloc: std.mem.Allocator, timestamp: std.Io.Timestamp, data: []const u8) !*Event { if (data.len < 1) return error.ShortReport; const event_type = std.enums.fromInt(EventType, data[0]) orelse return error.UnknownEventType; const self = try alloc.create(Event); errdefer alloc.destroy(self); self.* = .{ .timestamp = timestamp, .event = undefined, }; switch (event_type) { .push => { self.event = .{ .push = .{ .states = try alloc.alloc(State, data.len - 1), }, }; for (data[1..], 0..) |state, i| { // An unrecognised byte reads as `up`, for the same // reason it does in `Keys.Event.init`. self.event.push.states[i] = std.enums.fromInt(State, state) orelse .up; } }, .turn => { self.event = .{ .turn = .{ .states = try alloc.alloc(i8, data.len - 1), }, }; for (data[1..], 0..) |state, i| { self.event.turn.states[i] = @bitCast(state); } }, } return self; } /// Free the event and the states it holds. `alloc` must be the /// allocator the event was created with. pub fn deinit(self: *const Event, alloc: std.mem.Allocator) void { switch (self.event) { .push => |p| alloc.free(p.states), .turn => |t| alloc.free(t.states), } alloc.destroy(self); } }; /// A `StreamDeck` of the given model with nothing behind it; see the /// note on `Keys.testDeck`. fn testDeck(t: StreamDeck.Type) StreamDeck { return .{ .type = t, .device = .none }; } test count { // Only the two Plus models have encoders, and the read size is one // byte of the report body per encoder. var plus = testDeck(.ElgatoStreamDeckPlus); try std.testing.expectEqual(4, plus.encoders.count()); // An event type byte, and then one byte per encoder. try std.testing.expectEqual(5, plus.encoders.readSize()); var plus_xl = testDeck(.ElgatoStreamDeckPlusXL); try std.testing.expectEqual(6, plus_xl.encoders.count()); // A model with no encoders claims no room at all, rather than the // lone type byte of a report it can never send. var mk2 = testDeck(.ElgatoStreamDeckMK2); try std.testing.expectEqual(0, mk2.encoders.count()); try std.testing.expectEqual(0, mk2.encoders.readSize()); } test ledRingSteps { // Only the Galleon's encoders carry a ring, and it is four LEDs. var galleon = testDeck(.CorsairGalleonK100); try std.testing.expectEqual(4, galleon.encoders.ledRingSteps()); // The Plus has encoders and no rings, which is the case worth // stating: "has encoders" and "has encoder LEDs" are different // questions and this model answers them differently. var plus = testDeck(.ElgatoStreamDeckPlus); try std.testing.expectEqual(4, plus.encoders.count()); try std.testing.expectEqual(0, plus.encoders.ledRingSteps()); var mk2 = testDeck(.ElgatoStreamDeckMK2); try std.testing.expectEqual(0, mk2.encoders.ledRingSteps()); var studio = testDeck(.ElgatoStreamDeckStudio); try std.testing.expectEqual(24, studio.encoders.ledRingSteps()); try std.testing.expect(studio.encoders.hasLed()); try std.testing.expect(!galleon.encoders.hasLed()); } test "a Studio's rings are turned into this library's numbering" { // Segment 0 marked white and segments 1 to 3 green, as `probe // --studio-rings` marked the device's own LED 0 and 1 to 3. var colors: [studio_ring_steps][3]u8 = @splat(.{ 1, 1, 1 }); colors[0] = .{ 255, 255, 255 }; for (1..4) |i| colors[i] = .{ 0, 255, 0 }; var packet: [StreamDeck.MAX_PACKET_SIZE]u8 = undefined; // The left ring: the LED at the top is the device's 23, and it // counts clockwise as segments do, so segment 1 is its 0. const left = studioRingReport(&packet, 0, &colors); try std.testing.expectEqualSlices(u8, &.{ 0x02, 0x0f, 0x00 }, left[0..3]); try std.testing.expectEqualSlices(u8, &.{ 255, 255, 255 }, left[3 + 23 * 3 ..][0..3]); try std.testing.expectEqualSlices(u8, &.{ 0, 255, 0 }, left[3..6]); try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1 }, left[3 + 22 * 3 ..][0..3]); // The right ring, a half turn round: the top is its 11 and // segment 1 its 12. const right = studioRingReport(&packet, 1, &colors); try std.testing.expectEqual(0x01, right[2]); try std.testing.expectEqualSlices(u8, &.{ 255, 255, 255 }, right[3 + 11 * 3 ..][0..3]); try std.testing.expectEqualSlices(u8, &.{ 0, 255, 0 }, right[3 + 12 * 3 ..][0..3]); try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1 }, right[3 + 10 * 3 ..][0..3]); // Nothing past the twenty-four colours. for (right[3 + 24 * 3 ..]) |b| try std.testing.expectEqual(0, b); } test "an encoder ring's segments are numbered from the right-hand encoder" { // The whole table, because it is two surprises stacked on each // other and either one alone would light the wrong LED: the rings // run right to left, so the left encoder's four are 4..7, and each // ring's segment zero sits at a different angle, so the segments // within a ring are rotated as well. // // The rotations are the ones rust-elgato-streamdeck asserts, read // the other way round: it maps hardware segment to logical, and // this maps logical to the flat index. node-elgato-stream-deck // arrives at the same through a `ledRingOffset` of three and one. // Both number the result anticlockwise, and this library reverses // it to run clockwise, so segments 1 and 3 have traded places with // what those two assert. var galleon = testDeck(.CorsairGalleonK100); const e = &galleon.encoders; try std.testing.expectEqual(5, e.ledIndex(0, 0)); try std.testing.expectEqual(4, e.ledIndex(0, 1)); try std.testing.expectEqual(7, e.ledIndex(0, 2)); try std.testing.expectEqual(6, e.ledIndex(0, 3)); try std.testing.expectEqual(3, e.ledIndex(1, 0)); try std.testing.expectEqual(2, e.ledIndex(1, 1)); try std.testing.expectEqual(1, e.ledIndex(1, 2)); try std.testing.expectEqual(0, e.ledIndex(1, 3)); // Between them the two rings address all eight LEDs exactly once, // which is what says the rotations are a permutation rather than a // fudge that happens to fit the examples. var seen: [8]bool = @splat(false); for (0..2) |encoder| { for (0..4) |segment| { const index = e.ledIndex(@intCast(encoder), @intCast(segment)); try std.testing.expect(!seen[index]); seen[index] = true; } } for (seen) |s| try std.testing.expect(s); } test "a model with no encoder rings refuses to light one" { var plus = testDeck(.ElgatoStreamDeckPlus); try std.testing.expectError( error.Unsupported, plus.encoders.setRingColor(std.testing.io, 0, 255, 0, 0), ); // The model has rings but not that many encoders, which is a // different refusal and has to happen before anything is written. var galleon = testDeck(.CorsairGalleonK100); try std.testing.expectError( error.NoSuchEncoder, galleon.encoders.setRingColor(std.testing.io, 2, 255, 0, 0), ); try std.testing.expectError( error.WrongNumberOfColors, galleon.encoders.setRingColors(std.testing.io, 0, &.{.{ 255, 0, 0 }}), ); } test "a push report gives the state of every encoder" { const alloc = std.testing.allocator; const event = try Event.init(alloc, .{ .nanoseconds = 0 }, &.{ 0, 0, 1, 0, 0 }); defer event.deinit(alloc); try std.testing.expectEqualSlices( State, &.{ .up, .down, .up, .up }, event.event.push.states, ); } test "a turn report is signed, so counterclockwise is negative" { const alloc = std.testing.allocator; const event = try Event.init(alloc, .{ .nanoseconds = 0 }, &.{ 1, 1, 0xff, 0, 0x81 }); defer event.deinit(alloc); try std.testing.expectEqualSlices( i8, &.{ 1, -1, 0, -127 }, event.event.turn.states, ); } test "an unknown event type is refused rather than guessed at" { const alloc = std.testing.allocator; const saved = std.testing.log_level; std.testing.log_level = .err; defer std.testing.log_level = saved; try std.testing.expectError( error.UnknownEventType, Event.init(alloc, .{ .nanoseconds = 0 }, &.{ 0x7f, 0, 0 }), ); // And an empty report has no event type in it to read at all. try std.testing.expectError( error.ShortReport, Event.init(alloc, .{ .nanoseconds = 0 }, &.{}), ); } test "an encoder report cleans up after a failed allocation" { // Both variants: the event is created before the states are, so // either allocation failing has to leave nothing behind. inline for (.{ [_]u8{ 0, 0, 1, 0, 0 }, [_]u8{ 1, 1, 0xff, 0, 0x81 }, }) |report| { try std.testing.checkAllAllocationFailures(std.testing.allocator, struct { fn run(alloc: std.mem.Allocator) !void { const event = try Event.init(alloc, .{ .nanoseconds = 0 }, &report); defer event.deinit(alloc); } }.run, .{}); } } test { std.testing.refAllDecls(@This()); std.testing.refAllDecls(Event); }