neobridge_rust/
lib.rs

1use std::str;
2use std::time::Duration;
3
4use serialport::{self, SerialPort};
5pub struct Neobridge {
6    port: Box<dyn SerialPort>, 
7    number_of_leds: u32
8}
9
10#[derive(Debug, Clone, Copy)]
11pub struct RGB(pub u8, pub u8, pub u8);
12
13impl RGB {
14    pub fn to_string(&self) -> String {
15        return format!("({0}, {1}, {2})", self.0, self.1, self.2);
16    }
17}
18
19impl Neobridge {
20
21    pub fn new(port: &str, number_of_leds: u32) -> Neobridge {
22        Neobridge {
23            port: serialport::new(port, 115_200)
24                .timeout(Duration::from_millis(10))
25                .open().expect("Failed to open port"),
26            number_of_leds: number_of_leds
27        }
28    }
29
30    fn replace_with_color(&mut self, msg: &str, color: RGB) -> String {
31        let mut replace = str::replace(msg, "{0}", color.0.to_string().as_str());
32        replace = str::replace(replace.as_str(), "{1}", color.1.to_string().as_str());
33        replace = str::replace(replace.as_str(), "{2}", color.2.to_string().as_str());
34        return replace;
35    }
36
37    fn send_message(&mut self, message: &str) {
38        self.port.write(message.as_bytes()).expect("could not write to serial port");
39        self.port.write("\r\n".as_bytes()).expect("could not write to serial port");
40        self.port.flush().expect("could not flush to serial port");
41    }
42    
43    pub fn show(&mut self) {
44        self.send_message(r#"{"command": -3}"#);
45    }
46
47    pub fn set_all(&mut self, color: RGB) {
48        let msg = self.replace_with_color(r#"{"command": 0, "r": {0}, "g": {1}, "b": {2}}"#, color);
49        let binding = msg.as_str();
50
51        self.send_message(binding);
52    }
53
54    pub fn set_one(&mut self, color: RGB, index: u32) {
55        if self.number_of_leds < index
56            {panic!("You give me an index greater than what you set as!");}
57        let msg = self.replace_with_color(r#"{"command": 1, "r": {0}, "g": {1}, "b": {2}, "index": {3}}"#, color);
58        let index_replace = msg.replace("{3}", index.to_string().as_str());
59        let binding = index_replace.as_str();
60
61        self.send_message(binding);
62    }
63
64    
65    pub fn set_list(&mut self, colors: &Vec<RGB>)  {
66        let mut result: String = colors.into_iter().map(|x| x.to_string() + ",").collect();
67        result.pop();
68        
69        let msg = r#"{"command": 2, "rgb_list": [{0}]}"#.replace("{0}", &result.replace("(", "[").replace(")", "]"));
70        let binding = msg.as_str();
71
72        self.send_message(binding);
73    }
74
75    pub fn reset(&mut self) {
76        self.set_all(RGB(0, 0, 0));
77        self.show();
78    }
79}