contourwall_core 0.2.1

Provides a low-level interface to control the Contour Wall
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
//! Tile struct and implementation. This struct implements the protocol to communicate with individual tiles.
use std::time::Duration;

use crate::{
    status_code::StatusCode,
    util::{extract_mutated_pixels, generate_index_conversion_vector, millis_since_epoch},
};
use log::error;
use serialport::SerialPort;

#[derive(Debug)]
pub enum InitError {
    NotAnEllieTile,
    FailedToOpenConnection,
}

#[derive(Debug)]
pub struct Tile {
    pub frame_time: u64,
    last_serial_write_time: u64,
    port: Box<dyn SerialPort>,

    index_converter_vector: [usize; 1200],
    previous_framebuffer: [u8; 1200],
}

impl Tile {
    /// Initializes the tile,
    ///
    /// It connects to the tile over serial, and asks for the magic numbers. If are not correct the connection is terminated.
    /// Otherwise the initialized tile is returned.
    ///
    /// ## Parameters
    /// - port: string which is port location
    /// - baudrate: an unsigned 32bit integer, default value of 2.000.000
    ///
    /// ## Returns
    ///
    /// A Result is returned, the `Result::Ok` value contains the tile. If it is an `Result::Err`, it returns an `InitError`
    ///
    /// ```
    /// let port = String::from("COM5"); // If on Linux, the port is going to look something like this /dev/ttyUSB5
    /// let baudrate: u32 = 2_000_000; // Default speed of 2MHz
    ///
    /// let tile: Tile = Tile::init(port, baudrate).expect("Tile initialization is unsuccessful.");
    /// ```
    pub fn init(port: String, baudrate: u32) -> Result<Tile, InitError> {
        let Ok(port) = serialport::new(&port, baudrate)
            .timeout(Duration::from_millis(25))
            .stop_bits(serialport::StopBits::One)
            .parity(serialport::Parity::None)
            .open()
        else {
            return Result::Err(InitError::FailedToOpenConnection);
        };

        let mut tile = Tile {
            port: port,
            frame_time: 15,
            last_serial_write_time: 0,
            index_converter_vector: generate_index_conversion_vector(),
            previous_framebuffer: [0u8; 1200],
        };

        let magic_numbers = tile.command_6_magic_numbers()[0..5]
            .into_iter()
            .map(|&x| x as char)
            .collect::<String>();

        if magic_numbers != "Ellie" {
            Result::Err(InitError::NotAnEllieTile)
        } else {
            Result::Ok(tile)
        }

        // Ok(tile)
    }

    /// Executes `command_0_show` of the protocol.
    ///
    /// This command signals to the tile that the its current framebuffer needs to be displayed or shown.
    /// It expects a `100` or StatusCode::Ok, which is being returned by the tile _before_ it update its LED's.
    ///
    /// The time in between calls needs to be atleast `ContourWallCore::frame_time` (this), which by default is 33ms.
    ///
    /// ## Return
    /// - StatusCode
    ///
    /// ## Example
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    ///
    /// let status_code = cw.command_0_show();
    /// ```
    pub fn command_0_show(&mut self) -> StatusCode {
        // Sleeping if the time between "show" commands to too little. The frametimes cannot be shorter than ContourWallCore::frame_time.
        // This calculates the left over time for the thread to sleep, if any at all.
        let timespan = millis_since_epoch() - self.last_serial_write_time;
        if timespan < self.frame_time.into() {
            std::thread::sleep(Duration::from_millis((self.frame_time as u64) - timespan));
        }

        if self.write_over_serial(&[0]).is_err() {
            StatusCode::ErrorInternal
        } else {
            self.last_serial_write_time = millis_since_epoch();
            StatusCode::Ok
        }
    }

    /// Executes `command_1_solid_color` of the protocol, which sets *all* pixels on a tile to one specific color.
    ///
    /// Although possible, the function is not meant for developers to call this function "bare"
    /// The intent of this function is for background optimizations. If the vast majority of the framebuffer is one color,
    /// than you could execute two protocol commands, E.G. `command_1_solid_color()` and `command_3_update_specific_led`.
    /// A background optimization could lead to faster frame times.
    ///
    /// ## Parameters
    /// - red: 8-bit value of color red
    /// - green: 8-bit value of color red
    /// - blue: 8-bit value of color red
    ///
    /// ## Return
    /// - StatusCode
    ///
    /// ## Examples
    ///
    /// Sets all LEDs on tile to purple
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    ///
    /// let red: u8 = 255;
    /// let green: u8 = 0;
    /// let blue: u8 = 255;
    ///
    /// let status_code = tile.command_1_solid_color(red, green ,blue);
    /// let status_code = tile.command_0_show();
    /// ```
    ///
    /// Fades tiles from black to white
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    ///
    /// for i in 0..255 {
    ///     let status_code = tile.command_1_solid_color(i, i ,i);
    ///
    ///     let status_code = tile.command_0_show();
    /// }
    /// ```
    pub fn command_1_solid_color(&mut self, red: u8, green: u8, blue: u8) -> StatusCode {
        let crc = red.wrapping_add(green).wrapping_add(blue);
        if self.write_over_serial(&[1, red, green, blue, crc]).is_err() {
            return StatusCode::ErrorInternal;
        }

        for i in (0..self.previous_framebuffer.len()).step_by(3) {
            self.previous_framebuffer[i] = red;
            self.previous_framebuffer[i + 1] = green;
            self.previous_framebuffer[i + 2] = blue;
        }

        // Read response of tile
        let read_buf = &mut [0; 1];
        if self.read_from_serial(read_buf).is_err() || StatusCode::new(read_buf[0]).is_none() {
            StatusCode::ErrorInternal
        } else {
            StatusCode::new(read_buf[0]).unwrap()
        }
    }

    /// Executes `command_2_update_all` of the protocol, sets LED's to individually assigned colors based on index of the RGB values
    ///
    /// The order of the RGB values is expected to be identical to how they are wired on a tile.
    ///
    /// ## Warning
    ///
    /// The size of the framebuffer array needs to be 1200. A red, green and blue value for 400 LEDs.
    ///
    /// ## Parameters
    /// - this: mutable pointer to the ContourWallCore struct
    /// - frame_buffer: the framebuffer array
    ///
    /// ## Return
    /// - StatusCode
    ///
    /// ## Example
    ///
    /// Sets first LED to RED, the rest is set to black (off)
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    ///
    /// let mut framebuffer = &mut[0; 1200];
    /// framebuffer[0] = 255;
    ///
    /// let status_code = tile.command_2_update_all(framebuffer);
    /// ```
    pub fn command_2_update_all(
        &mut self,
        frame_buffer_unordered: &[u8],
        optimize: bool,
    ) -> StatusCode {
        let timespan = millis_since_epoch() - self.last_serial_write_time;
        if timespan < self.frame_time.into() {
            std::thread::sleep(Duration::from_millis((self.frame_time as u64) - timespan));
        }

        // Indicate to tile that command 2 is about to be executed
        if self.write_over_serial(&[2]).is_err() {
            return StatusCode::ErrorInternal;
        }

        // Generate framebuffer from pointer and generating the CRC by taking the sum of all the RGB values of the framebuffer

        // CRC overflowsum mechanism is replicated by using modular, the CRC sum is now type usize allows is being sum to the max of usize.
        // Note: CRC is not able to implemented as normal in c/c++ or other language, since Rust has memory safety feature,
        // which does not allow overflow to happend. Hence, modular is implemented to get the same result.
        let mut frame_buffer = [0; 1201];
        let mut crc: usize = 0;
        for (i, byte) in frame_buffer_unordered.into_iter().enumerate() {
            crc += *byte as usize;
            frame_buffer[self.index_converter_vector[i]] = *byte;
        }

        frame_buffer[1200] = (crc % 256) as u8;

        // If the user opts in into protocol optimization, then a check will be done how different their current framebuffer is to the previous one.
        // If the framebuffer is similar enough (defined below) then a different command will be used to transfer the pixel values.
        // This optimization could allow for a bit faster frametimes.
        if optimize {
            let comparison_framebuffer = frame_buffer[0..1200].try_into().unwrap();
            let mutated_frame_buffer =
                extract_mutated_pixels(&mut self.previous_framebuffer, &comparison_framebuffer);
            self.previous_framebuffer = comparison_framebuffer;
            // If there are less then 100 changed pixels then command_3_update_specific_led will be used.
            // The 100 is an arbitrary limit. This could very well be changed in the future to decide what the optimal limit is.
            if mutated_frame_buffer.len() / 5 < 100 {
                let sent_mutated_frame_buffer: &[u8] = &mutated_frame_buffer;
                return self.command_3_update_specific_led(sent_mutated_frame_buffer);
            }
        }

        // Write framebuffer over serial to tile
        if self.write_over_serial(&frame_buffer).is_err() {
            return StatusCode::ErrorInternal;
        }

        // Read response of tile
        let read_buf = &mut [0; 1];
        if self.read_from_serial(read_buf).is_err() || StatusCode::new(read_buf[0]).is_none() {
            StatusCode::ErrorInternal
        } else {
            StatusCode::new(read_buf[0]).unwrap()
        }
    }

    /// Executes `command_3_update_specific_led` of the protocol, sets some LED's to individually assigned colors based given index with RGB code.
    ///
    /// For every specific LED being updated, five bytes are needed. Two bytes for the LED index, one byte for red, blue and green.
    /// The index for the LED is stored in [big-endian](https://en.wikipedia.org/wiki/Endianness) format, most significant byte on the smaller address.
    ///
    /// ## Performance
    ///
    /// Although the `led_count` can go up to 255, it is recommeneded to not update more then 200 LED's or so with this protocol command.
    /// At around 200 updated LED's, this command will be slower then `command_2_update_all`,
    /// as less efficient at transferring data and requires more processing time
    ///
    /// ## Parameters
    /// - frame_buffer: the framebuffer array
    ///
    /// ## Return
    /// - StatusCode
    ///
    /// ## Example
    ///
    /// Sets 4th LED to red, 256th LED to blue
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    /// let framebuffer = &[0, 3, 255, 0, 0, 1, 0, 0, 0, 255];
    ///
    /// let status_code = tile.command_3_update_specific_led(framebuffer);
    /// ```

    pub fn command_3_update_specific_led(&mut self, frame_buffer: &[u8]) -> StatusCode {
        let timespan = millis_since_epoch() - self.last_serial_write_time;
        if timespan < self.frame_time.into() {
            std::thread::sleep(Duration::from_millis((self.frame_time as u64) - timespan));
        }

        // Indicate to tile that command 3 is about to be executed
        if self.write_over_serial(&[3]).is_err() {
            return StatusCode::ErrorInternal;
        }

        assert!(
            frame_buffer.len() <= (255 * 5),
            "When using command_3_update_specific_led you cannot transfer more then 255 LED"
        );

        //send the number of leds
        let led_count = (frame_buffer.len() / 5) as u8;
        if self.write_over_serial(&[led_count, led_count]).is_err() {
            return StatusCode::ErrorInternal;
        }

        //Reading the next response from eps32
        let read_buf = &mut [0; 1];
        if self.read_from_serial(read_buf).is_err() || StatusCode::new(read_buf[0]).is_none() {
            return StatusCode::ErrorInternal;
        }

        let status_code = StatusCode::new(read_buf[0]).unwrap();

        if status_code != StatusCode::Next {
            return status_code;
        }

        // Generate framebuffer from pointer and generating the CRC by taking the sum of all the RGB values of the framebuffer
        let mut crc: usize = 0;
        for byte in frame_buffer {
            crc += *byte as usize;
        }
        let binding = [frame_buffer, &[(crc % 256) as u8]].concat();
        let frame_buffer = binding.as_slice();

        // Write framebuffer over serial to tile
        if self.write_over_serial(frame_buffer).is_err() {
            return StatusCode::ErrorInternal;
        }

        let read_buf = &mut [0; 1];
        if self.read_from_serial(read_buf).is_err() || StatusCode::new(read_buf[0]).is_none() {
            StatusCode::ErrorInternal
        } else {
            StatusCode::new(read_buf[0]).unwrap()
        }
    }

    /// Executes `command_4_get_tile_identifier` of the protocol. Returns the tile identifier which is set in the EEPROM of the ESP32
    ///
    /// Returns an tuple of which the first element is the StatusCode and the second element is the actual identifier.
    ///
    /// ## Example
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    ///
    /// let (status_code, identifier) = tile.command_4_get_tile_identifier();
    /// ```
    pub fn command_4_get_tile_identifier(&mut self) -> (StatusCode, u8) {
        if self.write_over_serial(&[4]).is_err() {
            return (StatusCode::ErrorInternal, 0);
        }

        let read_buf = &mut [0; 3];
        if self.read_from_serial(read_buf).is_err() {
            return (StatusCode::ErrorInternal, 0);
        }

        if StatusCode::new(read_buf[2]).is_none() {
            (StatusCode::ErrorInternal, 0)
        } else {
            if read_buf[0] != read_buf[1] {
                (StatusCode::NonMatchingCRC, 0)
            } else {
                (StatusCode::new(read_buf[2]).unwrap(), read_buf[0])
            }
        }
    }

    /// Executes `command_5_set_tile_identifier` of the protocol. Sets a new tile identifier in the EEPROM of the ESP32
    ///
    /// *WARNING*: DO NOT USE 0 AS AN ADDRESS.
    /// ## Example
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    ///
    /// let status_code = tile.command_4_set_tile_identifier(4);
    /// ```
    pub fn command_5_set_tile_identifier(&mut self, identifier: u8) -> StatusCode {
        if identifier == 0 {
            error!("Cannot set a tile identifier to 0");
            return StatusCode::Error;
        }

        if self
            .write_over_serial(&[5, identifier, identifier])
            .is_err()
        {
            return StatusCode::ErrorInternal;
        }

        let read_buf = &mut [0; 1];
        if self.read_from_serial(read_buf).is_err() || StatusCode::new(read_buf[0]).is_none() {
            StatusCode::ErrorInternal
        } else {
            StatusCode::new(read_buf[0]).unwrap()
        }
    }

    /// Executes `command_6_magic_numbers` of the protocol. Returns the 5 magic_numbers of the tile
    ///
    /// The magic numbers are the ASCII values of the word: "Ellie".
    ///
    /// ## Example
    /// ```
    /// let mut tile: Tile = Tile::init(com_port, baud_rate).expect("Init is unsuccesfull");
    ///
    /// let magic_numbers = tile.command_6_magic_numbers()[0..5]
    ///     .into_iter()
    ///     .map(|&x| x as char)
    ///     .collect::<String>();
    ///     
    /// if magic_numbers != "Ellie" {
    ///     pritnln!("Tile is not part of ELLIE");
    /// } else {
    ///     pritnln!("Tile is part of ELLIE");
    /// }
    /// ```
    pub fn command_6_magic_numbers(&mut self) -> [u8; 5] {
        if self.write_over_serial(&[6]).is_err() {
            return [0, 0, 0, 0, 0];
        }

        let read_buf = &mut [0; 5];

        if self.read_from_serial(read_buf).is_err() {
            [0, 0, 0, 0, 0]
        } else {
            *read_buf
        }
    }

    fn read_from_serial(&mut self, buffer: &mut [u8]) -> Result<(), ()> {
        let port = self.port.as_mut();

        let size = match port.read(buffer) {
            Ok(size) => size,
            Err(e) => {
                error!("Error occurred during reading of Serial buffer: {}", e);
                let _ = port.clear(serialport::ClearBuffer::All);
                return Err(());
            }
        };

        if size == buffer.len() {
            Ok(())
        } else {
            error!(
                "Only {}/{} bytes were received within the {}ms allocated time",
                port.bytes_to_read().unwrap_or(666),
                buffer.len(),
                port.timeout().as_millis()
            );
            let _ = port.clear(serialport::ClearBuffer::All);
            Err(())
        }
    }

    fn write_over_serial(&mut self, bytes: &[u8]) -> Result<usize, std::io::Error> {
        let port = self.port.as_mut();
        port.write(bytes)
    }
}