adborc 0.1.0

Orchestrator for a network of distributed Android devices
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
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
use std::time::Duration;

/// Constants used by the system.
pub struct SysStateDefaultConfig;

impl SysStateDefaultConfig {
    /// Default host address for the system listener.
    /// Bind to all interfaces.
    pub const BIND_HOST: &'static str = "0.0.0.0";
    /// Default port for the system listener.
    pub const BIND_PORT: u16 = 16063;
}

/// Minimum `adb` major version supported by the system.
pub const MIN_ADB_VER: u8 = 41;
/// Minimum `adb` revision required for `supplier` mode on the system.
pub const MIN_ADB_REV: u8 = 33;
/// Minimim `scrcpy` version required. Only used for `consumer` mode.
/// This is required if device screen mirroring and control is required.
pub const MIN_SCRCPY_VER: u8 = 13;

/// Interval used for sending `heartbeat` messages to the marketmaker.
/// This is used by both `consumer` and `supplier` modes.
pub(crate) const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);
/// Interval used by marketmaker to check for heartbeat messages from
/// peer systems. If a system does not send a heartbeat message within
/// this interval, for three consecutive times, it is considered dead
/// and removed from the network.
pub(crate) const UNDERTAKER_INTERVAL: Duration = Duration::from_secs(60);
/// Connection timeout for TCP connections.
pub(crate) const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
/// Byte representation of the string "0009host:kill".
pub(crate) const ADB_KILL_SERVER_COMMAND: &[u8; 13] =
    b"\x30\x30\x30\x39\x68\x6f\x73\x74\x3a\x6b\x69\x6c\x6c";

pub(crate) const ADBORC_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Logfile name for logging standard output of the executable.
pub const STDOUT_LOGFILE: &str = "adborc_stdout.log";
/// Logfile name for logging standard error of the executable.
pub const STDERR_LOGFILE: &str = "adborc_stderr.log";
/// PID file name. To be used for checking if the system is already running.
/// Note: This is available only on unix systems.
pub const PID_FILE: &str = "adborc.pid";
/// Environment variable to check, if `adb` messages should be logged.
pub const ADBORC_LOG_ADB: &str = "ADBORC_LOG_ADB";

#[allow(dead_code)]
pub(crate) fn test_with_logs() {
    let debug_test = std::env::var("ADBORC_DEBUG_TEST").unwrap_or_default() == "true";
    if debug_test {
        use env_logger::Builder;
        use log::LevelFilter;
        let mut builder = Builder::from_default_env();
        let _ = builder.filter(None, LevelFilter::Debug).try_init();
    }
}

/// Utils related to `adb` and `scrcpy`.
pub mod adb_utils {

    use super::*;
    use lazy_static::lazy_static;
    use log::{debug, error};
    use pathsearch;
    use portpicker;
    use serde::{Deserialize, Serialize};
    use std::fmt::{self, Display, Formatter};
    use std::io::{self, Error, ErrorKind};
    use std::path::PathBuf;
    use std::process::{Child, Command, Stdio};
    use std::sync::Mutex;

    #[cfg(windows)]
    use std::os::windows::process::CommandExt;

    #[allow(dead_code)]
    const CREATE_NO_WINDOW: u32 = 0x08000000;

    /// Struct to hold adb version information.
    #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq)]
    pub struct AdbVersionInfo {
        /// The major version of adb.
        pub version: String,
        /// The revision of adb.
        pub revision: String,
        /// Path to the adb executable.
        pub path: String,
    }

    impl Display for AdbVersionInfo {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
            writeln!(
                f,
                "ADB Version: {}\tRevision: {}\nPath: {}",
                self.version, self.revision, self.path
            )
        }
    }

    /// Struct to hold scrcpy version information.
    #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq)]
    pub struct ScrcpyVersionInfo {
        /// The major version of scrcpy.
        pub version: String,
        /// Path to the scrcpy executable.
        pub path: String,
    }

    impl Display for ScrcpyVersionInfo {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
            writeln!(f, "Scrcpy Version: {}\nPath: {}", self.version, self.path)
        }
    }

    /// Struct to hold information about device.
    #[derive(Serialize, Deserialize, Debug, Default)]
    pub struct DeviceInfo {
        /// Brand of the device.
        pub brand: String,
        /// Name of the device.
        pub name: String,
        /// Model of the device.
        pub model: String,
        /// Android Serial of the device.
        pub android_id: String,
    }

    impl Display for DeviceInfo {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
            let s = format!(
                "Brand: {}   Name: {}   Model: {}",
                self.brand, self.name, self.model
            );
            write!(f, "{}", s)
        }
    }

    // DeviceInfo from String of the form: "Brand: <brand>   Name: <name>   Model: <model>"
    // Should return: DeviceInfo {
    //    brand: <brand>,
    //    name: <name>,
    //    model: <model>,
    //    android_id: ""
    // }
    // If the string is not in the expected format, return default DeviceInfo.
    impl From<String> for DeviceInfo {
        fn from(s: String) -> Self {
            let mut device_info = Self::default();
            let split = s.split("   ").collect::<Vec<&str>>();
            if split.len() == 3 {
                device_info.brand = split[0].split(": ").last().unwrap_or_default().to_string();
                device_info.name = split[1].split(": ").last().unwrap_or_default().to_string();
                device_info.model = split[2].split(": ").last().unwrap_or_default().to_string();
            }
            device_info
        }
    }

    /// Arguments to be passed to the `SCRCPY` executable.
    /// Currently supported arguments:
    /// - `--max-fps`: Maximum frames per second.
    /// - `--bit-rate`: Bit rate in Mbps.
    /// - `--max-size`: Maximum size of the device screen.
    #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
    pub struct ScrCpyArgs {
        /// Maximum frames per second. Corresponds to the `--max-fps` argument.
        pub max_fps: u8,
        /// Bit rate in Mbps. Corresponds to the `--bit-rate` argument.
        pub bit_rate: u32,
        /// Maximum size of the device screen.
        /// Corresponds to the `--max-size` argument.
        pub max_size: u16,
    }

    impl Default for ScrCpyArgs {
        fn default() -> Self {
            ScrCpyArgs {
                max_fps: 30,
                bit_rate: 2_000_000,
                max_size: 1920,
            }
        }
    }
    impl Display for ScrCpyArgs {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
            write!(
                f,
                "max-fps: {}\nbit-rate: {}\nmax-size: {}",
                self.max_fps, self.bit_rate, self.max_size
            )
        }
    }

    impl ScrCpyArgs {
        pub fn to_vec(&self) -> Vec<String> {
            vec![
                format!("--max-fps={}", self.max_fps),
                format!("--bit-rate={}", self.bit_rate),
                format!("--max-size={}", self.max_size),
            ]
        }
    }

    #[derive(Default)]
    pub(crate) struct ToolsPath {
        adb: Option<PathBuf>,
        scrcpy: Option<PathBuf>,
    }

    lazy_static! {
        static ref TOOLS_PATH: Mutex<ToolsPath> = Mutex::new(ToolsPath::default());
    }

    impl ToolsPath {
        fn set_adb(adb_path: PathBuf) {
            let mut tools_path = TOOLS_PATH.lock().unwrap();
            tools_path.adb = Some(adb_path);
        }

        fn set_scrcpy(scrcpy_path: PathBuf) {
            let mut tools_path = TOOLS_PATH.lock().unwrap();
            tools_path.scrcpy = Some(scrcpy_path);
        }

        fn get_adb() -> Option<PathBuf> {
            let tools_path = TOOLS_PATH.lock().unwrap();
            tools_path.adb.clone()
        }

        fn get_scrcpy() -> Option<PathBuf> {
            let tools_path = TOOLS_PATH.lock().unwrap();
            tools_path.scrcpy.clone()
        }

        fn find_scrcpy_in_path() -> Option<PathBuf> {
            use std::env;
            let current_exe = env::current_exe().unwrap();
            let current_exe_dir = current_exe.parent().unwrap();
            // During bundling, the `scrcpy` executable is copied to the
            // same location as that of the `adborc` executable.
            // So, we check if it is in the executable directory.
            let scrcpy_exe = if cfg!(windows) {
                current_exe_dir.join("scrcpy").with_extension("exe")
            } else {
                current_exe_dir.join("scrcpy")
            };

            if scrcpy_exe.exists() {
                Some(scrcpy_exe)
            } else {
                pathsearch::find_executable_in_path("scrcpy")
            }
        }

        fn find_adb_in_path() -> Option<PathBuf> {
            use std::env;
            let current_exe = env::current_exe().unwrap();
            let current_exe_dir = current_exe.parent().unwrap();
            // During bundling, the `adb` executable is copied to the
            // same location as that of the `adborc` executable.
            // So, we check if it is in the executable directory.
            let adb_exe = if cfg!(windows) {
                current_exe_dir.join("adb").with_extension("exe")
            } else {
                current_exe_dir.join("adb")
            };

            if adb_exe.exists() {
                Some(adb_exe)
            } else {
                pathsearch::find_executable_in_path("adb")
            }
        }
    }

    pub(crate) fn set_adb_path(adb_path: PathBuf) -> io::Result<()> {
        // Check if the path is valid.
        if !adb_path.exists() {
            return Err(Error::new(
                ErrorKind::NotFound,
                format!("Invalid path specified: {}", adb_path.display()),
            ));
        }
        // Check if the path is a directory.
        if adb_path.is_dir() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("Path is a directory: {}", adb_path.display()),
            ));
        }
        // Check if the path is not absolute.
        if !adb_path.is_absolute() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("Path is not absolute: {}", adb_path.display()),
            ));
        }
        // Check if the path is "adb".
        if adb_path.file_stem().unwrap_or_default() != "adb" {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("Path not pointing to adb: {}", adb_path.display()),
            ));
        }
        ToolsPath::set_adb(adb_path);
        Ok(())
    }

    pub(crate) fn set_scrcpy_path(scrcpy_path: PathBuf) -> io::Result<()> {
        // Check if the path is valid.
        if !scrcpy_path.exists() {
            return Err(Error::new(
                ErrorKind::NotFound,
                format!("Invalid path specified: {}", scrcpy_path.display()),
            ));
        }
        // Check if the path is a directory.
        if scrcpy_path.is_dir() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("Path is a directory: {}", scrcpy_path.display()),
            ));
        }
        // Check if the path is not absolute.
        if !scrcpy_path.is_absolute() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("Path is not absolute: {}", scrcpy_path.display()),
            ));
        }
        // Check if the path is "scrcpy".
        if scrcpy_path.file_stem().unwrap_or_default() != "scrcpy" {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("Path not pointing to scrcpy: {}", scrcpy_path.display()),
            ));
        }
        ToolsPath::set_scrcpy(scrcpy_path);
        Ok(())
    }

    /// Get the adb version info.
    /// Returns the version string if successful, otherwise returns an error.
    pub(crate) fn get_adb_version() -> io::Result<AdbVersionInfo> {
        let adb_path = match ToolsPath::get_adb() {
            Some(path) => path,
            None => {
                let adb_path = ToolsPath::find_adb_in_path().ok_or_else(|| {
                    Error::new(
                        ErrorKind::NotFound,
                        "adb not found in PATH. Please install adb and try again.",
                    )
                })?;
                ToolsPath::set_adb(adb_path.clone());
                adb_path
            }
        };
        debug!("ADB Path: {}", adb_path.display());
        let mut command = Command::new(adb_path);

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        command.arg("version");
        let output = command
            .output()
            .map_err(|e| Error::new(ErrorKind::Other, e))?;
        if output.status.success() {
            let version =
                String::from_utf8(output.stdout).map_err(|e| Error::new(ErrorKind::Other, e))?;
            // Version info is of the form:
            // Android Debug Bridge version <version>
            // Version <rev>
            // Installed as <path>
            // Result versionInfo is of the form:
            // ADB_VERSION:<ver> REVISION_NO:<rev> ADB_PATH:<path>
            let version_info = version
                .lines()
                .map(|line| line.split(' ').last().unwrap_or_default())
                .collect::<Vec<&str>>();
            Ok(AdbVersionInfo {
                version: version_info[0].to_string(),
                revision: version_info[1].to_string(),
                path: version_info[2].to_string(),
            })
        } else {
            let stderr =
                String::from_utf8(output.stderr).map_err(|e| Error::new(ErrorKind::Other, e))?;
            Err(Error::new(ErrorKind::Other, stderr))
        }
    }

    /// Check if adb version is valid.
    /// Minimum supported adb version is 1.0.41.
    /// For suppliers, minimum adb revision no. required is 33.
    /// Returns true if valid, otherwise returns false.
    #[allow(dead_code)]
    pub(crate) fn check_adb_version(ver_info: &AdbVersionInfo, is_supplier: bool) -> bool {
        let ver_number = ver_info
            .version
            .split('.')
            .last()
            .unwrap_or_default()
            .parse::<u8>()
            .unwrap_or(0);
        if is_supplier {
            let rev_number = ver_info
                .revision
                .split('.')
                .next()
                .unwrap_or_default()
                .parse::<u8>()
                .unwrap_or(0);
            ver_number >= MIN_ADB_VER && rev_number >= MIN_ADB_REV
        } else {
            ver_number >= MIN_ADB_VER
        }
    }

    /// Get the scrcpy version info.
    /// Returns the version string if successful, otherwise returns an error.
    pub(crate) fn get_scrcpy_version() -> io::Result<ScrcpyVersionInfo> {
        let scrcpy_path = match ToolsPath::get_scrcpy() {
            Some(path) => path,
            None => {
                let scrcpy_path = ToolsPath::find_scrcpy_in_path().ok_or_else(|| {
                    Error::new(
                        ErrorKind::NotFound,
                        "scrcpy not found in PATH. Please install scrcpy and try again.",
                    )
                })?;
                ToolsPath::set_scrcpy(scrcpy_path.clone());
                scrcpy_path
            }
        };
        debug!("SCRCPY Path: {}", scrcpy_path.display());
        let mut command = Command::new(scrcpy_path.clone());
        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        command.arg("--version");

        let output = command
            .output()
            .map_err(|e| Error::new(ErrorKind::Other, e))?;
        if output.status.success() {
            let version =
                String::from_utf8(output.stdout).map_err(|e| Error::new(ErrorKind::Other, e))?;
            // Version info is of the form:
            // scrcpy 1.17 <https://github.com/Genymobile/scrcpy>
            // ...
            // ...
            // Result versionInfo is of the form:
            // SCRCPY_VERSION:<ver>
            let version_info = version
                .lines()
                .take(1)
                .map(|line| line.split(' ').nth(1).unwrap_or_default())
                .collect::<Vec<&str>>();
            Ok(ScrcpyVersionInfo {
                version: version_info[0].to_string(),
                path: scrcpy_path.to_string_lossy().to_string(),
            })
        } else {
            let stderr =
                String::from_utf8(output.stderr).map_err(|e| Error::new(ErrorKind::Other, e))?;
            Err(Error::new(ErrorKind::Other, stderr))
        }
    }

    /// Get the devices connected on the system.
    pub fn get_connected_devices() -> Option<Vec<(String, DeviceInfo)>> {
        let stdio = if std::env::var(ADBORC_LOG_ADB).is_ok() {
            Stdio::inherit()
        } else {
            Stdio::null()
        };
        // Start the adb server if not already started.
        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));
        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        command
            .args(["start-server"])
            .stdout(Stdio::inherit())
            .stderr(stdio)
            .output()
            .expect("Failed to start adb server");

        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));
        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        let output = command.arg("devices").output().ok()?;
        if output.status.success() {
            let devices = String::from_utf8(output.stdout).ok()?;
            let mut devices_lines = devices.lines().skip(1).collect::<Vec<&str>>();
            devices_lines.pop();
            let devices_list = devices_lines
                .iter()
                .map(|line| line.split('\t').next().unwrap_or_default().to_string())
                .collect::<Vec<String>>();
            let mut ret_vec: Vec<(String, DeviceInfo)> = Vec::new();
            for device in devices_list {
                let device_info = get_device_info(&device, None);

                ret_vec.push((device, device_info));
            }
            Some(ret_vec)
        } else {
            None
        }
    }

    fn get_device_info(device_id: &str, port: Option<u16>) -> DeviceInfo {
        let mut device_info = DeviceInfo::default();
        let port = port.unwrap_or(5037);
        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        let output = command
            .args([
                "-P",
                &port.to_string(),
                "-s",
                device_id,
                "shell",
                "getprop",
                "ro.product.brand",
            ])
            .output();

        if let Ok(output) = output {
            if output.status.success() {
                let brand = String::from_utf8_lossy(&output.stdout).to_string();
                device_info.brand = brand.trim().to_string();
            } else {
                error!("`getprop ro.product.brand` returned failure. Failed to get device brand");
            }
        } else {
            error!("Failed to get device brand");
        }

        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        let output = command
            .args([
                "-P",
                &port.to_string(),
                "-s",
                device_id,
                "shell",
                "getprop",
                "ro.product.name",
            ])
            .output();

        if let Ok(output) = output {
            if output.status.success() {
                let name = String::from_utf8_lossy(&output.stdout).to_string();
                device_info.name = name.trim().to_string();
            } else {
                error!("`getprop ro.product.name` returned failure. Failed to get device name");
            }
        } else {
            error!("Failed to get device name");
        }

        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        let output = command
            .args([
                "-P",
                &port.to_string(),
                "-s",
                device_id,
                "shell",
                "getprop",
                "ro.product.model",
            ])
            .output();

        if let Ok(output) = output {
            if output.status.success() {
                let model = String::from_utf8_lossy(&output.stdout).to_string();
                device_info.model = model.trim().to_string();
            } else {
                error!("`getprop ro.product.model` returned failure. Failed to get device model");
            }
        } else {
            error!("Failed to get device model");
        }

        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        let output = command
            .args([
                "-s",
                device_id,
                "-P",
                port.to_string().as_str(),
                "shell",
                "settings",
                "get",
                "secure",
                "android_id",
            ])
            .output();

        if let Ok(output) = output {
            if output.status.success() {
                let android_id = String::from_utf8_lossy(&output.stdout).to_string();
                device_info.android_id = android_id.trim().to_string();
            } else {
                error!("`settings get secure android_id` returned failure. Failed to get secure android_id");
            }
        } else {
            error!("Failed to get device secure android id");
        }

        device_info
    }

    /// Restart the adb server for specific devices at different TCP ports.
    /// Eg: If there are two devices, restart the adb server for each device at different TCP ports.
    /// Takes an Optional vector of device_ids as an argument.
    /// If the Option is None, restart the adb server for all devices.
    /// Returns an Optional vector of tuples (device_id, port).
    pub(crate) fn restart_adb_server_for_devices(
        devices: Option<Vec<String>>,
        secure_comms: bool,
    ) -> Option<Vec<(String, DeviceInfo, u16)>> {
        // Extract the connected devices in the system into a Vector.
        let connected_devices = get_connected_devices()?;

        debug!("Connected devices: {:?}", connected_devices);

        // First, kill the adb server at default port.
        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        command.args(["kill-server"]).output().ok()?;

        debug!("Killed adb server at default port");

        // Then, iterate throught the connected_devices list.
        // If the devices vector is None, restart the adb server for all devices.
        // Else, check if the connected device is in the devices list.
        // If it is found, get an available port in the range 20000:21000.
        // Start the adb server for device at the available port.
        let mut ret_vec = Vec::new();

        if let Some(devices) = devices {
            for (device, device_info) in connected_devices {
                if devices.contains(&device) {
                    let port = start_adb_server_for_device(device.clone(), secure_comms);
                    ret_vec.push((device, device_info, port));
                }
            }
        } else {
            for (device, device_info) in connected_devices {
                let port = start_adb_server_for_device(device.clone(), secure_comms);
                ret_vec.push((device, device_info, port));
            }
        }

        if ret_vec.is_empty() {
            None
        } else {
            debug!("Restarted adb server for devices: {:?}", ret_vec);
            Some(ret_vec)
        }
    }

    /// Starts an adb server for a device (identified by `android_serial`) at a random port.
    fn start_adb_server_for_device(device: String, secure_comms: bool) -> u16 {
        let port = portpicker::pick_unused_port().expect("Failed to get an available port");
        debug!("Port allocated for device {} is: {}", device, port);
        let port_as_str = port.to_string();
        let port_as_str = port_as_str.as_str();

        // In windows, `adb --one-device <device_id> start-server` command is not working.
        // So, we use the `adb --one-device <device_id> server nodaemon` command instead.
        let mut start_server_args = vec![
            "--one-device",
            &device,
            "-P",
            port_as_str,
            "server",
            "nodaemon",
        ];

        // Listen on all interfaces if secure comms is disabled.
        if !secure_comms {
            start_server_args.push("-a");
        }

        let stdio = if std::env::var(ADBORC_LOG_ADB).is_ok() {
            Stdio::inherit()
        } else {
            Stdio::null()
        };
        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        command
            .args(&start_server_args)
            .stdout(Stdio::inherit())
            .stderr(stdio)
            .spawn()
            .expect("Failed to start adb server for device");

        port
    }

    pub(crate) fn kill_adb_server_for_port(port: u16) {
        let stdio = if std::env::var(ADBORC_LOG_ADB).is_ok() {
            Stdio::inherit()
        } else {
            Stdio::null()
        };
        let mut command =
            Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        command
            .args(["-P", port.to_string().as_str(), "kill-server"])
            .stdout(Stdio::inherit())
            .stderr(stdio)
            .output()
            .expect("Failed to kill adb server for port");
    }

    #[tokio::main]
    pub(crate) async fn start_scrcpy(
        adb_port: u16,
        port: u16,
        scrcpy_args: ScrCpyArgs,
    ) -> io::Result<Child> {
        debug!("Port allocated for scrcpy is: {}", port);
        let port_as_str = port.to_string();
        let scrcpy_args_vec = scrcpy_args.to_vec();
        let mut scrcpy_args_vec = scrcpy_args_vec.iter().map(|s| s.as_str()).collect();

        let mut args = vec!["--port", port_as_str.as_str()];

        args.append(&mut scrcpy_args_vec);

        debug!("Scrcpy args: {:?}", args);

        let scrcpy_path = ToolsPath::get_scrcpy().unwrap_or_else(|| PathBuf::from("scrcpy"));

        let mut command = Command::new(scrcpy_path);

        #[cfg(windows)]
        command.creation_flags(CREATE_NO_WINDOW);

        command
            .env("ADB_SERVER_SOCKET", format!("tcp:127.0.0.1:{}", adb_port))
            .args(&args)
            .stderr(Stdio::piped())
            .spawn()
    }

    #[cfg(test)]

    mod tests {
        use super::*;

        #[test]
        fn test_get_adb_version() {
            let ver_info = adb_utils::get_adb_version().unwrap();
            assert_eq!(ver_info.version, "1.0.41");
            #[cfg(target_os = "windows")]
            {
                assert_eq!(ver_info.revision, "33.0.1-8253317");
            }
            #[cfg(not(target_os = "windows"))]
            assert_eq!(ver_info.revision, "33.0.2-8557947");
        }

        #[test]
        fn test_check_adb_version() {
            let ver_info = adb_utils::get_adb_version().unwrap();
            assert!(adb_utils::check_adb_version(&ver_info, false));
            let ver_info = adb_utils::get_adb_version().unwrap();
            assert!(adb_utils::check_adb_version(&ver_info, true));
        }

        #[test]
        fn test_restart_adb_server_for_devices() {
            let devices = None;
            let port_map = adb_utils::restart_adb_server_for_devices(devices, false);
            // Since these are device-only tests, we only check if the test does not panic,
            // incase no device is attached to test machine.
            if let Some(port_map) = port_map {
                for (device, _, port) in port_map {
                    let mut command =
                        Command::new(ToolsPath::get_adb().unwrap_or_else(|| PathBuf::from("adb")));
                    #[cfg(windows)]
                    command.creation_flags(CREATE_NO_WINDOW);

                    command.args(["-P", port.to_string().as_str(), "devices"]);

                    let output = command.output().unwrap();
                    assert!(String::from_utf8(output.stdout).unwrap().contains(&device));
                }
            }
        }
    }
}