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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use crate::arm_config;
use async_trait::async_trait;
pub use lss_driver::LedColor;
use lss_driver::{CommandModifier, LSSDriver};
use serde::{Deserialize, Serialize};
use std::{fs, include_bytes, str, sync::Arc, time::Duration};
use thiserror::Error;
use tokio::sync::Mutex;

#[derive(Error, Debug)]
pub enum DriverError {
    #[error("error while accessing configuration")]
    IoError(#[from] std::io::Error),
    #[error("error while parsing json")]
    DeserializationError(#[from] serde_json::error::Error),
    #[error("failed when talking to arm")]
    LssDriverError(#[from] lss_driver::LssDriverError),
}

type Result<T> = std::result::Result<T, DriverError>;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ServoControlSettings {
    /// Settings for servo in arm
    #[serde(skip_serializing_if = "Option::is_none")]
    pub motion_profile: Option<bool>,
    /// useful for non interpolated mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub angular_holding_stiffness: Option<i32>,
    /// -10 to 10, usually -4 to 4
    #[serde(skip_serializing_if = "Option::is_none")]
    pub angular_stiffness: Option<i32>,
    /// -10 to 10, usually -4 to 4
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter_position_count: Option<u8>,
    /// I don't know how this works
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maximum_motor_duty: Option<u32>,
    /// useful for compliance, 255 to 1023
    #[serde(skip_serializing_if = "Option::is_none")]
    pub angular_acceleration: Option<i32>,
    /// only when motion_profile is on
    #[serde(skip_serializing_if = "Option::is_none")]
    pub angular_deceleration: Option<i32>,
    /// only when motion_profile is on
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maximum_speed_degrees: Option<u32>,
}

impl ServoControlSettings {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        motion_profile: Option<bool>,
        angular_holding_stiffness: Option<i32>,
        angular_stiffness: Option<i32>,
        filter_position_count: Option<u8>,
        maximum_motor_duty: Option<u32>,
        angular_acceleration: Option<i32>,
        angular_deceleration: Option<i32>,
        maximum_speed_degrees: Option<u32>,
    ) -> ServoControlSettings {
        ServoControlSettings {
            motion_profile,
            angular_holding_stiffness,
            angular_stiffness,
            filter_position_count,
            maximum_motor_duty,
            angular_acceleration,
            angular_deceleration,
            maximum_speed_degrees,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ArmControlSettings {
    /// Settings for each servo in the arm
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base: Option<ServoControlSettings>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shoulder: Option<ServoControlSettings>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elbow: Option<ServoControlSettings>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wrist: Option<ServoControlSettings>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gripper: Option<ServoControlSettings>,
}

impl ArmControlSettings {
    fn parse_json(json: &str) -> Result<ArmControlSettings> {
        let config = serde_json::from_str(json)?;
        Ok(config)
    }

    pub fn load_json(path: &str) -> Result<ArmControlSettings> {
        let text = fs::read_to_string(path)?;
        let config = ArmControlSettings::parse_json(&text)?;
        Ok(config)
    }

    pub fn save_json(&self, path: &str) -> Result<()> {
        let json = serde_json::to_string_pretty(self)?;
        fs::write(path, json)?;
        Ok(())
    }

    /// Guppy comes with an included config file.
    ///
    /// This file is packaged with the binary
    /// This method retrieves this included version
    pub fn included_continuous() -> ArmControlSettings {
        let json =
            str::from_utf8(include_bytes!("../config/motor_settings_continuous.json")).unwrap();
        ArmControlSettings::parse_json(json).unwrap()
    }

    /// Guppy comes with an included config file.
    ///
    /// This file is packaged with the binary
    /// This method retrieves this included version
    pub fn included_trajectory() -> ArmControlSettings {
        let json =
            str::from_utf8(include_bytes!("../config/motor_settings_trajectory.json")).unwrap();
        ArmControlSettings::parse_json(json).unwrap()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct JointPositions {
    pub base: f32,
    pub shoulder: f32,
    pub elbow: f32,
    pub wrist: f32,
}

impl JointPositions {
    pub fn new(base: f32, shoulder: f32, elbow: f32, wrist: f32) -> JointPositions {
        JointPositions {
            base,
            shoulder,
            elbow,
            wrist,
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum MotorStatus {
    Ok,
    SafeMode,
    NotDetected,
}

impl MotorStatus {
    fn from_safety_mode_query_result(
        response: std::result::Result<lss_driver::SafeModeStatus, lss_driver::LssDriverError>,
    ) -> Self {
        // This is some pretty awkward logic
        match response {
            Ok(lss_driver::SafeModeStatus::NoLimits) => MotorStatus::Ok,
            Ok(_) => MotorStatus::SafeMode,
            Err(_) => MotorStatus::NotDetected,
        }
    }
}

#[derive(Debug)]
pub struct ArmMotorStatus {
    base: MotorStatus,
    shoulder: MotorStatus,
    elbow: MotorStatus,
    wrist: MotorStatus,
    gripper: MotorStatus,
}

impl ArmMotorStatus {
    pub fn is_arm_okay(&self) -> bool {
        self.base == MotorStatus::Ok
            && self.shoulder == MotorStatus::Ok
            && self.elbow == MotorStatus::Ok
            && self.wrist == MotorStatus::Ok
            && self.gripper == MotorStatus::Ok
    }
}

#[async_trait]
pub trait ArmDriver: Send + Sync {
    async fn set_color(&mut self, color: lss_driver::LedColor) -> Result<()>;
    async fn setup_motors(&mut self, settings: ArmControlSettings) -> Result<()>;
    async fn load_motor_settings(&mut self) -> Result<ArmControlSettings>;
    async fn halt(&mut self) -> Result<()>;
    async fn limp(&mut self) -> Result<()>;
    async fn move_to(&mut self, position: JointPositions) -> Result<()>;
    async fn move_to_timed(&mut self, position: JointPositions, duration: Duration) -> Result<()>;
    async fn read_position(&mut self) -> Result<JointPositions>;
    /// 0.0 is fully open
    /// 1.0 is fully closed
    async fn move_gripper(
        &mut self,
        closed: f32,
        current_limit: u32,
        duration: Duration,
    ) -> Result<()>;
    async fn query_motor_status(&mut self) -> Result<ArmMotorStatus>;
}

pub struct SerialArmDriver {
    driver: lss_driver::LSSDriver,
    config: arm_config::ArmConfig,
}

impl SerialArmDriver {
    pub async fn new(
        port: &str,
        config: arm_config::ArmConfig,
        control_settings: ArmControlSettings,
    ) -> Result<Box<Self>> {
        let driver = lss_driver::LSSDriver::new(port)?;
        let mut arm_driver = SerialArmDriver { driver, config };
        arm_driver.setup_motors(control_settings).await?;
        Ok(Box::new(arm_driver))
    }
}

#[async_trait]
impl ArmDriver for SerialArmDriver {
    async fn set_color(&mut self, color: lss_driver::LedColor) -> Result<()> {
        for id in self.config.get_ids().iter() {
            self.driver.set_color(*id, color).await?;
        }
        Ok(())
    }

    async fn setup_motors(&mut self, settings: ArmControlSettings) -> Result<()> {
        async fn set_motor(
            driver: &mut lss_driver::LSSDriver,
            motor_id: u8,
            settings: &ServoControlSettings,
        ) -> Result<()> {
            if let Some(motion_profile) = settings.motion_profile {
                driver.set_motion_profile(motor_id, motion_profile).await?;
            }
            if let Some(angular_holding_stiffness) = settings.angular_holding_stiffness {
                driver
                    .set_angular_holding_stiffness(motor_id, angular_holding_stiffness)
                    .await?;
            }
            if let Some(angular_stiffness) = settings.angular_stiffness {
                driver
                    .set_angular_stiffness(motor_id, angular_stiffness)
                    .await?;
            }
            if let Some(filter_position_count) = settings.filter_position_count {
                driver
                    .set_filter_position_count(motor_id, filter_position_count)
                    .await?;
            }
            if let Some(maximum_motor_duty) = settings.maximum_motor_duty {
                driver
                    .set_maximum_motor_duty(motor_id, maximum_motor_duty as i32)
                    .await?;
            }
            if let Some(angular_acceleration) = settings.angular_acceleration {
                driver
                    .set_angular_acceleration(motor_id, angular_acceleration)
                    .await?;
            }
            if let Some(angular_deceleration) = settings.angular_deceleration {
                driver
                    .set_angular_deceleration(motor_id, angular_deceleration)
                    .await?;
            }
            if let Some(maximum_speed_degrees) = settings.maximum_speed_degrees {
                driver
                    .set_maximum_speed(motor_id, maximum_speed_degrees as f32)
                    .await?;
            }
            Ok(())
        }
        if let Some(base_settings) = &settings.base {
            set_motor(&mut self.driver, self.config.base_id, base_settings).await?;
        }
        if let Some(shoulder_settings) = &settings.shoulder {
            set_motor(&mut self.driver, self.config.shoulder_id, shoulder_settings).await?;
        }
        if let Some(elbow_settings) = &settings.elbow {
            set_motor(&mut self.driver, self.config.elbow_id, elbow_settings).await?;
        }
        if let Some(wrist_settings) = &settings.wrist {
            set_motor(&mut self.driver, self.config.wrist_id, wrist_settings).await?;
        }
        if let Some(gripper_settings) = &settings.gripper {
            set_motor(&mut self.driver, self.config.gripper_id, gripper_settings).await?;
        }
        Ok(())
    }

    async fn load_motor_settings(&mut self) -> Result<ArmControlSettings> {
        async fn read_motor_config(
            driver: &mut lss_driver::LSSDriver,
            motor_id: u8,
        ) -> Result<ServoControlSettings> {
            let motion_profile = driver.query_motion_profile(motor_id).await?;
            let angular_holding_stiffness =
                driver.query_angular_holding_stiffness(motor_id).await?;
            let angular_stiffness = driver.query_angular_stiffness(motor_id).await?;
            let filter_position_count = driver.query_filter_position_count(motor_id).await?;
            let maximum_motor_duty = driver.query_maximum_motor_duty(motor_id).await? as u32;
            let angular_acceleration = driver.query_angular_acceleration(motor_id).await?;
            let angular_deceleration = driver.query_angular_deceleration(motor_id).await?;
            let maximum_speed_degrees = driver.query_maximum_speed(motor_id).await? as u32;
            Ok(ServoControlSettings::new(
                Some(motion_profile),
                Some(angular_holding_stiffness),
                Some(angular_stiffness),
                Some(filter_position_count),
                Some(maximum_motor_duty),
                Some(angular_acceleration),
                Some(angular_deceleration),
                Some(maximum_speed_degrees),
            ))
        }
        let base = Some(read_motor_config(&mut self.driver, self.config.base_id).await?);
        let shoulder = Some(read_motor_config(&mut self.driver, self.config.shoulder_id).await?);
        let elbow = Some(read_motor_config(&mut self.driver, self.config.elbow_id).await?);
        let wrist = Some(read_motor_config(&mut self.driver, self.config.wrist_id).await?);
        let gripper = Some(read_motor_config(&mut self.driver, self.config.gripper_id).await?);
        Ok(ArmControlSettings {
            base,
            shoulder,
            elbow,
            wrist,
            gripper,
        })
    }

    async fn halt(&mut self) -> Result<()> {
        for id in self.config.get_ids().iter() {
            self.driver.halt_hold(*id).await?;
        }
        Ok(())
    }

    async fn limp(&mut self) -> Result<()> {
        for id in self.config.get_ids().iter() {
            self.driver.limp(*id).await?;
        }
        Ok(())
    }

    async fn move_to(&mut self, position: JointPositions) -> Result<()> {
        self.driver
            .move_to_position(self.config.base_id, position.base)
            .await?;
        self.driver
            .move_to_position(self.config.shoulder_id, position.shoulder)
            .await?;
        self.driver
            .move_to_position(self.config.elbow_id, position.elbow)
            .await?;
        self.driver
            .move_to_position(self.config.wrist_id, position.wrist)
            .await?;
        Ok(())
    }

    async fn move_to_timed(&mut self, position: JointPositions, duration: Duration) -> Result<()> {
        self.driver
            .move_to_position_with_modifier(
                self.config.base_id,
                position.base,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        self.driver
            .move_to_position_with_modifier(
                self.config.shoulder_id,
                position.shoulder,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        self.driver
            .move_to_position_with_modifier(
                self.config.elbow_id,
                position.elbow,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        self.driver
            .move_to_position_with_modifier(
                self.config.wrist_id,
                position.wrist,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        Ok(())
    }

    async fn read_position(&mut self) -> Result<JointPositions> {
        let base_position = self.driver.query_position(self.config.base_id).await?;
        let shoulder_position = self.driver.query_position(self.config.shoulder_id).await?;
        let elbow_position = self.driver.query_position(self.config.elbow_id).await?;
        let wrist_position = self.driver.query_position(self.config.wrist_id).await?;
        Ok(JointPositions::new(
            base_position,
            shoulder_position,
            elbow_position,
            wrist_position,
        ))
    }

    /// Set how open the gripper is
    /// 0.0 is fully open
    /// 1.0 is fully closed
    async fn move_gripper(
        &mut self,
        closed: f32,
        current_limit: u32,
        duration: Duration,
    ) -> Result<()> {
        let desired_position = calc_gripper(closed);
        self.driver
            .move_to_position_with_modifiers(
                self.config.gripper_id,
                desired_position,
                &[
                    CommandModifier::CurrentHold(current_limit),
                    CommandModifier::TimedDuration(duration),
                ],
            )
            .await?;
        Ok(())
    }

    async fn query_motor_status(&mut self) -> Result<ArmMotorStatus> {
        let base = MotorStatus::from_safety_mode_query_result(
            self.driver.query_safety_status(self.config.base_id).await,
        );
        let shoulder = MotorStatus::from_safety_mode_query_result(
            self.driver
                .query_safety_status(self.config.shoulder_id)
                .await,
        );
        let elbow = MotorStatus::from_safety_mode_query_result(
            self.driver.query_safety_status(self.config.elbow_id).await,
        );
        let wrist = MotorStatus::from_safety_mode_query_result(
            self.driver.query_safety_status(self.config.wrist_id).await,
        );
        let gripper = MotorStatus::from_safety_mode_query_result(
            self.driver
                .query_safety_status(self.config.gripper_id)
                .await,
        );
        Ok(ArmMotorStatus {
            base,
            shoulder,
            elbow,
            wrist,
            gripper,
        })
    }
}

pub struct SharedSerialArmDriver {
    driver: Arc<Mutex<LSSDriver>>,
    config: arm_config::ArmConfig,
}

impl SharedSerialArmDriver {
    pub async fn new(
        driver: Arc<Mutex<LSSDriver>>,
        config: arm_config::ArmConfig,
        control_settings: ArmControlSettings,
    ) -> Result<Box<Self>> {
        let mut arm_driver = Self { driver, config };
        arm_driver.setup_motors(control_settings).await?;
        Ok(Box::new(arm_driver))
    }
}

#[async_trait]
impl ArmDriver for SharedSerialArmDriver {
    async fn set_color(&mut self, color: lss_driver::LedColor) -> Result<()> {
        let mut driver = self.driver.lock().await;
        for id in self.config.get_ids().iter() {
            driver.set_color(*id, color).await?;
        }
        Ok(())
    }

    async fn setup_motors(&mut self, settings: ArmControlSettings) -> Result<()> {
        async fn set_motor(
            driver: &mut lss_driver::LSSDriver,
            motor_id: u8,
            settings: &ServoControlSettings,
        ) -> Result<()> {
            if let Some(motion_profile) = settings.motion_profile {
                driver.set_motion_profile(motor_id, motion_profile).await?;
            }
            if let Some(angular_holding_stiffness) = settings.angular_holding_stiffness {
                driver
                    .set_angular_holding_stiffness(motor_id, angular_holding_stiffness)
                    .await?;
            }
            if let Some(angular_stiffness) = settings.angular_stiffness {
                driver
                    .set_angular_stiffness(motor_id, angular_stiffness)
                    .await?;
            }
            if let Some(filter_position_count) = settings.filter_position_count {
                driver
                    .set_filter_position_count(motor_id, filter_position_count)
                    .await?;
            }
            if let Some(maximum_motor_duty) = settings.maximum_motor_duty {
                driver
                    .set_maximum_motor_duty(motor_id, maximum_motor_duty as i32)
                    .await?;
            }
            if let Some(angular_acceleration) = settings.angular_acceleration {
                driver
                    .set_angular_acceleration(motor_id, angular_acceleration)
                    .await?;
            }
            if let Some(angular_deceleration) = settings.angular_deceleration {
                driver
                    .set_angular_deceleration(motor_id, angular_deceleration)
                    .await?;
            }
            if let Some(maximum_speed_degrees) = settings.maximum_speed_degrees {
                driver
                    .set_maximum_speed(motor_id, maximum_speed_degrees as f32)
                    .await?;
            }
            Ok(())
        }
        let mut driver = self.driver.lock().await;
        if let Some(base_settings) = &settings.base {
            set_motor(&mut driver, self.config.base_id, base_settings).await?;
        }
        if let Some(shoulder_settings) = &settings.shoulder {
            set_motor(&mut driver, self.config.shoulder_id, shoulder_settings).await?;
        }
        if let Some(elbow_settings) = &settings.elbow {
            set_motor(&mut driver, self.config.elbow_id, elbow_settings).await?;
        }
        if let Some(wrist_settings) = &settings.wrist {
            set_motor(&mut driver, self.config.wrist_id, wrist_settings).await?;
        }
        if let Some(gripper_settings) = &settings.gripper {
            set_motor(&mut driver, self.config.gripper_id, gripper_settings).await?;
        }
        Ok(())
    }

    async fn load_motor_settings(&mut self) -> Result<ArmControlSettings> {
        async fn read_motor_config(
            driver: &mut lss_driver::LSSDriver,
            motor_id: u8,
        ) -> Result<ServoControlSettings> {
            let motion_profile = driver.query_motion_profile(motor_id).await?;
            let angular_holding_stiffness =
                driver.query_angular_holding_stiffness(motor_id).await?;
            let angular_stiffness = driver.query_angular_stiffness(motor_id).await?;
            let filter_position_count = driver.query_filter_position_count(motor_id).await?;
            let maximum_motor_duty = driver.query_maximum_motor_duty(motor_id).await? as u32;
            let angular_acceleration = driver.query_angular_acceleration(motor_id).await?;
            let angular_deceleration = driver.query_angular_deceleration(motor_id).await?;
            let maximum_speed_degrees = driver.query_maximum_speed(motor_id).await? as u32;
            Ok(ServoControlSettings::new(
                Some(motion_profile),
                Some(angular_holding_stiffness),
                Some(angular_stiffness),
                Some(filter_position_count),
                Some(maximum_motor_duty),
                Some(angular_acceleration),
                Some(angular_deceleration),
                Some(maximum_speed_degrees),
            ))
        }
        let mut driver = self.driver.lock().await;
        let base = Some(read_motor_config(&mut driver, self.config.base_id).await?);
        let shoulder = Some(read_motor_config(&mut driver, self.config.shoulder_id).await?);
        let elbow = Some(read_motor_config(&mut driver, self.config.elbow_id).await?);
        let wrist = Some(read_motor_config(&mut driver, self.config.wrist_id).await?);
        let gripper = Some(read_motor_config(&mut driver, self.config.gripper_id).await?);
        Ok(ArmControlSettings {
            base,
            shoulder,
            elbow,
            wrist,
            gripper,
        })
    }

    async fn halt(&mut self) -> Result<()> {
        let mut driver = self.driver.lock().await;
        for id in self.config.get_ids().iter() {
            driver.halt_hold(*id).await?;
        }
        Ok(())
    }

    async fn limp(&mut self) -> Result<()> {
        let mut driver = self.driver.lock().await;
        for id in self.config.get_ids().iter() {
            driver.limp(*id).await?;
        }
        Ok(())
    }

    async fn move_to(&mut self, position: JointPositions) -> Result<()> {
        let mut driver = self.driver.lock().await;
        driver
            .move_to_position(self.config.base_id, position.base)
            .await?;
        driver
            .move_to_position(self.config.shoulder_id, position.shoulder)
            .await?;
        driver
            .move_to_position(self.config.elbow_id, position.elbow)
            .await?;
        driver
            .move_to_position(self.config.wrist_id, position.wrist)
            .await?;
        Ok(())
    }

    async fn move_to_timed(&mut self, position: JointPositions, duration: Duration) -> Result<()> {
        let mut driver = self.driver.lock().await;
        driver
            .move_to_position_with_modifier(
                self.config.base_id,
                position.base,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        driver
            .move_to_position_with_modifier(
                self.config.shoulder_id,
                position.shoulder,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        driver
            .move_to_position_with_modifier(
                self.config.elbow_id,
                position.elbow,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        driver
            .move_to_position_with_modifier(
                self.config.wrist_id,
                position.wrist,
                CommandModifier::TimedDuration(duration),
            )
            .await?;
        Ok(())
    }

    async fn read_position(&mut self) -> Result<JointPositions> {
        let mut driver = self.driver.lock().await;
        let base_position = driver.query_position(self.config.base_id).await?;
        let shoulder_position = driver.query_position(self.config.shoulder_id).await?;
        let elbow_position = driver.query_position(self.config.elbow_id).await?;
        let wrist_position = driver.query_position(self.config.wrist_id).await?;
        Ok(JointPositions::new(
            base_position,
            shoulder_position,
            elbow_position,
            wrist_position,
        ))
    }

    /// Set how open the gripper is
    /// 0.0 is fully open
    /// 1.0 is fully closed
    async fn move_gripper(
        &mut self,
        closed: f32,
        current_limit: u32,
        duration: Duration,
    ) -> Result<()> {
        let desired_position = calc_gripper(closed);
        self.driver
            .lock()
            .await
            .move_to_position_with_modifiers(
                self.config.gripper_id,
                desired_position,
                &[
                    CommandModifier::TimedDuration(duration),
                    CommandModifier::CurrentHold(current_limit),
                ],
            )
            .await?;
        Ok(())
    }

    async fn query_motor_status(&mut self) -> Result<ArmMotorStatus> {
        let mut driver = self.driver.lock().await;
        let base = MotorStatus::from_safety_mode_query_result(
            driver.query_safety_status(self.config.base_id).await,
        );
        let shoulder = MotorStatus::from_safety_mode_query_result(
            driver.query_safety_status(self.config.shoulder_id).await,
        );
        let elbow = MotorStatus::from_safety_mode_query_result(
            driver.query_safety_status(self.config.elbow_id).await,
        );
        let wrist = MotorStatus::from_safety_mode_query_result(
            driver.query_safety_status(self.config.wrist_id).await,
        );
        let gripper = MotorStatus::from_safety_mode_query_result(
            driver.query_safety_status(self.config.gripper_id).await,
        );
        Ok(ArmMotorStatus {
            base,
            shoulder,
            elbow,
            wrist,
            gripper,
        })
    }
}

fn calc_gripper(open: f32) -> f32 {
    let val = open.min(1.0).max(0.0);
    -1.0 * (1.0 - val) * 90.0
}

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

    #[test]
    fn arm_driver_includes_continuous_config() {
        ArmControlSettings::included_continuous();
    }

    #[test]
    fn arm_driver_includes_trajectory_config() {
        ArmControlSettings::included_trajectory();
    }

    #[test]
    fn test_closed_gripper() {
        let res = calc_gripper(1.0);
        assert_relative_eq!(res, 0.0)
    }

    #[test]
    fn test_opened_gripper() {
        let res = calc_gripper(0.0);
        assert_relative_eq!(res, -90.0)
    }

    #[test]
    fn gripper_clamps_opened() {
        let res = calc_gripper(-2.0);
        assert_relative_eq!(res, -90.0)
    }

    #[test]
    fn gripper_clamps_closed() {
        let res = calc_gripper(20.0);
        assert_relative_eq!(res, 0.0)
    }
}