Browse Source

[routes] update routes

Maxime Alves LIRMM@home 3 years ago
parent
commit
30c1b66c41
6 changed files with 194 additions and 34 deletions
  1. 2
    1
      pyheatpump/db.py
  2. 9
    9
      pyheatpump/heatpump.py
  3. 62
    0
      pyheatpump/modbus.py
  4. 26
    23
      pyheatpump/modbus_get.py
  5. 86
    0
      pyheatpump/variable_values.py
  6. 9
    1
      pyheatpump/variables.py

+ 2
- 1
pyheatpump/db.py View File

@@ -3,6 +3,7 @@ import sqlite3
3 3
 from subprocess import Popen
4 4
 from .conf import config
5 5
 import sys
6
+from pprint import pprint
6 7
 
7 8
 conn = None
8 9
 
@@ -28,8 +29,8 @@ def sql(query):
28 29
     if conn is None:
29 30
         connect()
30 31
 
32
+    pprint(conn)
31 33
     cursor = conn.cursor()
32
-
33 34
     print(f'Will execute query : \n{query}\n')
34 35
     cursor.execute(query)
35 36
 

+ 9
- 9
pyheatpump/heatpump.py View File

@@ -5,19 +5,19 @@ from starlette.responses import JSONResponse
5 5
 from conf import config
6 6
 from db.db import sql
7 7
 
8
-def get_variables(request):
9
-    pass
8
+from pyheatpump.models import *
10 9
 
10
+def get_variable_values(request):
11
+    res = {}
12
+    for var_type_id, var_type in VariableType.getall():
13
+        res[var_type_id] = {}
14
+        for address, value in var_type.get_variables_values():
15
+            res[address] = value
11 16
 
12
-def get_variables_by_type(request):
13
-    pass
17
+    return JSONResponse(res)
14 18
 
15 19
 
16
-def get_var_type_addresses(request):
17
-    request.path_params['type'] 
18
-
19 20
 heatpump = [
20
-    Route('/', get_variables, methods=['GET']),
21
-    Route('/{type:str}', get_variables_by_type, methods=['GET'])
21
+    Route('/', get_all_variable_values, methods=['GET'])
22 22
 ]
23 23
 

+ 62
- 0
pyheatpump/modbus.py View File

@@ -0,0 +1,62 @@
1
+#!/usr/bin/env python3
2
+from serial import Serial
3
+from serial.serialutil import SerialException
4
+from umodbus.client.serial import rtu
5
+from pprint import pprint
6
+
7
+from pyheatpump.conf import config
8
+
9
+serial_conn = None
10
+
11
+def connect():
12
+    global serial_conn
13
+
14
+    if serial_conn is None:
15
+        print('Connecting to serial port *{}*'.format(
16
+            config.get('heatpump', 'serial_port')))
17
+        serial_conn = Serial(config.get('heatpump', 'serial_port'),
18
+            config.get('heatpump', 'baudrate'))
19
+
20
+    if serial_conn.open is False:
21
+        print('Opening serial port')
22
+        serial_conn.open()
23
+
24
+    return serial_conn
25
+
26
+def read_coils(start, end):
27
+    global serial_con
28
+    res = []
29
+
30
+    # digital - boolean
31
+    req_adu = rtu.read_coils(
32
+        slave_id=1,
33
+        starting_address=start,
34
+        quantity=end - start)
35
+
36
+    resp = rtu.send_message(req_adu, serial_conn)
37
+
38
+    return res
39
+
40
+
41
+def read_holding_registers(start, end):
42
+    global serial_conn
43
+    res = []
44
+
45
+
46
+    for address in range(start, end + 1, 125):
47
+        qty = 125 if (end - address) >= 125 else (end - address)
48
+        if not qty:
49
+            break
50
+        print(start, end, address, qty)
51
+        req_adu = rtu.read_coils(
52
+            slave_id=1,
53
+            starting_address=address,
54
+            quantity=qty)
55
+
56
+        resp = rtu.send_message(req_adu, serial_conn)
57
+        res.extend(resp)
58
+    return res
59
+
60
+if __name__ == '__main__':
61
+    connect()
62
+    read_holding_registers(1, 10)

+ 26
- 23
pyheatpump/modbus_get.py View File

@@ -1,4 +1,4 @@
1
-#!/usr/bin/env python
1
+#!/usr/bin/env python3
2 2
 # scripts/examples/simple_tcp_client.py
3 3
 import fcntl
4 4
 import sys
@@ -9,7 +9,9 @@ from serial.serialutil import SerialException
9 9
 from umodbus.client.serial import rtu
10 10
 import json
11 11
 
12
-from db.db import sql
12
+from pyheatpump.db import sql
13
+from pyheatpump.conf import config
14
+config.set('heatpump', 'database', '/home/emixam/src/otec/pyHeatpump/db/pyheatpump.db')
13 15
 
14 16
 s = Serial('/dev/ttyUSB0',19200)
15 17
 try:
@@ -27,8 +29,7 @@ def read_digital():
27 29
     global s
28 30
 
29 31
     start_address, end_address = sql(
30
-        f"SELECT start_address, end_address FROM var_type
31
-        WHERE slabel LIKE 'D';")
32
+        "SELECT start_address, end_address FROM var_type WHERE slabel LIKE 'D'")
32 33
 
33 34
     res = []
34 35
 
@@ -58,8 +59,11 @@ def read_analog():
58 59
     global s
59 60
 
60 61
     start_address, end_address = sql(
61
-        f"SELECT start_address, end_address FROM var_type
62
-        WHERE slabel LIKE 'A';")
62
+        """
63
+        SELECT start_address, end_address FROM var_type
64
+        WHERE slabel LIKE 'A';
65
+        """
66
+    )
63 67
 
64 68
     # analog - float
65 69
     for address in range(1, end_address - start_address, 125):
@@ -86,29 +90,28 @@ def read_int():
86 90
 
87 91
     res = []
88 92
 
89
-    start_address, end_address = sql(
90
-        f"SELECT start_address, end_address FROM var_type
91
-        WHERE slabel LIKE 'I';")
93
+    start_address, end_address = 1, 1000
94
+    #next(sql(
95
+    """
96
+        SELECT start_address, end_address FROM var_type
97
+        WHERE slabel LIKE 'I'
98
+    """
99
+    #))
92 100
 
93 101
     # integer - int
94
-    for address in range(1, end_address - start_address, 125):
95
-        req_adu = rtu.read_coils(
96
-            slave_id=1,
97
-            starting_address=start_address + address,
98
-            quantity=125)
99
-
100
-        resp = rtu.send_message(req_adu, s)
101
-
102
-        for n in range(125):
103
-            try:
104
-                res[address + n] = int(resp[n])
105
-            except KeyError as e:
106
-                print(e)
107
-                res[address + n] = 0
102
+    req_adu = rtu.read_holding_registers(
103
+        slave_id=1,
104
+        starting_address=start_address,
105
+        quantity=125)
106
+    resp = rtu.send_message(req_adu, s)
107
+    for r in resp:
108
+        print(r)
108 109
 
109 110
     return res
110 111
 
111 112
 
113
+read_int()
114
+
112 115
 s.close()
113 116
 
114 117
 sys.exit(0)

+ 86
- 0
pyheatpump/variable_values.py View File

@@ -0,0 +1,86 @@
1
+#!/usr/bin/env python3
2
+import os
3
+from datetime import datetime
4
+from configparser import ConfigParser
5
+from starlette.routing import Route, Router
6
+from starlette.responses import PlainTextResponse, JSONResponse
7
+from starlette.exceptions import HTTPException
8
+from pprint import pprint
9
+import uvicorn
10
+import json
11
+
12
+# pyHeatpump modules
13
+from pyheatpump.db import sql
14
+from pyheatpump.models.variable import Variable
15
+from pyheatpump.models.variable_type import VariableType
16
+from pyheatpump.models.variable_value import VariableValue
17
+
18
+
19
+async def get_variable_values(request):
20
+    return JSONResponse({})
21
+
22
+
23
+async def set_variable_values(request):
24
+    raise NotImplementedError
25
+
26
+
27
+async def get_variable_value(type: str, address: int, time: str=None):
28
+    try:
29
+        args = {
30
+            'type': type,
31
+            'address': address,
32
+            'time': time
33
+        }
34
+        if time is None:
35
+            args.pop('time')
36
+        else:
37
+            args['time'] = datetime.fromisoformat(time)
38
+
39
+        row = VariableValue.get(**args)
40
+
41
+        return PlainTextResponse(str(row.value))
42
+    except StopIteration:
43
+        raise HTTPException(404)
44
+
45
+
46
+async def set_variable_value(request):
47
+    raise NotImplementedError
48
+
49
+
50
+async def variable_values_routes(request, *args, **kwargs):
51
+    if request['method'] == 'GET':
52
+        return await get_variable_values(request)
53
+    elif request['method'] == 'POST':
54
+        return await set_variable_values(request)
55
+
56
+async def variable_value_routes(request, *args, **kwargs):
57
+    if request['method'] == 'GET':
58
+        if 'type' not in request.path_params.keys():
59
+            raise HTTPException(422)
60
+        if 'address' not in request.path_params.keys():
61
+            raise HTTPException(422)
62
+        if 'time' not in request.path_params.keys():
63
+            return await get_variable_value(
64
+                request.path_params['type'],
65
+                request.path_params['address'])
66
+        return await get_variable_value(
67
+            request.path_params['type'],
68
+            request.path_params['address'],
69
+            request.path_params['time'])
70
+
71
+    elif request['method'] == 'POST':
72
+        return await set_variable_value(request *args, **kwargs)
73
+
74
+
75
+ROUTES=[
76
+    Route('/', variable_values_routes, methods=['GET', 'POST']),
77
+    Route('/{type:str}/{address:int}', variable_value_routes, methods=['GET', 'POST']),
78
+    Route('/{type:str}/{address:int}/{time:str}', variable_value_routes, methods=['GET'])
79
+]
80
+
81
+app = Router(routes=ROUTES)
82
+
83
+if __name__ == '__main__':
84
+    uvicorn.run('pyHeatpump:conf.app',
85
+        host='127.0.0.1',
86
+        port=8000)

+ 9
- 1
pyheatpump/variables.py View File

@@ -14,7 +14,15 @@ from pyheatpump.models.variable import Variable
14 14
 
15 15
 
16 16
 async def get_variables(request):
17
-    return JSONResponse(Variable.getall())
17
+    return JSONResponse(dict([
18
+        (key, dict(
19
+            [
20
+                (add, var.__dict__)
21
+                for add, var in var_type.items()
22
+            ])
23
+        )
24
+        for key, var_type in Variable.getall().items()
25
+    ]))
18 26
 
19 27
 
20 28
 async def set_variables(request):

Loading…
Cancel
Save