Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
# Changelog

## [Unreleased]

### Added
- Multiple hardware on-board profile slots (1–5) on supported mice without Razer Synapse:
list, create, switch, and delete slots (`05:80`, `05:81`, `05:02`, `05:03`, `05:04`/`05:84`,
`05:08`/`05:88`) from `secbird slot` / `secbird button save-to-mouse --slot N` and from
"Saved on the mouse" in the editor, with independent per-slot backups.
- Command line: `-v` / `--verbose` (or `SECBIRD_TRACE=1`) prints Protocol 2.5 requests and
replies to stderr for diagnosing device issues; serial replies are redacted.

### Fixed
- Naga V3 Pro (Wireless, `00E8`): uses interface 3 and standard polling (`00:85`), matching
its device report (`00:C0` returns `NotSupported`, #91).
- Button remapping and "Save to mouse": reads and writes now require replies to echo the
requested `[slot, button]` bytes (avoiding stale replies on wireless receivers while
accepting the Naga V3 Pro's `args[2]` reply byte), and on-board slot writes (`02:0C`)
are read back and retried up to 3 times, returning an error if the device doesn't keep
the assignment.

## [0.6.1] - 2026-11-21

### Added
Expand Down
2 changes: 1 addition & 1 deletion crates/secbird-core/devices.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@
{"pid":"00E3","name":"Basilisk V4 Pro (Wireless)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"underglow","id":10}],"wireless":true,"source":"Synapse DualDongleCompatibleDevices.json (pairs with the Mouse Dock Pro); DPI max not confirmed; LEDs 1 and 4 from #16, 8K polling from #16, underglow 10 from #54"},
{"pid":"00E6","name":"Viper V4 Pro","kind":"mouse","interface":3,"txid":"1F","dpi":{"min":100,"max":35000,"step":50},"polling":"high","wireless":true,"source":"user report (#36): txid 1F on interface 3, battery, HyperPolling 00:C0, no LEDs; DPI max not confirmed"},
{"pid":"00E7","name":"Naga V3 Pro (Wired)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"side","id":5}],"wireless":true,"source":"Synapse DualDongleCompatibleDevices.json (pairs with the Mouse Dock Pro); DPI max not confirmed; scroll LED 1 seen in 0F:84 (#26); side plate LED 5 from #26"},
{"pid":"00E8","name":"Naga V3 Pro (Wireless)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"side","id":5}],"wireless":true,"source":"Synapse DualDongleCompatibleDevices.json (pairs with the Mouse Dock Pro); DPI max not confirmed; scroll LED 1 seen in 0F:84 (#26); side plate LED 5 from #26"},
{"pid":"00E8","name":"Naga V3 Pro (Wireless)","kind":"mouse","interface":3,"txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"standard","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"side","id":5}],"wireless":true,"source":"user report (#91): interface 3, txid 1F, 00:85 standard polling (00:C0 NotSupported), LEDs 1/4/5, battery; pairs with Mouse Dock Pro (#26); DPI max not confirmed"},
{"pid":"00EA","name":"Basilisk V4 HyperSpeed (Wireless)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"standard","lighting":"extended","leds":[{"name":"underglow","id":10}],"unsupported_effects":["reactive","starlight"],"wireless":true,"source":"Razer product specification: single underglow zone; user 2.4 GHz report: LED 10 on 00EA; 00EB layout mirrors same physical mouse; DPI max not confirmed"},
{"pid":"00EB","name":"Basilisk V4 HyperSpeed (Wired)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"standard","lighting":"extended","leds":[{"name":"underglow","id":10}],"unsupported_effects":["reactive","starlight"],"wireless":true,"source":"Razer product specification: single underglow zone; user 2.4 GHz report: LED 10 on 00EA; 00EB layout mirrors same physical mouse; DPI max not confirmed"},
{"pid":"00F1","name":"Mouse on Mouse Dock V2 Pro","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1}],"wireless":true,"source":"user reports (#61, #72): works like the Mouse Dock Pro; answers the docked mouse at txid 1F (00:BF lists it, 00:C0 polling) and its own light, LED 15, at txid FF"},
Expand Down
64 changes: 49 additions & 15 deletions crates/secbird-core/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,9 @@ fn keeps_a_left_click(dev: &Device, id: u8, layer: crate::buttons::Layer, action
/// again. A "Save to mouse" is put back first, so this is a full way back. Returns how many
/// buttons were restored.
pub fn restore_all_buttons(dev: &Device, store: &mut Store) -> Result<usize> {
if store.for_device(dev).onboard.is_some() {
put_back_onboard(dev, store)?;
let saves = store.for_device(dev).all_onboard_saves();
for save in saves {
put_back_slot(dev, store, save.slot)?;
}
let keys: Vec<String> = store.for_device(dev).active().buttons.keys().cloned().collect();
let mut restored = 0;
Expand All @@ -288,20 +289,37 @@ pub fn restore_all_buttons(dev: &Device, store: &mut Store) -> Result<usize> {
}

/// "Save to mouse": the active profile's button remaps go into the mouse's active on-board
/// slot, so they work without Secretarybird. What each button held there before is kept
/// first (once, so it stays Synapse's or the factory setting), and buttons an earlier save
/// wrote that this profile doesn't remap go back to it. Returns the slot written.
/// slot, so they work without Secretarybird. Returns the slot written.
pub fn save_buttons_to_mouse(dev: &Device, store: &mut Store) -> Result<u8> {
save_buttons_to_slot(dev, store, dev.saved_slot())
}

/// Write the active profile's button remaps into on-board slot `slot` (1-5), creating the
/// slot first if the mouse doesn't have it yet. What each button held there before is kept
/// first (once, so it stays Synapse's or the factory setting), and buttons an earlier save
/// wrote to that same slot that this profile doesn't remap go back to it. Other slots are
/// left untouched. Returns the slot written.
pub fn save_buttons_to_slot(dev: &Device, store: &mut Store, slot: u8) -> Result<u8> {
if dev.buttons().is_empty() {
return Err(crate::error::Error::Unsupported(format!("{} keeps no button settings on board", dev.name())));
}
let slot = dev.saved_slot();
if store.for_device(dev).onboard.as_ref().is_some_and(|o| o.slot != slot) {
put_back_onboard(dev, store)?;
let max = dev.max_onboard_slots();
if !(1..=max).contains(&slot) {
return Err(crate::error::Error::InvalidArg(format!("on-board slot {slot}: use 1 to {max}")));
}
let profile_name = store.for_device(dev).active.clone();
// Create the hardware slot if the device reports a slot list and doesn't have it yet;
// otherwise update its 250-byte header name (best-effort).
if let Ok(ids) = dev.onboard_slot_ids() {
if !ids.contains(&slot) {
dev.create_onboard_slot(slot, Some(&profile_name))?;
} else {
let _ = dev.set_onboard_slot_name(slot, &profile_name);
}
}
let profiles = store.for_device(dev);
let want = profiles.active().buttons.clone();
let mut save = profiles.onboard.clone().unwrap_or_default();
let mut save = profiles.onboard_save(slot).cloned().unwrap_or_default();
// The backup goes to disk before anything is written to the mouse.
for key in want.keys() {
if !save.before.contains_key(key) {
Expand All @@ -310,7 +328,7 @@ pub fn save_buttons_to_mouse(dev: &Device, store: &mut Store) -> Result<u8> {
}
}
save.slot = slot;
profiles.onboard = Some(save.clone());
profiles.set_onboard_save(save.clone());
store.save()?;

for (key, original) in save.before.iter().filter(|(k, _)| !want.contains_key(*k)) {
Expand All @@ -325,20 +343,36 @@ pub fn save_buttons_to_mouse(dev: &Device, store: &mut Store) -> Result<u8> {
save.before.retain(|k, _| want.contains_key(k));
save.profile = profiles.active.clone();
save.buttons = want;
profiles.onboard = Some(save);
profiles.set_onboard_save(save);
store.save()?;
Ok(slot)
}

/// Undo "Save to mouse": the on-board slot gets back what it held before. The live remaps
/// stay as they are. Returns how many buttons were put back.
/// Undo "Save to mouse" for the active (or last saved) slot. The live remaps stay as they are.
/// Returns how many buttons were put back.
pub fn put_back_onboard(dev: &Device, store: &mut Store) -> Result<usize> {
let Some(save) = store.for_device(dev).onboard.clone() else { return Ok(0) };
let slot = {
let p = store.for_device(dev);
let active = dev.saved_slot();
if p.onboard_save(active).is_some() {
active
} else if let Some(o) = &p.onboard {
o.slot
} else {
return Ok(0);
}
};
put_back_slot(dev, store, slot)
}

/// Undo "Save to mouse" for a specific on-board slot (1-5). Returns how many buttons were put back.
pub fn put_back_slot(dev: &Device, store: &mut Store, slot: u8) -> Result<usize> {
let Some(save) = store.for_device(dev).onboard_save(slot).cloned() else { return Ok(0) };
for (key, original) in &save.before {
let (input, layer) = crate::buttons::parse_setting_key(key)?;
dev.set_slot_input(save.slot, input, layer, original.parse()?)?;
}
store.for_device(dev).onboard = None;
store.for_device(dev).remove_onboard_save(slot);
store.save()?;
Ok(save.before.len())
}
Expand Down
40 changes: 29 additions & 11 deletions crates/secbird-core/src/buttons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,9 @@ impl FromStr for Action {
impl Device {
fn read_input(&self, slot: u8, input: Input, layer: Layer) -> Result<Action> {
let (command, size, id) = input.command();
let r = self.get(command, size, &[slot, id, layer as u8])?;
// Echo-match [slot, id] only: the Naga V3 Pro (00E8) does not always echo the
// layer byte in args[2] of 02:8C replies (observed on hardware).
let r = self.get_echo(command, size, &[slot, id, layer as u8], 2)?;
let a = r.args();
Ok(Action::decode(a[3], [a[5], a[6], a[7], a[8], a[9]]))
}
Expand All @@ -748,14 +750,15 @@ impl Device {
/// Set a button or key in the live slot. Returns whether anything was sent: an
/// unchanged one is left alone.
pub fn set_input(&self, input: Input, layer: Layer, action: Action) -> Result<bool> {
if self.input(input, layer).ok() == Some(action) {
return Ok(false);
}
let (command, size, id) = input.command();
let (function, data_size, data) = action.encode();
let expected = Action::decode(function, data);
if self.input(input, layer).ok() == Some(expected) {
return Ok(false);
}
let mut args = vec![cmd::BUTTON_LIVE_SLOT, id, layer as u8, function, data_size];
args.extend_from_slice(&data);
self.transact(command, size, &args)?;
self.transact_echo(command, size, &args, 2)?;
Ok(true)
}

Expand All @@ -766,20 +769,35 @@ impl Device {

/// Write a button or key into on-board slot `slot` (1-5), which the device keeps
/// without any software ("Save to mouse"). A flash write: only on request, never on a
/// profile switch.
/// profile switch. Reads back to verify, retrying if the flash write didn't stick.
pub fn set_slot_input(&self, slot: u8, input: Input, layer: Layer, action: Action) -> Result<()> {
if !(1..=5).contains(&slot) {
return Err(Error::InvalidArg(format!("on-board slot {slot}: use 1 to 5")));
}
if self.slot_input(slot, input, layer).ok() == Some(action) {
return Ok(());
}
let (command, size, id) = input.command();
let (function, data_size, data) = action.encode();
let expected = Action::decode(function, data);
if self.slot_input(slot, input, layer).ok() == Some(expected) {
return Ok(());
}
let mut args = vec![slot, id, layer as u8, function, data_size];
args.extend_from_slice(&data);
self.transact_slow(command, size, &args)?;
Ok(())
// Flash writes can acknowledge without persisting (as seen on macro writes) or
// receive a stale reply on wireless receivers; echo-match and read back to verify.
let mut got = None;
for _ in 0..3 {
self.transact_slow_echo(command, size, &args, 2)?;
let back = self.slot_input(slot, input, layer)?;
if back == expected {
return Ok(());
}
got = Some(back);
}
Err(Error::Unsupported(format!(
"the device didn't keep {} in on-board slot {slot} (wrote {expected}, read {})",
input.name(),
got.map_or_else(|| "nothing".into(), |a| a.to_string()),
)))
}

/// Put a button or key back to its saved-slot setting.
Expand Down
26 changes: 25 additions & 1 deletion crates/secbird-core/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,32 @@ pub const SCROLL_SIZE: u8 = 0x02;
/// Button slot 0 is live and unsaved, and wins over the saved profile slots 1-5.
/// Verified (Basilisk V3): a remap in slot 0 took effect while slot 1 was active.
pub const BUTTON_LIVE_SLOT: u8 = 0x00;
/// Active saved on-board profile slot: `[slot]`. GET verified (Basilisk V3: 1 of 5).
/// Maximum number of hardware on-board profile slots on Razer mice.
pub const MAX_ONBOARD_SLOTS: u8 = 5;
/// On-board profile slots (class 05, from Synapse 4's `obmEngine` / `rzDevice25`).
/// Number of saved on-board profiles: GET only, `[count]`.
pub const PROFILE_COUNT: Command = Command::new(0x05, 0x00);
pub const PROFILE_COUNT_SIZE: u8 = 0x01;
/// Saved on-board profile slot ids: GET only, `[total, id1, id2, ...]`.
pub const PROFILE_IDS: Command = Command::new(0x05, 0x01);
pub const PROFILE_IDS_SIZE: u8 = 0x50;
/// Create a new on-board profile slot: SET `[slot]` (1-5).
pub const PROFILE_CREATE: Command = Command::new(0x05, 0x02);
/// Delete an on-board profile slot: SET `[slot]` (1-5).
pub const PROFILE_DELETE: Command = Command::new(0x05, 0x03);
/// Active saved on-board profile slot: `[slot]` (1-5). GET verified (Basilisk V3, Naga V3 Pro).
pub const ACTIVE_SLOT: Command = Command::new(0x05, 0x04);
pub const PROFILE_SLOT_SIZE: u8 = 0x01;
/// 250-byte on-board profile header (16-byte guid, 100-byte UTF-8 name, 128-byte owner,
/// 6-byte hash): `[slot, offset u16, total_size u16, data...]`, at most 64 data bytes per report.
pub const PROFILE_NAME: Command = Command::new(0x05, 0x08);
pub const PROFILE_NAME_CHUNK: usize = 64;
pub const PROFILE_HEADER_LEN: usize = 250;
/// Reset an on-board profile slot to factory defaults: SET `[slot]` (1-5).
pub const PROFILE_RESET: Command = Command::new(0x05, 0x0B);
/// Indicator LED color of an on-board profile slot: `[slot, r, g, b]`.
pub const PROFILE_COLOR: Command = Command::new(0x05, 0x0C);
pub const PROFILE_COLOR_SIZE: u8 = 0x04;

/// Polling rate code (sent to the device) for a rate in Hz.
pub fn polling_code(hz: u32) -> Option<u8> {
Expand Down
12 changes: 12 additions & 0 deletions crates/secbird-core/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,18 @@ mod tests {
}
}

#[test]
fn naga_v3_pro_wireless_matches_report() {
let db = Db::builtin().unwrap();
let spec = db.get(0x00E8).expect("Naga V3 Pro (Wireless)");
assert_eq!(spec.interface, Some(3));
assert_eq!(spec.txid, Some(0x1F));
assert_eq!(spec.polling, Some(Polling::Standard));
assert!(spec.wireless);
let led_ids: Vec<u8> = spec.leds.iter().map(|l| l.id).collect();
assert_eq!(led_ids, [4, 1, 5]);
}

#[test]
fn builtin_entries_are_sane() {
let text = BUILTIN;
Expand Down
55 changes: 55 additions & 0 deletions crates/secbird-core/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,34 @@ use hidapi::HidApi;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::ffi::CString;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
use std::thread::sleep;

static TRACE: AtomicBool = AtomicBool::new(false);
static TRACE_ENV: OnceLock<bool> = OnceLock::new();

/// Log every Protocol 2.5 request and reply to stderr (serial replies are redacted).
/// Also enabled when `SECBIRD_TRACE` is set to a non-empty value other than `0`.
pub fn set_trace(enabled: bool) {
TRACE.store(enabled, Ordering::Relaxed);
}

fn trace_enabled() -> bool {
TRACE.load(Ordering::Relaxed)
|| *TRACE_ENV.get_or_init(|| {
std::env::var("SECBIRD_TRACE").is_ok_and(|v| !v.is_empty() && v != "0")
})
}

fn trace_reply(rep: &Report, note: &str) {
if rep.command() == cmd::SERIAL.get() && rep.status() == Status::Success {
eprintln!("[trace] <- Report[Success tx={:02X} cmd=00:82 <redacted>]{note}", rep.txid());
} else {
eprintln!("[trace] <- {rep:?}{note}");
}
}

/// Synapse retries reads up to 30 times (5 ms apart, see [`Transport::read_delay`]).
const READ_RETRIES: u32 = 30;

Expand Down Expand Up @@ -191,6 +217,19 @@ impl Device {
transact(self.transport.as_ref(), self.txid, command, size, args, FLASH_RETRIES, false, &[])
}

/// [`Device::transact_slow`] that only takes a reply echoing `args[..echo]`.
pub(crate) fn transact_slow_echo(&self, command: Command, size: u8, args: &[u8], echo: usize) -> Result<Report> {
let echo = &args[..echo.min(args.len())];
let mut result = Err(Error::NoReply(command));
for _ in 0..ECHO_SENDS {
result = transact(self.transport.as_ref(), self.txid, command, size, args, FLASH_RETRIES, false, echo);
if !matches!(result, Err(Error::NoReply(_))) {
break;
}
}
result
}

/// [`Device::transact`] with another transaction id (see [`DOCK_TXID`]).
pub fn transact_as(&self, txid: u8, command: Command, size: u8, args: &[u8]) -> Result<Report> {
transact(self.transport.as_ref(), txid, command, size, args, READ_RETRIES, true, &[])
Expand Down Expand Up @@ -273,6 +312,10 @@ fn transact(
echo: &[u8],
) -> Result<Report> {
let req = Report::request(txid, command, size, args);
let tracing = trace_enabled();
if tracing {
eprintln!("[trace] -> {req:?}");
}
let mut buf = [0u8; REPORT_LEN + 1]; // byte 0 is the HID report id (0)
buf[1..].copy_from_slice(&req.0);
hid.send_feature_report(&buf)?;
Expand All @@ -288,21 +331,33 @@ fn transact(
body.copy_from_slice(&reply[n - REPORT_LEN..n]);
let rep = Report(body);
if rep.command() != command || (exact && rep.txid() != txid) {
if tracing {
trace_reply(&rep, " (ignored: command/txid mismatch)");
}
continue;
}
// The echo check only sorts out successful replies meant for another request. A
// refusal ends the wait as it is: it need not repeat the arguments, and skipping it
// would turn "not supported" into a slow "no reply" after every resend.
let status = rep.status();
if !rep.args().starts_with(echo) && matches!(status, Status::Success | Status::Busy | Status::New) {
if tracing {
trace_reply(&rep, " (ignored: echo mismatch)");
}
continue;
}
if tracing {
trace_reply(&rep, "");
}
match status {
Status::Success => return Ok(rep),
Status::Busy | Status::New => continue,
status => return Err(Error::Device { cmd: command, status }),
}
}
if tracing {
eprintln!("[trace] <- no reply for {command}");
}
Err(Error::NoReply(command))
}

Expand Down
1 change: 1 addition & 0 deletions crates/secbird-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub mod laptop;
pub mod log;
pub mod macros;
pub mod net;
pub mod onboard;
pub mod profile;
pub mod proto;
pub mod report;
Expand Down
Loading