moteus 0.5.4

Rust client library for moteus brushless motor controllers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Copyright 2026 mjbots Robotic Systems, LLC.  info@mjbots.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Async transport factory system for creating async CAN-FD transports.
//!
//! This module provides the factory pattern for creating async transport devices
//! from different backends (fdcanusb, socketcan, etc.) using tokio.
//!
//! External crates can register additional async factories via [`register_async()`].

use std::sync::{Arc, Mutex, OnceLock};

use crate::error::{Error, Result};
use crate::transport::args::ArgSpec;
use crate::transport::async_transport::BoxFuture;
use crate::transport::device::AsyncTransportDevice;

/// Options for configuring async transport creation.
///
/// This is the same type as [`super::factory::TransportOptions`], re-exported
/// for convenience in async contexts.
pub use super::factory::TransportOptions as AsyncTransportOptions;

/// A factory for creating async transport devices.
///
/// Factories are tried in priority order (lower numbers first).
/// External crates implement this trait and call [`register_async()`] to
/// add themselves to the async auto-detection flow.
pub trait AsyncTransportFactory: Send + Sync {
    /// The priority of this factory (lower = tried first).
    fn priority(&self) -> u32;

    /// The name of this transport type.
    fn name(&self) -> &'static str;

    /// Command-line argument specifications for this factory.
    ///
    /// Override this to declare factory-specific CLI arguments.
    fn arg_specs(&self) -> Vec<ArgSpec> {
        Vec::new()
    }

    /// Create async transport devices using this factory.
    ///
    /// Returns a future that resolves to a list of devices.
    fn create<'a>(
        &'a self,
        options: &'a AsyncTransportOptions,
    ) -> BoxFuture<'a, Result<Vec<Box<dyn AsyncTransportDevice>>>>;
}

/// Factory for async fdcanusb devices.
#[derive(Debug, Default)]
pub struct AsyncFdcanusbFactory;

impl AsyncFdcanusbFactory {
    /// Create a new async fdcanusb factory.
    pub fn new() -> Self {
        Self
    }
}

impl AsyncTransportFactory for AsyncFdcanusbFactory {
    fn priority(&self) -> u32 {
        10 // Higher priority than socketcan
    }

    fn name(&self) -> &'static str {
        "fdcanusb"
    }

    fn arg_specs(&self) -> Vec<ArgSpec> {
        use crate::transport::args::ArgType;
        vec![
            ArgSpec {
                name: "fdcanusb",
                help: "Path to fdcanusb device (can be specified multiple times)",
                arg_type: ArgType::MultiString,
                default: None,
                possible_values: None,
            },
            ArgSpec {
                name: "fdcanusb-baudrate",
                help: "Serial baud rate (only matters for UART connections)",
                arg_type: ArgType::Integer,
                default: None,
                possible_values: None,
            },
        ]
    }

    fn create<'a>(
        &'a self,
        options: &'a AsyncTransportOptions,
    ) -> BoxFuture<'a, Result<Vec<Box<dyn AsyncTransportDevice>>>> {
        Box::pin(async move {
            use crate::transport::async_fdcanusb::AsyncFdcanusbDevice;
            use crate::transport::device::TransportDeviceInfo;
            use crate::transport::discovery::{detect_fdcanusbs, FdcanusbInfo};
            use crate::transport::fdcanusb::FdcanusbOptions;

            let explicit_paths = !options.fdcanusb_paths.is_empty();

            let infos: Vec<FdcanusbInfo> = if explicit_paths {
                options
                    .fdcanusb_paths
                    .iter()
                    .map(|path| FdcanusbInfo {
                        path: path.clone(),
                        serial_number: None,
                    })
                    .collect()
            } else {
                detect_fdcanusbs()
            };

            let mut device_options = FdcanusbOptions::new()
                .timeout(options.timeout)
                .disable_brs(options.disable_brs);
            if let Some(baudrate) = options.fdcanusb_baudrate {
                device_options = device_options.baudrate(baudrate);
            }
            // Auto-detected devices are fdcanusbs by construction.
            // Explicitly specified paths may instead be a moteus
            // connected directly over UART, so leave UART
            // auto-detection enabled for them.
            if !explicit_paths {
                device_options = device_options.uart_mode(false);
            }

            let mut devices: Vec<Box<dyn AsyncTransportDevice>> = Vec::new();
            for (idx, info) in infos.iter().enumerate() {
                match AsyncFdcanusbDevice::open_with(&info.path, &device_options).await {
                    Ok(mut device) => {
                        // Update device info
                        let mut dev_info = TransportDeviceInfo::new(idx, "AsyncFdcanusb");
                        if let Some(ref sn) = info.serial_number {
                            dev_info.detail = Some(format!("sn='{}'", sn));
                            dev_info.serial_number = Some(sn.clone());
                        }
                        device.info = dev_info;
                        devices.push(Box::new(device));
                    }
                    Err(_) => continue,
                }
            }

            Ok(devices)
        })
    }
}

/// Factory for async socketcan devices (Linux only).
#[cfg(target_os = "linux")]
#[derive(Debug, Default)]
pub struct AsyncSocketCanFactory;

#[cfg(target_os = "linux")]
impl AsyncSocketCanFactory {
    /// Create a new async socketcan factory.
    pub fn new() -> Self {
        Self
    }
}

#[cfg(target_os = "linux")]
impl AsyncTransportFactory for AsyncSocketCanFactory {
    fn priority(&self) -> u32 {
        11 // Lower priority than fdcanusb
    }

    fn name(&self) -> &'static str {
        "socketcan"
    }

    fn arg_specs(&self) -> Vec<ArgSpec> {
        use crate::transport::args::ArgType;
        vec![ArgSpec {
            name: "can-chan",
            help: "SocketCAN interface (can be specified multiple times)",
            arg_type: ArgType::MultiString,
            default: None,
            possible_values: None,
        }]
    }

    fn create<'a>(
        &'a self,
        options: &'a AsyncTransportOptions,
    ) -> BoxFuture<'a, Result<Vec<Box<dyn AsyncTransportDevice>>>> {
        Box::pin(async move {
            use crate::transport::async_socketcan::AsyncSocketCanDevice;
            use crate::transport::device::TransportDeviceInfo;
            use crate::transport::discovery::detect_socketcan_interfaces;

            let interfaces = if options.socketcan_interfaces.is_empty() {
                detect_socketcan_interfaces()
                    .into_iter()
                    .map(|info| info.interface)
                    .collect()
            } else {
                options.socketcan_interfaces.clone()
            };

            let mut devices: Vec<Box<dyn AsyncTransportDevice>> = Vec::new();
            for (idx, interface) in interfaces.iter().enumerate() {
                match AsyncSocketCanDevice::with_options(
                    interface,
                    options.timeout,
                    options.disable_brs,
                )
                .await
                {
                    Ok(mut device) => {
                        device.info = TransportDeviceInfo::new(idx, "AsyncSocketCan")
                            .with_serial(interface)
                            .with_detail(format!("'{}'", interface));
                        devices.push(Box::new(device));
                    }
                    Err(_) => continue,
                }
            }

            Ok(devices)
        })
    }
}

// -- Global async transport factory registry --

static ASYNC_REGISTRY: OnceLock<Mutex<Vec<Arc<dyn AsyncTransportFactory>>>> = OnceLock::new();

fn get_async_registry() -> &'static Mutex<Vec<Arc<dyn AsyncTransportFactory>>> {
    ASYNC_REGISTRY.get_or_init(|| {
        let factories: Vec<Arc<dyn AsyncTransportFactory>> = vec![
            Arc::new(AsyncFdcanusbFactory),
            #[cfg(target_os = "linux")]
            Arc::new(AsyncSocketCanFactory),
        ];
        Mutex::new(factories)
    })
}

/// Register an external async transport factory.
///
/// The factory will be included in all subsequent calls to
/// [`get_async_factories()`], [`create_async_transports()`], and
/// async singleton creation.
pub fn register_async(factory: Arc<dyn AsyncTransportFactory>) {
    get_async_registry().lock().unwrap().push(factory);
}

/// Collect the command-line argument specifications of every
/// registered async factory -- built-in and external -- in
/// registration order.
pub(crate) fn registered_arg_specs() -> Vec<ArgSpec> {
    get_async_registry()
        .lock()
        .unwrap()
        .iter()
        .flat_map(|factory| factory.arg_specs())
        .collect()
}

/// Get the built-in async transport factories.
///
/// Returns fresh instances of the built-in factories. For the full set
/// of registered factories (including external ones), use
/// [`create_async_transports()`] which reads the global registry.
pub fn get_async_factories() -> Vec<Box<dyn AsyncTransportFactory>> {
    vec![
        Box::new(AsyncFdcanusbFactory::new()),
        #[cfg(target_os = "linux")]
        Box::new(AsyncSocketCanFactory::new()),
    ]
}

/// Create async transport devices using all registered factories.
///
/// This is the main entry point for creating async transports with auto-discovery.
/// It tries each factory in priority order and returns all successfully created devices.
/// Duplicate socketcan interfaces backed by fdcanusb devices are filtered out.
///
/// # Errors
///
/// A factory failure propagates when that transport was explicitly
/// forced via `force_transport`, or when no factory produced any
/// device at all (in which case the first failure is returned rather
/// than an empty list).  Otherwise failing factories are skipped.
pub async fn create_async_transports(
    options: &AsyncTransportOptions,
) -> Result<Vec<Box<dyn AsyncTransportDevice>>> {
    use std::collections::HashSet;

    // Snapshot the registry under lock, then release the lock before awaiting.
    let mut factories: Vec<Arc<dyn AsyncTransportFactory>> = {
        let registry = get_async_registry().lock().unwrap();
        registry.clone()
    };

    // Sort by priority
    factories.sort_by_key(|f| f.priority());

    // Filter by forced transport if specified
    if let Some(ref force) = options.force_transport {
        factories.retain(|f| f.name() == force.as_str());
    }

    let mut all_devices = Vec::new();
    let mut fdcanusb_serials: HashSet<String> = HashSet::new();
    let mut first_error: Option<Error> = None;

    for factory in &factories {
        match factory.create(options).await {
            Ok(devices) => {
                // Track fdcanusb serial numbers for deduplication
                if factory.name() == "fdcanusb" {
                    for device in &devices {
                        if let Some(serial) = device.info().serial_number.as_ref() {
                            fdcanusb_serials.insert(serial.clone());
                        }
                    }
                }
                all_devices.extend(devices);
            }
            Err(e) => {
                // A forced transport's failure is the caller's answer
                // (e.g. a pi3hat needing root reports the permission
                // error rather than a bare "no transport found").
                if options.force_transport.is_some() {
                    return Err(e);
                }
                // In auto-detection, keep trying other factories but
                // remember the failure in case nothing else works out.
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
    }

    // Deduplicate: remove socketcan interfaces that are backed by fdcanusb
    // devices we're already using via CDC serial
    #[cfg(target_os = "linux")]
    {
        use crate::transport::discovery::detect_socketcan_interfaces;

        let socketcan_infos = detect_socketcan_interfaces();
        let mut filtered_devices = Vec::new();

        for device in all_devices {
            // Check if this is a socketcan device that duplicates an fdcanusb
            let should_skip = socketcan_infos.iter().any(|info| {
                // For SocketCanDevice devices, the interface name is stored in serial_number
                (device.info().serial_number.as_ref() == Some(&info.interface))
                    && info
                        .fdcanusb_serial
                        .as_ref()
                        .is_some_and(|serial| fdcanusb_serials.contains(serial))
            });

            if !should_skip {
                filtered_devices.push(device);
            }
        }

        all_devices = filtered_devices;
    }

    // With nothing created at all, a factory failure is more useful
    // than the empty list (which callers report as "not connected").
    if all_devices.is_empty() {
        if let Some(e) = first_error {
            return Err(e);
        }
    }

    Ok(all_devices)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(target_os = "linux")]
    #[test]
    fn test_async_factory_priorities() {
        let fdcanusb = AsyncFdcanusbFactory::new();
        assert_eq!(fdcanusb.priority(), 10);
        let socketcan = AsyncSocketCanFactory::new();
        assert!(fdcanusb.priority() < socketcan.priority());
    }

    #[test]
    fn test_async_factory_arg_specs() {
        let fdcanusb = AsyncFdcanusbFactory::new();
        let specs = fdcanusb.arg_specs();
        assert_eq!(specs.len(), 2);
        assert_eq!(specs[0].name, "fdcanusb");
        assert_eq!(specs[1].name, "fdcanusb-baudrate");

        #[cfg(target_os = "linux")]
        {
            let socketcan = AsyncSocketCanFactory::new();
            let specs = socketcan.arg_specs();
            assert_eq!(specs.len(), 1);
            assert_eq!(specs[0].name, "can-chan");
        }
    }

    #[test]
    fn test_get_async_factories() {
        let factories = get_async_factories();
        assert!(!factories.is_empty());

        let names: Vec<_> = factories.iter().map(|f| f.name()).collect();
        assert!(names.contains(&"fdcanusb"));
    }
}