ctucx.git: smartied

[nimlang] smarthome server

commit 0f7d1e7016cb63a963bd953808ba57b59f13b09c
parent 5e443b37c3f245d200eff6abf08ebf15ba3597de
Author: Milan Pässler <me@pbb.lc>
Date: Wed, 1 Jan 2020 15:42:26 +0100

retry 2
2 files changed, 19 insertions(+), 12 deletions(-)
M
src/backend_powermeter.nim
|
1
-
M
src/modbus.nim
|
30
+++++++++++++++++++-----------
diff --git a/src/backend_powermeter.nim b/src/backend_powermeter.nim
@@ -25,7 +25,6 @@ proc updatePowermeter(key: string, device: DeviceConfig) {.async.} =
   broadcast($(%*server.state))
 
 proc updatePowermeters() {.async.} =
-  echo "updating powermeters"
   for key, device in server.config.devices.pairs():
     if device.type != PowerMeter:
       continue
diff --git a/src/modbus.nim b/src/modbus.nim
@@ -14,13 +14,19 @@ proc mkPacket_mbTcp(mb_packet: string): string =
   inc(transaction_id)
   return parseHexStr(toHex(transaction_id) & toHex(0u16) & toHex(uint16(len(mb_packet)))) & mb_packet
 
+proc reconnect() {.async.} =
+  echo "verbindung putt, ich fix das mal"
+  await sleepAsync(5000)
+  echo "jetzt"
+  sock = await asyncnet.dial(server.config.modbusAddr, Port(server.config.modbusPort))
+
 proc readPacket_mbTcp(): Future[(uint16, string)] {.async.} =
   var res = ""
 
   res = await sock.recv(8)
   while res == "":
-	  echo "verbindung putt, ich fix das mal"
-    sock = await asyncnet.dial(server.config.modbusAddr, Port(server.config.modbusPort))
+    await reconnect()
+    res = await sock.recv(8)
 
   let transaction_id = fromHex[uint16](toHex(res[0..1]))
   let length = fromHex[uint16](toHex(res[4..5]))

@@ -28,10 +34,9 @@ proc readPacket_mbTcp(): Future[(uint16, string)] {.async.} =
 
   res = await sock.recv(int(length) - 2)
   while res == "":
-	  echo "verbindung putt, ich fix das mal"
-    sock = await asyncnet.dial(server.config.modbusAddr, Port(server.config.modbusPort))
+    await reconnect()
+    res = await sock.recv(8)
 
-  echo toHex(res)
   if function_code >= 128u8:
     raise newException(OsError, "mordbus error: " & toHex(res))
 

@@ -52,20 +57,23 @@ proc doRequest[T](req: string, parse_proc: proc(foo: string): T): Future[T] =
   let tcp_packet = mkPacket_mbTcp(req)
   asyncCheck sock.send(tcp_packet)
   transactions[transaction_id] = proc(answer: string) =
-    transactions.del(transaction_id)
+    #transactions.del(transaction_id)
     fut.complete(parse_proc(answer))
 
   return fut
 
 proc retry[T](req: string, parse_proc: proc(foo: string): T): Future[T] {.async.} =
   var retries = 5
-  var result: T
+  var res: T
 
   while retries > 0:
-    retries = retries - 1
-    result = await doRequest(req, parse_proc)
-
-  return result
+    try:
+      res = await doRequest(req, parse_proc)
+      return res
+    except:
+      retries = retries - 1
+      let e = getCurrentException()
+      echo("error while processing mordbus answer: ", e.msg)
 
 ### readInputRegisters ###