vcontrol/
protocol.rs

1use std::{fmt, io};
2
3use crate::Optolink;
4
5mod vs1;
6use self::vs1::Vs1;
7
8mod vs2;
9use self::vs2::Vs2;
10
11#[derive(Debug, Clone, Copy)]
12pub enum Protocol {
13  Vs1,
14  Vs2,
15}
16
17impl Protocol {
18  /// Try detecting the protocol automatically.
19  pub async fn detect(o: &mut Optolink) -> Option<Self> {
20    if Vs2::negotiate(o).await.is_ok() {
21      return Some(Self::Vs2)
22    }
23
24    if Vs1::negotiate(o).await.is_ok() {
25      return Some(Self::Vs1)
26    }
27
28    None
29  }
30
31  /// Negotiate the protocol.
32  pub async fn negotiate(&self, o: &mut Optolink) -> Result<(), io::Error> {
33    match self {
34      Self::Vs1 => Vs1::negotiate(o).await,
35      Self::Vs2 => Vs2::negotiate(o).await,
36    }
37  }
38
39  /// Reads the value at the address `addr` into `buf`.
40  pub async fn get(&self, o: &mut Optolink, addr: u16, buf: &mut [u8]) -> Result<(), io::Error> {
41    match self {
42      Self::Vs1 => Vs1::get(o, addr, buf).await,
43      Self::Vs2 => Vs2::get(o, addr, buf).await,
44    }
45  }
46
47  /// Writes the given value `value` to the the address `addr`.
48  pub async fn set(&self, o: &mut Optolink, addr: u16, value: &[u8]) -> Result<(), io::Error> {
49    match self {
50      Self::Vs1 => Vs1::set(o, addr, value).await,
51      Self::Vs2 => Vs2::set(o, addr, value).await,
52    }
53  }
54}
55
56impl fmt::Display for Protocol {
57  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58    match self {
59      Self::Vs1 => "VS1",
60      Self::Vs2 => "VS2",
61    }
62    .fmt(f)
63  }
64}