// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT const std = @import("std"); const streamdeck = @import("streamdeck"); const log = std.log.scoped(.example); pub fn main(init: std.process.Init) !void { const io = init.io; const alloc = init.gpa; try streamdeck.init(); defer streamdeck.deinit(); var group: std.Io.Group = .init; defer group.cancel(io); // Any addresses on the command line are networked decks -- a // Studio, or a Network Dock -- which enumeration will never find, // because they are somewhere on a network rather than plugged into // this machine. Written `1.2.3.4:5343`, or with the port left off // to take the default. var args = init.minimal.args.iterate(); // The first argument is this program's own name. _ = args.next(); while (args.next()) |arg| { const address = parseAddress(arg) catch |err| { log.warn("{s}: not an address: {t}", .{ arg, err }); continue; }; const deck = streamdeck.connect(io, alloc, address) catch |err| { log.warn("{s}: {t}", .{ arg, err }); continue; }; // A networked deck was not enumerated, so nothing described it // beforehand; the empty info says so rather than inventing one. try group.concurrent(io, sd_handler, .{ io, alloc, streamdeck.StreamDeckInfo{ .deck = deck, .info = .empty }, }); } var decks: streamdeck.Enumerator = undefined; try decks.init(io, alloc); defer decks.deinit(io, alloc); while (try decks.next(io, alloc)) |found| { try group.concurrent(io, sd_handler, .{ io, alloc, found }); } try group.await(io); } /// An address with an optional port, defaulting to the one these /// devices 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; fall through and supply the // default instead. if (port != 0) return address; } else |_| {} return std.Io.net.IpAddress.parse(text, streamdeck.Tcp.default_port); } pub fn sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.StreamDeckInfo) error{Canceled}!void { _sd_handler(io, alloc, info) catch |err| { log.warn("error: {t}", .{err}); }; } pub fn _sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.StreamDeckInfo) !void { defer info.deinit(io, alloc); const sd = info.deck; { var buf: [1024]u8 = undefined; const locked_stderr = std.debug.lockStderr(&buf); defer std.debug.unlockStderr(); const stderr = &locked_stderr.file_writer.interface; // The library no longer prints any of this itself, so what a // caller wants to know about a device it asks for and prints. try stderr.print("model : {t}\n", .{sd.type}); try stderr.print("transport : {t}\n", .{sd.device.kind()}); // What the system said about the device when it was found. // This comes from the enumeration rather than from the open // device, which answers less: on Linux the device does not // report a manufacturer at all. A deck reached over the network // was never enumerated and has none of it. if (info.info.product.slice()) |product| { try stderr.print("product : {s}\n", .{product}); } if (info.info.manufacturer.slice()) |manufacturer| { try stderr.print("manufacturer : {s}\n", .{manufacturer}); } if (info.info.physical_location.slice()) |where| { try stderr.print("location : {s}\n", .{where}); } try stderr.print("bus : {t}\n", .{info.info.bus_type}); var serial_buffer: [32]u8 = undefined; const serial = try sd.getSerialNumber(io, &serial_buffer); try stderr.print("serial : {s}\n", .{serial}); var version_buffer: [32]u8 = undefined; const version = try sd.getFirmwareVersion(io, &version_buffer); try stderr.print("firmware version: {s}\n", .{version}); // Zero means the device never blanks itself, which is what a // program driving the keys usually wants -- so say what it is // rather than changing it behind the user's back. if (sd.getSleepTimeout(io)) |seconds| { if (seconds == 0) { try stderr.print("sleep timeout : disabled\n", .{}); } else { try stderr.print("sleep timeout : {d}s\n", .{seconds}); } } else |err| { try stderr.print("sleep timeout : {t}\n", .{err}); } } { var serial_buffer: [32]u8 = undefined; const serial = try sd.getSerialNumber(io, &serial_buffer); // Resetting has no known encoding over the network, so a // networked deck is left as it is rather than refusing to run. sd.reset(io) catch |err| switch (err) { error.Unsupported => {}, else => return err, }; try sd.resetKeyStream(io); try sd.setBrightness(io, 50); // Every key says which key it is, so that a key landing in the // wrong place or the wrong way up is obvious at a glance. for (0..sd.keys.count()) |i| { try showKey(io, alloc, &sd, @intCast(i), .yellow_on_black); } // And the screen, on a model that has one, is blanked so that // the manufacturer's logo is not left sitting there looking // like something this program put up. try clearScreen(io, alloc, &sd); // A key report describes every key at once rather than just the // one that moved, so the previous states are what say which one // actually changed and therefore which key to redraw. const previous = try alloc.alloc(streamdeck.Keys.State, sd.keys.count()); defer alloc.free(previous); @memset(previous, .up); while (true) { // Tell the device the host is still here, on every pass // round the loop. Only the Galleon needs this -- it leaves // Stream Deck mode about two seconds after the last write, // taking the panel and the meaning of its input reports // with it -- and `keepAlive` does nothing at all on every // other model, so there is no need to ask which one this // is. Losing the device is silent when it happens: the // reports keep coming and every one of them stops parsing. sd.keepAlive(io) catch |err| { log.warn("{s} keepAlive: {t}", .{ serial, err }); }; // A timed read rather than a blocking one, because the // above has to happen and a program parked in a blocking // read never gets to. Half a second is comfortably inside // the Galleon's two, and on every other model it costs // nothing but going round this loop when nothing happened. const maybe = sd.events.readTimeout(io, alloc, .{ .duration = .{ .raw = .fromMilliseconds(500), .clock = .awake }, }) catch |err| switch (err) { error.ShortReport, error.UnknownReportType, error.UnknownControlType, error.UnknownEventType, => { // A report the library will not parse says // something about the device, or about this // library's tables for it, and is worth saying out // loud -- but it is not a reason to stop listening. // Deciding that is the application's job, which is // why the library reports these rather than logging // them itself. log.warn("{s} ignoring report: {t}", .{ serial, err }); continue; }, // Anything else means the deck is no longer reachable // -- unplugged, or a connection that has dropped -- // which is the end of this device rather than a report // to skip. Before `read` reported these, the loop spun // here forever. else => { log.warn("{s} disconnected: {t}", .{ serial, err }); return; }, }; // Nothing said anything in that half second, which is not a // failure -- it is what the timeout was asked for. const event = maybe orelse continue; defer event.deinit(alloc); switch (event) { .keys => |e| { log.info("{s} {any}", .{ serial, e.event }); for (e.event.push.states, 0..) |state, i| { if (i >= previous.len) break; if (state == previous[i]) continue; previous[i] = state; try showKey(io, alloc, &sd, @intCast(i), switch (state) { .up => .yellow_on_black, .down => .black_on_yellow, }); // The screen echoes whichever key went down, so // that pressing a key checks the key path and // the screen path against each other in one go: // the same figure has to appear in both places. if (state == .down) { try showOnScreen(io, alloc, &sd, @intCast(i)); } } }, .encoders => |e| log.info("{s} {any}", .{ serial, e.event }), .touchscreen => |e| log.info("{s} {any}", .{ serial, e.event }), } } } } /// Blank the device's screen. Does nothing on a device without one. fn clearScreen(io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck) !void { var blank = try sd.touchscreen.blankImage(alloc) orelse return; defer blank.deinit(alloc); try sd.touchscreen.setImage(io, alloc, 0, 0, blank); } /// Put `index` on the device's screen, in the figures the keys use. /// Does nothing on a device without a screen. /// /// The whole screen is redrawn rather than the part the figures occupy, /// because the Neo's strip is the screen this was written for and it /// takes nothing else -- its header carries no rectangle, so /// `Touchscreen.setImage` refuses a partial write. fn showOnScreen( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, index: u8, ) !void { const feature = sd.touchscreen.getFeature() orelse return; var surface = try streamdeck.diagnostic.keyIndexImage( alloc, feature.width, feature.height, index, .yellow_on_black, ); defer surface.deinit(alloc); try sd.touchscreen.setImage(io, alloc, 0, 0, surface); } /// Show one key in the given polarity: its own index if the key has a /// display, or the matching backlight color if it is one of the touch /// keys that takes a color instead of an image. Does nothing for a key /// that can show neither, as every key on the Pedal. fn showKey( io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck, key: u8, polarity: streamdeck.diagnostic.Polarity, ) !void { if (try sd.keys.indexImage(alloc, key, polarity)) |image| { var owned = image; defer owned.deinit(alloc); try sd.keys.setImage(io, alloc, key, owned); return; } const feature = sd.keys.getFeature(key) orelse return; if (feature != .touchled) return; // A touch key has no display to draw figures on, so it takes the // color the figures would have been: lit at rest and dark while it // is held down. const ink = polarity.foregroundRgb(); try sd.keys.setTouchKeyColor(io, key, ink.r, ink.g, ink.b); }