mqtt-rs 0.20.2

MQTT driver for epics-rs — publish/subscribe MQTT topics as EPICS records
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use asyn_rs::param::ParamType;

use crate::error::{MqttError, MqttResult};

/// Payload format: flat single-value or structured JSON.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PayloadFormat {
    Flat,
    Json,
}

/// Expected value type of the MQTT payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueType {
    Int,
    Float,
    Digital,
    String,
    IntArray,
    FloatArray,
}

/// Parsed topic address from a drvInfo string.
///
/// Format: `"FORMAT:TYPE topic/name [json field]"`
///
/// Grammar follows C `MqttDriver::parseDeviceAddress` (drvMqtt.cpp:64-96):
/// - **FLAT**: everything after `FORMAT:TYPE ` is the topic (spaces allowed),
///   `topicName = arguments`.
/// - **JSON**: the topic is the text before the FIRST whitespace and the JSON
///   field is the entire remaining suffix (`arguments.substr(spacePos + 1)`),
///   so a JSON object key may itself contain spaces. A topic containing
///   spaces is not expressible in the C grammar; this port adds an explicit
///   quoted-topic extension `FORMAT:TYPE "topic with spaces" field` for that
///   case only, leaving the reference grammar for unquoted drvInfo intact.
///
/// Examples:
/// - `"FLAT:INT test/temperature"`
/// - `"JSON:FLOAT sensors/data humidity"`
/// - `"JSON:STRING device/topic key with spaces"` (field is `key with spaces`)
/// - `"JSON:FLOAT \"zigbee2mqtt/living room plug\" power"` (quoted topic)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TopicAddress {
    pub format: PayloadFormat,
    pub value_type: ValueType,
    pub topic: String,
    pub json_field: Option<String>,
    /// When true, string values "1"/"on"/"true" → "ON", "0"/"off"/"false" → "OFF".
    /// Set by Z2M builders for state control topics. Generic MQTT leaves this false.
    pub normalize_on_off: bool,
}

impl TopicAddress {
    /// Parse a drvInfo string into a `TopicAddress`.
    ///
    /// See the type docs for the grammar. The unquoted JSON form mirrors C
    /// `parseDeviceAddress` (drvMqtt.cpp:74-92) exactly: first whitespace
    /// separates the topic from the whole JSON field suffix. The quoted JSON
    /// form is a port-only extension for topics that contain spaces.
    pub fn parse(drv_info: &str) -> MqttResult<Self> {
        // Split off FORMAT:TYPE (first token)
        let (format_type_str, rest) =
            drv_info.split_once(char::is_whitespace).ok_or_else(|| {
                MqttError::InvalidAddress(format!(
                    "expected at least 'FORMAT:TYPE topic', got: {drv_info:?}"
                ))
            })?;

        let rest = rest.trim_start();
        if rest.is_empty() {
            return Err(MqttError::InvalidAddress(
                "missing topic after FORMAT:TYPE".into(),
            ));
        }

        let (format, value_type) = Self::parse_format_type(format_type_str)?;

        let (topic, json_field) = match format {
            PayloadFormat::Flat => {
                // Everything remaining is the topic
                (rest.to_string(), None)
            }
            PayloadFormat::Json => {
                if let Some(after_open) = rest.strip_prefix('"') {
                    // Quoted-topic extension: the topic is the text between the
                    // quotes (spaces allowed), the field is the remainder.
                    let close = after_open.find('"').ok_or_else(|| {
                        MqttError::InvalidAddress("unterminated quoted JSON topic".into())
                    })?;
                    let topic = after_open[..close].to_string();
                    if topic.is_empty() {
                        return Err(MqttError::InvalidAddress("empty quoted JSON topic".into()));
                    }
                    let field = after_open[close + 1..].trim();
                    if field.is_empty() {
                        return Err(MqttError::InvalidAddress(
                            "JSON format requires a field after the quoted topic".into(),
                        ));
                    }
                    (topic, Some(field.to_string()))
                } else {
                    // C grammar (drvMqtt.cpp:75,86,92): topic is the text before
                    // the first whitespace; the JSON field is the entire rest of
                    // the suffix and may itself contain spaces.
                    let (topic, field) = rest.split_once(char::is_whitespace).ok_or_else(|| {
                        MqttError::InvalidAddress("JSON format requires 'topic field'".into())
                    })?;
                    if topic.is_empty() {
                        return Err(MqttError::InvalidAddress(
                            "empty topic before JSON field".into(),
                        ));
                    }
                    if field.is_empty() {
                        return Err(MqttError::InvalidAddress("empty JSON field".into()));
                    }
                    (topic.to_string(), Some(field.to_string()))
                }
            }
        };

        Self::validate_topic(&topic)?;

        Ok(Self {
            format,
            value_type,
            topic,
            json_field,
            normalize_on_off: false,
        })
    }

    /// Convert this address's value type to the corresponding asyn `ParamType`.
    pub fn param_type(&self) -> ParamType {
        match self.value_type {
            ValueType::Int => ParamType::Int32,
            ValueType::Float => ParamType::Float64,
            ValueType::Digital => ParamType::UInt32Digital,
            ValueType::String => ParamType::Octet,
            ValueType::IntArray => ParamType::Int32Array,
            ValueType::FloatArray => ParamType::Float64Array,
        }
    }

    /// Reconstruct the drvInfo string for use as a parameter name.
    pub fn to_drv_info(&self) -> String {
        let fmt = match self.format {
            PayloadFormat::Flat => "FLAT",
            PayloadFormat::Json => "JSON",
        };
        let typ = match self.value_type {
            ValueType::Int => "INT",
            ValueType::Float => "FLOAT",
            ValueType::Digital => "DIGITAL",
            ValueType::String => "STRING",
            ValueType::IntArray => "INTARRAY",
            ValueType::FloatArray => "FLOATARRAY",
        };
        match &self.json_field {
            // A topic containing spaces is only round-trippable through the
            // quoted-topic extension; an unquoted topic re-parses C-faithfully.
            Some(field) if self.topic.contains(char::is_whitespace) => {
                format!("{fmt}:{typ} \"{}\" {field}", self.topic)
            }
            Some(field) => format!("{fmt}:{typ} {} {field}", self.topic),
            None => format!("{fmt}:{typ} {}", self.topic),
        }
    }

    fn parse_format_type(s: &str) -> MqttResult<(PayloadFormat, ValueType)> {
        let (fmt_str, type_str) = s
            .split_once(':')
            .ok_or_else(|| MqttError::InvalidAddress(format!("missing ':' in {s:?}")))?;

        let format = match fmt_str.to_ascii_uppercase().as_str() {
            "FLAT" => PayloadFormat::Flat,
            "JSON" => PayloadFormat::Json,
            _ => {
                return Err(MqttError::UnsupportedType(format!(
                    "unknown format: {fmt_str:?}"
                )));
            }
        };

        let value_type = match type_str.to_ascii_uppercase().as_str() {
            "INT" => ValueType::Int,
            "FLOAT" => ValueType::Float,
            "DIGITAL" => ValueType::Digital,
            "STRING" => ValueType::String,
            "INTARRAY" => ValueType::IntArray,
            "FLOATARRAY" => ValueType::FloatArray,
            _ => {
                return Err(MqttError::UnsupportedType(format!(
                    "unknown type: {type_str:?}"
                )));
            }
        };

        Ok((format, value_type))
    }

    fn validate_topic(topic: &str) -> MqttResult<()> {
        if topic.is_empty() {
            return Err(MqttError::InvalidTopic("empty topic".into()));
        }
        if topic.contains('#') || topic.contains('+') {
            return Err(MqttError::InvalidTopic(format!(
                "wildcards not allowed in topic address: {topic:?}"
            )));
        }
        Ok(())
    }
}

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

    #[test]
    fn parse_flat_int() {
        let addr = TopicAddress::parse("FLAT:INT test/temperature").unwrap();
        assert_eq!(addr.format, PayloadFormat::Flat);
        assert_eq!(addr.value_type, ValueType::Int);
        assert_eq!(addr.topic, "test/temperature");
        assert_eq!(addr.json_field, None);
        assert_eq!(addr.param_type(), ParamType::Int32);
    }

    #[test]
    fn parse_flat_float() {
        let addr = TopicAddress::parse("FLAT:FLOAT sensors/pressure").unwrap();
        assert_eq!(addr.format, PayloadFormat::Flat);
        assert_eq!(addr.value_type, ValueType::Float);
        assert_eq!(addr.topic, "sensors/pressure");
    }

    #[test]
    fn parse_flat_string() {
        let addr = TopicAddress::parse("FLAT:STRING device/status").unwrap();
        assert_eq!(addr.value_type, ValueType::String);
        assert_eq!(addr.param_type(), ParamType::Octet);
    }

    #[test]
    fn parse_flat_arrays() {
        let addr = TopicAddress::parse("FLAT:INTARRAY data/counts").unwrap();
        assert_eq!(addr.value_type, ValueType::IntArray);
        assert_eq!(addr.param_type(), ParamType::Int32Array);

        let addr = TopicAddress::parse("FLAT:FLOATARRAY data/waveform").unwrap();
        assert_eq!(addr.value_type, ValueType::FloatArray);
        assert_eq!(addr.param_type(), ParamType::Float64Array);
    }

    #[test]
    fn parse_json_float() {
        let addr = TopicAddress::parse("JSON:FLOAT sensors/data humidity").unwrap();
        assert_eq!(addr.format, PayloadFormat::Json);
        assert_eq!(addr.value_type, ValueType::Float);
        assert_eq!(addr.topic, "sensors/data");
        assert_eq!(addr.json_field.as_deref(), Some("humidity"));
    }

    #[test]
    fn parse_json_nested_field() {
        let addr = TopicAddress::parse("JSON:INT sensors/data reading.value").unwrap();
        assert_eq!(addr.topic, "sensors/data");
        assert_eq!(addr.json_field.as_deref(), Some("reading.value"));
    }

    // C parity: the JSON field is the entire suffix after the first space, so a
    // key containing spaces is one literal key matched against the payload
    // (drvMqtt.cpp:92). The topic is the first token only.
    #[test]
    fn parse_json_field_with_spaces() {
        let addr = TopicAddress::parse("JSON:STRING device/topic key with spaces").unwrap();
        assert_eq!(addr.format, PayloadFormat::Json);
        assert_eq!(addr.topic, "device/topic");
        assert_eq!(addr.json_field.as_deref(), Some("key with spaces"));
    }

    #[test]
    fn parse_case_insensitive() {
        let addr = TopicAddress::parse("flat:int test/topic").unwrap();
        assert_eq!(addr.format, PayloadFormat::Flat);
        assert_eq!(addr.value_type, ValueType::Int);
    }

    #[test]
    fn parse_roundtrip() {
        let original = "FLAT:INT test/temperature";
        let addr = TopicAddress::parse(original).unwrap();
        assert_eq!(addr.to_drv_info(), original);

        let original = "JSON:FLOAT sensors/data humidity";
        let addr = TopicAddress::parse(original).unwrap();
        assert_eq!(addr.to_drv_info(), original);
    }

    #[test]
    fn reject_empty_input() {
        assert!(TopicAddress::parse("").is_err());
    }

    #[test]
    fn reject_missing_topic() {
        assert!(TopicAddress::parse("FLAT:INT").is_err());
    }

    #[test]
    fn reject_missing_colon() {
        assert!(TopicAddress::parse("FLATINT test/topic").is_err());
    }

    #[test]
    fn reject_unknown_format() {
        assert!(TopicAddress::parse("XML:INT test/topic").is_err());
    }

    #[test]
    fn reject_unknown_type() {
        assert!(TopicAddress::parse("FLAT:BOOL test/topic").is_err());
    }

    #[test]
    fn reject_wildcard_topics() {
        assert!(TopicAddress::parse("FLAT:INT test/+/data").is_err());
        assert!(TopicAddress::parse("FLAT:INT test/#").is_err());
    }

    #[test]
    fn reject_json_without_field() {
        assert!(TopicAddress::parse("JSON:FLOAT sensors/data").is_err());
    }

    // --- Topics with spaces (e.g. Z2M Korean device names) ---
    //
    // FLAT topics may contain spaces directly (C `topicName = arguments`).
    // JSON topics with spaces require the quoted-topic extension, because the
    // unquoted C grammar reserves whitespace for the topic/field boundary.

    #[test]
    fn parse_flat_topic_with_spaces() {
        let addr = TopicAddress::parse("FLAT:FLOAT zigbee2mqtt/living room plug").unwrap();
        assert_eq!(addr.format, PayloadFormat::Flat);
        assert_eq!(addr.value_type, ValueType::Float);
        assert_eq!(addr.topic, "zigbee2mqtt/living room plug");
        assert_eq!(addr.json_field, None);
    }

    #[test]
    fn parse_json_quoted_topic_with_spaces() {
        let addr =
            TopicAddress::parse("JSON:FLOAT \"zigbee2mqtt/living room plug\" power").unwrap();
        assert_eq!(addr.format, PayloadFormat::Json);
        assert_eq!(addr.topic, "zigbee2mqtt/living room plug");
        assert_eq!(addr.json_field.as_deref(), Some("power"));
    }

    #[test]
    fn parse_json_quoted_topic_nested_field() {
        let addr =
            TopicAddress::parse("JSON:FLOAT \"zigbee2mqtt/desk light\" update.installed_version")
                .unwrap();
        assert_eq!(addr.topic, "zigbee2mqtt/desk light");
        assert_eq!(addr.json_field.as_deref(), Some("update.installed_version"));
    }

    // The unquoted JSON form must NOT absorb topic spaces — that is the C
    // behavior this port restores: first token is the topic, the rest is field.
    #[test]
    fn parse_json_unquoted_splits_at_first_space() {
        let addr = TopicAddress::parse("JSON:FLOAT zigbee2mqtt/living room plug power").unwrap();
        assert_eq!(addr.topic, "zigbee2mqtt/living");
        assert_eq!(addr.json_field.as_deref(), Some("room plug power"));
    }

    #[test]
    fn reject_json_unterminated_quoted_topic() {
        assert!(TopicAddress::parse("JSON:FLOAT \"zigbee2mqtt/living room power").is_err());
    }

    #[test]
    fn parse_flat_topic_with_multiple_spaces() {
        let addr = TopicAddress::parse("FLAT:STRING zigbee2mqtt/my cool device name").unwrap();
        assert_eq!(addr.topic, "zigbee2mqtt/my cool device name");
    }

    #[test]
    fn roundtrip_topic_with_spaces() {
        let original = "FLAT:FLOAT zigbee2mqtt/living room plug";
        let addr = TopicAddress::parse(original).unwrap();
        assert_eq!(addr.to_drv_info(), original);

        // A spaced JSON topic round-trips through the quoted-topic extension.
        let original = "JSON:INT \"zigbee2mqtt/bedroom plug\" device_temperature";
        let addr = TopicAddress::parse(original).unwrap();
        assert_eq!(addr.topic, "zigbee2mqtt/bedroom plug");
        assert_eq!(addr.json_field.as_deref(), Some("device_temperature"));
        assert_eq!(addr.to_drv_info(), original);

        // A JSON field containing spaces round-trips unquoted (C grammar).
        let original = "JSON:STRING device/topic key with spaces";
        let addr = TopicAddress::parse(original).unwrap();
        assert_eq!(addr.to_drv_info(), original);
    }
}