This commit is contained in:
LordMZTE 2021-10-21 17:00:42 +02:00
commit 868999bce8
9 changed files with 715 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
Cargo.lock

18
Cargo.toml Normal file
View File

@ -0,0 +1,18 @@
[package]
name = "rhue"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
miette = "3.2.0"
reqwest = "0.11.6"
serde = { version = "1.0.130", features = ["derive"] }
serde_json = "1.0.68"
serde_repr = "0.1.7"
ssdp-client = "1.0.0"
thiserror = "1.0.30"
tokio = { version = "1.12.0", features = ["rt-multi-thread", "macros"] }
tokio-stream = "0.1.7"
url = "2.2.2"

165
LICENSE Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

22
README.md Normal file
View File

@ -0,0 +1,22 @@
# rhue
Phillips hue library for rust.
```rust
let bridge = Bridge::new("username", Url::parse("http://192.168.2.123"));
let lights = bridge.get_lights().await?;
for (id, _) in lights {
bridge.update_light(
id,
StateUpdate { on: Some(true), ..Default::default() }
).await?;
}
```
## features
- registration
- bridge discovery
- light requesting & control
- group requesting & control

12
rustfmt.toml Normal file
View File

@ -0,0 +1,12 @@
unstable_features = true
binop_separator = "Back"
format_code_in_doc_comments = true
format_macro_matchers = true
format_strings = true
imports_layout = "HorizontalVertical"
match_block_trailing_comma = true
merge_imports = true
normalize_comments = true
use_field_init_shorthand = true
use_try_shorthand = true
wrap_comments = true

19
src/api/internal.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use super::ApiError;
#[derive(Debug, Serialize)]
pub struct RegisterReq<'a> {
pub devicetype: &'a str,
}
#[derive(Debug, Deserialize)]
pub struct RegisterResponse {
pub error: Option<ApiError>,
pub success: Option<RegisterSuccess>,
}
#[derive(Debug, Deserialize)]
pub struct RegisterSuccess {
pub username: String,
}

206
src/api/mod.rs Normal file
View File

@ -0,0 +1,206 @@
use miette::Diagnostic;
use serde::{Deserialize, Serialize};
use serde_repr::Deserialize_repr;
use std::collections::HashMap;
use thiserror::Error;
pub(crate) mod internal;
#[derive(Debug, Clone, Deserialize, Error, Diagnostic)]
#[error("Failed to register bridge: {description}")]
pub struct ApiError {
#[serde(rename = "type")]
pub err_type: ApiErrorType,
pub address: String,
pub description: String,
}
#[derive(Debug, Clone, Deserialize_repr)]
#[repr(u8)]
pub enum ApiErrorType {
InvalidValue = 7,
LinkButtonNotPressed = 101,
NotAvailable = 2,
ParameterNotAvailable = 6,
ParameterNotModifiable = 201,
ResourceNotAvailable = 3,
UnauthorizedUser = 1,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Light {
pub state: State,
pub swupdate: SwUpdate,
#[serde(rename = "type")]
pub light_type: String,
pub name: String,
pub modelid: String,
pub manufacturername: String,
pub productname: String,
pub capabilities: LightCapabilities,
pub config: LightConfig,
pub uniqueid: String,
pub swversion: String,
pub swconfigid: Option<String>,
pub productid: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct LightConfig {
pub archetype: String,
pub function: String,
pub direction: String,
pub startup: LightStartupConfig,
}
#[derive(Debug, Clone, Deserialize)]
pub struct LightStartupConfig {
// TODO: find variants and use enum
pub mode: String,
pub configured: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct LightCapabilities {
#[serde(default)]
pub certified: bool,
pub control: LightControlCapabilities,
pub streaming: Option<LightStreamingCapabilities>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct LightStreamingCapabilities {
pub renderer: bool,
pub proxy: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct LightControlCapabilities {
pub mindimlevel: Option<u32>,
pub maxlumen: Option<u32>,
pub colorgamuttype: Option<String>,
pub colorgamut: Option<[[f32; 2]; 3]>,
pub ct: Option<LightCtCapabilities>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct LightCtCapabilities {
pub min: u16,
pub max: u16,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SwUpdate {
pub state: String,
pub lastinstall: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct State {
pub on: bool,
pub bri: u8,
pub hue: u16,
pub sat: u8,
pub effect: LightEffect,
pub xy: [f32; 2],
pub ct: Option<u16>,
pub alert: LightAlert,
pub colormode: ColorMode,
// TODO: find out what variants this has and replace with enum
pub mode: Option<String>,
pub reachable: Option<bool>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LightAlert {
Select,
LSelect,
}
#[derive(Debug, Default, Clone, Serialize)]
pub struct StateUpdate {
#[serde(skip_serializing_if = "Option::is_none")]
pub on: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bri: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hue: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sat: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub effect: Option<LightEffect>,
#[serde(skip_serializing_if = "Option::is_none")]
pub xy: Option<[f32; 2]>,
#[serde(skip_serializing_if = "Option::is_none")]
pub colormode: Option<ColorMode>,
// TODO: find out what variants this has and replace with enum
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reachable: Option<bool>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum LightEffect {
None,
ColorLoop,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum ColorMode {
#[serde(rename = "hs")]
HueSatBri,
#[serde(rename = "xy")]
Xy,
#[serde(rename = "ct")]
ColorTemp,
}
#[derive(Debug, Clone, Deserialize)]
pub struct UpdateStatus {
pub success: Option<HashMap<String, serde_json::Value>>,
pub error: Option<ApiError>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Group {
pub name: String,
pub lights: Vec<String>,
#[serde(rename = "type")]
pub group_type: GroupType,
pub state: Grouptate,
#[serde(default)]
pub recycle: bool,
pub class: GroupClass,
pub action: State,
pub stream: Option<GroupStream>,
pub locations: Option<HashMap<String, [f32; 3]>>,
}
#[derive(Debug, Clone, Deserialize)]
pub enum GroupType {
Room,
Entertainment,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Grouptate {
pub all_on: bool,
pub any_on: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub enum GroupClass {
Other,
}
#[derive(Debug, Clone, Deserialize)]
pub struct GroupStream {
// TODO: enumify
pub proxymode: String,
pub proxynode: String,
pub active: bool,
pub owner: Option<String>,
}

204
src/bridge.rs Normal file
View File

@ -0,0 +1,204 @@
use std::{collections::HashMap, sync::Arc};
use crate::api::{
internal::{RegisterReq, RegisterResponse, RegisterSuccess},
ApiError, Group, Light, UpdateStatus,
};
use miette::Diagnostic;
use reqwest::Client;
use thiserror::Error;
use url::Url;
pub use crate::api::StateUpdate;
pub type BridgeResult<T> = Result<T, BridgeError>;
#[derive(Error, Debug, Diagnostic)]
pub enum BridgeError {
#[error("Error sending HTTP request")]
ReqwestError(#[from] reqwest::Error),
#[error("Error while serializing JSON data")]
JsonError(#[from] serde_json::Error),
#[error("Error parsing URL")]
UrlParseError(#[from] url::ParseError),
#[error("Response from bridge had invalid data.")]
ResponseFormatError,
}
#[derive(Debug)]
pub struct Bridge {
pub endpoint: Url,
pub username: String,
http: Arc<Client>,
}
#[derive(Debug)]
pub enum ActionStatus<T> {
Success(T),
SuccessAndError(T, ApiError),
Error(ApiError),
}
impl<T> ActionStatus<T> {
pub fn to_result(self) -> Result<T, ApiError> {
match self {
Self::Success(b) => Ok(b),
Self::SuccessAndError(b, _) => Ok(b),
Self::Error(e) => Err(e),
}
}
}
impl Bridge {
/// tries to register a new user at the given bridge endpoint with a given username.
pub async fn register(
http: Arc<Client>,
devicetype: &str,
addr: Url,
) -> BridgeResult<ActionStatus<Bridge>> {
let req = serde_json::to_vec(&RegisterReq { devicetype })?;
let response = http
.post(addr.join("api")?)
.body(req)
.send()
.await?
.bytes()
.await?;
if let Ok(s) = std::str::from_utf8(&response) {
println!("{}", s);
}
// no clue why the response is an array, and not just a single object
let mut response = serde_json::from_slice::<Vec<RegisterResponse>>(&response)?;
let response = response.pop().ok_or(BridgeError::ResponseFormatError)?;
match response {
RegisterResponse {
error: Some(error),
success: Some(RegisterSuccess { username }),
} => Ok(ActionStatus::SuccessAndError(
Bridge::with_http(username, addr, http),
error,
)),
RegisterResponse {
error: None,
success: Some(RegisterSuccess { username }),
} => Ok(ActionStatus::Success(Bridge::with_http(
username, addr, http,
))),
RegisterResponse {
error: Some(error),
success: None,
} => Ok(ActionStatus::Error(error)),
RegisterResponse {
error: None,
success: None,
} => Err(BridgeError::ResponseFormatError),
}
}
pub fn new(username: impl ToString, endpoint: Url) -> Self {
Self::with_http(username, endpoint, Arc::new(Client::new()))
}
pub fn with_http(username: impl ToString, endpoint: Url, http: Arc<Client>) -> Self {
Self {
endpoint,
username: username.to_string(),
http,
}
}
fn api_endpoint(&self) -> Result<Url, url::ParseError> {
self.endpoint
.join("api/")?
.join(&(self.username.clone() + "/"))
}
pub async fn get_lights(&self) -> BridgeResult<HashMap<String, Light>> {
let resp = self
.http
.get(self.api_endpoint()?.join("lights/")?)
.send()
.await?
.bytes()
.await?;
Ok(serde_json::from_slice(&resp)?)
}
async fn update_endpoint(
&self,
endpoint: &str,
update: StateUpdate,
) -> BridgeResult<Vec<ActionStatus<HashMap<String, serde_json::Value>>>> {
let payload = serde_json::to_vec(&update)?;
let res = self
.http
.put(self.api_endpoint()?.join(endpoint)?)
.body(payload)
.send()
.await?
.bytes()
.await?;
let res = serde_json::from_slice::<Vec<UpdateStatus>>(&res)?;
let mut results = vec![];
for status in res {
results.push(match status {
UpdateStatus {
success: Some(s),
error: None,
} => ActionStatus::Success(s),
UpdateStatus {
success: None,
error: Some(e),
} => ActionStatus::Error(e),
UpdateStatus {
success: Some(s),
error: Some(e),
} => ActionStatus::SuccessAndError(s, e),
UpdateStatus {
success: None,
error: None,
} => return Err(BridgeError::ResponseFormatError),
});
}
Ok(results)
}
pub async fn update_light(
&self,
id: &str,
update: StateUpdate,
) -> BridgeResult<Vec<ActionStatus<HashMap<String, serde_json::Value>>>> {
self.update_endpoint(&format!("lights/{}/state", id), update)
.await
}
pub async fn get_groups(&self) -> BridgeResult<HashMap<String, Group>> {
let res = self
.http
.get(self.api_endpoint()?.join("groups")?)
.send()
.await?
.bytes()
.await?;
Ok(serde_json::from_slice(&res)?)
}
pub async fn update_group(
&self,
id: &str,
update: StateUpdate,
) -> BridgeResult<Vec<ActionStatus<HashMap<String, serde_json::Value>>>> {
self.update_endpoint(&format!("groups/{}/action", id), update)
.await
}
}

67
src/lib.rs Normal file
View File

@ -0,0 +1,67 @@
use std::sync::Arc;
use miette::Diagnostic;
use std::{io, time::Duration};
use thiserror::Error;
use tokio_stream::StreamExt;
use url::Url;
use ssdp_client::SearchTarget;
pub mod api;
pub mod bridge;
/// an error that can occur while discovering a hue bridge
#[derive(Error, Debug, Diagnostic)]
pub enum DiscoverError {
#[error(transparent)]
IoError(#[from] io::Error),
#[error(transparent)]
SsdpError(#[from] ssdp_client::Error),
#[error(transparent)]
ReqwestError(#[from] reqwest::Error),
#[error(transparent)]
UrlError(#[from] url::ParseError),
}
/// Looks for hue bridges in the local network using the SSDP protocol.
/// A reqwest client is required, to fetch the device's description, which is needed to make sure a
/// device is a hue bridge. If a bridge is found, it's URL is returned.
pub async fn discover_bridge(
reqwest_client: Arc<reqwest::Client>,
timeout: Duration,
) -> Result<Option<Url>, DiscoverError> {
let mut ssdp = ssdp_client::search(&SearchTarget::All, timeout, 2).await?;
while let Some(resp) = ssdp.next().await {
let resp = resp?;
if resp.location().ends_with("/description.xml") {
let mut url = Url::parse(resp.location())?;
// this check is needed so we don't think that all devices that use description.xml are
// hue bridges.
if reqwest_client
.get(url.clone())
.send()
.await?
.text()
.await?
.contains("hue")
{
url.set_path("");
return Ok(Some(url));
}
}
}
Ok(None)
}
#[derive(Error, Debug, Diagnostic)]
pub enum Error {
#[error("Reqwest error")]
ReqwestError(#[from] reqwest::Error),
#[error("JSON error")]
JsonError(#[from] serde_json::Error),
}