mqtt-rs 0.16.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Zigbee2MQTT device type builders.
//!
//! Each builder registers MQTT topics and generates EPICS records
//! for a specific Z2M device type, eliminating manual db/st.cmd boilerplate.
//!
//! # Usage (st.cmd)
//! ```text
//! mqttZ2mPlug("MQTT1", "TEST:MQTT:", "SWR:Plug", "zigbee2mqtt/living room plug")
//! mqttZ2mTempSensor("MQTT1", "TEST:MQTT:", "LR:Sens", "zigbee2mqtt/living room sensor")
//! mqttZ2mLight("MQTT1", "TEST:MQTT:", "SWR:Desk", "zigbee2mqtt/desk light")
//! mqttZ2mSwitch("MQTT1", "TEST:MQTT:", "MBath:Light", "zigbee2mqtt/bathroom light")
//! mqttZ2mMotion("MQTT1", "TEST:MQTT:", "ENT:Motion", "zigbee2mqtt/entrance motion")
//! mqttZ2mRemote2("MQTT1", "TEST:MQTT:", "LBath:Sw", "zigbee2mqtt/bathroom switch")
//! mqttDriverConfigure("MQTT1", "mqtt://localhost:1883", "epics-mqtt-ioc", 1)
//! iocInit()
//! ```

use std::collections::HashMap;
use std::fmt::Write;

use epics_base_rs::server::db_loader;
use epics_base_rs::server::iocsh::registry::*;

use crate::address::TopicAddress;
use crate::ioc::register_pending_topic;

/// A single record definition to be generated.
struct RecordDef {
    record_type: &'static str,
    suffix: &'static str,
    dtyp: &'static str,
    link_field: &'static str, // "INP" or "OUT"
    drv_info: String,         // e.g. "JSON:FLOAT zigbee2mqtt/living room plug power"
    egu: &'static str,
    prec: Option<i16>,
    scan_io_intr: bool,
}

/// Generate a .db string from record definitions and load it via db_loader.
fn load_records(prefix: &str, dev: &str, port: &str, records: &[RecordDef], ctx: &CommandContext) {
    let mut db_string = String::new();
    for r in records {
        let pv_name = format!("{prefix}{dev}:{}", r.suffix);
        let _ = writeln!(db_string, "record({}, \"{pv_name}\") {{", r.record_type);
        let _ = writeln!(db_string, "    field(DTYP, \"{}\")", r.dtyp);
        if r.scan_io_intr {
            let _ = writeln!(db_string, "    field(SCAN, \"I/O Intr\")");
        }
        let _ = writeln!(
            db_string,
            "    field({}, \"@asyn({port}) {}\")",
            r.link_field, r.drv_info
        );
        if !r.egu.is_empty() {
            let _ = writeln!(db_string, "    field(EGU, \"{}\")", r.egu);
        }
        if let Some(prec) = r.prec {
            let _ = writeln!(db_string, "    field(PREC, \"{prec}\")");
        }
        let _ = writeln!(db_string, "}}");
    }

    let macros = HashMap::new();
    match db_loader::parse_db(&db_string, &macros) {
        Ok(defs) => {
            for def in defs {
                match db_loader::create_record(&def.record_type) {
                    Ok(mut record) => {
                        let mut common_fields = Vec::new();
                        if let Err(e) =
                            db_loader::apply_fields(&mut record, &def.fields, &mut common_fields)
                        {
                            eprintln!("z2m: apply_fields for {}: {e}", def.name);
                            continue;
                        }
                        ctx.block_on(async {
                            if let Err(e) = ctx.db().add_record(&def.name, record).await {
                                eprintln!("z2m: register '{}' skipped: {e}", def.name);
                                return;
                            }
                            if let Some(rec_arc) = ctx.db().get_record(&def.name).await {
                                let mut instance = rec_arc.write().await;
                                for (name, value) in common_fields {
                                    let _ = instance.put_common_field(&name, value);
                                }
                            }
                        });
                    }
                    Err(e) => eprintln!("z2m: create_record({}): {e}", def.record_type),
                }
            }
        }
        Err(e) => eprintln!("z2m: parse_db failed: {e}"),
    }
}

/// Register a topic and return the drvInfo string.
fn add_topic(port: &str, drv_info: &str) -> String {
    add_topic_opts(port, drv_info, false)
}

/// Register a topic with ON/OFF normalization enabled.
fn add_topic_normalized(port: &str, drv_info: &str) -> String {
    add_topic_opts(port, drv_info, true)
}

fn add_topic_opts(port: &str, drv_info: &str, normalize: bool) -> String {
    if let Ok(mut addr) = TopicAddress::parse(drv_info) {
        addr.normalize_on_off = normalize;
        register_pending_topic(port, addr);
    }
    drv_info.to_string()
}

// ============ Helper: common 4-arg extraction ============

fn extract_args(args: &[ArgValue]) -> Result<(String, String, String, String), String> {
    let port = match &args[0] {
        ArgValue::String(s) => s.clone(),
        _ => return Err("portName required".into()),
    };
    let prefix = match &args[1] {
        ArgValue::String(s) => s.clone(),
        _ => return Err("prefix required".into()),
    };
    let dev = match &args[2] {
        ArgValue::String(s) => s.clone(),
        _ => return Err("devName required".into()),
    };
    let topic = match &args[3] {
        ArgValue::String(s) => s.clone(),
        _ => return Err("mqttTopic required".into()),
    };
    Ok((port, prefix, dev, topic))
}

fn z2m_arg_defs() -> Vec<ArgDesc> {
    vec![
        ArgDesc {
            name: "portName",
            arg_type: ArgType::String,
            optional: false,
        },
        ArgDesc {
            name: "prefix",
            arg_type: ArgType::String,
            optional: false,
        },
        ArgDesc {
            name: "devName",
            arg_type: ArgType::String,
            optional: false,
        },
        ArgDesc {
            name: "mqttTopic",
            arg_type: ArgType::String,
            optional: false,
        },
    ]
}

// ============ Device type builders ============

/// Smart plug: power(W), energy(kWh), device_temperature(degC), state + control
pub fn cmd_z2m_plug() -> CommandDef {
    CommandDef::new(
        "mqttZ2mPlug",
        z2m_arg_defs(),
        "mqttZ2mPlug port prefix dev topic - Z2M smart plug (power/energy/temp/state)",
        |args: &[ArgValue], ctx: &CommandContext| {
            let (port, prefix, dev, topic) = extract_args(args)?;
            println!("mqttZ2mPlug: {dev} -> {topic}");

            let records = vec![
                RecordDef {
                    record_type: "ai",
                    suffix: "Power",
                    dtyp: "asynFloat64",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:FLOAT {topic} power")),
                    egu: "W",
                    prec: Some(1),
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "ai",
                    suffix: "Energy",
                    dtyp: "asynFloat64",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:FLOAT {topic} energy")),
                    egu: "kWh",
                    prec: Some(2),
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "longin",
                    suffix: "DevTemp",
                    dtyp: "asynInt32",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:INT {topic} device_temperature")),
                    egu: "degC",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "stringin",
                    suffix: "State",
                    dtyp: "asynOctetRead",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:STRING {topic} state")),
                    egu: "",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "stringout",
                    suffix: "SetState",
                    dtyp: "asynOctetWrite",
                    link_field: "OUT",
                    drv_info: add_topic_normalized(
                        &port,
                        &format!("JSON:STRING {topic}/set state"),
                    ),
                    egu: "",
                    prec: None,
                    scan_io_intr: false,
                },
            ];
            load_records(&prefix, &dev, &port, &records, ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// Temperature/humidity sensor: temperature(degC), humidity(%), battery(%)
pub fn cmd_z2m_temp_sensor() -> CommandDef {
    CommandDef::new(
        "mqttZ2mTempSensor",
        z2m_arg_defs(),
        "mqttZ2mTempSensor port prefix dev topic - Z2M temp/humidity sensor",
        |args: &[ArgValue], ctx: &CommandContext| {
            let (port, prefix, dev, topic) = extract_args(args)?;
            println!("mqttZ2mTempSensor: {dev} -> {topic}");

            let records = vec![
                RecordDef {
                    record_type: "ai",
                    suffix: "Temp",
                    dtyp: "asynFloat64",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:FLOAT {topic} temperature")),
                    egu: "degC",
                    prec: Some(1),
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "ai",
                    suffix: "Hum",
                    dtyp: "asynFloat64",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:FLOAT {topic} humidity")),
                    egu: "%",
                    prec: Some(1),
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "longin",
                    suffix: "Batt",
                    dtyp: "asynInt32",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:INT {topic} battery")),
                    egu: "%",
                    prec: None,
                    scan_io_intr: true,
                },
            ];
            load_records(&prefix, &dev, &port, &records, ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// Light (Aqara-style): brightness, color_temp, state + control (state, brightness)
pub fn cmd_z2m_light() -> CommandDef {
    CommandDef::new(
        "mqttZ2mLight",
        z2m_arg_defs(),
        "mqttZ2mLight port prefix dev topic - Z2M dimmable light",
        |args: &[ArgValue], ctx: &CommandContext| {
            let (port, prefix, dev, topic) = extract_args(args)?;
            println!("mqttZ2mLight: {dev} -> {topic}");

            let records = vec![
                RecordDef {
                    record_type: "longin",
                    suffix: "Brightness",
                    dtyp: "asynInt32",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:INT {topic} brightness")),
                    egu: "",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "longin",
                    suffix: "ColorTemp",
                    dtyp: "asynInt32",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:INT {topic} color_temp")),
                    egu: "mired",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "stringin",
                    suffix: "State",
                    dtyp: "asynOctetRead",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:STRING {topic} state")),
                    egu: "",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "stringout",
                    suffix: "SetState",
                    dtyp: "asynOctetWrite",
                    link_field: "OUT",
                    drv_info: add_topic_normalized(
                        &port,
                        &format!("JSON:STRING {topic}/set state"),
                    ),
                    egu: "",
                    prec: None,
                    scan_io_intr: false,
                },
                RecordDef {
                    record_type: "longout",
                    suffix: "SetBright",
                    dtyp: "asynInt32",
                    link_field: "OUT",
                    drv_info: add_topic(&port, &format!("JSON:INT {topic}/set brightness")),
                    egu: "",
                    prec: None,
                    scan_io_intr: false,
                },
            ];
            load_records(&prefix, &dev, &port, &records, ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// On/off switch module: state + control
pub fn cmd_z2m_switch() -> CommandDef {
    CommandDef::new(
        "mqttZ2mSwitch",
        z2m_arg_defs(),
        "mqttZ2mSwitch port prefix dev topic - Z2M on/off switch",
        |args: &[ArgValue], ctx: &CommandContext| {
            let (port, prefix, dev, topic) = extract_args(args)?;
            println!("mqttZ2mSwitch: {dev} -> {topic}");

            let records = vec![
                RecordDef {
                    record_type: "stringin",
                    suffix: "State",
                    dtyp: "asynOctetRead",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:STRING {topic} state")),
                    egu: "",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "stringout",
                    suffix: "SetState",
                    dtyp: "asynOctetWrite",
                    link_field: "OUT",
                    drv_info: add_topic_normalized(
                        &port,
                        &format!("JSON:STRING {topic}/set state"),
                    ),
                    egu: "",
                    prec: None,
                    scan_io_intr: false,
                },
            ];
            load_records(&prefix, &dev, &port, &records, ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// Motion sensor: occupancy (string "true"/"false"), battery(%)
pub fn cmd_z2m_motion() -> CommandDef {
    CommandDef::new(
        "mqttZ2mMotion",
        z2m_arg_defs(),
        "mqttZ2mMotion port prefix dev topic - Z2M motion sensor",
        |args: &[ArgValue], ctx: &CommandContext| {
            let (port, prefix, dev, topic) = extract_args(args)?;
            println!("mqttZ2mMotion: {dev} -> {topic}");

            let records = vec![
                RecordDef {
                    record_type: "stringin",
                    suffix: "Occ",
                    dtyp: "asynOctetRead",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:STRING {topic} occupancy")),
                    egu: "",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "longin",
                    suffix: "Batt",
                    dtyp: "asynInt32",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:INT {topic} battery")),
                    egu: "%",
                    prec: None,
                    scan_io_intr: true,
                },
            ];
            load_records(&prefix, &dev, &port, &records, ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// 2-button remote: action (string), battery(%)
pub fn cmd_z2m_remote2() -> CommandDef {
    CommandDef::new(
        "mqttZ2mRemote2",
        z2m_arg_defs(),
        "mqttZ2mRemote2 port prefix dev topic - Z2M 2-button remote",
        |args: &[ArgValue], ctx: &CommandContext| {
            let (port, prefix, dev, topic) = extract_args(args)?;
            println!("mqttZ2mRemote2: {dev} -> {topic}");

            let records = vec![
                RecordDef {
                    record_type: "stringin",
                    suffix: "Act",
                    dtyp: "asynOctetRead",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:STRING {topic} action")),
                    egu: "",
                    prec: None,
                    scan_io_intr: true,
                },
                RecordDef {
                    record_type: "longin",
                    suffix: "Batt",
                    dtyp: "asynInt32",
                    link_field: "INP",
                    drv_info: add_topic(&port, &format!("JSON:INT {topic} battery")),
                    egu: "%",
                    prec: None,
                    scan_io_intr: true,
                },
            ];
            load_records(&prefix, &dev, &port, &records, ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// Register all Z2M builder commands on an IocApplication.
pub fn register_z2m_commands(
    app: epics_ca_rs::server::ioc_app::IocApplication,
) -> epics_ca_rs::server::ioc_app::IocApplication {
    app.register_startup_command(cmd_z2m_plug())
        .register_startup_command(cmd_z2m_temp_sensor())
        .register_startup_command(cmd_z2m_light())
        .register_startup_command(cmd_z2m_switch())
        .register_startup_command(cmd_z2m_motion())
        .register_startup_command(cmd_z2m_remote2())
}