Get device names into frontend

This commit is contained in:
hodasemi 2023-09-21 10:46:23 +02:00
parent 07b9b6c0be
commit 00c8cef19d
6 changed files with 56 additions and 18 deletions

14
.vscode/launch.json vendored
View file

@ -7,8 +7,18 @@
{
"type": "lldb",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/<executable file>",
"name": "Debug executable 'home_server'",
"cargo": {
"args": [
"build",
"--bin=home_server",
"--package=home_server"
],
"filter": {
"name": "home_server",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}

View file

@ -0,0 +1,11 @@
fetch("/devices", {
method: "GET"
})
.then(response => {
const div = document.getElementById("main");
let json = response.json();
console.log(json);
})
.catch(error => console.error(error));

View file

@ -77,16 +77,18 @@ impl DataBase {
pub fn register_devices(&self, devices: &Devices) -> Result<()> {
for device in devices.plugs.iter() {
self.sql.execute(
&format!(
"INSERT INTO devices (device, type)
SELECT ?1, \"plug\"
SELECT \"{device}\", \"plug\"
WHERE
NOT EXISTS (
SELECT device
FROM devices
WHERE device=\"?1\"
WHERE device=\"{device}\"
)
",
&[device],
"
),
[],
)?;
}
@ -94,12 +96,12 @@ impl DataBase {
}
pub fn write(&self, device_name: &str, time: u64, watts: f32) -> Result<()> {
let params: &[&dyn ToSql] = &[&time, &watts, &device_name];
let params: &[&dyn ToSql] = &[&time, &watts];
self.sql.execute(
&format!(
"INSERT INTO data (time, watts, device_id)
VALUES (?1, ?2, (SELECT id FROM devices WHERE device=?3) )"
VALUES (?1, ?2, (SELECT id FROM devices WHERE device=\"{device_name}\") )"
),
params,
)?;
@ -120,7 +122,7 @@ impl DataBase {
))?
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
{
let (device, dev_type, name): (String, String, String) = row?;
let (device, dev_type, name): (String, String, Option<String>) = row?;
match dev_type.as_str() {
"plug" => devices.plugs.push((device, name)),
@ -137,11 +139,11 @@ impl DataBase {
&format!(
"
UPDATE devices
SET name=?1
WHERE device=?2
SET name=\"{description}\"
WHERE device=\"{device}\"
"
),
&[&description, device],
[],
)?;
Ok(())
@ -210,7 +212,14 @@ mod test {
})?;
db.write(device_name, 0, 5.5)?;
db.change_device_name(device_name, "udo")?;
let device_descriptor = "udo";
db.change_device_name(device_name, device_descriptor)?;
let devices = db.devices()?;
assert_eq!(devices.plugs[0].1.as_ref().unwrap(), device_descriptor);
assert_eq!(devices.plugs[0].0, device_name);
fs::remove_file("write_test.db")?;

View file

@ -28,7 +28,7 @@ impl Devices {
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct DevicesWithName {
pub plugs: Vec<(String, String)>,
pub plugs: Vec<(String, Option<String>)>,
}
impl DevicesWithName {

View file

@ -18,7 +18,7 @@ use anyhow::Result;
use devices::Devices;
use futures::{future::try_join_all, try_join, Future};
use tasmota::Tasmota;
use web_server::{change_plug_state, device_query, index, plug_state};
use web_server::{change_device_name, change_plug_state, device_query, index, plug_state};
fn since_epoch() -> Result<u64> {
Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs())
@ -63,6 +63,7 @@ async fn run_web_server(
.service(device_query)
.service(plug_state)
.service(change_plug_state)
.service(change_device_name)
})
.bind(("127.0.0.1", 8062))
.map_err(|err| anyhow::Error::msg(format!("failed binding to address: {err:#?}")))?

View file

@ -54,10 +54,17 @@ async fn device_query(
) -> Result<impl Responder, impl ResponseError> {
db.lock()
.unwrap()
.devices()?
.devices()
.map_err(|err| {
println!("{err:?}");
MyError::from(err)
})?
.to_json()
.map(|json| Json(json))
.map_err(|err| MyError::from(err))
.map_err(|err| {
println!("{err:?}");
MyError::from(err)
})
}
#[post("/device_name/{device}/{name}")]