1use serde_json::{json, Value};
5
6const BINARY: &[(&str, &str)] = &[
8 ("generic_boolean", ""),
9 ("power_on", "power"),
10 ("opening", "opening"),
11 ("battery_low", "battery"),
12 ("battery_charging", "battery_charging"),
13 ("carbon_monoxide", "carbon_monoxide"),
14 ("cold", "cold"),
15 ("connectivity", "connectivity"),
16 ("door", "door"),
17 ("garage_door", "garage_door"),
18 ("gas_detected", "gas"),
19 ("heat", "heat"),
20 ("light", "light"),
21 ("lock", "lock"),
22 ("moisture_detected", "moisture"),
23 ("motion", "motion"),
24 ("moving", "moving"),
25 ("occupancy", "occupancy"),
26 ("plug", "plug"),
27 ("presence", "presence"),
28 ("problem", "problem"),
29 ("running", "running"),
30 ("safety", "safety"),
31 ("smoke", "smoke"),
32 ("sound", "sound"),
33 ("tamper", "tamper"),
34 ("vibration", "vibration"),
35 ("window", "window"),
36];
37
38fn device_class(key: &str, unit: &str) -> Option<&'static str> {
40 let base = key.trim_end_matches(|c: char| c.is_ascii_digit() || c == '_');
41 Some(match base {
42 "temperature" | "dewpoint" => "temperature",
43 "humidity" => "humidity",
44 "moisture" => "moisture",
45 "battery" if unit == "%" => "battery",
46 "voltage" => "voltage",
47 "pressure" => "atmospheric_pressure",
48 "illuminance" => "illuminance",
49 "co2" => "carbon_dioxide",
50 "pm2_5" => "pm25",
51 "pm10" => "pm10",
52 "tvoc" => "volatile_organic_compounds",
53 "energy" => "energy",
54 "power" => "power",
55 "current" => "current",
56 "mass" => "weight",
57 "distance" => "distance",
58 "speed" => "speed",
59 "volume" | "volume_storage" => "volume",
60 "water" => "water",
61 "gas" => "gas",
62 "duration" => "duration",
63 "rssi" => "signal_strength",
64 "conductivity" => "conductivity",
65 "precipitation" => "precipitation",
66 _ => return None,
67 })
68}
69
70fn is_cumulative(key: &str) -> bool {
71 matches!(
72 key.trim_end_matches(|c: char| c.is_ascii_digit() || c == '_'),
73 "energy" | "gas" | "water" | "volume"
74 )
75}
76
77#[allow(clippy::too_many_arguments)]
79pub fn entity(
80 prefix: &str,
81 base: &str,
82 device_id: &str,
83 device_name: &str,
84 model: &str,
85 manufacturer: Option<&str>,
86 key: &str,
87 unit: &str,
88) -> (String, Value) {
89 let binary = BINARY.iter().find(|(k, _)| *k == key);
90 let component = if binary.is_some() {
91 "binary_sensor"
92 } else {
93 "sensor"
94 };
95 let object = format!("bluetooth_{}_{key}", device_id.to_lowercase());
96 let mut c = json!({
97 "name": key.replace('_', " "),
98 "unique_id": object,
99 "object_id": object,
100 "state_topic": format!("{base}/device/{device_id}"),
101 "availability_topic": crate::mqtt::state_topic(base),
102 "availability_template": "{{ value_json.state }}",
103 "device": {
104 "identifiers": [format!("bluetooth_{}", device_id.to_lowercase())],
105 "connections": [["bluetooth", device_id_to_mac(device_id)]],
106 "name": device_name,
107 "model": model,
108 "via_device": bridge_id(base),
109 },
110 });
111 if let Some(m) = manufacturer {
112 c["device"]["manufacturer"] = json!(m);
113 }
114 match binary {
115 Some((_, class)) => {
116 c["value_template"] = json!(format!("{{{{ 'ON' if value_json.{key} else 'OFF' }}}}"));
117 if !class.is_empty() {
118 c["device_class"] = json!(class);
119 }
120 }
121 None => {
122 c["value_template"] = json!(format!("{{{{ value_json.{key} }}}}"));
123 if !unit.is_empty() {
124 c["unit_of_measurement"] = json!(unit);
125 }
126 if let Some(class) = device_class(key, unit) {
127 c["device_class"] = json!(class);
128 }
129 c["state_class"] = json!(if is_cumulative(key) {
130 "total_increasing"
131 } else {
132 "measurement"
133 });
134 if key == "rssi" {
135 c["entity_category"] = json!("diagnostic");
136 c["enabled_by_default"] = json!(false);
137 }
138 }
139 }
140 (
141 format!(
142 "{prefix}/{component}/bluetooth_{}/{key}/config",
143 device_id.to_lowercase()
144 ),
145 c,
146 )
147}
148
149pub fn bridge_id(base: &str) -> String {
155 if base == "bluetooth" {
156 return "bluetooth_bridge".into();
157 }
158 let slug: String = base
159 .chars()
160 .map(|c| {
161 if c.is_ascii_alphanumeric() {
162 c.to_ascii_lowercase()
163 } else {
164 '_'
165 }
166 })
167 .collect();
168 format!("bluetooth_bridge_{slug}")
169}
170
171pub fn bridge_device(prefix: &str, base: &str, version: &str) -> (String, Value) {
173 let id = bridge_id(base);
174 (
175 format!("{prefix}/binary_sensor/{id}/connection_state/config"),
176 json!({
177 "name": "connection state",
178 "unique_id": format!("{id}_connection_state"),
179 "state_topic": crate::mqtt::state_topic(base),
180 "value_template": "{{ 'ON' if value_json.state == 'online' else 'OFF' }}",
181 "device_class": "connectivity",
182 "entity_category": "diagnostic",
183 "device": {
184 "identifiers": [id],
185 "name": if base == "bluetooth" { "Bluetooth bridge".to_string() } else { format!("Bluetooth bridge {base}") },
186 "model": "bluetooth-bridge",
187 "sw_version": version,
188 },
189 }),
190 )
191}
192
193fn device_id_to_mac(id: &str) -> String {
195 id.as_bytes()
196 .chunks(2)
197 .map(|c| String::from_utf8_lossy(c).into_owned())
198 .collect::<Vec<_>>()
199 .join(":")
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 #[test]
207 fn two_bridges_on_one_broker_are_two_devices() {
208 let (t1, c1) = bridge_device("homeassistant", "bluetooth", "0");
209 let (t2, c2) = bridge_device("homeassistant", "bluetooth/garage", "0");
210 assert_eq!(
211 t1, "homeassistant/binary_sensor/bluetooth_bridge/connection_state/config",
212 "the default bridge keeps its device"
213 );
214 assert_eq!(
215 t2,
216 "homeassistant/binary_sensor/bluetooth_bridge_bluetooth_garage/connection_state/config"
217 );
218 assert_ne!(c1["unique_id"], c2["unique_id"]);
219 assert_ne!(c1["device"]["identifiers"], c2["device"]["identifiers"]);
220 let (_, s) = entity(
221 "homeassistant",
222 "bluetooth/garage",
223 "BC5729000001",
224 "x",
225 "m",
226 None,
227 "temperature",
228 "°C",
229 );
230 assert_eq!(s["device"]["via_device"], c2["device"]["identifiers"][0]);
231 }
232
233 #[test]
234 fn sensors_and_binary_sensors() {
235 let (t, c) = entity(
236 "homeassistant",
237 "bluetooth",
238 "A4C138000001",
239 "Living room",
240 "BTHome",
241 None,
242 "temperature",
243 "°C",
244 );
245 assert_eq!(
246 t,
247 "homeassistant/sensor/bluetooth_a4c138000001/temperature/config"
248 );
249 assert_eq!(c["device_class"], "temperature");
250 assert_eq!(c["state_topic"], "bluetooth/device/A4C138000001");
251 assert_eq!(c["value_template"], "{{ value_json.temperature }}");
252 assert_eq!(c["device"]["connections"][0][1], "A4:C1:38:00:00:01");
253 let (t, c) = entity(
254 "homeassistant",
255 "bluetooth",
256 "A4C138000001",
257 "x",
258 "BTHome",
259 None,
260 "door",
261 "",
262 );
263 assert!(t.starts_with("homeassistant/binary_sensor/"));
264 assert_eq!(c["device_class"], "door");
265 let (_, c) = entity(
266 "homeassistant",
267 "bluetooth",
268 "A",
269 "x",
270 "m",
271 None,
272 "temperature_2",
273 "°C",
274 );
275 assert_eq!(c["device_class"], "temperature");
276 let (_, c) = entity(
277 "homeassistant",
278 "bluetooth",
279 "A",
280 "x",
281 "m",
282 None,
283 "energy",
284 "kWh",
285 );
286 assert_eq!(c["state_class"], "total_increasing");
287 }
288}