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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use serialport::SerialPort;
mod packet;
use packet::{InstructionPacket, Packet, StatusPacket};
mod v1;
use v1::V1;
mod v2;
use v2::V2;
use crate::Result;
#[derive(Debug)]
enum ProtocolKind {
V1(V1),
V2(V2),
}
#[derive(Debug)]
/// Raw dynamixel communication messages controller (protocol v1 or v2)
pub struct DynamixelProtocolHandler {
protocol: ProtocolKind,
post_delay: Option<Duration>,
}
impl DynamixelProtocolHandler {
/// Creates a protocol v1 communication IO.
///
/// For more information on protocol v1, please refer to <https://emanual.robotis.com/docs/en/dxl/protocol1/>
///
/// # Examples
/// ```no_run
/// use rustypot::{DynamixelProtocolHandler, servo::dynamixel::mx};
/// use std::time::Duration;
///
/// let mut serial_port = serialport::new("/dev/ttyACM0", 1_000_000)
/// .timeout(Duration::from_millis(10))
/// .open()
/// .expect("Failed to open port");
///
/// let dph = DynamixelProtocolHandler::v1();
///
/// let pos =
/// mx::read_present_position(&dph, serial_port.as_mut(), 11).expect("Communication error");
/// println!("Motor MX ID: 11 present position: {:?}", pos);
/// ```
pub fn v1() -> Self {
DynamixelProtocolHandler {
protocol: ProtocolKind::V1(V1),
post_delay: None,
}
}
/// Creates a protocol v2 communication IO.
///
/// For more information on protocol v2, please refer to <https://emanual.robotis.com/docs/en/dxl/protocol2/>
///
/// # Examples
/// ```no_run
/// use rustypot::{DynamixelProtocolHandler, servo::dynamixel::xl320};
/// use std::time::Duration;
///
/// let mut serial_port = serialport::new("/dev/ttyACM0", 1_000_000)
/// .timeout(Duration::from_millis(10))
/// .open()
/// .expect("Failed to open port");
///
/// let dph = DynamixelProtocolHandler::v2();
///
/// let pos =
/// xl320::read_present_position(&dph, serial_port.as_mut(), 11).expect("Communication error");
/// println!("Motor XL-320 ID: 11 present position: {:?}", pos);
/// ```
pub fn v2() -> Self {
DynamixelProtocolHandler {
protocol: ProtocolKind::V2(V2),
post_delay: None,
}
}
/// Set a delay after each communication.
pub fn with_post_delay(self, delay: Duration) -> Self {
DynamixelProtocolHandler {
post_delay: Some(delay),
..self
}
}
/// Send a ping instruction.
///
/// Ping the motor with specified `id`.
/// Returns an [CommunicationErrorKind] if the communication fails.
///
/// # Examples
/// ```no_run
/// use rustypot::DynamixelProtocolHandler;
/// use std::time::Duration;
///
/// let mut serial_port = serialport::new("/dev/ttyACM0", 1_000_000)
/// .timeout(Duration::from_millis(10))
/// .open()
/// .expect("Failed to open port");
///
/// let dph = DynamixelProtocolHandler::v1();
///
/// match dph
/// .ping(serial_port.as_mut(), 42)
/// .expect("Communication error")
/// {
/// true => println!("Motor 42 found!"),
/// false => println!("Motor 42 did not respond"),
/// }
/// ```
pub fn ping(&self, serial_port: &mut dyn serialport::SerialPort, id: u8) -> Result<bool> {
match &self.protocol {
ProtocolKind::V1(p) => p.ping(serial_port, id),
ProtocolKind::V2(p) => p.ping(serial_port, id),
}
}
/// Send a reboot instruction.
///
/// Reboot the motor with specified `id`.
/// Returns an [CommunicationErrorKind] if the communication fails.
pub fn reboot(&self, serial_port: &mut dyn serialport::SerialPort, id: u8) -> Result<bool> {
match &self.protocol {
ProtocolKind::V1(p) => p.reboot(serial_port, id),
ProtocolKind::V2(p) => p.reboot(serial_port, id),
}
}
/// Factory reset instruction.
///
/// Reset the Control Table of DYNAMIXEL to the factory default values.
/// Please note that conserving ID and/or Baudrate is only supported on protocol v2.
pub fn factory_reset(
&self,
serial_port: &mut dyn serialport::SerialPort,
id: u8,
conserve_id_only: bool,
conserve_id_and_baudrate: bool,
) -> Result<()> {
match &self.protocol {
ProtocolKind::V1(p) => {
if conserve_id_only || conserve_id_and_baudrate {
return Err(Box::new(CommunicationErrorKind::Unsupported));
}
p.factory_reset(serial_port, id, conserve_id_only, conserve_id_and_baudrate)
}
ProtocolKind::V2(p) => {
p.factory_reset(serial_port, id, conserve_id_only, conserve_id_and_baudrate)
}
}
}
/// Reads raw register bytes.
///
/// Sends a read instruction to the motor and wait for the status packet in response.
/// Returns raw bytes without interpretation.
/// For higher level methods, check the [device] implementation.
///
/// # Arguments
///
/// * `serial_port` - the serial port to use for communication
/// * `id` - id of the motor
/// * `addr` - register address
/// * `length` - number of bytes to read
///
/// # Examples
/// ```no_run
/// use rustypot::DynamixelProtocolHandler;
/// use std::time::Duration;
///
/// let mut serial_port = serialport::new("/dev/ttyACM0", 1_000_000)
/// .timeout(Duration::from_millis(10))
/// .open()
/// .expect("Failed to open port");
///
/// let dph = DynamixelProtocolHandler::v1();
///
/// // Read 2 bytes from register address 36 of motor 10
/// let bytes = dph
/// .read(serial_port.as_mut(), 10, 36, 2)
/// .expect("Communication error");
/// assert_eq!(bytes.len(), 2);
/// ```
pub fn read(
&self,
serial_port: &mut dyn serialport::SerialPort,
id: u8,
addr: u8,
length: u8,
) -> Result<Vec<u8>> {
let res = match &self.protocol {
ProtocolKind::V1(p) => p.read(serial_port, id, addr, length),
ProtocolKind::V2(p) => p.read(serial_port, id, addr, length),
};
if let Some(delay) = self.post_delay {
std::thread::sleep(delay);
}
res
}
/// Writes raw bytes to register.
///
/// Sends a write instruction with the raw bytes as parameter to the motor.
/// Wait for the status packet in response.
/// For higher level methods, check the [device] implementation.
///
/// # Arguments
///
/// * `serial_port` - the serial port to use for communication
/// * `id` - id of the motor
/// * `addr` - register address
/// * `data` - raw bytes to write
///
/// # Examples
/// ```no_run
/// use rustypot::DynamixelProtocolHandler;
/// use std::time::Duration;
///
/// let mut serial_port = serialport::new("/dev/ttyACM0", 1_000_000)
/// .timeout(Duration::from_millis(10))
/// .open()
/// .expect("Failed to open port");
///
/// let dph = DynamixelProtocolHandler::v1();
///
/// // Write a single byte to register address 24 of motor 33
/// dph.write(serial_port.as_mut(), 33, 24, &vec![0])
/// .expect("Communication error");
/// ```
pub fn write(
&self,
serial_port: &mut dyn serialport::SerialPort,
id: u8,
addr: u8,
data: &[u8],
) -> Result<()> {
match &self.protocol {
ProtocolKind::V1(p) => p.write(serial_port, id, addr, data),
ProtocolKind::V2(p) => p.write(serial_port, id, addr, data),
}?;
if let Some(delay) = self.post_delay {
std::thread::sleep(delay);
}
Ok(())
}
pub fn write_fb(
&self,
serial_port: &mut dyn serialport::SerialPort,
id: u8,
addr: u8,
data: &[u8],
) -> Result<Vec<u8>> {
match &self.protocol {
ProtocolKind::V1(p) => {
let res = p.write_fb(serial_port, id, addr, data);
if let Some(delay) = self.post_delay {
std::thread::sleep(delay);
}
res
}
ProtocolKind::V2(_) => Err(Box::new(CommunicationErrorKind::Unsupported)),
}
}
/// Reads raw register bytes from multiple ids at once.
///
/// Sends a sync read instruction to the specified motors and wait for the status packet in response.
/// Returns raw bytes without interpretation.
/// For higher level methods, check the [device] implementation.
///
/// *Note: sync read support on protocol v1 depends on usb to serial hardware used!*
///
/// # Arguments
///
/// * `serial_port` - the serial port to use for communication
/// * `ids` - specfied motors id
/// * `addr` - register address
/// * `length` - number of bytes to read
///
/// # Examples
/// ```no_run
/// use rustypot::DynamixelProtocolHandler;
/// use std::time::Duration;
///
/// let mut serial_port = serialport::new("/dev/ttyACM0", 1_000_000)
/// .timeout(Duration::from_millis(10))
/// .open()
/// .expect("Failed to open port");
///
/// let dph = DynamixelProtocolHandler::v1();
///
/// // Read a single byte from motor 10, 11 and 12 (addr 43)
/// let resp = dph
/// .sync_read(serial_port.as_mut(), &[10, 11, 12], 43, 1)
/// .expect("Communication error");
///
/// assert_eq!(resp.len(), 3);
/// for bytes in resp {
/// assert_eq!(bytes.len(), 1);
/// }
/// ```
pub fn sync_read(
&self,
serial_port: &mut dyn serialport::SerialPort,
ids: &[u8],
addr: u8,
length: u8,
) -> Result<Vec<Vec<u8>>> {
match &self.protocol {
ProtocolKind::V1(p) => p.sync_read(serial_port, ids, addr, length),
ProtocolKind::V2(p) => p.sync_read(serial_port, ids, addr, length),
}
}
/// Write raw bytes to multiple ids at once.
///
/// Sends a sync write instruction to the specified motors.
/// No status response is sent back.
/// For higher level methods, check the [device] implementation.
///
/// # Arguments
///
/// * `serial_port` - the serial port to use for communication
/// * `ids` - specfied motors id
/// * `addr` - register address
/// * `data` - bytes to write to each motor
///
/// # Examples
/// ```no_run
/// use rustypot::DynamixelProtocolHandler;
/// use std::time::Duration;
///
/// let mut serial_port = serialport::new("/dev/ttyACM0", 1_000_000)
/// .timeout(Duration::from_millis(10))
/// .open()
/// .expect("Failed to open port");
///
/// let dph = DynamixelProtocolHandler::v1();
///
/// // In a single message
/// // * writes 0 to register 25 of motor 40
/// // * writes 1 to register 25 of motor 41
/// dph.sync_write(serial_port.as_mut(), &[40, 41], 25, &[vec![0], vec![1]])
/// .expect("Communication error");
/// ```
pub fn sync_write(
&self,
serial_port: &mut dyn serialport::SerialPort,
ids: &[u8],
addr: u8,
data: &[Vec<u8>],
) -> Result<()> {
match &self.protocol {
ProtocolKind::V1(p) => p.sync_write(serial_port, ids, addr, data),
ProtocolKind::V2(p) => p.sync_write(serial_port, ids, addr, data),
}
}
}
trait Protocol<P: Packet> {
fn ping(&self, port: &mut dyn SerialPort, id: u8) -> Result<bool> {
self.send_instruction_packet(port, P::ping_packet(id).as_ref())?;
Ok(self.read_status_packet(port, id).is_ok())
}
fn reboot(&self, port: &mut dyn SerialPort, id: u8) -> Result<bool> {
self.send_instruction_packet(port, P::reboot_packet(id).as_ref())?;
Ok(self.read_status_packet(port, id).is_ok())
}
fn factory_reset(
&self,
port: &mut dyn SerialPort,
id: u8,
conserve_id_only: bool,
conserve_id_and_baudrate: bool,
) -> Result<()> {
self.send_instruction_packet(
port,
P::factory_reset_packet(id, conserve_id_only, conserve_id_and_baudrate).as_ref(),
)?;
self.read_status_packet(port, id).map(|_| ())
}
fn read(&self, port: &mut dyn SerialPort, id: u8, addr: u8, length: u8) -> Result<Vec<u8>> {
self.send_instruction_packet(port, P::read_packet(id, addr, length).as_ref())?;
self.read_status_packet(port, id)
.map(|sp| sp.params().to_vec())
}
fn write(&self, port: &mut dyn SerialPort, id: u8, addr: u8, data: &[u8]) -> Result<()> {
self.send_instruction_packet(port, P::write_packet(id, addr, data).as_ref())?;
self.read_status_packet(port, id).map(|_| ())
}
fn write_fb(
&self,
port: &mut dyn SerialPort,
id: u8,
addr: u8,
data: &[u8],
) -> Result<Vec<u8>> {
self.send_instruction_packet(port, P::write_packet(id, addr, data).as_ref())?;
self.read_status_packet(port, id)
.map(|sp| sp.params().to_vec())
}
fn sync_read(
&self,
port: &mut dyn SerialPort,
ids: &[u8],
addr: u8,
length: u8,
) -> Result<Vec<Vec<u8>>> {
self.send_instruction_packet(port, P::sync_read_packet(ids, addr, length).as_ref())?;
let mut result = Vec::new();
for id in ids {
let sp = self.read_status_packet(port, *id)?;
result.push(sp.params().to_vec());
}
Ok(result)
}
fn sync_write(
&self,
port: &mut dyn SerialPort,
ids: &[u8],
addr: u8,
data: &[Vec<u8>],
) -> Result<()> {
self.send_instruction_packet(port, P::sync_write_packet(ids, addr, data).as_ref())?;
Ok(())
}
const MAX_FLUSH_RETRIES: usize = 3;
const FLUSH_RETRY_DELAY_MS: u64 = 5;
fn flush_if_needed(
&self,
port: &mut dyn SerialPort,
max_retries: usize,
flush_after_delay: Duration,
) -> Result<()> {
for _attempt in 1..=max_retries {
if self.is_input_buffer_empty(port)? {
return Ok(());
}
// log::warn!(
// "Input buffer not empty before sending instruction, flushing... (retry {}/{})",
// attempt,
// max_retries
// );
self.flush(port)?;
std::thread::sleep(flush_after_delay);
}
if self.is_input_buffer_empty(port)? {
Ok(())
} else {
// log::error!("Could not flush input buffer before sending instruction");
Err(Box::new(CommunicationErrorKind::TimeoutError))
}
}
fn send_instruction_packet(
&self,
port: &mut dyn SerialPort,
packet: &dyn InstructionPacket<P>,
) -> Result<()> {
// Before we send an instruction
// The input buffer should always be empty
// (if not, it means that an old corrupted message need to be flushed)
self.flush_if_needed(
port,
Self::MAX_FLUSH_RETRIES,
Duration::from_millis(Self::FLUSH_RETRY_DELAY_MS),
)?;
// log::debug!(">>> {:?}", packet.to_bytes());
match port.write_all(&packet.to_bytes()) {
Ok(_) => Ok(()),
Err(_) => Err(Box::new(CommunicationErrorKind::TimeoutError)),
}
}
fn read_status_packet(
&self,
port: &mut dyn SerialPort,
sender_id: u8,
) -> Result<Box<dyn StatusPacket<P>>> {
let mut header = vec![0u8; P::HEADER_SIZE];
port.read_exact(&mut header)?;
let payload_size = P::get_payload_size(&header)?;
let mut payload = vec![0u8; payload_size];
port.read_exact(&mut payload)?;
let mut data = Vec::new();
data.extend(header);
data.extend(payload);
// log::debug!("<<< {data:?}");
P::status_packet(&data, sender_id)
}
fn is_input_buffer_empty(&self, port: &mut dyn SerialPort) -> Result<bool> {
let n = port.bytes_to_read()? as usize;
Ok(n == 0)
}
fn flush(&self, port: &mut dyn SerialPort) -> Result<()> {
let n = port.bytes_to_read()? as usize;
if n > 0 {
// log::info!("Needed to flush serial port ({n} bytes)...");
let mut buff = vec![0u8; n];
port.read_exact(&mut buff)?;
}
Ok(())
}
}
use std::{fmt, time::Duration};
/// Dynamixel Communication Error
#[derive(Debug, Clone, Copy)]
pub enum CommunicationErrorKind {
/// Incorrect checksum
ChecksumError,
/// Could not parse incoherent message
ParsingError,
/// Timeout
TimeoutError,
/// Incorrect response id - different from sender (sender id, response id)
IncorrectId(u8, u8),
/// Operation not supported
Unsupported,
}
impl fmt::Display for CommunicationErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CommunicationErrorKind::ChecksumError => write!(f, "Checksum error"),
CommunicationErrorKind::ParsingError => write!(f, "Parsing error"),
CommunicationErrorKind::TimeoutError => write!(f, "Timeout error"),
CommunicationErrorKind::IncorrectId(sender_id, resp_id) => {
write!(f, "Incorrect id ({resp_id} instead of {sender_id})")
}
CommunicationErrorKind::Unsupported => write!(f, "Operation not supported"),
}
}
}
impl std::error::Error for CommunicationErrorKind {}