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
use crate::{
command::{Command, CommandResponse, NotificationResult},
method::Method,
};
use rand::Rng;
use std::{
collections::HashMap,
net::SocketAddr,
sync::{atomic::AtomicI32, Arc},
};
use thiserror::Error;
use tokio::io;
use tokio::{
io::AsyncWriteExt,
net::TcpStream,
sync::{Mutex, Notify},
};
/// Default Port of Yeelight Bulbs
pub const DEFAULT_PORT: u16 = 55443;
/// Errors that can occur when interacting with a Yeelight Bulb
#[derive(Error, Debug)]
pub enum DeviceError {
/// Error when connecting or sending packets to the Yeelight Bulb
#[error(transparent)]
Io(#[from] std::io::Error),
/// Error when parsing a packet from the Yeelight Bulb
#[error(transparent)]
Json(#[from] serde_json::Error),
/// Error when a response times out
#[error(transparent)]
Timeout(#[from] tokio::time::error::Elapsed),
#[error(transparent)]
/// Error when a response contains invalid utf8
Utf8(#[from] std::str::Utf8Error),
}
struct UniqueCommandId {
id: AtomicI32,
}
impl UniqueCommandId {
fn new() -> Self {
let rand = rand::thread_rng().gen_range(15..1500);
Self {
id: AtomicI32::new(rand),
}
}
fn next(&self) -> i32 {
self.id.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
}
struct Responses {
responses: HashMap<i32, CommandResponse>,
}
impl Responses {
fn new() -> Self {
Self {
responses: HashMap::new(),
}
}
fn add(&mut self, response: CommandResponse) {
self.responses.insert(response.id, response);
}
fn consume(&mut self, id: i32) -> Option<CommandResponse> {
self.responses.remove(&id)
}
}
/// A Yeelight device.
pub struct Device {
/// The Address of the device.
pub address: SocketAddr,
responses: Arc<Mutex<Responses>>,
tcp_stream: Arc<Mutex<TcpStream>>,
command_id: UniqueCommandId,
notify: Arc<Notify>,
}
type ExecutionResult = Result<CommandResponse, DeviceError>;
type DeviceResult = Result<Device, DeviceError>;
impl Device {
/// Creates a new device with ip and port.
/// The device will connect to the device at the given IP address and port.
/// If the connection fails, the function will return an error.
/// The device will also start listening for responses from the device.
///
/// # Arguments
/// * `ip` - The IP address of the device.
/// * `port` - The port of the device.
///
/// # Errors
/// * `DeviceError::Io` - If the connection fails.
///
/// # Examples
/// ```no_run
/// use apyee::device::Device;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a new Device with the IP address and port of the device.
/// // creating the Device will also connect to it and start listening for responses.
/// let mut device = Device::new_with_port("192.168.100.5", 55443).await?;
///
/// Ok(())
/// }
/// ```
pub async fn new_with_port(ip: &str, port: u16) -> DeviceResult {
let stream = TcpStream::connect(format!("{}:{}", ip, port)).await?;
let addr = stream.peer_addr()?;
let stream = Arc::new(Mutex::new(stream));
let responses = Arc::new(Mutex::new(Responses::new()));
let notify = Arc::new(Notify::new());
tokio::spawn(Self::listen_responses_console_error(
Arc::clone(&stream),
Arc::clone(&responses),
Arc::clone(¬ify),
));
let device = Self {
address: addr,
tcp_stream: stream,
responses,
command_id: UniqueCommandId::new(),
notify,
};
Ok(device)
}
/// Creates a new device with ip and default port.
/// The device will connect to the device at the given IP address and default port.
/// If the connection fails, the function will return an error.
/// The device will also start listening for responses from the device.
///
/// # Arguments
/// * `ip` - The IP address of the device.
///
/// # Errors
/// * `DeviceError::Io` - If the connection fails.
///
/// # Examples
/// ```no_run
/// use apyee::device::Device;
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a new Device with the IP address of the device and the default port.
/// // creating the Device will also connect to it and start listening for responses.
/// let mut device = Device::new("192.168.100.5").await?;
///
/// Ok(())
/// }
/// ```
pub async fn new(ip: &str) -> DeviceResult {
Self::new_with_port(ip, DEFAULT_PORT).await
}
/// Converts u8 RGB values into the i32 RGB format used by the Yeelight device.\
/// The i32 RGB format is a 24-bit integer with the red, green, and blue values packed into a single integer.
///
/// # Arguments
/// * `r` - The red value.
/// * `g` - The green value.
/// * `b` - The blue value.
pub const fn get_rgb_color(r: u8, g: u8, b: u8) -> i32 {
(r as i32) << 16 | (g as i32) << 8 | (b as i32)
}
/// Sets the color of the device, given as separate u8 RGB values.
///
/// # Arguments
/// * `r` - The red value.
/// * `g` - The green value.
/// * `b` - The blue value.
pub async fn set_rgb(&mut self, r: u8, g: u8, b: u8) -> ExecutionResult {
self.execute_method(Method::SetRgb(Self::get_rgb_color(r, g, b), None, None))
.await
}
/// Sets the background color of the device, given as separate u8 RGB values.
///
/// # Arguments
/// * `r` - The red value.
/// * `g` - The green value.
/// * `b` - The blue value.
pub async fn set_bg_rgb(&mut self, r: u8, g: u8, b: u8) -> ExecutionResult {
self.execute_method(Method::BgSetRgb(Self::get_rgb_color(r, g, b), None, None))
.await
}
/// Toggles the devices power state.
/// If the device is on, it will be turned off.
/// If the device is off, it will be turned on.
pub async fn toggle(&mut self) -> ExecutionResult {
self.execute_method(Method::Toggle).await
}
/// Sets the power state of the device to on.
pub async fn power_on(&mut self) -> ExecutionResult {
self.execute_method(Method::SetPower(true, None, None))
.await
}
/// Sets the power state of the device to off.
pub async fn power_off(&mut self) -> ExecutionResult {
self.execute_method(Method::SetPower(false, None, None))
.await
}
/// Executes a given [`Method`] on the device by creating a new command with a unique id.
pub async fn execute_method(&mut self, method: Method) -> ExecutionResult {
let command = Command::new(self.command_id.next(), method);
self.execute_command(command).await
}
/// Executes a given [`Command`] on the device.
pub async fn execute_command(&mut self, command: Command) -> ExecutionResult {
// terminate every message with \r\n"
let json = serde_json::to_string(&command)?;
let json_command = format!("{}\r\n", json);
self.tcp_stream
.lock()
.await
.write_all(json_command.as_bytes())
.await?;
// check for multiple responses in case we get an older one with a different id
tokio::time::timeout(std::time::Duration::from_secs(20), async {
loop {
// check if we have a response for our current id
if let Some(response) = self.responses.lock().await.consume(command.id) {
return Ok(response);
}
// otherwise wait for a new notification
tokio::time::timeout(std::time::Duration::from_secs(5), self.notify.notified())
.await?;
}
})
.await?
}
async fn listen_responses(
tcp_stream: Arc<Mutex<TcpStream>>,
responses: Arc<Mutex<Responses>>,
notify: Arc<Notify>,
) -> Result<(), DeviceError> {
loop {
let mut buffer = [0u8; 8192];
match tcp_stream.lock().await.try_read(&mut buffer) {
Ok(0) => {
// if the connection is closed, return
return Ok(());
}
Ok(n) => {
// parse the json
let data = std::str::from_utf8(&buffer[..n])?;
let entries = data.split_terminator("\r\n");
for entry in entries {
if let Ok(response) = serde_json::from_str::<CommandResponse>(entry) {
responses.lock().await.add(response);
notify.notify_one();
};
if let Ok(response) = serde_json::from_str::<NotificationResult>(entry) {
// TODO: Save properties somewhere
}
}
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
continue;
}
Err(e) => {
return Err(e.into());
}
}
}
}
async fn listen_responses_console_error(
tcp_stream: Arc<Mutex<TcpStream>>,
responses: Arc<Mutex<Responses>>,
notify: Arc<Notify>,
) {
match Self::listen_responses(tcp_stream, responses, notify).await {
Ok(_) => (),
Err(e) => {
eprintln!("{}", e);
}
}
}
}