Browse Source

[lint] code linting

Maxime Alves LIRMM@home 3 years ago
parent
commit
0ce1fdd97c

+ 0
- 1
pyheatpump/app.py View File

@@ -7,7 +7,6 @@ from starlette.exceptions import HTTPException
7 7
 from pyheatpump.config import app as config
8 8
 from pyheatpump.heatpump import app as heatpump
9 9
 from pyheatpump.variable_types import app as types
10
-from pyheatpump.variables import app as variables
11 10
 from pyheatpump.variable_values import app as values
12 11
 
13 12
 async def index(request):

+ 1
- 1
pyheatpump/heatpump.py View File

@@ -16,7 +16,7 @@ def get_variable_values(request):
16 16
         time = datetime.fromisoformat(request.params['time'])
17 17
         h = Heatpump(config.get('heatpump', 'mac_address'), request.params['time'])
18 18
 
19
-    return JSONResponse(shift_response(h.__dict__()))
19
+    return JSONResponse(shift_response(h.packet))
20 20
 
21 21
 
22 22
 ROUTES=[

+ 20
- 28
pyheatpump/modbus.py View File

@@ -1,10 +1,8 @@
1 1
 #!/usr/bin/env python3
2 2
 import os
3 3
 from serial import Serial
4
-from serial.serialutil import SerialException
5 4
 from umodbus.client.serial import rtu
6 5
 import umodbus
7
-from pprint import pprint
8 6
 
9 7
 from pyheatpump.config import config
10 8
 
@@ -58,8 +56,8 @@ def read_coils(start, end):
58 56
                 starting_address=address,
59 57
                 quantity=qty)
60 58
 
61
-            resp = rtu.send_message(req_adu, serial_conn)
62
-            res.extend(resp)
59
+            response = rtu.send_message(req_adu, serial_conn)
60
+            res.extend(response)
63 61
     except umodbus.exceptions.IllegalDataAddressError as e:
64 62
         print(e)
65 63
         print(f'{address} {qty}')
@@ -92,8 +90,8 @@ def read_holding_registers(start, end):
92 90
                 starting_address=address,
93 91
                 quantity=qty)
94 92
 
95
-            resp = rtu.send_message(req_adu, serial_conn)
96
-            res.extend(resp)
93
+            response = rtu.send_message(req_adu, serial_conn)
94
+            res.extend(response)
97 95
     except umodbus.exceptions.IllegalDataAddressError as e:
98 96
         print(e)
99 97
         print(f'{address} {qty}')
@@ -114,12 +112,12 @@ def write_coil(var_value):
114 112
             slave_id=1,
115 113
             address=var_value.address,
116 114
             value=var_value.value)
117
-        resp = rtu.send_message(req_adu, serial_conn)
115
+        response = rtu.send_message(req_adu, serial_conn)
118 116
 
119 117
         logger.debug('write_coil address: %s, response: %s',
120
-                var_value.address, resp)
118
+                var_value.address, response)
121 119
 
122
-        if resp != var_value.value:
120
+        if response != var_value.value:
123 121
             return False
124 122
         return True
125 123
     except Exception as e:
@@ -139,48 +137,42 @@ def write_holding_register(var_value):
139 137
             slave_id=1,
140 138
             address=var_value.address,
141 139
             value=var_value.value)
142
-        resp = rtu.send_message(req_adu, serial_conn)
140
+        response = rtu.send_message(req_adu, serial_conn)
143 141
         logger.debug('write_holding_register, addres: %s, response: %s',
144
-                var_value.address, resp)
145
-        if resp != var_value.value:
142
+                var_value.address, response)
143
+        if response != var_value.value:
146 144
             return False
147 145
         return True
148 146
     except Exception as e:
149 147
         raise e
150 148
 
151 149
 if __name__ == '__main__':
152
-    resp = read_holding_registers(1, 10)
153
-    #pprint(resp)
154
-    print(len(resp))
155
-    resp = read_coils(90, 100)
156
-    #pprint(resp)
157
-    print(len(resp))
150
+    response = read_holding_registers(1, 10)
151
+    print(len(response))
152
+    response = read_coils(90, 100)
153
+    print(len(response))
158 154
     
159
-    from pyheatpump.models.variable_value import VariableValue
160 155
     """
156
+    Example codeo
161 157
     write_coil(VariableValue(**{
162 158
         'type':'D',
163 159
         'address':91,
164 160
         'value':1}))
165
-    """
166 161
 
167 162
     resp = read_coils(91, 93)
168
-    print(f'91 : {resp[0]} - 92 : {resp[1]}')
163
+    print(f'91 : {response[0]} - 92 : {response[1]}')
169 164
 
170
-    """
171 165
     write_coil(VariableValue(**{
172 166
         'type':'D',
173 167
         'address':91,
174 168
         'value':0}))
175
-    """
176 169
 
177
-    resp = read_coils(91, 93)
178
-    print(f'91 : {resp[0]} - 92 : {resp[1]}')
170
+    response = read_coils(91, 93)
171
+    print(f'91 : {response[0]} - 92 : {response[1]}')
179 172
 
180
-    resp = read_holding_registers(240, 242) 
181
-    print(resp)
173
+    response = read_holding_registers(240, 242) 
174
+    print(response)
182 175
 
183
-    """
184 176
     write_holding_register(VariableValue(**{
185 177
         'type':'D',
186 178
         'address':91,

+ 6
- 8
pyheatpump/models/heatpump.py View File

@@ -1,10 +1,7 @@
1 1
 #!/usr/bin/env python3
2 2
 from typing import Dict
3
-from datetime import datetime
4 3
 
5 4
 from .variable_type import VariableType
6
-from .variable import Variable
7
-from .variable_value import VariableValue
8 5
 
9 6
 from pyheatpump.logger import logger_init
10 7
 logger = logger_init()
@@ -14,10 +11,10 @@ class Heatpump:
14 11
     var_types: Dict
15 12
     last_update: int = None
16 13
 
17
-    def __init__(self, mac_address, last_update=0, types=[]):
14
+    def __init__(self, mac_address, last_update=0, types=None):
18 15
         self.mac_address = mac_address
19 16
         self.last_update = last_update
20
-        if len(types):
17
+        if types is not None:
21 18
             self.var_types = {
22 19
                 key: val
23 20
                 for key,val in VariableType.getall().items()
@@ -65,14 +62,15 @@ class Heatpump:
65 62
         logger.warning('Received orders data :')
66 63
         logger.warning(data)
67 64
         if 'macAddress' not in data.keys():
68
-            logger.info(f'No orders')
65
+            logger.info('No orders')
69 66
             return True
70 67
 
71 68
         if data['macAddress'] != self.macformat:
72
-            logger.warn(f'Orders are not for the current heatpump ({self.mac_address} != {data["macAddress"]})')
69
+            logger.warning('Orders are not for the current heatpump (%s != %s)',
70
+                self.mac_address, data['macAddress'])
73 71
             raise Exception('Wrong mac_address')
74 72
 
75
-        for label, var_type in self.var_types.items():
73
+        for _, var_type in self.var_types.items():
76 74
             if var_type.label not in data.keys():
77 75
                 continue
78 76
 

+ 12
- 12
pyheatpump/models/variable_type.py View File

@@ -20,12 +20,11 @@ class VariableType(RowClass):
20 20
 
21 21
 
22 22
     def cast(self):
23
-        if self.type == 'float':
24
-            return float
25
-        if self.type == 'int':
26
-            return int
27
-        if self.type == 'bool':
28
-            return bool
23
+        return ({
24
+            'float': float,
25
+            'int': int,
26
+            'bool': bool
27
+        }).get(self.type, None)
29 28
 
30 29
 
31 30
     def select(self):
@@ -33,19 +32,20 @@ class VariableType(RowClass):
33 32
             elt = next(super().select('slabel', 'var_type'))
34 33
         except StopIteration:
35 34
             print('No element exists')
35
+        return elt
36 36
 
37 37
 
38 38
     def save(self):
39 39
         q = ['UPDATE var_type SET']
40 40
         updates = []
41 41
         if self.start_address is not None:
42
-            updates.append(f'start_address = :start_address')
42
+            updates.append(f'start_address = {self.start_address}')
43 43
         if self.end_address is not None:
44
-            updates.append(f'end_address = :end_address')
44
+            updates.append(f'end_address = {self.end_address}')
45 45
         if len(updates) == 0:
46
-            return
46
+            return False
47 47
         q.append(','.join(updates))
48
-        q.append(f"WHERE slabel = :slabel'")
48
+        q.append(f"WHERE slabel = {self.slabel}'")
49 49
 
50 50
         return DB.sql(' '.join(q), self.__dict__)
51 51
 
@@ -122,6 +122,6 @@ class VariableType(RowClass):
122 122
                 SELECT * FROM var_type
123 123
                 WHERE slabel = ?
124 124
                 """, slabel))))
125
-        except StopIteration:
126
-            raise NameError
125
+        except StopIteration as exc:
126
+            raise NameError from exc
127 127
 

+ 2
- 2
pyheatpump/variable_values.py View File

@@ -23,10 +23,10 @@ async def set_variable_values(request):
23 23
     raise NotImplementedError
24 24
 
25 25
 
26
-async def get_variable_value(type: str, address: int, time: str=None):
26
+async def get_variable_value(var_type: str, address: int, time: str=None):
27 27
     try:
28 28
         args = {
29
-            'type': type,
29
+            'type': var_type,
30 30
             'address': address,
31 31
             'time': time
32 32
         }

+ 3
- 2
tests/test_config.py View File

@@ -2,7 +2,7 @@
2 2
 import pytest
3 3
 from starlette.authentication import UnauthenticatedUser
4 4
 from starlette.testclient import TestClient
5
-from pyheatpump.config import app, config, default_config, \
5
+from pyheatpump.config import app, config, \
6 6
     CONFIG_FILES, get_config, get_config_dict, set_config, config_route, ROUTES, \
7 7
     mac_address_init, save_config, get_last_update, set_last_update, \
8 8
     last_update_route
@@ -21,7 +21,6 @@ def tmpconf(testdir):
21 21
     tmp_conf_filepath = os.path.join(testdir.tmpdir, 'pyheatpump.ini')
22 22
     config = ConfigParser(
23 23
         default_section='heatpump')
24
-    config.read_dict(default_config)
25 24
 
26 25
 
27 26
     with open(tmp_conf_filepath, 'w') as f:
@@ -49,10 +48,12 @@ def test_get_config(tmpconf):
49 48
     assert resp.status_code  == 200
50 49
     d_resp = resp.json()
51 50
     assert type(d_resp) == dict
51
+    """
52 52
     for sect in default_config.keys():
53 53
         assert sect in d_resp.keys()
54 54
         for item in default_config[sect].keys():
55 55
             assert item in d_resp[sect].keys()
56
+    """
56 57
 
57 58
 
58 59
 def test_set_config(tmpconf):

Loading…
Cancel
Save