ctucx.git: smartied

[nimlang] smarthome server

commit 5f16dddda552f8b79c9488385ef82e553059164f
parent d4b070d3e7085e9124f233743727dceed6c9f39f
Author: Milan Pässler <me@pbb.lc>
Date: Fri, 13 Sep 2019 06:47:44 +0200

mordbus error handling
1 file changed, 24 insertions(+), 10 deletions(-)
M
src/modbus.nim
|
34
++++++++++++++++++++++++----------
diff --git a/src/modbus.nim b/src/modbus.nim
@@ -17,23 +17,33 @@ proc mkPacket_mbTcp(mb_packet: string): string =
 proc readPacket_mbTcp(): Future[(uint16, string)] {.async.} =
   var res = ""
 
-  res = await sock.recv(6)
+  res = await sock.recv(8)
   if res == "":
     raise newException(OsError, "verbindung putt")
 
   let transaction_id = fromHex[uint16](toHex(res[0..1]))
   let length = fromHex[uint16](toHex(res[4..5]))
+  let function_code = cast[uint8](res[7])
 
-  res = await sock.recv(int(length))
+  res = await sock.recv(int(length) - 2)
   if res == "":
     raise newException(OsError, "verbindung putt")
 
+
+  echo toHex(res)
+  if function_code >= 128u8:
+    raise newException(OsError, "mordbus error: " & toHex(res))
+
   return (transaction_id, res)
 
 proc processAnswers() {.async.} =
   while true:
-    let (transaction_id, mb_packet) = await readPacket_mbTcp()
-    transactions[transaction_id](mb_packet)
+    try:
+      let (transaction_id, mb_packet) = await readPacket_mbTcp()
+      transactions[transaction_id](mb_packet)
+    except:
+      let e = getCurrentException()
+      echo("error while processing mordbus answer: ", e.msg)
 
 proc doRequest[T](req: string, parse_proc: proc(foo: string): T): Future[T] =
   var fut = newFuture[T]()

@@ -52,9 +62,11 @@ proc mkPacket_readInputRegisters(unit_id: uint8, address: uint16, count: uint16)
 
 proc parsePacket_readInputRegisters(packet: string): seq[uint16] =
   var res: seq[uint16] = @[]
-  let count = fromHex[int](toHex(packet[2..2])) / 2
-  for i in int(1)..int(count):
-    res.add(fromHex[uint16](toHex(packet[2*i+1..2*i+2])))
+  let bytes = cast[uint8](packet[0])
+  var i = 1
+  while i < int(bytes):
+    res.add(fromHex[uint16](toHex(packet[i..i+1])))
+    i += 2
   return res
 
 proc readInputRegisters*(unit_id: uint8, address: uint16, count: uint16): Future[seq[uint16]] {.async.} =

@@ -67,9 +79,11 @@ proc mkPacket_readRegisters(unit_id: uint8, address: uint16, count: uint16): str
 
 proc parsePacket_readRegisters(packet: string): seq[uint16] =
   var res: seq[uint16] = @[]
-  let count = fromHex[int](toHex(packet[2..2])) / 2
-  for i in int(1)..int(count):
-    res.add(fromHex[uint16](toHex(packet[2*i+1..2*i+2])))
+  let bytes = cast[uint8](packet[0])
+  var i = 1
+  while i < int(bytes):
+    res.add(fromHex[uint16](toHex(packet[i..i+1])))
+    i += 2
   return res
 
 proc readRegisters*(unit_id: uint8, address: uint16, count: uint16): Future[seq[uint16]] {.async.} =