Browse Source

test code that works for checking cable

Maxime Alves LIRMM@home 3 years ago
parent
commit
7cc18bccf8
1 changed files with 80 additions and 0 deletions
  1. 80
    0
      modbus_get.py

+ 80
- 0
modbus_get.py View File

@@ -0,0 +1,80 @@
1
+#!/usr/bin/env python
2
+# scripts/examples/simple_tcp_client.py
3
+import fcntl
4
+import sys
5
+import socket
6
+import struct
7
+from serial import Serial
8
+from serial.serialutil import SerialException
9
+from umodbus.client.serial import rtu
10
+import json
11
+
12
+s = Serial('/dev/ttyUSB0',19200)
13
+try:
14
+    s.open()
15
+except SerialException:
16
+    print('already open')
17
+
18
+BOOLEAN=1000
19
+FLOAT=500
20
+INT=1250
21
+try:
22
+    res = {'A':{},'D':{},'I':{}}
23
+
24
+    # digital - boolean
25
+    req_adu = rtu.read_coils(
26
+        slave_id=1,
27
+        starting_address=1,
28
+        quantity=1)
29
+
30
+    resp = rtu.send_message(req_adu, s)
31
+
32
+    address = -1
33
+    try:
34
+        for address in range(0, BOOLEAN, 1):
35
+            res['D'][address+1] = (resp[address] > 0)
36
+    except KeyError as e:
37
+        print(e)
38
+        res['D'][address] = False
39
+    except IndexError:
40
+        print(address)
41
+
42
+    # analog - float
43
+    for address in range(0, FLOAT, 125):
44
+        req_adu = rtu.read_holding_registers(
45
+            slave_id=1,
46
+            starting_address=1+address,
47
+            quantity=125)
48
+
49
+        resp = rtu.send_message(req_adu, s)
50
+
51
+        for n in range(125):
52
+            try:
53
+                res['A'][address + n] =  int(resp[n]) / 10
54
+            except Exception as e:
55
+                print(e)
56
+                res['A'][address + n] = 0.
57
+            #res['A'][ str(address + var) ] = int(resp[var]) / 10.
58
+
59
+    # integer - int
60
+    for address in range(1, INT, 125):
61
+        req_adu = rtu.read_coils(
62
+            slave_id=1,
63
+            starting_address=address+5002,
64
+            quantity=125)
65
+
66
+        resp = rtu.send_message(req_adu, s)
67
+
68
+        for n in range(125):
69
+            try:
70
+                res['I'][address + n] = int(resp[n])
71
+            except KeyError as e:
72
+                print(e)
73
+                res['I'][address + n] = 0
74
+except KeyboardInterrupt:
75
+    print("Quitting")
76
+    pass
77
+
78
+s.close()
79
+
80
+sys.exit(0)

Loading…
Cancel
Save