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
mod pwm_streamer;
use std::time::Duration;

pub use pwm_streamer::*;

use readformat::{readf, readf1};
pub use serialport;
use serialport::{Error, SerialPort};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PicoGPIOVersion {
    V1_0,
    Unknown,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PinValueRead {
    Floating(Option<bool>),
    Analog(u32),
    Digital(bool),
    PWM(u32),
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PinValueWrite {
    Floating,
    Digital(bool),
    PWM(u32),
}

impl PinValueRead {
    pub fn matches(&self, written: &PinValueWrite) -> bool {
        match (self, written) {
            (PinValueRead::Floating(_), PinValueWrite::Floating) => true,
            (PinValueRead::Digital(a), PinValueWrite::Digital(b)) if a == b => true,
            (PinValueRead::PWM(a), PinValueWrite::PWM(b)) if a == b => true,
            _ => false,
        }
    }

    pub fn matches_in(&self, asked: &PinInput) -> bool {
        matches!(
            (self, asked),
            (PinValueRead::Floating(_), PinInput::Floating)
                | (PinValueRead::Analog(_), PinInput::Analog)
                | (PinValueRead::Digital(_), PinInput::PDown)
                | (PinValueRead::Digital(_), PinInput::PUp)
        )
    }
}

/*
impl From<PinValueRead> for PinValueWrite {
    fn from(value: PinValueRead) -> Self {
        match value {
            PinValueRead::Floating(_) => PinValueWrite::Floating,
            PinValueRead::Analog(_) => PinValueWrite::Floating,
            PinValueRead::Digital(b) => PinValueWrite::Digital(b),
            PinValueRead::PWM(v) => PinValueWrite::PWM(v),
        }
    }
}
*/

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PinInput {
    Analog,
    Floating,
    PDown,
    PUp,
}

struct Params<PVType, const PINS: usize> {
    pins: [PVType; PINS],
    pwmfreq: u32,
    pwmres: u8,
    inares: u8,
    streaming: bool,
}

pub struct PicoGPIO<Port: SerialPort, const PINS: usize = 256> {
    port: Port,
    version: PicoGPIOVersion,
    // Intended values, set immediately
    intended: Params<PinValueWrite, PINS>,
    // Actual values, set when receiving a response
    actual: Params<PinValueRead, PINS>,
    blocking: bool,
}

impl<Port: SerialPort, const PINS: usize> PicoGPIO<Port, PINS> {
    pub fn new(mut serial_port: Port) -> Result<Self, Error> {
        serial_port.set_timeout(Duration::from_millis(500))?;
        serial_port.write_all("\r\n".as_bytes())?;
        Ok(Self {
            port: serial_port,
            version: PicoGPIOVersion::Unknown,
            intended: Params {
                pins: [PinValueWrite::Floating; PINS],
                pwmfreq: 0,
                pwmres: 8,
                inares: 10,
                streaming: false,
            },
            actual: Params {
                pins: [PinValueRead::Floating(None); PINS],
                pwmfreq: 0,
                pwmres: 8,
                inares: 10,
                streaming: false,
            },
            blocking: true,
        })
    }

    pub fn poll(&mut self, mut min_lines: usize) -> Result<(), Error> {
        loop {
            if self.port.bytes_to_read()? == 0 && min_lines == 0 {
                break;
            }
            let mut buf = [0u8; 1];
            self.port.read_exact(&mut buf)?;
            let mut line = vec![buf[0]];
            loop {
                let mut buf = [0u8; 1024];
                let amt = self.port.read(&mut buf)?;
                line.append(&mut buf[..amt].to_vec());
                if *line.last().unwrap() as char == '\n' {
                    break;
                }
            }
            for line in String::from_utf8(line).unwrap().split('\n') {
                self.parse_line(line.trim())?;
                min_lines = min_lines.saturating_sub(1);
            }
        }
        Ok(())
    }

    fn parse_line(&mut self, line: &str) -> Result<(), Error> {
        if line == "!OK" {
            // pass
        } else if let Some(v) = readf1("+PICO_GPIO {}", line) {
            self.version = match v.as_str() {
                "V1.0" => PicoGPIOVersion::V1_0,
                _ => PicoGPIOVersion::Unknown,
            };
        } else if let Some(err) = readf1("!ERROR:{}", line) {
            panic!("PicoGPIO version mismatch: ERROR {err}.");
        } else if let Some(freq) = readf1("!PWMFREQ:{}", line) {
            self.actual.pwmfreq = freq.parse().unwrap();
        } else if let Some(res) = readf1("!PWMRES:{}", line) {
            self.actual.pwmres = res.parse().unwrap();
        } else if let Some(res) = readf1("!INARES:{}", line) {
            self.actual.inares = res.parse().unwrap();
        } else if line == "!STREAMING" {
            self.actual.streaming = true;
        } else if let Some([pin, val]) = readf("~{}={}", line).as_deref() {
            self.actual.pins[pin.parse::<usize>().expect("invalid data from PicoGPIO!")] =
                PinValueRead::Floating(Some(
                    val.parse::<u8>().expect("invalid data from PicoGPIO!") != 0,
                ))
        } else if let Some([pin, val]) = readf("/{}={}", line).as_deref() {
            self.actual.pins[pin.parse::<usize>().expect("invalid data from PicoGPIO!")] =
                PinValueRead::Analog(val.parse::<u32>().expect("invalid data from PicoGPIO!"))
        } else if let Some([pin, val]) = readf("#{}={}", line).as_deref() {
            self.actual.pins[pin.parse::<usize>().expect("invalid data from PicoGPIO!")] =
                PinValueRead::PWM(val.parse::<u32>().expect("invalid data from PicoGPIO!"))
        } else if let Some([pin, val]) = readf("{}={}", line).as_deref() {
            self.actual.pins[pin.parse::<usize>().expect("invalid data from PicoGPIO!")] =
                PinValueRead::Digital(val.parse::<u8>().expect("invalid data from PicoGPIO!") != 0)
        }
        Ok(())
    }

    pub fn set_manual(
        &mut self,
        pin: usize,
        value: PinValueWrite,
        block: bool,
    ) -> Result<(), Error> {
        self.intended.pins[pin] = value;
        match value {
            PinValueWrite::Floating => {
                self.port.write_all(format!("float {pin}\r\n").as_bytes())?
            }
            PinValueWrite::Digital(val) => self
                .port
                .write_all(format!("out {pin}={}\r\n", if val { 1 } else { 0 }).as_bytes())?,
            PinValueWrite::PWM(val) => self
                .port
                .write_all(format!("pwm {pin}={val}\r\n").as_bytes())?,
        }
        self.poll(0)?;
        if block {
            while !self.actual.pins[pin].matches(&value) {
                self.poll(1)?;
            }
        }
        Ok(())
    }

    pub fn get_manual(
        &mut self,
        pin: usize,
        kind: PinInput,
        cached: bool,
        block: bool,
    ) -> Result<PinValueRead, Error> {
        if !cached {
            self.intended.pins[pin] = PinValueWrite::Floating;
            self.poll(0)?;
            match kind {
                PinInput::Floating => self.port.write_all(format!("float {pin}\r\n").as_bytes())?,
                PinInput::Analog => self.port.write_all(format!("ina {pin}\r\n").as_bytes())?,
                PinInput::PDown => self.port.write_all(format!("in {pin}\r\n").as_bytes())?,
                PinInput::PUp => self.port.write_all(format!("in^ {pin}\r\n").as_bytes())?,
            }
            if block {
                self.poll(1)?;
            }
            while !self.actual.pins[pin].matches_in(&kind) {
                self.poll(1)?;
            }
        }

        Ok(self.actual.pins[pin])
    }

    pub fn float(&mut self, pin: usize) -> Result<(), Error> {
        self.set_manual(pin, PinValueWrite::Floating, self.blocking)
    }

    pub fn out_d(&mut self, pin: usize, val: bool) -> Result<(), Error> {
        self.set_manual(pin, PinValueWrite::Digital(val), self.blocking)
    }

    pub fn out_pwm(&mut self, pin: usize, val: u32) -> Result<(), Error> {
        self.set_manual(pin, PinValueWrite::PWM(val), self.blocking)
    }

    pub fn in_float(&mut self, pin: usize) -> Result<bool, Error> {
        self.get_manual(pin, PinInput::Floating, false, self.blocking)
            .map(|x| match x {
                PinValueRead::Floating(Some(x)) => x,
                _ => unreachable!(),
            })
    }

    pub fn in_pulldn(&mut self, pin: usize) -> Result<bool, Error> {
        self.get_manual(pin, PinInput::PDown, false, self.blocking)
            .map(|x| match x {
                PinValueRead::Digital(x) => x,
                _ => unreachable!(),
            })
    }

    pub fn in_pullup(&mut self, pin: usize) -> Result<bool, Error> {
        self.get_manual(pin, PinInput::PUp, false, self.blocking)
            .map(|x| match x {
                PinValueRead::Digital(x) => x,
                _ => unreachable!(),
            })
    }

    pub fn init_pwm(&mut self, freq: u32, res: u8, block: bool) -> Result<(), Error> {
        self.intended.pwmres = res;
        self.intended.pwmfreq = freq;
        self.port
            .write_all(format!("pwmres {res}\r\npwmfreq {freq}\r\n").as_bytes())?;
        self.poll(0)?;
        if block {
            while self.actual.pwmfreq != freq || self.actual.pwmres != res {
                self.poll(1)?;
            }
        }
        Ok(())
    }

    pub fn pwmstream(mut self, pin: usize) -> Result<PwmStreamer<Port, PINS>, (Self, Error)> {
        if let Err(e) = self
            .init_pwm(self.intended.pwmfreq, 8, true)
            .and_then(|()| {
                self.port
                    .write_all(format!("pwmstream {pin}").as_bytes())
                    .map_err(|x| x.into())
            })
        {
            return Err((self, e));
        }
        Ok(PwmStreamer::new(self, PwmStreamMode::PWM))
    }

    pub fn audiostream(mut self, pin: usize) -> Result<PwmStreamer<Port, PINS>, (Self, Error)> {
        if let Err(e) = self
            .init_pwm(self.intended.pwmfreq, 8, true)
            .and_then(|()| {
                self.port
                    .write_all(format!("audiostream {pin}").as_bytes())
                    .map_err(|x| x.into())
            })
        {
            return Err((self, e));
        }
        Ok(PwmStreamer::new(self, PwmStreamMode::Audio))
    }
}