Use &str instead of String whenever possible

This commit is contained in:
Dreaded_X 2023-01-12 23:43:45 +01:00
parent 13f5c87c03
commit 06389d83f7
14 changed files with 76 additions and 62 deletions

View File

@ -5,14 +5,14 @@ use crate::{response, types::Type, traits::{AsOnOff, Trait, AsScene}, errors::{D
pub trait GoogleHomeDevice: AsOnOff + AsScene { pub trait GoogleHomeDevice: AsOnOff + AsScene {
fn get_device_type(&self) -> Type; fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name; fn get_device_name(&self) -> Name;
fn get_id(&self) -> String; fn get_id(&self) -> &str;
fn is_online(&self) -> bool; fn is_online(&self) -> bool;
// Default values that can optionally be overriden // Default values that can optionally be overriden
fn will_report_state(&self) -> bool { fn will_report_state(&self) -> bool {
false false
} }
fn get_room_hint(&self) -> Option<String> { fn get_room_hint(&self) -> Option<&str> {
None None
} }
fn get_device_info(&self) -> Option<Info> { fn get_device_info(&self) -> Option<Info> {

View File

@ -13,7 +13,7 @@ impl GoogleHome {
Self { user_id: user_id.into() } Self { user_id: user_id.into() }
} }
pub fn handle_request(&self, request: Request, mut devices: &mut HashMap<String, &mut dyn GoogleHomeDevice>) -> Result<Response, anyhow::Error> { pub fn handle_request(&self, request: Request, mut devices: &mut HashMap<&str, &mut dyn GoogleHomeDevice>) -> Result<Response, anyhow::Error> {
// @TODO What do we do if we actually get more then one thing in the input array, right now // @TODO What do we do if we actually get more then one thing in the input array, right now
// we only respond to the first thing // we only respond to the first thing
let payload = request let payload = request
@ -26,12 +26,12 @@ impl GoogleHome {
}).next(); }).next();
match payload { match payload {
Some(payload) => Ok(Response::new(request.request_id, payload)), Some(payload) => Ok(Response::new(&request.request_id, payload)),
_ => Err(anyhow::anyhow!("Expected at least one ResponsePayload")), _ => Err(anyhow::anyhow!("Expected at least one ResponsePayload")),
} }
} }
fn sync(&self, devices: &HashMap<String, &mut dyn GoogleHomeDevice>) -> sync::Payload { fn sync(&self, devices: &HashMap<&str, &mut dyn GoogleHomeDevice>) -> sync::Payload {
let mut resp_payload = sync::Payload::new(&self.user_id); let mut resp_payload = sync::Payload::new(&self.user_id);
resp_payload.devices = devices resp_payload.devices = devices
.iter() .iter()
@ -41,7 +41,7 @@ impl GoogleHome {
return resp_payload; return resp_payload;
} }
fn query(&self, payload: request::query::Payload, devices: &HashMap<String, &mut dyn GoogleHomeDevice>) -> query::Payload { fn query(&self, payload: request::query::Payload, devices: &HashMap<&str, &mut dyn GoogleHomeDevice>) -> query::Payload {
let mut resp_payload = query::Payload::new(); let mut resp_payload = query::Payload::new();
resp_payload.devices = payload.devices resp_payload.devices = payload.devices
.into_iter() .into_iter()
@ -63,7 +63,7 @@ impl GoogleHome {
} }
fn execute(&self, payload: request::execute::Payload, devices: &mut HashMap<String, &mut dyn GoogleHomeDevice>) -> execute::Payload { fn execute(&self, payload: request::execute::Payload, devices: &mut HashMap<&str, &mut dyn GoogleHomeDevice>) -> execute::Payload {
let mut resp_payload = response::execute::Payload::new(); let mut resp_payload = response::execute::Payload::new();
payload.commands payload.commands
@ -128,6 +128,7 @@ mod tests {
use super::*; use super::*;
use crate::{request::Request, device::{GoogleHomeDevice, self}, types, traits, errors::ErrorCode}; use crate::{request::Request, device::{GoogleHomeDevice, self}, types, traits, errors::ErrorCode};
#[derive(Debug)]
struct TestOutlet { struct TestOutlet {
name: String, name: String,
on: bool, on: bool,
@ -152,16 +153,16 @@ mod tests {
return name; return name;
} }
fn get_id(&self) -> String { fn get_id(&self) -> &str {
return self.name.clone(); return &self.name;
} }
fn is_online(&self) -> bool { fn is_online(&self) -> bool {
true true
} }
fn get_room_hint(&self) -> Option<String> { fn get_room_hint(&self) -> Option<&str> {
Some("Bedroom".into()) Some("Bedroom")
} }
fn get_device_info(&self) -> Option<device::Info> { fn get_device_info(&self) -> Option<device::Info> {
@ -185,7 +186,8 @@ mod tests {
} }
} }
struct TestScene {} #[derive(Debug)]
struct TestScene;
impl TestScene { impl TestScene {
fn new() -> Self { fn new() -> Self {
@ -202,16 +204,16 @@ mod tests {
device::Name::new("Party") device::Name::new("Party")
} }
fn get_id(&self) -> String { fn get_id(&self) -> &str {
return "living/party_mode".into(); return "living/party_mode";
} }
fn is_online(&self) -> bool { fn is_online(&self) -> bool {
true true
} }
fn get_room_hint(&self) -> Option<String> { fn get_room_hint(&self) -> Option<&str> {
Some("Living room".into()) Some("Living room")
} }
} }
@ -241,10 +243,13 @@ mod tests {
let mut nightstand = TestOutlet::new("bedroom/nightstand"); let mut nightstand = TestOutlet::new("bedroom/nightstand");
let mut lamp = TestOutlet::new("living/lamp"); let mut lamp = TestOutlet::new("living/lamp");
let mut scene = TestScene::new(); let mut scene = TestScene::new();
let mut devices: HashMap<String, &mut dyn GoogleHomeDevice> = HashMap::new(); let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
devices.insert(nightstand.get_id(), &mut nightstand); let id = nightstand.get_id().to_owned();
devices.insert(lamp.get_id(), &mut lamp); devices.insert(&id, &mut nightstand);
devices.insert(scene.get_id(), &mut scene); let id = lamp.get_id().to_owned();
devices.insert(&id, &mut lamp);
let id = scene.get_id().to_owned();
devices.insert(&id, &mut scene);
let resp = gh.handle_request(req, &mut devices).unwrap(); let resp = gh.handle_request(req, &mut devices).unwrap();
@ -281,10 +286,13 @@ mod tests {
let mut nightstand = TestOutlet::new("bedroom/nightstand"); let mut nightstand = TestOutlet::new("bedroom/nightstand");
let mut lamp = TestOutlet::new("living/lamp"); let mut lamp = TestOutlet::new("living/lamp");
let mut scene = TestScene::new(); let mut scene = TestScene::new();
let mut devices: HashMap<String, &mut dyn GoogleHomeDevice> = HashMap::new(); let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
devices.insert(nightstand.get_id(), &mut nightstand); let id = nightstand.get_id().to_owned();
devices.insert(lamp.get_id(), &mut lamp); devices.insert(&id, &mut nightstand);
devices.insert(scene.get_id(), &mut scene); let id = lamp.get_id().to_owned();
devices.insert(&id, &mut lamp);
let id = scene.get_id().to_owned();
devices.insert(&id, &mut scene);
let resp = gh.handle_request(req, &mut devices).unwrap(); let resp = gh.handle_request(req, &mut devices).unwrap();
@ -333,10 +341,13 @@ mod tests {
let mut nightstand = TestOutlet::new("bedroom/nightstand"); let mut nightstand = TestOutlet::new("bedroom/nightstand");
let mut lamp = TestOutlet::new("living/lamp"); let mut lamp = TestOutlet::new("living/lamp");
let mut scene = TestScene::new(); let mut scene = TestScene::new();
let mut devices: HashMap<String, &mut dyn GoogleHomeDevice> = HashMap::new(); let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
devices.insert(nightstand.get_id(), &mut nightstand); let id = nightstand.get_id().to_owned();
devices.insert(lamp.get_id(), &mut lamp); devices.insert(&id, &mut nightstand);
devices.insert(scene.get_id(), &mut scene); let id = lamp.get_id().to_owned();
devices.insert(&id, &mut lamp);
let id = scene.get_id().to_owned();
devices.insert(&id, &mut scene);
let resp = gh.handle_request(req, &mut devices).unwrap(); let resp = gh.handle_request(req, &mut devices).unwrap();

View File

@ -12,8 +12,8 @@ pub struct Response {
} }
impl Response { impl Response {
pub fn new(request_id: String, payload: ResponsePayload) -> Self { pub fn new(request_id: &str, payload: ResponsePayload) -> Self {
Self { request_id, payload } Self { request_id: request_id.to_owned(), payload }
} }
} }

View File

@ -93,7 +93,7 @@ mod tests {
command.ids.push("456".into()); command.ids.push("456".into());
execute_resp.add_command(command); execute_resp.add_command(command);
let resp = Response::new("ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_owned(), ResponsePayload::Execute(execute_resp)); let resp = Response::new("ff36a3cc-ec34-11e6-b1a0-64510650abcf", ResponsePayload::Execute(execute_resp));
let json = serde_json::to_string(&resp).unwrap(); let json = serde_json::to_string(&resp).unwrap();

View File

@ -81,7 +81,7 @@ mod tests {
device.state.on = Some(false); device.state.on = Some(false);
query_resp.add_device("456", device); query_resp.add_device("456", device);
let resp = Response::new("ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_owned(), ResponsePayload::Query(query_resp)); let resp = Response::new("ff36a3cc-ec34-11e6-b1a0-64510650abcf", ResponsePayload::Query(query_resp));
let json = serde_json::to_string(&resp).unwrap(); let json = serde_json::to_string(&resp).unwrap();

View File

@ -85,7 +85,7 @@ mod tests {
sync_resp.add_device(device); sync_resp.add_device(device);
let resp = Response::new("ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_owned(), ResponsePayload::Sync(sync_resp)); let resp = Response::new("ff36a3cc-ec34-11e6-b1a0-64510650abcf", ResponsePayload::Sync(sync_resp));
let json = serde_json::to_string(&resp).unwrap(); let json = serde_json::to_string(&resp).unwrap();

View File

@ -206,7 +206,7 @@ impl Config {
impl Device { impl Device {
#[async_recursion] #[async_recursion]
pub async fn create(self, identifier: String, config: &Config, client: AsyncClient) -> Result<DeviceBox, FailedToCreateDevice> { pub async fn create(self, identifier: &str, config: &Config, client: AsyncClient) -> Result<DeviceBox, FailedToCreateDevice> {
let device: Result<DeviceBox, Error> = match self { let device: Result<DeviceBox, Error> = match self {
Device::IkeaOutlet { info, mqtt, kettle } => { Device::IkeaOutlet { info, mqtt, kettle } => {
trace!(id = identifier, "IkeaOutlet [{} in {:?}]", info.name, info.room); trace!(id = identifier, "IkeaOutlet [{} in {:?}]", info.name, info.room);
@ -229,8 +229,10 @@ impl Device {
Device::AudioSetup { mqtt, mixer, speakers } => { Device::AudioSetup { mqtt, mixer, speakers } => {
trace!(id = identifier, "AudioSetup [{}]", identifier); trace!(id = identifier, "AudioSetup [{}]", identifier);
// Create the child devices // Create the child devices
let mixer = (*mixer).create(identifier.clone() + ".mixer", config, client.clone()).await?; let mixer_id = identifier.to_owned() + ".mixer";
let speakers = (*speakers).create(identifier.clone() + ".speakers", config, client.clone()).await?; let mixer = (*mixer).create(&mixer_id, config, client.clone()).await?;
let speakers_id = identifier.to_owned() + ".speakers";
let speakers = (*speakers).create(&speakers_id, config, client.clone()).await?;
match AudioSetup::build(&identifier, mqtt, mixer, speakers, client).await { match AudioSetup::build(&identifier, mqtt, mixer, speakers, client).await {
Ok(device) => Ok(Box::new(device)), Ok(device) => Ok(Box::new(device)),

View File

@ -27,7 +27,7 @@ impl_cast::impl_cast!(Device, GoogleHomeDevice);
impl_cast::impl_cast!(Device, OnOff); impl_cast::impl_cast!(Device, OnOff);
pub trait Device: AsGoogleHomeDevice + AsOnMqtt + AsOnPresence + AsOnDarkness + AsOnOff + std::fmt::Debug { pub trait Device: AsGoogleHomeDevice + AsOnMqtt + AsOnPresence + AsOnDarkness + AsOnOff + std::fmt::Debug {
fn get_id(&self) -> String; fn get_id(&self) -> &str;
} }
// @TODO Add an inner type that we can wrap with Arc<RwLock<>> to make this type a little bit nicer // @TODO Add an inner type that we can wrap with Arc<RwLock<>> to make this type a little bit nicer
@ -39,12 +39,12 @@ struct Devices {
macro_rules! get_cast { macro_rules! get_cast {
($trait:ident) => { ($trait:ident) => {
paste::paste! { paste::paste! {
pub fn [< as_ $trait:snake s >](&mut self) -> HashMap<String, &mut dyn $trait> { pub fn [< as_ $trait:snake s >](&mut self) -> HashMap<&str, &mut dyn $trait> {
self.devices self.devices
.iter_mut() .iter_mut()
.filter_map(|(id, device)| { .filter_map(|(id, device)| {
if let Some(listener) = [< As $trait >]::cast_mut(device.as_mut()) { if let Some(listener) = [< As $trait >]::cast_mut(device.as_mut()) {
return Some((id.clone(), listener)); return Some((id.as_str(), listener));
}; };
return None; return None;
}).collect() }).collect()
@ -136,7 +136,7 @@ impl Devices {
fn add_device(&mut self, device: DeviceBox) { fn add_device(&mut self, device: DeviceBox) {
debug!(id = device.get_id(), "Adding device"); debug!(id = device.get_id(), "Adding device");
self.devices.insert(device.get_id(), device); self.devices.insert(device.get_id().to_owned(), device);
} }
get_cast!(OnMqtt); get_cast!(OnMqtt);

View File

@ -39,8 +39,8 @@ impl AudioSetup {
} }
impl Device for AudioSetup { impl Device for AudioSetup {
fn get_id(&self) -> String { fn get_id(&self) -> &str {
self.identifier.clone() &self.identifier
} }
} }

View File

@ -38,8 +38,8 @@ impl ContactSensor {
} }
impl Device for ContactSensor { impl Device for ContactSensor {
fn get_id(&self) -> String { fn get_id(&self) -> &str {
self.identifier.clone() &self.identifier
} }
} }

View File

@ -1,5 +1,4 @@
use std::time::Duration; use std::time::Duration;
use async_trait::async_trait; use async_trait::async_trait;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::{GoogleHomeDevice, device, types::Type, traits::{self, OnOff}}; use google_home::{GoogleHomeDevice, device, types::Type, traits::{self, OnOff}};
@ -35,16 +34,16 @@ impl IkeaOutlet {
} }
} }
async fn set_on(client: AsyncClient, topic: String, on: bool) { async fn set_on(client: AsyncClient, topic: &str, on: bool) {
let message = OnOffMessage::new(on); let message = OnOffMessage::new(on);
// @TODO Handle potential errors here // @TODO Handle potential errors here
client.publish(topic.clone() + "/set", rumqttc::QoS::AtLeastOnce, false, serde_json::to_string(&message).unwrap()).await.map_err(|err| warn!("Failed to update state on {topic}: {err}")).ok(); client.publish(topic.to_owned() + "/set", rumqttc::QoS::AtLeastOnce, false, serde_json::to_string(&message).unwrap()).await.map_err(|err| warn!("Failed to update state on {topic}: {err}")).ok();
} }
impl Device for IkeaOutlet { impl Device for IkeaOutlet {
fn get_id(&self) -> String { fn get_id(&self) -> &str {
self.identifier.clone() &self.identifier
} }
} }
@ -106,7 +105,7 @@ impl OnMqtt for IkeaOutlet {
// @TODO Idealy we would call self.set_on(false), however since we want to do // @TODO Idealy we would call self.set_on(false), however since we want to do
// it after a timeout we have to put it in a seperate task. // it after a timeout we have to put it in a seperate task.
// I don't think we can really get around calling outside function // I don't think we can really get around calling outside function
set_on(client, topic, false).await; set_on(client, &topic, false).await;
}) })
); );
} }
@ -137,7 +136,7 @@ impl GoogleHomeDevice for IkeaOutlet {
device::Name::new(&self.info.name) device::Name::new(&self.info.name)
} }
fn get_id(&self) -> String { fn get_id(&self) -> &str {
Device::get_id(self) Device::get_id(self)
} }
@ -145,8 +144,8 @@ impl GoogleHomeDevice for IkeaOutlet {
true true
} }
fn get_room_hint(&self) -> Option<String> { fn get_room_hint(&self) -> Option<&str> {
self.info.room.clone() self.info.room.as_deref()
} }
fn will_report_state(&self) -> bool { fn will_report_state(&self) -> bool {
@ -161,7 +160,7 @@ impl traits::OnOff for IkeaOutlet {
} }
fn set_on(&mut self, on: bool) -> Result<(), ErrorCode> { fn set_on(&mut self, on: bool) -> Result<(), ErrorCode> {
set_on(self.client.clone(), self.mqtt.topic.clone(), on).block_on(); set_on(self.client.clone(), &self.mqtt.topic, on).block_on();
Ok(()) Ok(())
} }

View File

@ -19,8 +19,8 @@ impl KasaOutlet {
} }
impl Device for KasaOutlet { impl Device for KasaOutlet {
fn get_id(&self) -> String { fn get_id(&self) -> &str {
self.identifier.clone() &self.identifier
} }
} }

View File

@ -27,8 +27,8 @@ impl WakeOnLAN {
} }
impl Device for WakeOnLAN { impl Device for WakeOnLAN {
fn get_id(&self) -> String { fn get_id(&self) -> &str {
self.identifier.clone() &self.identifier
} }
} }
@ -63,7 +63,7 @@ impl GoogleHomeDevice for WakeOnLAN {
return name; return name;
} }
fn get_id(&self) -> String { fn get_id(&self) -> &str {
Device::get_id(self) Device::get_id(self)
} }
@ -71,8 +71,8 @@ impl GoogleHomeDevice for WakeOnLAN {
true true
} }
fn get_room_hint(&self) -> Option<String> { fn get_room_hint(&self) -> Option<&str> {
self.info.room.clone() self.info.room.as_deref()
} }
} }

View File

@ -79,7 +79,9 @@ async fn app() -> Result<(), Box<dyn std::error::Error>> {
.clone() .clone()
.into_iter() .into_iter()
.map(|(identifier, device_config)| async { .map(|(identifier, device_config)| async {
let device = device_config.create(identifier, &config, client.clone()).await?; // Force the async block to move identifier
let identifier = identifier;
let device = device_config.create(&identifier, &config, client.clone()).await?;
devices.add_device(device).await?; devices.add_device(device).await?;
Ok::<(), Box<dyn std::error::Error>>(()) Ok::<(), Box<dyn std::error::Error>>(())
}) })