lium 0.1.2

Abstraction Layer of ChromiumOS development
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
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
// Copyright 2023 The ChromiumOS Authors
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

/// Servo is a special USB device that is used for debugging Chromebook
/// hardware. For more details, please check:
/// https://chromium.googlesource.com/chromiumos/third_party/hdctools/+/HEAD/docs/servo_v4.md

/// # Servo v4p1 Tips
/// - Servo has three major ports: HOST, DUT_POWER, SERVO_POWER
///   - HOST should be connected to your workstation / development machine
///   - DUT_POWER should be connected to a USB-C Charger
///     - Without DUT_POWER, some devices does not expose EC reliably
///     - Also, some USB-C chargers does not work well with Servo
///       - If it's not working well, try another type of chargers
///   - SERVO_POWER also should be connected to a USB-C Charger
///     - Sometimes (especially when using Chromebook as a HOST) Servo keeps
///       rebooting after connecting HOST. In that case, connecting SERVO_POWER
///       to a charger and HOST to a charger (not the host machine!), then
///       unplug the charger from HOST port and reconnect it to actual host
///       machine may work. (By following the steps, Servo will be kept on even
///       when HOST is not connected)
use core::str::FromStr;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fs;
use std::iter::FromIterator;
use std::os::unix::fs::FileTypeExt;
use std::path::Path;
use std::time::Duration;

use anyhow::anyhow;
use anyhow::bail;
use anyhow::Context;
use anyhow::Result;
use async_process::Child;
use futures::executor::block_on;
use futures::select;
use futures::FutureExt;
use futures::StreamExt;
use lazy_static::lazy_static;
use macaddr::MacAddr6;
use macaddr::MacAddr8;
use rand::seq::SliceRandom;
use rand::thread_rng;
use regex::Regex;
use retry::delay;
use retry::retry;
use serde::Deserialize;
use serde::Serialize;
use tracing::error;
use tracing::info;
use tracing::trace;
use tracing::warn;

use crate::chroot::Chroot;
use crate::config::Config;
use crate::util::shell_helpers::get_async_lines;
use crate::util::shell_helpers::get_stdout;
use crate::util::shell_helpers::run_bash_command;
use crate::util::shell_helpers::run_bash_command_with_timeout;
use crate::util::super_user_helpers::has_root_privilege;
use crate::util::super_user_helpers::run_lium_with_sudo;

lazy_static! {
    static ref RE_MAC_ADDR: Regex =
        Regex::new(r"(?P<addr>([0-9A-Za-z]{2}:){5}([0-9A-Za-z]{2}))").unwrap();
    static ref RE_EC_VERSION: Regex = Regex::new(r"RO:\s*(?P<version>.*)\n").unwrap();
    static ref RE_GBB_FLAGS: Regex = Regex::new(r"^flags: 0x(?P<flags>[0-9a-fA-F]+)$").unwrap();
    static ref RE_USB_SYSFS_PATH_FUNC: Regex = Regex::new(r"\.[0-9]+$").unwrap();
}
#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;
    #[test]
    fn regex() {
        assert!(RE_MAC_ADDR.is_match("FF:FF:FF:FF:FF:FF"));
        assert!(RE_MAC_ADDR.is_match("00:00:00:00:00:00"));
        assert!(RE_MAC_ADDR.is_match("99:99:99:99:99:99"));
        assert_eq!(
            &RE_MAC_ADDR
                .captures("Mac addr ff:ff:ff:ff:ff:ff should match")
                .unwrap()["addr"],
            "ff:ff:ff:ff:ff:ff"
        );
        assert_eq!(
            &RE_GBB_FLAGS.captures("flags: 0x000040b9").unwrap()["flags"],
            "000040b9"
        );
    }
    fn create_mock_servo(serial: &str, sysfs_path: &str) -> LocalServo {
        let slow_info = SlowServoInfo {
            mac_addr: Some("00:00:5e:00:53:01".to_string()),
            ec_version: None,
        };
        let mut tty_list = BTreeMap::new();
        tty_list.insert("Atmega UART".to_string(), "/dev/ttyUSB3".to_string());
        tty_list.insert("DUT UART".to_string(), "/dev/ttyUSB2".to_string());
        tty_list.insert("Firmware update".to_string(), "/dev/ttyUSB4".to_string());
        tty_list.insert("I2C".to_string(), "/dev/ttyUSB1".to_string());
        tty_list.insert("Servo EC Shell".to_string(), "/dev/ttyUSB0".to_string());
        LocalServo {
            product: "Servo V4p1".to_string(),
            serial: serial.to_string(),
            usb_sysfs_path: sysfs_path.to_string(),
            tty_list,
            slow_info: Some(slow_info),
        }
    }
    #[test]
    fn local_servo_info_in_json() {
        let servo = create_mock_servo("SERVOV4P1-S-0000000000", "/sys/bus/usb/devices/1-2.3");
        let serialized = format!("\n{servo}");
        assert_eq!(
            serialized,
            r#"
{
  "product": "Servo V4p1",
  "serial": "SERVOV4P1-S-0000000000",
  "usb_sysfs_path": "/sys/bus/usb/devices/1-2.3",
  "tty_list": {
    "Atmega UART": "/dev/ttyUSB3",
    "DUT UART": "/dev/ttyUSB2",
    "Firmware update": "/dev/ttyUSB4",
    "I2C": "/dev/ttyUSB1",
    "Servo EC Shell": "/dev/ttyUSB0"
  },
  "slow_info": {
    "mac_addr": "00:00:5e:00:53:01"
  }
}"#
        );
    }
    #[test]
    fn servo_info_sorted_by_sysfs_path() {
        let servo0 = create_mock_servo("SERVOV4P1-S-0000000001", "/sys/bus/usb/devices/0-0.0");
        let servo1 = create_mock_servo("SERVOV4P1-S-0000000000", "/sys/bus/usb/devices/1-1.1");
        let list = ServoList::new(vec![servo0.clone(), servo1.clone()]);
        let serialized = format!("\n{list}\n");
        assert_eq!(
            serialized,
            r#"
{
  "devices": [
    {
      "product": "Servo V4p1",
      "serial": "SERVOV4P1-S-0000000001",
      "usb_sysfs_path": "/sys/bus/usb/devices/0-0.0",
      "tty_list": {
        "Atmega UART": "/dev/ttyUSB3",
        "DUT UART": "/dev/ttyUSB2",
        "Firmware update": "/dev/ttyUSB4",
        "I2C": "/dev/ttyUSB1",
        "Servo EC Shell": "/dev/ttyUSB0"
      },
      "slow_info": {
        "mac_addr": "00:00:5e:00:53:01"
      }
    },
    {
      "product": "Servo V4p1",
      "serial": "SERVOV4P1-S-0000000000",
      "usb_sysfs_path": "/sys/bus/usb/devices/1-1.1",
      "tty_list": {
        "Atmega UART": "/dev/ttyUSB3",
        "DUT UART": "/dev/ttyUSB2",
        "Firmware update": "/dev/ttyUSB4",
        "I2C": "/dev/ttyUSB1",
        "Servo EC Shell": "/dev/ttyUSB0"
      },
      "slow_info": {
        "mac_addr": "00:00:5e:00:53:01"
      }
    }
  ]
}
"#
        );
        let list = ServoList::new(vec![servo1.clone(), servo0.clone()]);
        let serialized = format!("\n{list}\n");
        assert_eq!(
            serialized,
            r#"
{
  "devices": [
    {
      "product": "Servo V4p1",
      "serial": "SERVOV4P1-S-0000000001",
      "usb_sysfs_path": "/sys/bus/usb/devices/0-0.0",
      "tty_list": {
        "Atmega UART": "/dev/ttyUSB3",
        "DUT UART": "/dev/ttyUSB2",
        "Firmware update": "/dev/ttyUSB4",
        "I2C": "/dev/ttyUSB1",
        "Servo EC Shell": "/dev/ttyUSB0"
      },
      "slow_info": {
        "mac_addr": "00:00:5e:00:53:01"
      }
    },
    {
      "product": "Servo V4p1",
      "serial": "SERVOV4P1-S-0000000000",
      "usb_sysfs_path": "/sys/bus/usb/devices/1-1.1",
      "tty_list": {
        "Atmega UART": "/dev/ttyUSB3",
        "DUT UART": "/dev/ttyUSB2",
        "Firmware update": "/dev/ttyUSB4",
        "I2C": "/dev/ttyUSB1",
        "Servo EC Shell": "/dev/ttyUSB0"
      },
      "slow_info": {
        "mac_addr": "00:00:5e:00:53:01"
      }
    }
  ]
}
"#
        );
    }
}

fn get_usb_sysfs_path_stem(path: &str) -> String {
    RE_USB_SYSFS_PATH_FUNC.replace(path, "").to_string()
}

pub fn get_servo_attached_to_cr50(cr50: &LocalServo) -> Result<LocalServo> {
    let usb_path = cr50.usb_sysfs_path();
    let common_path = get_usb_sysfs_path_stem(usb_path);
    let list = discover()?;
    list.iter()
        .filter(|s| s.is_servo())
        .find(|s| get_usb_sysfs_path_stem(s.usb_sysfs_path()) == common_path)
        .cloned()
        .context(anyhow!("No Cr50 attached with the Servo found"))
}
pub fn get_cr50_attached_to_servo(servo: &LocalServo) -> Result<LocalServo> {
    let usb_path = servo.usb_sysfs_path();
    let common_path = get_usb_sysfs_path_stem(usb_path);
    let list = discover()?;
    list.iter()
        .filter(|s| s.is_cr50())
        .find(|s| get_usb_sysfs_path_stem(s.usb_sysfs_path()) == common_path)
        .cloned()
        .context(anyhow!("No Cr50 attached with the Servo found"))
}

fn read_usb_attribute(dir: &Path, name: &str) -> Result<String> {
    let value = dir.join(name);
    let value = fs::read_to_string(value)?;
    Ok(value.trim().to_string())
}

// This is private since users should use ServoList instead
fn discover() -> Result<Vec<LocalServo>> {
    let paths = fs::read_dir("/sys/bus/usb/devices/").unwrap();
    Ok(paths
        .flat_map(|usb_path| -> Result<LocalServo> {
            let usb_sysfs_path = usb_path?.path();
            let product = read_usb_attribute(&usb_sysfs_path, "product")?;
            let serial = read_usb_attribute(&usb_sysfs_path, "serial")?;
            if product.starts_with("Servo")
                || product.starts_with("Cr50")
                || product.starts_with("Ti50")
            {
                let paths = fs::read_dir(&usb_sysfs_path).context("failed to read dir")?;
                let tty_list: BTreeMap<String, String> = paths
                    .flat_map(|path| -> Result<(String, String)> {
                        let path = path?.path();
                        let interface = fs::read_to_string(path.join("interface"))?
                            .trim()
                            .to_string();
                        let tty_name = fs::read_dir(path)?
                            .find_map(|p| {
                                let s = p.ok()?.path();
                                let s = s.file_name()?.to_string_lossy().to_string();
                                s.starts_with("ttyUSB").then_some("/dev/".to_string() + &s)
                            })
                            .context("ttyUSB not found")?;
                        Ok((interface, tty_name))
                    })
                    .collect();
                Ok(LocalServo {
                    product,
                    serial,
                    usb_sysfs_path: usb_sysfs_path.to_string_lossy().to_string(),
                    tty_list,
                    ..Default::default()
                })
            } else {
                bail!("Not a servo")
            }
        })
        .collect())
}

fn discover_slow() -> Result<Vec<LocalServo>> {
    let mut servos = discover()?;
    servos.iter_mut().for_each(|s| {
        info!("Checking {}", s.serial);
        let mac_addr = s.read_mac_addr().ok();
        let ec_version = s.read_ec_version().ok();
        s.slow_info = Some(SlowServoInfo {
            mac_addr,
            ec_version,
        })
    });
    Ok(servos)
}

pub fn reset_devices(serials: &Vec<String>) -> Result<()> {
    let servo_info = discover()?;
    let servo_info: Vec<LocalServo> = if !serials.is_empty() {
        let serials: HashSet<_> = HashSet::from_iter(serials.iter());
        servo_info
            .iter()
            .filter(|s| serials.contains(&s.serial().to_string()))
            .cloned()
            .collect()
    } else {
        servo_info
    };
    for s in &servo_info {
        s.reset()?;
    }
    std::thread::sleep(Duration::from_millis(1000));

    Ok(())
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct ServoList {
    devices: Vec<LocalServo>,
}
impl ServoList {
    pub fn new(mut devices: Vec<LocalServo>) -> Self {
        devices.sort();
        Self { devices }
    }
    pub fn discover() -> Result<Self> {
        Ok(Self::new(discover()?))
    }
    pub fn discover_slow() -> Result<Self> {
        Ok(Self::new(discover_slow()?))
    }
    pub fn find_by_serial(&self, serial: &str) -> Result<&LocalServo> {
        self.devices
            .iter()
            .find(|s| s.serial() == serial)
            .context("Servo not found with a given serial")
    }
    pub fn devices(&self) -> &Vec<LocalServo> {
        &self.devices
    }
}
impl Display for ServoList {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            serde_json::to_string_pretty(&self).map_err(|_| fmt::Error)?
        )
    }
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct SlowServoInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    mac_addr: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    ec_version: Option<String>,
}
impl SlowServoInfo {}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct LocalServo {
    product: String,
    serial: String,
    usb_sysfs_path: String,
    // Using BTreeMap here to keep the ordering when printing this structure
    tty_list: BTreeMap<String, String>,
    slow_info: Option<SlowServoInfo>,
}
impl LocalServo {
    pub fn product(&self) -> &str {
        &self.product
    }
    pub fn serial(&self) -> &str {
        &self.serial
    }
    pub fn tty_list(&self) -> &BTreeMap<String, String> {
        &self.tty_list
    }
    pub fn tty_path(&self, tty_type: &str) -> Result<String> {
        let path = self
            .tty_list()
            .get(tty_type)
            .context(anyhow!("tty[{}] not found", tty_type))?;
        Ok(path.clone())
    }
    pub fn run_cmd(&self, tty_type: &str, cmd: &str) -> Result<String> {
        let tty_path = &self.tty_path(tty_type)?;
        // Check if socat is installed
        let socat_path = run_bash_command("which socat", None)?;
        let socat_path = get_stdout(&socat_path);
        if socat_path.trim().is_empty() {
            return Err(anyhow!(
                "socat not found. Please install socat with something like: `sudo apt install \
                 socat`"
            ));
        }
        if !fs::metadata(tty_path)?.file_type().is_char_device() {
            bail!("{tty_path} is not a char device");
        }
        let output = run_bash_command_with_timeout(
            &format!("echo {cmd} | socat - {tty_path},echo=0,crtscts=1 2>&1"),
            None,
            Duration::from_secs(1),
        )
        .context(anyhow!("Servo command failed: {cmd}"))?;
        Ok(output)
    }
    pub fn usb_sysfs_path(&self) -> &str {
        &self.usb_sysfs_path
    }
    pub fn reset(&self) -> Result<()> {
        if has_root_privilege()? {
            info!("Resetting servo device: {}", self.serial);
            let path = Path::new(&self.usb_sysfs_path).join("authorized");
            fs::write(&path, b"0").context(anyhow!("Failed to set authorized = 0 {path:?}"))?;
            if let Err(e) = fs::write(&path, b"1") {
                // sometimes writing to `authorized` fails with EPIPE, but it can be ignored.
                warn!("Warning: Failed to set authorized = 1 {path:?} ({e:?})");
            }
            Ok(())
        } else {
            run_lium_with_sudo(&["servo", "reset", self.serial()])
        }
    }
    pub fn from_serial(serial: &str) -> Result<LocalServo> {
        let servos = discover()?;
        Ok(servos
            .iter()
            .find(|&s| s.serial == serial)
            .context(anyhow!("Servo not found: {serial}"))?
            .clone())
    }
    fn start_servod_on_port(&self, chroot: &Chroot, port: u16) -> Result<Child> {
        chroot
            .exec_in_chroot_async(&[
                "sudo",
                "servod",
                "-s",
                &self.serial,
                "-p",
                &port.to_string(),
            ])
            .context("failed to launch servod")
    }
    pub fn start_servod(&self, chroot: &Chroot) -> Result<ServodConnection> {
        block_on(async {
            info!("Starting servod...");
            let mut ports = (9000..9099).collect::<Vec<u16>>();
            let mut rng = thread_rng();
            ports.shuffle(&mut rng);
            for port in ports {
                let mut servod = self.start_servod_on_port(chroot, port)?;
                let (servod_stdout, servod_stderr) = get_async_lines(&mut servod);
                let mut servod_stdout = servod_stdout.context(anyhow!("servod_stdout was None"))?;
                let mut servod_stderr = servod_stderr.context(anyhow!("servod_stdout was None"))?;
                loop {
                    let mut servod_stdout = servod_stdout.next().fuse();
                    let mut servod_stderr = servod_stderr.next().fuse();
                    select! {
                            line = servod_stderr => {
                                if let Some(line) = line {
                                    let line = line?;
                                trace!("{}", line);
                                    if line.contains("is busy") {
                                        break;
                                    }
                                } else {
                    bail!("servod failed unexpectedly");
                                }
                            }
                            line = servod_stdout => {
                                if let Some(line) = line {
                                    let line = line?;
                                    trace!("{}", line);
                                    if line.contains("Listening on localhost port") {
                                        return Result::Ok(servod);
                                    }
                                } else {
                    bail!("servod failed unexpectedly");
                                }
                            }
                        }
                }
            }

            bail!("servod failed unexpectedly")
        })?;
        ServodConnection::from_serial(&self.serial)
    }
    pub fn is_cr50(&self) -> bool {
        self.product() == "Cr50" || self.product() == "Ti50"
    }
    pub fn is_servo(&self) -> bool {
        self.product().starts_with("Servo")
    }
    pub fn read_ec_version(&self) -> Result<String> {
        if !self.is_cr50() {
            return Err(anyhow!(
                "{} is not a Cr50, but {}",
                self.serial(),
                self.product()
            ));
        }
        retry(delay::Fixed::from_millis(500).take(2), || {
            let output = self.run_cmd("EC", "version").inspect_err(|e| {
                error!("version command on EC failed: {e}");
            })?;
            RE_EC_VERSION
                .captures(&output)
                .map(|c| c["version"].trim().to_lowercase())
                .context(anyhow!("Failed to get EC version"))
                .inspect_err(|e| {
                    error!("{:#?}: {output}", e);
                })
        })
        .or(Err(anyhow!("Failed to get EC version after retries")))
    }
    pub fn read_mac_addr(&self) -> Result<String> {
        if !self.is_servo() {
            return Err(anyhow!(
                "{} is not a Servo, but {}",
                self.serial(),
                self.product()
            ));
        }
        retry(delay::Fixed::from_millis(1000).take(10), || {
            let output = &self
                .run_cmd("Servo EC Shell", "macaddr")
                .inspect_err(|_| error!("macaddr cmd failed. retrying..."))?;
            RE_MAC_ADDR
                .captures(output)
                .map(|c| c["addr"].to_lowercase())
                .ok_or(anyhow!("macaddr not found in the output. retrying..."))
                .inspect_err(|e| error!("{e}"))
        })
        .or(Err(anyhow!("Failed to get mac_addr after retries")))
    }
    pub fn read_mac_addr6(&self) -> Result<MacAddr6> {
        MacAddr6::from_str(&self.read_mac_addr()?)
            .context("Failed to convert MAC address string to MacAddr6")
    }
    pub fn read_mac_addr8(&self) -> Result<MacAddr8> {
        MacAddr8::from_str(&self.read_mac_addr()?)
            .context("Failed to convert MAC address string to MacAddr8")
    }
    pub fn read_ipv6_addr(&self) -> Result<String> {
        let mac_addr = self.read_mac_addr6()?;
        let config = Config::read()?;
        let prefix = config
            .default_ipv6_prefix()
            .context("Config default_ipv6_prefix is needed")?;
        let mac_addr = mac_addr.as_bytes();
        let mut eui64_bytes = [0; 8];
        eui64_bytes.copy_from_slice(
            [&mac_addr[0..3], [0xff, 0xfe].as_slice(), &mac_addr[3..6]]
                .concat()
                .as_slice(),
        );
        eui64_bytes[0] |= 0x02; // Modified EUI-64 has universal/local bit = 1 (universal)
        Ok(format!(
            "[{}{}]",
            prefix,
            format!("{:#}", MacAddr8::from(eui64_bytes))
                .replace('.', ":")
                .to_lowercase()
        ))
    }
    pub fn read_gbb_flags(&self, repo: &str) -> Result<u64> {
        if !self.is_cr50() {
            return get_cr50_attached_to_servo(self)?.read_gbb_flags(repo);
        }
        let chroot = Chroot::new(repo)?;
        info!("Reading gbb flags via Cr50...");
        chroot.exec_in_chroot(&[
            "sudo",
            "flashrom",
            "-p",
            &format!("raiden_debug_spi:target=AP,serial={}", self.serial),
            "-r",
            "-i",
            "GBB:/tmp/gbb.bin",
        ])?;
        info!("Extracting gbb flags...");
        let flags =
            chroot.exec_in_chroot(&["sudo", "futility", "gbb", "-g", "--flags", "/tmp/gbb.bin"])?;
        let flags = &RE_GBB_FLAGS
            .captures(&flags)
            .context("Invalid output of futility: {flags}")?["flags"];
        u64::from_str_radix(flags, 16).context("Failed to convert value: {flags}")
    }
}
impl Display for LocalServo {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            serde_json::to_string_pretty(&self).map_err(|_| fmt::Error)?
        )
    }
}
impl PartialEq for LocalServo {
    fn eq(&self, other: &Self) -> bool {
        self.usb_sysfs_path == other.usb_sysfs_path
    }
}
impl Eq for LocalServo {}
impl PartialOrd for LocalServo {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.usb_sysfs_path.cmp(&other.usb_sysfs_path))
    }
}
impl Ord for LocalServo {
    fn cmp(&self, other: &Self) -> Ordering {
        self.usb_sysfs_path.cmp(&other.usb_sysfs_path)
    }
}

pub struct ServodConnection {
    serial: String,
    host: String,
    port: u16,
}
impl ServodConnection {
    pub fn from_serial(serial: &str) -> Result<Self> {
        let output = run_bash_command(
            &format!(
                "ps ax | grep /servod | grep -e '-s {}' | grep -E -o -e '-p [0-9]+' | cut -d ' ' \
                 -f 2",
                serial
            ),
            None,
        );
        if let Ok(output) = output {
            let stdout = get_stdout(&output);
            let port = stdout.parse::<u16>()?;
            Ok(Self {
                serial: serial.to_string(),
                host: "localhost".to_string(),
                port,
            })
        } else {
            bail!("Servod for {serial} is not running")
        }
    }
    pub fn serial(&self) -> &str {
        &self.serial
    }
    pub fn host(&self) -> &str {
        &self.host
    }
    pub fn port(&self) -> u16 {
        self.port
    }
    pub fn run_dut_control<T: AsRef<str>>(&self, chroot: &Chroot, args: &[T]) -> Result<String> {
        info!("Using servod port {:?}", self.port);
        let output = chroot.exec_in_chroot(
            &[
                ["dut-control", "-p", &self.port.to_string()].as_slice(),
                args.iter()
                    .map(AsRef::as_ref)
                    .collect::<Vec<&str>>()
                    .as_slice(),
            ]
            .concat(),
        )?;
        Ok(output)
    }
}