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
use std::io::prelude::*;
use std::os::unix::net::UnixStream;
use std::io;
const BRIGHTNESS: u8 = 0;
const SET_PIXEL: u8 = 1;
const SET_ALL_PIXELS: u8 = 2;
const SHOW: u8 = 3;
#[repr(C,packed)]
#[derive(Copy,Clone)]
pub struct Pos {
pub x: u8,
pub y: u8
}
#[repr(C,packed)]
#[derive(Copy,Clone)]
pub struct Pixel {
pub g: u8,
pub r: u8,
pub b: u8
}
#[repr(C,packed)]
struct SetBrightnessCmd{
code: u8,
brightness: u8
}
#[repr(C,packed)]
struct SetPixelCmd {
code: u8,
pos: Pos,
col: Pixel
}
#[repr(C,packed)]
struct SetAllPixelsCmd {
code: u8,
pixels: [Pixel; 64]
}
pub struct UnicorndClient {
sd: UnixStream
}
impl UnicorndClient {
pub fn new(path: String) -> Option<Self> {
let p = path.clone();
let sd = match UnixStream::connect(path) {
Ok(sd) => sd,
Err(e) => {
eprintln!("Cannot connect to {}: {}", p, e);
return None
},
};
return Some(UnicorndClient{sd});
}
pub fn set_brightness(&mut self, brightness: u8) -> io::Result<()> {
self.write(&SetBrightnessCmd{
code: BRIGHTNESS,
brightness: brightness
})
}
pub fn set_pixel(&mut self, pos: Pos, col: Pixel) -> io::Result<()> {
self.write(&SetPixelCmd{
code: SET_PIXEL,
pos: pos,
col: col
})
}
pub fn set_all_pixels(&mut self, pixels: [Pixel; 64]) -> io::Result<()> {
self.write(&SetAllPixelsCmd{
code: SET_ALL_PIXELS,
pixels: pixels
})
}
pub fn show(&mut self) -> io::Result<()> {
self.write(&SHOW)
}
fn write<T: Sized>(&mut self, p: &T) -> io::Result<()> {
let buf = unsafe {
::std::slice::from_raw_parts(
(p as *const T) as *const u8,
::std::mem::size_of::<T>()
)
};
self.sd.write_all(buf)
}
}