HomeServer/src/tasmota.rs

70 lines
1.4 KiB
Rust
Raw Normal View History

2023-09-19 08:52:12 +00:00
use anyhow::Result;
pub struct Tasmota {
device: String,
}
impl Tasmota {
pub fn new(device: impl ToString) -> Self {
Self {
device: device.to_string(),
}
}
pub fn name(&self) -> &str {
&self.device
}
fn command(&self, command: &str) -> String {
format!("http://{}/cm?cmnd={}", self.device, command)
}
async fn post(&self, command: &str) -> Result<String> {
Ok(reqwest::Client::new()
.post(&self.command(command))
.send()
.await?
.text()
.await?)
}
async fn get(&self, command: &str) -> Result<String> {
Ok(reqwest::Client::new()
.get(&self.command(command))
.send()
.await?
.text()
.await?)
}
pub async fn turn_on_led(&self) -> Result<()> {
2023-09-19 09:18:22 +00:00
self.post("LedPower=1").await?;
Ok(())
2023-09-19 08:52:12 +00:00
}
pub async fn turn_off_led(&self) -> Result<()> {
2023-09-19 09:18:22 +00:00
self.post("LedPower=2").await?;
Ok(())
2023-09-19 08:52:12 +00:00
}
pub async fn switch_on(&self) -> Result<()> {
2023-09-19 09:18:22 +00:00
self.post("Power0=1").await?;
Ok(())
2023-09-19 08:52:12 +00:00
}
pub async fn switch_off(&self) -> Result<()> {
2023-09-19 09:18:22 +00:00
self.post("Power0=0").await?;
Ok(())
2023-09-19 08:52:12 +00:00
}
pub async fn read_power_usage(&self) -> Result<f32> {
2023-09-19 09:18:22 +00:00
let res = self.get("Status=8").await?;
Ok(res.parse()?)
2023-09-19 08:52:12 +00:00
}
}