use std::sync::Arc;
use reqwest::Method;
use serde_json::{Map, Value, json};
use url::Url;
use crate::envelope::Envelope;
use crate::error::Error;
use crate::routes::{self, ApiVersion, Resource};
use crate::transport::{RequestBody, Transport};
const NODE_ACTIONS: &[&str] = &["POWER_CYCLE_ALL_PORTS", "POWER_CYCLE_ALL_PORTS_AND_REBOOT"];
const PORT_ACTIONS: &[&str] = &[
"ENABLE_DATA",
"DISABLE_DATA",
"ENABLE_POE",
"DISABLE_POE",
"ENABLE_PORT",
"DISABLE_PORT",
"RESTART_POWER",
"ENABLE_PORT_SECURITY",
"DISABLE_PORT_SECURITY",
];
fn resolve_self_preferred(
host: &Url,
id_or_url: &str,
route: &Resource,
parent: Option<&Value>,
) -> Result<Url, Error> {
if let Some(parent) = parent
&& let Some(url) = crate::links::self_url(host, parent)?
{
return Ok(url);
}
crate::links::resource_url(host, id_or_url, route.template, route.version)
}
fn nightlight_url_from_value(host: &Url, value: &Value) -> Result<Option<Url>, Error> {
let data = crate::links::as_data(value);
let Some(url) = data
.get("nightlight")
.and_then(|nightlight| nightlight.get("url"))
.and_then(Value::as_str)
else {
return Ok(None);
};
if url.is_empty() {
return Ok(None);
}
crate::links::join_api_path(host, url).map(Some)
}
fn validate_brightness(value: i32, field: &str) -> Result<i32, Error> {
if (0..=100).contains(&value) {
Ok(value)
} else {
Err(Error::validation(
field,
"must be an integer between 0 and 100",
))
}
}
#[derive(Debug)]
pub struct EerosApi {
transport: Arc<Transport>,
}
impl EerosApi {
#[must_use]
pub fn new(transport: Arc<Transport>) -> Self {
Self { transport }
}
pub async fn get_eeros(
&self,
network_id: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.transport
.resource(
&routes::GET_EEROS,
network_id,
parent,
&[],
RequestBody::None,
)
.await
}
pub async fn get_eero(&self, eero_id: &str, parent: Option<&Value>) -> Result<Envelope, Error> {
let url = resolve_self_preferred(
self.transport.api_host(),
eero_id,
&routes::GET_EERO,
parent,
)?;
self.transport
.request(Method::GET, url, &[], RequestBody::None)
.await
}
pub async fn get_led_status(
&self,
eero_id: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let url = resolve_self_preferred(
self.transport.api_host(),
eero_id,
&routes::GET_LED_STATUS,
parent,
)?;
self.transport
.request(Method::GET, url, &[], RequestBody::None)
.await
}
pub async fn set_location(
&self,
eero_id: &str,
location: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let url = resolve_self_preferred(
self.transport.api_host(),
eero_id,
&routes::EEROS_SET_LOCATION,
parent,
)?;
crate::links::warn_uncharacterised_write("set location for eero");
self.transport
.request(
Method::PUT,
url,
&[],
RequestBody::Form(vec![("location".to_owned(), location.to_owned())]),
)
.await
}
pub async fn reboot_eero(
&self,
eero_id: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.transport
.resource(
&routes::REBOOT_EERO,
eero_id,
parent,
&[],
RequestBody::EmptyJsonString,
)
.await
}
pub async fn set_led(
&self,
eero_id: &str,
enabled: bool,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let value = if enabled { "true" } else { "false" }.to_owned();
self.transport
.resource(
&routes::SET_LED,
eero_id,
parent,
&[],
RequestBody::Form(vec![("led_on".to_owned(), value)]),
)
.await
}
pub async fn set_led_brightness(
&self,
eero_id: &str,
brightness: i32,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let brightness = validate_brightness(brightness, "brightness")?;
self.transport
.resource(
&routes::SET_LED_BRIGHTNESS,
eero_id,
parent,
&[],
RequestBody::Form(vec![("led_brightness".to_owned(), brightness.to_string())]),
)
.await
}
pub async fn get_connections(
&self,
eero_id: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.transport
.resource(
&routes::GET_CONNECTIONS,
eero_id,
parent,
&[],
RequestBody::None,
)
.await
}
async fn resolve_nightlight_url(
&self,
eero_id: &str,
parent: Option<&Value>,
) -> Result<Url, Error> {
let host = self.transport.api_host();
if let Some(parent) = parent
&& let Some(url) = nightlight_url_from_value(host, parent)?
{
return Ok(url);
}
let own_url = resolve_self_preferred(host, eero_id, &routes::GET_EERO, None)?;
let envelope = self
.transport
.request(Method::GET, own_url, &[], RequestBody::None)
.await?;
if let Some(url) = nightlight_url_from_value(host, envelope.as_value())? {
return Ok(url);
}
Err(Error::FeatureUnavailable {
status: None,
message: "not available on this eero".to_owned(),
envelope: None,
error_code: None,
})
}
pub async fn get_nightlight(
&self,
eero_id: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let url = self.resolve_nightlight_url(eero_id, parent).await?;
self.transport
.request(Method::GET, url, &[], RequestBody::None)
.await
}
pub async fn set_nightlight(
&self,
eero_id: &str,
enabled: Option<bool>,
brightness_percentage: Option<i32>,
schedule: Option<Value>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let brightness_percentage = brightness_percentage
.map(|value| validate_brightness(value, "brightness_percentage"))
.transpose()?;
let mut body = Map::new();
if let Some(enabled) = enabled {
body.insert("enabled".to_owned(), Value::Bool(enabled));
}
if let Some(brightness_percentage) = brightness_percentage {
body.insert(
"brightness_percentage".to_owned(),
Value::from(brightness_percentage),
);
}
if let Some(schedule) = schedule {
body.insert("schedule".to_owned(), schedule);
}
if body.is_empty() {
return Err(Error::validation(
"nightlight",
"at least one of enabled, brightness_percentage, schedule must be supplied",
));
}
let url = self.resolve_nightlight_url(eero_id, parent).await?;
crate::links::warn_uncharacterised_write("set nightlight for eero");
self.transport
.request(
Method::PUT,
url,
&[],
RequestBody::Json(Value::Object(body)),
)
.await
}
pub async fn set_nightlight_brightness(
&self,
eero_id: &str,
brightness_percentage: i32,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.set_nightlight(eero_id, None, Some(brightness_percentage), None, parent)
.await
}
pub async fn set_nightlight_schedule(
&self,
eero_id: &str,
schedule: Value,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.set_nightlight(eero_id, None, None, Some(schedule), parent)
.await
}
pub async fn node_action(
&self,
eero_id: &str,
action: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
if !NODE_ACTIONS.contains(&action) {
return Err(Error::validation(
"action",
format!(
"must be one of {}, got {}",
crate::params::py_list(NODE_ACTIONS),
crate::params::py_quote(action)
),
));
}
let url = routes::EEROS_NODE_ACTION.resolve(self.transport.api_host(), eero_id, parent)?;
crate::links::warn_uncharacterised_write(&format!(
"perform node action '{action}' on eero -- power-cycles ports and, for \
POWER_CYCLE_ALL_PORTS_AND_REBOOT, reboots the eero"
));
self.transport
.request(
routes::EEROS_NODE_ACTION.method.clone(),
url,
&[],
RequestBody::Json(json!({ "action": action })),
)
.await
}
pub async fn port_action(
&self,
eero_id: &str,
interface_number: u32,
action: &str,
) -> Result<Envelope, Error> {
if !PORT_ACTIONS.contains(&action) {
return Err(Error::validation(
"action",
format!(
"must be one of {}, got {}",
crate::params::py_list(PORT_ACTIONS),
crate::params::py_quote(action)
),
));
}
let host = self.transport.api_host();
let ports_base =
crate::links::resource_url(host, eero_id, "eeros/{id}/ports", ApiVersion::V2_2)?;
let member = crate::links::child_url(&ports_base, &interface_number.to_string())?;
let url = Url::parse(&format!("{}/action", member.as_str().trim_end_matches('/')))
.map_err(|err| Error::validation("url", format!("not a valid URL: {err}")))?;
crate::links::warn_uncharacterised_write(&format!(
"perform port action '{action}' on eero port"
));
self.transport
.request(
Method::POST,
url,
&[],
RequestBody::Json(json!({ "action": action })),
)
.await
}
pub async fn led_cycle(
&self,
eero_serial: &str,
colors: &[String],
duration: u32,
time_per_color: u32,
) -> Result<Envelope, Error> {
let url = routes::EEROS_LED_CYCLE.resolve(self.transport.api_host(), eero_serial, None)?;
crate::links::warn_uncharacterised_write("cycle LED for eero");
let mut pairs: Vec<(String, String)> = colors
.iter()
.map(|color| ("colors[]".to_owned(), color.clone()))
.collect();
pairs.push(("duration".to_owned(), duration.to_string()));
pairs.push(("time_per_color".to_owned(), time_per_color.to_string()));
self.transport
.request(
routes::EEROS_LED_CYCLE.method.clone(),
url,
&[],
RequestBody::Form(pairs),
)
.await
}
pub async fn nightlight_override(
&self,
eero_id: &str,
brightness_percentage: i32,
) -> Result<Envelope, Error> {
let brightness_percentage =
validate_brightness(brightness_percentage, "brightness_percentage")?;
let url = routes::NIGHTLIGHT_OVERRIDE.resolve(self.transport.api_host(), eero_id, None)?;
crate::links::warn_uncharacterised_write("override nightlight preview for eero");
self.transport
.request(
routes::NIGHTLIGHT_OVERRIDE.method.clone(),
url,
&[],
RequestBody::Form(vec![(
"brightness_percentage".to_owned(),
brightness_percentage.to_string(),
)]),
)
.await
}
pub async fn get_eero_support(&self, eero_serial: &str) -> Result<Envelope, Error> {
self.transport
.resource(
&routes::GET_EERO_SUPPORT,
eero_serial,
None,
&[],
RequestBody::None,
)
.await
}
}