ctucx.git: sdm2mqtt

Publish data from SDM120M meters via MQTT

commit 2558947fb87a05427ba95359c91ed871d2939d1d
parent 2268741b67e973926dafc289109d0da565ab4be0
Author: Leah (ctucx) <git@ctu.cx>
Date: Sun, 4 Jun 2023 10:23:08 +0200

slow down sending of mqtt messages a bit
1 file changed, 11 insertions(+), 17 deletions(-)
M
src/sdm2mqtt.nim
|
28
+++++++++++-----------------
diff --git a/src/sdm2mqtt.nim b/src/sdm2mqtt.nim
@@ -22,29 +22,23 @@ proc CtrlCHook* () {.noconv.} =
   quit()
 
 proc updatePowermeter (deviceAddress: uint8, deviceName: string) {.async.} = 
-  let voltage   = mbFloatDCBA(await readInputRegisters(deviceAddress, 0, 2)).round(3)
-  let frequency = mbFloatDCBA(await readInputRegisters(deviceAddress, 70, 2)).round(3)
-  let `import`  = mbFloatDCBA(await readInputRegisters(deviceAddress, 72, 2)).round(3)
-  let cosphi    = mbFloatDCBA(await readInputRegisters(deviceAddress, 30, 2)).round(3)
-  let power     = mbFloatDCBA(await readInputRegisters(deviceAddress, 12, 2)).round(3)
   let json = %* {
     "id":         deviceAddress,
     "deviceName": deviceName,
-    "voltage":    voltage,
-    "power":      power,
-    "frequency":  frequency,
-    "cosphi":     cosphi,
-    "import":     `import`
+    "voltage":    mbFloatDCBA(await readInputRegisters(deviceAddress, 0, 2)).round(3),
+    "power":      mbFloatDCBA(await readInputRegisters(deviceAddress, 12, 2)).round(3),
+    "frequency":  mbFloatDCBA(await readInputRegisters(deviceAddress, 70, 2)).round(3),
+    "cosphi":     mbFloatDCBA(await readInputRegisters(deviceAddress, 30, 2)).round(3),
+    "import":     mbFloatDCBA(await readInputRegisters(deviceAddress, 72, 2)).round(3)
   }
 
   if mqttContext.isConnected:
-    await mqttContext.publish("sdm2mqtt/"&deviceName,              $json,        2, true)
-    await mqttContext.publish("sdm2mqtt/"&deviceName&"/id",        $deviceName,  2, true)
-    await mqttContext.publish("sdm2mqtt/"&deviceName&"/voltage",   $voltage,     2, true)
-    await mqttContext.publish("sdm2mqtt/"&deviceName&"/frequency", $frequency,   2, true)
-    await mqttContext.publish("sdm2mqtt/"&deviceName&"/import",    $`import`,    2, true)
-    await mqttContext.publish("sdm2mqtt/"&deviceName&"/cosphi",    $cosphi,      2, true)
-    await mqttContext.publish("sdm2mqtt/"&deviceName&"/power",     $power,       2, true)
+    await mqttContext.publish("sdm2mqtt/"&deviceName, $json, 2, true)
+
+    for key, value in json:
+      if key != "deviceName":
+        await sleepAsync(250)
+        await mqttContext.publish("sdm2mqtt/" & deviceName & "/" & key, $value, 2, true)
 
 proc updatePowermeters (config: Config) {.async.} =
   await sleepAsync(500)