Skip to content

Commit

Permalink
feat: replace illegal device id characters automatically
Browse files Browse the repository at this point in the history
  • Loading branch information
ctron committed Apr 7, 2024
1 parent 11c99b8 commit fbf96c3
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions agent/src/uplink/homeassistant/mod.rs
Expand Up @@ -325,9 +325,7 @@ impl Runner {
pub async fn run(options: Options, manager: Arc<Manager>) -> anyhow::Result<()> {
let Options { options, connector } = options;

let device_id = options
.device_id
.unwrap_or_else(|| gethostname().to_string_lossy().to_string());
let device_id = options.device_id.unwrap_or_else(default_device_id);

let availability_topic = format!("{base}/{device_id}/availability", base = options.base);
let availability = AvailabilityOptions::new(availability_topic.clone());
Expand All @@ -347,3 +345,25 @@ pub async fn run(options: Options, manager: Arc<Manager>) -> anyhow::Result<()>

Ok(())
}

// generate a default device id
fn default_device_id() -> String {
scrub_device_id(&gethostname().to_string_lossy())
}

fn scrub_device_id(device_id: &str) -> String {
device_id.replace(
|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'),
"_",
)
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_scrub_device_id() {
assert_eq!(scrub_device_id("foo.bar.baz"), "foo_bar_baz")
}
}

0 comments on commit fbf96c3

Please sign in to comment.