diff --git a/midi/src/identity.rs b/midi/src/identity.rs index 651dc91..366e18f 100644 --- a/midi/src/identity.rs +++ b/midi/src/identity.rs @@ -80,7 +80,7 @@ pub fn resolve_port( } fn model_matches(expected: &DeviceMatch, port: &PortIdentity) -> bool { - if port.name != expected.port_name { + if stable_port_name(&port.name) != stable_port_name(&expected.port_name) { return false; } match (&expected.vendor_id, &expected.product_id) { @@ -93,6 +93,24 @@ fn model_matches(expected: &DeviceMatch, port: &PortIdentity) -> bool { } } +fn stable_port_name(name: &str) -> &str { + let Some((prefix, suffix)) = name.rsplit_once(' ') else { + return name; + }; + let Some((client, port)) = suffix.split_once(':') else { + return name; + }; + if !client.is_empty() + && !port.is_empty() + && client.bytes().all(|byte| byte.is_ascii_digit()) + && port.bytes().all(|byte| byte.is_ascii_digit()) + { + prefix + } else { + name + } +} + fn candidates_matching( candidates: &[usize], ports: &[PortIdentity], diff --git a/midi/tests/identity.rs b/midi/tests/identity.rs index 362be23..0ca3e78 100644 --- a/midi/tests/identity.rs +++ b/midi/tests/identity.rs @@ -112,3 +112,32 @@ fn a_unique_virtual_port_can_fall_back_to_its_name() { } ); } + +#[test] +fn alsa_numeric_suffix_does_not_defeat_stable_usb_identity() { + let actual = PortIdentity { + backend_id: "36:0".into(), + name: "APC MINI:APC MINI MIDI 1 36:0".into(), + usb: Some(UsbDeviceIdentity { + vendor_id: "09e8".into(), + product_id: "0028".into(), + serial: Some("Ver00.10".into()), + path: Some("pci-usb-1".into()), + }), + }; + let hints = DeviceMatch { + port_name: "APC MINI:APC MINI MIDI 1".into(), + vendor_id: Some("09e8".into()), + product_id: Some("0028".into()), + serial: Some("Ver00.10".into()), + path: None, + }; + + assert_eq!( + resolve_port(&hints, &[actual], None), + PortResolution::Matched { + index: 0, + basis: MatchBasis::Serial, + } + ); +}