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
//! # i2c_mock
//!
//! A mock I2C library to support using the [HT16K33](../struct.HT16K33.html) driver on non-Linux systems that do
//! not have I2C support.
use embedded_hal as hal;

use core::fmt;

use crate::constants::ROWS_SIZE;
use crate::types::DisplayDataAddress;

/// Mock error to satisfy the I2C trait.
#[derive(Debug)]
pub struct I2cMockError;

#[cfg(feature = "std")]
impl std::error::Error for I2cMockError {}

impl fmt::Display for I2cMockError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "I2c MockError")
    }
}

/// The mock I2C state.
///
/// # Example
///
/// ```
/// use ht16k33::i2c_mock::I2cMock;
/// # fn main() {
///
/// // Create an I2cMock.
/// let i2c_mock = I2cMock::new();
///
/// # }
/// ```
pub struct I2cMock {
    /// Display RAM state.
    pub data_values: [u8; ROWS_SIZE],
}

impl I2cMock {
    /// Create an I2cMock.
    pub fn new() -> Self {
        I2cMock {
            data_values: [0; ROWS_SIZE],
        }
    }
}

impl hal::blocking::i2c::WriteRead for I2cMock {
    type Error = I2cMockError;

    /// `write_read` implementation.
    ///
    /// # Arguments
    ///
    /// * `_address` - The slave address. Ignored.
    /// * `bytes` - The command/address instructions to be written.
    /// * `buffer` - The read results.
    ///
    /// # Examples
    ///
    /// ```
    /// # use embedded_hal::blocking::i2c::WriteRead;
    /// # use ht16k33::i2c_mock::I2cMock;
    /// # fn main() {
    /// let mut i2c_mock = I2cMock::new();
    ///
    /// let mut read_buffer = [0u8; 16];
    /// i2c_mock.write_read(0, &[ht16k33::DisplayDataAddress::ROW_0.bits()], &mut read_buffer);
    ///
    /// # }
    /// ```
    fn write_read(
        &mut self,
        _address: u8,
        bytes: &[u8],
        buffer: &mut [u8],
    ) -> Result<(), Self::Error> {
        // The `bytes` have the `data_address` command + index to start reading from,
        // need to clear the command to extract the starting index.
        let mut data_offset = (bytes[0] ^ DisplayDataAddress::ROW_0.bits()) as usize;

        for value in buffer.iter_mut() {
            *value = self.data_values[data_offset];

            // The HT16K33 supports auto-increment and wrap-around, emulate that.
            data_offset = (data_offset + 1) % self.data_values.len();
        }

        Ok(())
    }
}

impl hal::blocking::i2c::Write for I2cMock {
    type Error = I2cMockError;

    /// `write` implementation.
    ///
    /// # Arguments
    ///
    /// * `_address` - The slave address. Ignored.
    /// * `bytes` - The command/address instructions to be written.
    ///
    /// # Examples
    ///
    /// ```
    /// # use embedded_hal::blocking::i2c::Write;
    /// # use ht16k33::i2c_mock::I2cMock;
    /// # fn main() {
    /// let mut i2c_mock = I2cMock::new();
    ///
    /// // First value is the data address, remaining values are to be written
    /// // starting at the data address which auto-increments and then wraps.
    /// let write_buffer = [ht16k33::DisplayDataAddress::ROW_0.bits(), 0u8, 0u8];
    ///
    /// i2c_mock.write(0, &write_buffer);
    ///
    /// # }
    /// ```
    fn write(&mut self, _address: u8, bytes: &[u8]) -> Result<(), Self::Error> {
        // "Command-only" writes are length 1 and write-only, and cannot be read back,
        // discard them for simplicity.
        if bytes.len() == 1 {
            return Ok(());
        }

        // Other writes have data, store them.
        let mut data_offset = (bytes[0] ^ DisplayDataAddress::ROW_0.bits()) as usize;
        let data = &bytes[1..];

        for value in data.iter() {
            self.data_values[data_offset] = *value;

            // The HT16K33 supports auto-increment and wrap-around, emulate that.
            data_offset = (data_offset + 1) % self.data_values.len();
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hal::blocking::i2c::{Write, WriteRead};

    const ADDRESS: u8 = 0;

    #[test]
    fn new() {
        let _i2c_mock = I2cMock::new();
    }

    #[test]
    fn write() {
        let mut i2c_mock = I2cMock::new();

        let write_buffer = [super::DisplayDataAddress::ROW_0.bits(), 1u8, 1u8];
        i2c_mock.write(ADDRESS, &write_buffer).unwrap();

        for value in 0..i2c_mock.data_values.len() {
            match value {
                0 | 1 => assert_eq!(
                    i2c_mock.data_values[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
                _ => assert_eq!(
                    i2c_mock.data_values[value], 0,
                    "index [{}] should be 0, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
            }
        }
    }

    #[test]
    fn write_with_offset() {
        let mut i2c_mock = I2cMock::new();

        let offset = 4u8;
        let write_buffer = [super::DisplayDataAddress::ROW_0.bits() | offset, 1u8, 1u8];
        i2c_mock.write(ADDRESS, &write_buffer).unwrap();

        for value in 0..i2c_mock.data_values.len() {
            match value {
                4 | 5 => assert_eq!(
                    i2c_mock.data_values[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
                _ => assert_eq!(
                    i2c_mock.data_values[value], 0,
                    "index [{}] should be 0, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
            }
        }
    }

    #[test]
    fn write_with_wraparound() {
        let mut i2c_mock = I2cMock::new();

        // Match the data values size, +2 to wrap around, +1 for the data command.
        let mut write_buffer = [1u8; super::ROWS_SIZE + 3];
        write_buffer[0] = super::DisplayDataAddress::ROW_0.bits();

        // These values should wrap and end up at indexes 0 & 1.
        write_buffer[write_buffer.len() - 1] = 2;
        write_buffer[write_buffer.len() - 2] = 2;

        i2c_mock.write(ADDRESS, &write_buffer).unwrap();

        for value in 0..i2c_mock.data_values.len() {
            match value {
                0 | 1 => assert_eq!(
                    i2c_mock.data_values[value], 2,
                    "index [{}] should be 2, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
                _ => assert_eq!(
                    i2c_mock.data_values[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
            }
        }
    }

    #[test]
    fn write_with_wraparound_and_offset() {
        let mut i2c_mock = I2cMock::new();

        // Match the data values size, +2 to wrap around, +1 for the data command.
        let mut write_buffer = [1u8; super::ROWS_SIZE + 3];

        let offset = 4u8;
        write_buffer[0] = super::DisplayDataAddress::ROW_0.bits() | offset;

        // These values should wrap and end up at indexes 4 & 5.
        write_buffer[write_buffer.len() - 1] = 2;
        write_buffer[write_buffer.len() - 2] = 2;

        i2c_mock.write(ADDRESS, &write_buffer).unwrap();

        for value in 0..i2c_mock.data_values.len() {
            match value {
                4 | 5 => assert_eq!(
                    i2c_mock.data_values[value], 2,
                    "index [{}] should be 2, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
                _ => assert_eq!(
                    i2c_mock.data_values[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, i2c_mock.data_values[value]
                ),
            }
        }
    }

    #[test]
    fn write_read() {
        let mut i2c_mock = I2cMock::new();

        i2c_mock.data_values[0] = 1;
        i2c_mock.data_values[1] = 1;

        let mut read_buffer = [0u8; super::ROWS_SIZE];
        i2c_mock
            .write_read(
                ADDRESS,
                &[super::DisplayDataAddress::ROW_0.bits()],
                &mut read_buffer,
            )
            .unwrap();

        for value in 0..read_buffer.len() {
            match value {
                0 | 1 => assert_eq!(
                    read_buffer[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, read_buffer[value]
                ),
                _ => assert_eq!(
                    read_buffer[value], 0,
                    "index [{}] should be 0, found [{}]",
                    value, read_buffer[value]
                ),
            }
        }
    }

    #[test]
    fn write_read_offset() {
        let mut i2c_mock = I2cMock::new();

        i2c_mock.data_values[2] = 1;
        i2c_mock.data_values[3] = 1;

        let mut read_buffer = [0u8; 4];

        let offset = 2u8;
        i2c_mock
            .write_read(
                ADDRESS,
                &[super::DisplayDataAddress::ROW_0.bits() | offset],
                &mut read_buffer,
            )
            .unwrap();

        for value in 0..read_buffer.len() {
            match value {
                0 | 1 => assert_eq!(
                    read_buffer[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, read_buffer[value]
                ),
                _ => assert_eq!(
                    read_buffer[value], 0,
                    "index [{}] should be 0, found [{}]",
                    value, read_buffer[value]
                ),
            }
        }
    }

    #[test]
    fn write_read_wraparound() {
        let mut i2c_mock = I2cMock::new();

        i2c_mock.data_values[2] = 1;
        i2c_mock.data_values[3] = 1;

        let mut read_buffer = [0u8; super::ROWS_SIZE + 4];

        i2c_mock
            .write_read(
                ADDRESS,
                &[super::DisplayDataAddress::ROW_0.bits()],
                &mut read_buffer,
            )
            .unwrap();

        for value in 0..read_buffer.len() {
            match value {
                2 | 3 | 18 | 19 => assert_eq!(
                    read_buffer[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, read_buffer[value]
                ),
                _ => assert_eq!(
                    read_buffer[value], 0,
                    "index [{}] should be 0, found [{}]",
                    value, read_buffer[value]
                ),
            }
        }
    }

    #[test]
    fn write_read_wraparound_and_offset() {
        let mut i2c_mock = I2cMock::new();

        i2c_mock.data_values[0] = 1;
        i2c_mock.data_values[1] = 1;

        let mut read_buffer = [0u8; super::ROWS_SIZE];

        let offset = 4u8;
        i2c_mock
            .write_read(
                ADDRESS,
                &[super::DisplayDataAddress::ROW_0.bits() | offset],
                &mut read_buffer,
            )
            .unwrap();

        for value in 0..read_buffer.len() {
            match value {
                // The indexes will be 12/13 b/c the data values are at 1/2, but the read is offset
                // by 4, so the read buffer will wraparound to load those values.
                12 | 13 => assert_eq!(
                    read_buffer[value], 1,
                    "index [{}] should be 1, found [{}]",
                    value, read_buffer[value]
                ),
                _ => assert_eq!(
                    read_buffer[value], 0,
                    "index [{}] should be 0, found [{}]",
                    value, read_buffer[value]
                ),
            }
        }
    }
}