fll-rs 0.1.4

Movement and ui apis for lego ev3 robots intended for use in the FIRST Lego League competition
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
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
use crate::error::Result;
use crate::input::Input;
use crate::movement::controller::MovementController;
use crate::movement::pid::PidConfig;
use crate::movement::spec::RobotSpec;
use crate::robot::{
    AngleProvider, ColorSensor, Command, Motor, MotorId, Robot, StopAction, TurnType,
};
use crate::types::{Degrees, DegreesPerSecond, Distance, Heading, Percent, Speed};
use anyhow::{bail, Context};
use ev3dev_lang_rust::motors::{MotorPort, TachoMotor as Ev3TachoMotor};
use ev3dev_lang_rust::sensors::ColorSensor as Ev3ColorSensor;
use ev3dev_lang_rust::sensors::GyroSensor as Ev3GyroSensor;
use ev3dev_lang_rust::sensors::Sensor;
use ev3dev_lang_rust::sensors::SensorPort;
use ev3dev_lang_rust::{wait, Ev3Button, Port, PowerSupply};
use ev3dev_lang_rust::{Attribute, Device};
use fxhash::FxHashMap as HashMap;
use std::cell::{RefCell, RefMut};
use std::fs::File;
use std::os::unix::io::AsRawFd;
use std::rc::Rc;
use std::thread;
use std::time::Duration;

pub struct LegoRobot {
    battery: PowerSupply,

    buttons: Ev3Button,
    buttons_raw: File,
    input: RefCell<Input>,

    pid_config: PidConfig,
    controller: RefCell<MovementController>,
    angle_algorithm: AngleAlgorithm,

    motors: HashMap<MotorId, RefCell<LegoMotor>>,
    motor_definitions: Vec<(MotorId, MotorPort)>,
    sensors: HashMap<String, LegoSensor>,

    spec: Rc<RobotSpec>,
}

pub enum AngleAlgorithm {
    Wheel,
    Gyro(SensorPort),
}

enum LegoSensor {
    Gyro(RefCell<LegoGyroSensor>),
    Color(RefCell<LegoColorSensor>),
}

struct LegoMotor {
    motor: Ev3TachoMotor,

    queued_command: Option<Command>,

    stopping_action: Option<StopAction>,

    speed_sp: Option<i32>,
    time_sp: Option<Duration>,
    position_sp: Option<i32>,

    spec: Rc<RobotSpec>,
}

struct LegoGyroSensor {
    gyro: Ev3GyroSensor,
}

struct LegoColorSensor {
    color: Ev3ColorSensor,
    white: f32,
    black: f32,
}

impl LegoRobot {
    pub fn new(
        motor_definitions: &[(MotorId, MotorPort)],
        pid_config: PidConfig,
        spec: RobotSpec,
        angle_algorithm: AngleAlgorithm,
    ) -> Result<Self> {
        // Wait for any drivers to start up
        thread::sleep(Duration::from_millis(300));

        let battery = PowerSupply::new().context("Couldn't find power supply")?;

        let controller = MovementController::new(pid_config).into();

        let spec = Rc::new(spec);

        // Setup input
        let buttons = Ev3Button::new().context("Couldn't find buttons")?;
        let input = Default::default();
        let buttons_raw = File::open("/dev/input/by-path/platform-gpio_keys-event")?;

        // Discover sensors and motors
        let motor_definitions: Vec<_> = motor_definitions.into();
        let motors =
            discover_motors(&motor_definitions, spec.clone()).context("Discover motors")?;
        let sensors = discover_sensors().context("Discover sensors")?;

        Ok(Self {
            battery,
            buttons,
            input,
            buttons_raw,
            controller,
            motors,
            spec,
            angle_algorithm,
            sensors,
            motor_definitions,
            pid_config,
        })
    }

    pub fn rediscover_motors(&mut self) -> Result<()> {
        self.motors = discover_motors(&self.motor_definitions, self.spec.clone())
            .context("Discover motors")?;

        Ok(())
    }

    pub fn rediscover_sensors(&mut self) -> Result<()> {
        self.sensors = discover_sensors().context("Discover sensors")?;

        Ok(())
    }

    fn update_button_state(&self) -> bool {
        self.buttons.process();

        let mut state = [false; 6];

        state[Input::UP] = self.buttons.is_up();
        state[Input::DOWN] = self.buttons.is_down();
        state[Input::LEFT] = self.buttons.is_left();
        state[Input::RIGHT] = self.buttons.is_right();
        state[Input::ENTER] = self.buttons.is_enter();
        state[Input::BACKSPACE] = self.buttons.is_backspace();

        self.input.borrow_mut().update(state)
    }
}

impl Robot for LegoRobot {
    fn drive(&self, distance: impl Into<Distance>, speed: impl Into<Speed>) -> Result<()> {
        self.controller.borrow_mut().drive(
            self,
            distance.into().to_deg(&self.spec),
            speed.into().to_dps(&self.spec),
        )
    }

    fn turn(&self, angle: Heading, speed: impl Into<Speed>) -> Result<()> {
        self.controller
            .borrow_mut()
            .turn(self, angle, speed.into().to_dps(&self.spec))
    }

    fn turn_named(&self, angle: Heading, speed: impl Into<Speed>, turn: TurnType) -> Result<()> {
        self.controller
            .borrow_mut()
            .turn_named(self, angle, speed.into().to_dps(&self.spec), turn)
    }

    fn motor(&self, motor_id: MotorId) -> Option<RefMut<dyn Motor>> {
        let motor = self.motors.get(&motor_id);

        if let Some(motor) = motor {
            Some(motor.borrow_mut())
        } else {
            None
        }
    }

    fn color_sensor(&self, port: SensorPort) -> Option<RefMut<dyn ColorSensor>> {
        let sensor = self.sensors.get(&port.address());

        if let Some(LegoSensor::Color(color)) = sensor {
            Some(color.borrow_mut())
        } else {
            None
        }
    }

    fn process_buttons(&self) -> Result<Input> {
        self.update_button_state();

        Ok(self.input.borrow().clone())
    }

    fn battery(&self) -> Result<Percent> {
        // let min = self
        //     .battery
        //     .get_voltage_min_design()
        //     .context("Get min voltage")? as f32;

        let max = self
            .battery
            .get_voltage_max_design()
            .context("Get max voltage")? as f32;
        let current = self.battery.get_voltage_now().context("Get voltage")? as f32;

        // Ok(Percent((dbg!(current) - dbg!(min)) / (dbg!(max) - min)))

        // Seems to be a bug in ev3dev
        Ok(Percent((current * 10.0 / max).min(1.0).max(0.0)))
    }

    fn await_input(&self, timeout: Option<Duration>) -> Result<Input> {
        wait::wait(
            self.buttons_raw.as_raw_fd(),
            || self.update_button_state(),
            timeout,
        );

        Ok(self.input.borrow().clone())
    }

    fn stop(&self) -> Result<()> {
        for motor in self.motors.values() {
            motor
                .borrow_mut()
                .motor_reset(Some(StopAction::Coast))
                .context("Reset motor")?;
        }
        Ok(())
    }

    fn reset(&self) -> Result<()> {
        for motor in self.motors.values() {
            motor
                .borrow_mut()
                .motor_reset(None)
                .context("Reset motor")?;
        }
        for sensor in self.sensors.values() {
            match sensor {
                LegoSensor::Gyro(gyro) => {
                    reset_gyro_soft(&mut gyro.borrow_mut())?;
                }
                LegoSensor::Color(_) => {}
            }
        }
        *self.input.borrow_mut() = Default::default();
        *self.controller.borrow_mut() = MovementController::new(self.pid_config);

        Ok(())
    }

    fn spec(&self) -> &RobotSpec {
        &self.spec
    }

    fn set_heading(&self, angle: Heading) -> Result<()> {
        self.controller.borrow_mut().target_direction = angle;
        Ok(())
    }
}

impl AngleProvider for LegoRobot {
    fn angle(&self) -> Result<Heading> {
        match self.angle_algorithm {
            AngleAlgorithm::Wheel => {
                let left = self
                    .motor(MotorId::DriveLeft)
                    .context("Left motor")?
                    .motor_angle()?;
                let right = self
                    .motor(MotorId::DriveRight)
                    .context("Right motor")?
                    .motor_angle()?;

                Ok(self.spec().get_approx_angle(left, right))
            }
            AngleAlgorithm::Gyro(port) => {
                let sensor = self.sensors.get(&port.address()).context("No gyro found")?;

                if let LegoSensor::Gyro(gyro) = sensor {
                    Ok(Heading(gyro.borrow().gyro.get_value0()? as f32))
                } else {
                    bail!("Sensor in {port:?} is not a gyro sensor");
                }
            }
        }
    }
}

impl LegoMotor {
    fn handle_command(&mut self, command: &Command, execute: bool) -> Result<()> {
        match command {
            Command::On(speed) => {
                let dps = speed.to_dps(&self.spec).0 as i32;

                if Some(dps) != self.speed_sp {
                    self.motor.set_speed_sp(dps).context("Set speed setpoint")?;
                    self.speed_sp = Some(dps);
                }

                if execute {
                    self.motor.run_forever().context("Run forever")?;
                }
            }
            Command::Stop(action) => {
                if Some(*action) != self.stopping_action {
                    self.motor
                        .set_stop_action(action.to_str())
                        .context("Set stop action")?;
                    self.stopping_action = Some(*action);
                }

                if execute {
                    self.motor.stop().context("Stop motor")?;
                }
            }
            Command::Distance(distance, speed) => {
                let deg = distance.to_deg(&self.spec).0 as i32;
                let dps = speed.to_dps(&self.spec).0 as i32;

                if Some(deg) != self.position_sp {
                    self.motor
                        .set_position_sp(deg)
                        .context("Set position setpoint")?;
                    self.position_sp = Some(deg);
                }

                if Some(dps) != self.speed_sp {
                    self.motor.set_speed_sp(dps).context("Set speed setpoint")?;
                    self.speed_sp = Some(dps);
                }

                if execute {
                    self.motor.run_to_rel_pos(None).context("Run relative")?;
                }
            }
            Command::To(position, speed) => {
                let deg = position.to_deg(&self.spec).0 as i32;
                let dps = speed.to_dps(&self.spec).0 as i32;

                if Some(deg) != self.position_sp {
                    self.motor
                        .set_position_sp(deg)
                        .context("Set position setpoint")?;
                    self.position_sp = Some(deg);
                }

                if Some(dps) != self.speed_sp {
                    self.motor.set_speed_sp(dps).context("Set speed setpoint")?;
                    self.speed_sp = Some(dps);
                }

                if execute {
                    self.motor.run_to_abs_pos(None).context("Run absloute")?;
                }
            }
            Command::Time(duration, speed) => {
                let dps = speed.to_dps(&self.spec).0 as i32;

                if Some(*duration) != self.time_sp {
                    self.motor
                        .set_time_sp(duration.as_millis() as i32)
                        .context("Set time setpoint")?;
                    self.time_sp = Some(*duration);
                }

                if Some(dps) != self.speed_sp {
                    self.motor.set_speed_sp(dps).context("Set speed setpoint")?;
                    self.speed_sp = Some(dps)
                }

                if execute {
                    self.motor.run_timed(None).context("Run timed")?;
                }
            }
            command => panic!("Got bad command {command:?}"),
        }

        Ok(())
    }
}

impl Motor for LegoMotor {
    fn raw(&mut self, command: Command) -> Result<()> {
        // Clear queued action if needed
        match command {
            Command::Queue(_) | Command::Execute => {}
            _ => {
                self.queued_command = None;
            }
        }

        match command {
            Command::Queue(queued_command) => {
                self.handle_command(&queued_command, false)?;

                self.queued_command = Some(*queued_command);
            }
            Command::Execute => {
                if let Some(queued_command) = self.queued_command.take() {
                    self.handle_command(&queued_command, true)?;
                } else {
                    bail!("Reveived `Command::Execute` when no command was queued");
                }
            }
            command => {
                self.handle_command(&command, true)?;
            }
        }

        Ok(())
    }

    fn motor_reset(&mut self, stop_action: Option<StopAction>) -> Result<()> {
        self.motor.reset().context("Reset motor")?;

        self.queued_command = None;
        self.stopping_action = None;
        self.speed_sp = None;
        self.time_sp = None;
        self.position_sp = None;

        if let Some(stop_action) = stop_action {
            self.motor
                .set_stop_action(stop_action.to_str())
                .context("Set stop action")?;

            self.stopping_action = Some(stop_action);
        }

        self.motor.stop().context("Stop motor")?;

        Ok(())
    }

    fn wait(&self, timeout: Option<Duration>) -> Result<()> {
        self.motor.wait_until_not_moving(timeout);

        Ok(())
    }

    fn speed(&self) -> Result<Speed> {
        self.motor
            .get_speed()
            .map(|it| DegreesPerSecond(it as f32).into())
            .context("Read motor speed")
    }

    fn motor_angle(&self) -> Result<Distance> {
        self.motor
            .get_position()
            .map(|it| Degrees(it as f32).into())
            .context("Read motor position")
    }
}

impl ColorSensor for LegoColorSensor {
    fn reflected_light(&self) -> Result<Percent> {
        let reflected = self.color.get_color().context("Read color sensor")?;
        let percent = reflected as f32 / 100.0;
        let adjusted = (percent - self.black) / (self.white - self.black);

        Ok(Percent(adjusted))
    }

    fn cal_white(&mut self) -> Result<()> {
        let reflected = self.color.get_color().context("Read color sensor")?;
        self.white = reflected as f32 / 100.0;

        Ok(())
    }

    fn cal_black(&mut self) -> Result<()> {
        let reflected = self.color.get_color().context("Read color sensor")?;
        self.black = reflected as f32 / 100.0;

        Ok(())
    }

    fn reset(&mut self) -> Result<()> {
        self.white = 1.0;
        self.black = 0.0;

        Ok(())
    }
}

fn discover_motors(
    motor_definitions: &[(MotorId, MotorPort)],
    spec: Rc<RobotSpec>,
) -> Result<HashMap<MotorId, RefCell<LegoMotor>>> {
    let mut motors = HashMap::default();

    for (motor_id, port) in motor_definitions {
        let motor = Ev3TachoMotor::get(*port)
            .with_context(|| format!("Couldn't find motor {:?}, port {:?}", motor_id, port))?;
        motors.insert(
            *motor_id,
            LegoMotor {
                motor,
                queued_command: None,
                stopping_action: None,
                speed_sp: None,
                time_sp: None,
                position_sp: None,
                spec: spec.clone(),
            }
            .into(),
        );
    }

    Ok(motors)
}

fn discover_sensors() -> Result<HashMap<String, LegoSensor>> {
    let mut sensors = HashMap::default();

    for color_sensor in Ev3ColorSensor::list().context("Find color sensors")? {
        let address = color_sensor
            .get_address()?
            .strip_prefix("ev3-ports:")
            .context("Strip prefix")?
            .to_owned();
        sensors.insert(
            address,
            LegoSensor::Color(
                init_color_sensor(color_sensor)
                    .context("Init color sensor")?
                    .into(),
            ),
        );
    }
    for gyro_sensor in Ev3GyroSensor::list().context("Find gyro sensors")? {
        let address = gyro_sensor
            .get_address()?
            .strip_prefix("ev3-ports:")
            .context("Strip prefix")?
            .to_owned();
        sensors.insert(
            address,
            LegoSensor::Gyro(
                init_gyro_sensor(gyro_sensor)
                    .context("Init gyro sensor")?
                    .into(),
            ),
        );
    }

    Ok(sensors)
}

fn init_color_sensor(color: Ev3ColorSensor) -> Result<LegoColorSensor> {
    color
        .set_mode_col_reflect()
        .context("Set color sensor mode")?;

    Ok(LegoColorSensor {
        color,
        white: 1.0,
        black: 0.0,
    })
}

fn init_gyro_sensor(gyro: Ev3GyroSensor) -> Result<LegoGyroSensor> {
    gyro.set_mode_gyro_ang().context("Set gyro sensor mode")?;

    let mut gyro = LegoGyroSensor { gyro };

    reset_gyro_hard(&mut gyro).context("Reset gyro hard")?;
    reset_gyro_soft(&mut gyro).context("Reset gyro soft")?;

    Ok(gyro)
}

fn reset_gyro_hard(gyro: &mut LegoGyroSensor) -> Result<()> {
    let address = gyro.gyro.get_address().context("Get sensor address")?;

    let mode = Attribute::from_path_with_discriminator(
        "/sys/class/lego-port",
        "/mode",
        "/address",
        address.as_str(),
    )
    .context("Get mode attribute")?;

    mode.set_str_slice("other-uart")
        .context("Hard reset gyro")?;
    thread::sleep(Duration::from_millis(300));
    mode.set_str_slice("auto").context("Hard reset gyro")?;

    for _ in 0..100 {
        let gyros = Ev3GyroSensor::list().context("Find gyro sensors")?;
        for new_gyro in gyros {
            if new_gyro
                .get_address()
                .context("Get new sensor address")?
                .contains(&address)
            {
                gyro.gyro = new_gyro;

                // Wait for driver to initalize
                thread::sleep(Duration::from_millis(500));

                return Ok(());
            }
        }

        // Busy wait the gyro to come back online
        thread::sleep(Duration::from_millis(100));
    }

    bail!("Gyro did not reconnect within 10s");
}

fn reset_gyro_soft(gyro: &mut LegoGyroSensor) -> Result<()> {
    gyro.gyro
        .get_attribute("direct")
        .set_str_slice("\x11")
        .context("Write reset command")?;

    thread::sleep(Duration::from_millis(25));

    Ok(())
}