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
// EndBASIC
// Copyright 2021 Julio Merino
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

//! Fake implementations of GPIO pins that work on all platforms.

use crate::gpio::{Pin, PinMode, Pins};
use endbasic_core::ast::{Value, VarRef, VarType};
use endbasic_core::syms::{Array, Symbol, Symbols};
use std::io;

/// Stand-in implementation of the EndBASIC GPIO operations that always returns an error.
#[derive(Default)]
pub(crate) struct NoopPins {}

impl Pins for NoopPins {
    fn setup(&mut self, _pin: Pin, _mode: PinMode) -> io::Result<()> {
        Err(io::Error::new(io::ErrorKind::Other, "GPIO backend not compiled in"))
    }

    fn clear(&mut self, _pin: Pin) -> io::Result<()> {
        Err(io::Error::new(io::ErrorKind::Other, "GPIO backend not compiled in"))
    }

    fn clear_all(&mut self) -> io::Result<()> {
        Err(io::Error::new(io::ErrorKind::Other, "GPIO backend not compiled in"))
    }

    fn read(&mut self, _pin: Pin) -> io::Result<bool> {
        Err(io::Error::new(io::ErrorKind::Other, "GPIO backend not compiled in"))
    }

    fn write(&mut self, _pin: Pin, _v: bool) -> io::Result<()> {
        Err(io::Error::new(io::ErrorKind::Other, "GPIO backend not compiled in"))
    }
}

/// Mock GPIO implementation that tracks operations and supplies fake reads.
///
/// This is an undocumented feature to support unit-testing of our own demo code and is quite
/// convoluted due to the fact that we don't have a lot of freedom in what we can do in the context
/// of the `Pins` implementation: we get no context passed in (intentionally), so the only context
/// we can grab with some contortions is a reference to the machine's symbols.  This reference is
/// only valid for the duration of a GPIO call and thus this structure must be recreated on each
/// GPIO call and cannot maintain state of its own (other than via symbols).
///
/// To enable mocking, the user must define the `__GPIO_MOCK_DATA` unidimensional array of integer
/// type (aka `data`) and the `__GPIO_MOCK_LAST` integer variable (aka `last`).  If these types are
/// not met, mocking is silently not enabled.
///
/// The `data` array represents an ordered trace of GPIO calls and `last` indicates the index
/// within the array that should be inspected on the next GPIO call.  Each `data[last]` value is
/// encoded as a pin number (times 100) plus a `MockOp` integer that identifies the operation that
/// happened.
///
/// For mutating GPIO calls, `data[last]` has to be zero on entry (or else the operation will fail)
/// and will be updated with the affected pin number and the operation.  The meta operation to clear
/// all pins has a special number.
///
/// For read GPIO calls, `data[last]` has to contain the pin number that matches the read operation
/// and the desired outcome of the operation.
///
/// When a test is complete, the test should inspect the values in `data` up to the `last` position
/// and ensure they match expectations.
pub(crate) struct MockPins<'a> {
    symbols: &'a mut Symbols,
}

/// Per-pin operation identifier in the mock data.
#[derive(PartialEq)]
enum MockOp {
    SetupIn = 1,
    SetupInPullDown = 2,
    SetupInPullUp = 3,
    SetupOut = 4,

    Clear = 5,
    ClearAll = -1,

    ReadLow = 10,
    ReadHigh = 11,

    WriteLow = 20,
    WriteHigh = 21,
}

impl MockOp {
    /// Encodes a `pin` and `op` pair as a datum for the mock data.
    fn encode(pin: Pin, op: Self) -> i32 {
        assert!(op != Self::ClearAll);
        (pin.0 as i32) * 100 + (op as i32)
    }

    /// Decodes a datum from the mock data that is to be used for a read operation.
    fn decode_read(pos: i32, datum: i32) -> io::Result<(Pin, bool)> {
        if datum < 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Negative read value at __GPIO_MOCK_DATA({})", pos),
            ));
        }
        let pin = datum / 100;
        if pin > std::u8::MAX as i32 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Pin number too large at __GPIO_MOCK_DATA({})", pos),
            ));
        }
        let pin = Pin(pin as u8);
        match datum % 100 {
            i if i == (MockOp::ReadLow as i32) => Ok((pin, false)),
            i if i == (MockOp::ReadHigh as i32) => Ok((pin, true)),
            i => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Unknown read operation {} at __GPIO_MOCK_DATA({})", i, pos),
            )),
        }
    }
}

impl<'a> MockPins<'a> {
    /// Creates a mock pins instance if `__GPIO_MOCK_DATA` *and* `__GPIO_MOCK_LAST` are set and of
    /// the correct types.
    ///
    /// Note that, while this object is alive (which is in the context of an individual GPIO call),
    /// we know that these symbols are valid so other methods can assume that they are.
    pub(crate) fn try_new(symbols: &'a mut Symbols) -> Option<MockPins<'a>> {
        if MockPins::get_last(symbols).is_none() || MockPins::get_mut_data(symbols).is_none() {
            None
        } else {
            Some(Self { symbols })
        }
    }

    /// Obtains the value of `__GPIO_MOCK_LAST` if present.
    fn get_last(symbols: &Symbols) -> Option<i32> {
        match symbols.get(&VarRef::new("__GPIO_MOCK_LAST", VarType::Integer)) {
            Ok(Some(Symbol::Variable(Value::Integer(i)))) => Some(*i),
            _ => None,
        }
    }

    /// Obtains a mutable reference to `__GPIO_MOCK_DATA` if present.
    fn get_mut_data(symbols: &mut Symbols) -> Option<&mut Array> {
        match symbols.get_mut(&VarRef::new("__GPIO_MOCK_DATA", VarType::Integer)) {
            Ok(Some(Symbol::Array(data))) if data.dimensions().len() == 1 => Some(data),
            _ => None,
        }
    }

    /// Reads the current value at `data[last]` with proper validation.
    fn raw_get(last: i32, data: &Array) -> io::Result<i32> {
        match data.index(&[last]) {
            Ok(Value::Integer(v)) => Ok(*v),
            Ok(_) => panic!("We know it's an integer"),
            Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string())),
        }
    }

    /// Increments `__GPIO_MOCK_LAST`.
    fn increment_last(&mut self) -> io::Result<()> {
        let last = MockPins::get_last(self.symbols).expect("Validated at construction time");
        let new_last = Value::Integer(last + 1);
        match self.symbols.set_var(&VarRef::new("__GPIO_MOCK_LAST", VarType::Integer), new_last) {
            Ok(()) => Ok(()),
            Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string())),
        }
    }

    /// Reads `__GPIO_MOCK_DATA[__GPIO_MOCK_LAST]` and advances `__GPIO_MOCK_LAST`.  Returns the
    /// position of the array that was read and the value at that position.
    fn read_and_advance(&mut self) -> io::Result<(i32, i32)> {
        let last = MockPins::get_last(self.symbols).expect("Validated at construction time");
        let data = MockPins::get_mut_data(self.symbols).expect("Validated at construction time");

        let v = MockPins::raw_get(last, data)?;
        self.increment_last()?;
        Ok((last, v))
    }

    /// Writes `datum` to `__GPIO_MOCK_DATA[__GPIO_MOCK_LAST]`, which must be zero upfront.
    fn append(&mut self, datum: i32) -> io::Result<()> {
        let last = MockPins::get_last(self.symbols).expect("Validated at construction time");
        let data = MockPins::get_mut_data(self.symbols).expect("Validated at construction time");

        let old_datum = MockPins::raw_get(last, data)?;
        if old_datum != 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Position already occupied at __GPIO_MOCK_READ({})", last),
            ));
        }

        let data = MockPins::get_mut_data(self.symbols).expect("Validated at construction time");
        match data.assign(&[last], Value::Integer(datum)) {
            Ok(()) => (),
            Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string())),
        };
        self.increment_last()
    }
}

impl<'a> Pins for MockPins<'a> {
    fn setup(&mut self, pin: Pin, mode: PinMode) -> io::Result<()> {
        let datum = match mode {
            PinMode::In => MockOp::encode(pin, MockOp::SetupIn),
            PinMode::InPullDown => MockOp::encode(pin, MockOp::SetupInPullDown),
            PinMode::InPullUp => MockOp::encode(pin, MockOp::SetupInPullUp),
            PinMode::Out => MockOp::encode(pin, MockOp::SetupOut),
        };
        self.append(datum)
    }

    fn clear(&mut self, pin: Pin) -> io::Result<()> {
        let datum = MockOp::encode(pin, MockOp::Clear);
        self.append(datum)
    }

    fn clear_all(&mut self) -> io::Result<()> {
        let datum = MockOp::ClearAll as i32;
        self.append(datum)
    }

    fn read(&mut self, pin: Pin) -> io::Result<bool> {
        let (pos, datum) = self.read_and_advance()?;
        let (datum_pin, value) = MockOp::decode_read(pos, datum)?;
        if datum_pin != pin {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "Want to read pin {} but __GPIO_MOCK_DATA({}) is for pin {}",
                    pin.0, pos, datum_pin.0
                ),
            ));
        }
        Ok(value)
    }

    fn write(&mut self, pin: Pin, v: bool) -> io::Result<()> {
        if v {
            self.append(MockOp::encode(pin, MockOp::WriteHigh))
        } else {
            self.append(MockOp::encode(pin, MockOp::WriteLow))
        }
    }
}