Browse Source

[clean] cleaned logs and old code

Maxime Alves LIRMM@home 3 years ago
parent
commit
bbf2baae2d

+ 0
- 12
pyheatpump/cli.py View File

10
 import time
10
 import time
11
 import urllib
11
 import urllib
12
 import uvicorn
12
 import uvicorn
13
-from pprint import pprint
14
 import requests
13
 import requests
15
 
14
 
16
 from pyheatpump.logger import logger_init
15
 from pyheatpump.logger import logger_init
189
 
188
 
190
     build_url = lambda d: '{scheme}://{hostname}:{port}{path}'.format(**d)
189
     build_url = lambda d: '{scheme}://{hostname}:{port}{path}'.format(**d)
191
 
190
 
192
-    """
193
-    @TODO : Use a proper certificate 
194
-
195
-    if base_url['scheme'] == 'https':
196
-        certificate = config.get('supervisor', 'certificate')
197
-        if not os.path.isfile(certificate):
198
-            raise Exception(f'Certificate not found :{certificate}') 
199
-        print(certificate)
200
-    else:
201
-        certificate = None
202
-    """
203
 
191
 
204
     post_url = {
192
     post_url = {
205
         **base_url,
193
         **base_url,

+ 5
- 6
pyheatpump/config.py View File

8
 from starlette.routing import Route, Router
8
 from starlette.routing import Route, Router
9
 from starlette.responses import PlainTextResponse, JSONResponse
9
 from starlette.responses import PlainTextResponse, JSONResponse
10
 from starlette.exceptions import HTTPException
10
 from starlette.exceptions import HTTPException
11
-from pprint import pprint
12
 import uvicorn
11
 import uvicorn
13
 import json
12
 import json
14
 
13
 
67
 
66
 
68
     interface = gateways()['default'][AF_INET][1]
67
     interface = gateways()['default'][AF_INET][1]
69
     if len(ifaddresses(interface)) == 0:
68
     if len(ifaddresses(interface)) == 0:
70
-        logger.error("Can't find interface")
69
+        logger.error("Can't find interface %s", interface)
71
         sys.exit(1)
70
         sys.exit(1)
72
 
71
 
73
     if len(ifaddresses(interface)[AF_LINK]) == 0:
72
     if len(ifaddresses(interface)[AF_LINK]) == 0:
74
-        logger.error("Can't find interface")
73
+        logger.error("Can't find interface %s", interface)
75
         sys.exit(1)
74
         sys.exit(1)
76
 
75
 
77
     addr = ifaddresses(interface)[AF_LINK][0]['addr']
76
     addr = ifaddresses(interface)[AF_LINK][0]['addr']
140
             config.set('heatpump','mac_address',mac_address)
139
             config.set('heatpump','mac_address',mac_address)
141
             save_config()
140
             save_config()
142
         else:
141
         else:
143
-            print(f'Wrong mac format : {mac_address}')
142
+            logger.error(f'Wrong mac format : {mac_address}')
144
 
143
 
145
         return PlainTextResponse(' '.join((
144
         return PlainTextResponse(' '.join((
146
             'Current ->',
145
             'Current ->',
172
         body = await request.body()
171
         body = await request.body()
173
         last_update = int(body.decode() or 0)
172
         last_update = int(body.decode() or 0)
174
         if last_update == 0:
173
         if last_update == 0:
175
-            print(f'Reset last update to current time')
176
             last_update = int(datetime.now().strftime('%s'))
174
             last_update = int(datetime.now().strftime('%s'))
175
+            logger.info('Reset last update to current time (%s)', last_update)
177
         else:
176
         else:
178
-            print(f'{"Forward" if last_update < 0 else "Rewind"} of {last_update} seconds')
177
+            logger.debug('%s of %s seconds', ("Forward" if last_update < 0 else "Rewind"), last_update)
179
             last_update = int(datetime.now().strftime('%s')) - last_update
178
             last_update = int(datetime.now().strftime('%s')) - last_update
180
 
179
 
181
 
180
 

+ 4
- 5
pyheatpump/db.py View File

3
 from subprocess import Popen
3
 from subprocess import Popen
4
 from .config import config
4
 from .config import config
5
 import sys
5
 import sys
6
-from pprint import pprint
7
 
6
 
8
 from pyheatpump.logger import logger_init
7
 from pyheatpump.logger import logger_init
9
 logger = logger_init()
8
 logger = logger_init()
22
             except sqlite3.ProgrammingError:
21
             except sqlite3.ProgrammingError:
23
                 pass
22
                 pass
24
             except Exception as e:
23
             except Exception as e:
25
-                print(e)
24
+                logger.error('DB.connect: %s', e)
26
                 sys.exit(1)
25
                 sys.exit(1)
27
 
26
 
28
         logger.info('Will connect to database {}'.format(
27
         logger.info('Will connect to database {}'.format(
71
 
70
 
72
             try:
71
             try:
73
                 return DB.Conn.execute((' '.join(f.readlines())).replace('\n', ''))
72
                 return DB.Conn.execute((' '.join(f.readlines())).replace('\n', ''))
74
-            except StopIteration:
75
-                print('failed')
73
+            except StopIteration as e:
74
+                logger.error('sqlf(%s): %s', filename, e)
76
                 return []
75
                 return []
77
             except sqlite3.IntegrityError as e:
76
             except sqlite3.IntegrityError as e:
78
-                print(e)
77
+                logger.error('sqlf(%s): %s', filename, e)
79
                 return []
78
                 return []
80
             except sqlite3.OperationalError as e:
79
             except sqlite3.OperationalError as e:
81
                 raise Exception(f'Can\'t find DB file {filename}') from e
80
                 raise Exception(f'Can\'t find DB file {filename}') from e

+ 7
- 40
pyheatpump/modbus.py View File

18
         real_serial_port = os.path.realpath(
18
         real_serial_port = os.path.realpath(
19
             config.get('heatpump', 'serial_port'))
19
             config.get('heatpump', 'serial_port'))
20
 
20
 
21
-        print('Connecting to serial port *{}* ({})'.format(
21
+        logger.info('Connecting to serial port *%s* (%s)',
22
             config.get('heatpump', 'serial_port'),
22
             config.get('heatpump', 'serial_port'),
23
-            real_serial_port))
23
+            real_serial_port)
24
 
24
 
25
         serial_conn = Serial(
25
         serial_conn = Serial(
26
             port=real_serial_port,
26
             port=real_serial_port,
31
             timeout=20)
31
             timeout=20)
32
 
32
 
33
     if serial_conn.open is False:
33
     if serial_conn.open is False:
34
-        print('Opening serial port')
34
+        logger.debug('Opening serial port *%s*', config.get('heatpump', 'serial_port')
35
         serial_conn.open()
35
         serial_conn.open()
36
 
36
 
37
     return serial_conn
37
     return serial_conn
59
             response = rtu.send_message(req_adu, serial_conn)
59
             response = rtu.send_message(req_adu, serial_conn)
60
             res.extend(response)
60
             res.extend(response)
61
     except umodbus.exceptions.IllegalDataAddressError as e:
61
     except umodbus.exceptions.IllegalDataAddressError as e:
62
-        print(e)
63
-        print(f'{address} {qty}')
62
+        logger.error(e)
63
+        logger.debug('address:%s qty:%s', address, qty)
64
 
64
 
65
     logger.debug('read_coils [%s, %s] result: %s', start, end, res)
65
     logger.debug('read_coils [%s, %s] result: %s', start, end, res)
66
     return res
66
     return res
93
             response = rtu.send_message(req_adu, serial_conn)
93
             response = rtu.send_message(req_adu, serial_conn)
94
             res.extend(response)
94
             res.extend(response)
95
     except umodbus.exceptions.IllegalDataAddressError as e:
95
     except umodbus.exceptions.IllegalDataAddressError as e:
96
-        print(e)
97
-        print(f'{address} {qty}')
96
+        logger.error('read_holding_registers(%s, %s): address:%s, qty:%s\n%s',
97
+            start, end, address, qty, e)
98
 
98
 
99
     logger.debug('read_holding_registers [%s, %s] result: %s', start, end, res)
99
     logger.debug('read_holding_registers [%s, %s] result: %s', start, end, res)
100
     return res
100
     return res
145
         return True
145
         return True
146
     except Exception as e:
146
     except Exception as e:
147
         raise e
147
         raise e
148
-
149
-if __name__ == '__main__':
150
-    response = read_holding_registers(1, 10)
151
-    print(len(response))
152
-    response = read_coils(90, 100)
153
-    print(len(response))
154
-    
155
-    """
156
-    Example codeo
157
-    write_coil(VariableValue(**{
158
-        'type':'D',
159
-        'address':91,
160
-        'value':1}))
161
-
162
-    resp = read_coils(91, 93)
163
-    print(f'91 : {response[0]} - 92 : {response[1]}')
164
-
165
-    write_coil(VariableValue(**{
166
-        'type':'D',
167
-        'address':91,
168
-        'value':0}))
169
-
170
-    response = read_coils(91, 93)
171
-    print(f'91 : {response[0]} - 92 : {response[1]}')
172
-
173
-    response = read_holding_registers(240, 242) 
174
-    print(response)
175
-
176
-    write_holding_register(VariableValue(**{
177
-        'type':'D',
178
-        'address':91,
179
-        'value':1})
180
-    """

+ 1
- 1
pyheatpump/models/variable.py View File

37
             })
37
             })
38
             return True
38
             return True
39
         except Exception as e:
39
         except Exception as e:
40
-            print(e)
40
+            logger.error('Variable.insert: %s', e)
41
             return False
41
             return False
42
 
42
 
43
 
43
 

+ 3
- 1
pyheatpump/models/variable_type.py View File

1
 from pyheatpump.db import DB, RowClass
1
 from pyheatpump.db import DB, RowClass
2
 
2
 
3
+from pyheatpump.logger import logger_init
4
+logger = logger_init()
3
 
5
 
4
 class VariableType(RowClass):
6
 class VariableType(RowClass):
5
     slabel: str = '' 
7
     slabel: str = '' 
39
         try:
41
         try:
40
             elt = next(super().select('slabel', 'var_type'))
42
             elt = next(super().select('slabel', 'var_type'))
41
         except StopIteration:
43
         except StopIteration:
42
-            print('No element exists')
44
+            logger.error('VariableType.select(%s, %s): does not exist')
43
         return elt
45
         return elt
44
 
46
 
45
 
47
 

+ 1
- 2
pyheatpump/models/variable_value.py View File

46
             )
46
             )
47
             return True
47
             return True
48
         except Exception as e:
48
         except Exception as e:
49
-            print(e)
49
+            logger.error('VariableValue.insert: %s', e)
50
             return False
50
             return False
51
 
51
 
52
 
52
 
67
     @staticmethod
67
     @staticmethod
68
     def get(var_type, address, time=datetime.now()):
68
     def get(var_type, address, time=datetime.now()):
69
         try:
69
         try:
70
-            print(int(time.strftime('%s'))+1)
71
             row = next(DB.sql(
70
             row = next(DB.sql(
72
             """SELECT * FROM var_value
71
             """SELECT * FROM var_value
73
             WHERE
72
             WHERE

+ 0
- 1
pyheatpump/variable_types.py View File

4
 from configparser import ConfigParser
4
 from configparser import ConfigParser
5
 from starlette.routing import Route, Router
5
 from starlette.routing import Route, Router
6
 from starlette.responses import PlainTextResponse, JSONResponse
6
 from starlette.responses import PlainTextResponse, JSONResponse
7
-from pprint import pprint
8
 import uvicorn
7
 import uvicorn
9
 import json
8
 import json
10
 
9
 

+ 0
- 2
pyheatpump/variable_values.py View File

5
 from starlette.routing import Route, Router
5
 from starlette.routing import Route, Router
6
 from starlette.responses import PlainTextResponse, JSONResponse
6
 from starlette.responses import PlainTextResponse, JSONResponse
7
 from starlette.exceptions import HTTPException
7
 from starlette.exceptions import HTTPException
8
-from pprint import pprint
9
 import uvicorn
8
 import uvicorn
10
 import json
9
 import json
11
 
10
 
30
             'address': address,
29
             'address': address,
31
             'time': time
30
             'time': time
32
         }
31
         }
33
-        print(args)
34
         if time is None:
32
         if time is None:
35
             args.pop('time')
33
             args.pop('time')
36
         else:
34
         else:

+ 0
- 1
pyheatpump/variables.py View File

4
 from configparser import ConfigParser
4
 from configparser import ConfigParser
5
 from starlette.routing import Route, Router
5
 from starlette.routing import Route, Router
6
 from starlette.responses import PlainTextResponse, JSONResponse
6
 from starlette.responses import PlainTextResponse, JSONResponse
7
-from pprint import pprint
8
 import uvicorn
7
 import uvicorn
9
 import json
8
 import json
10
 
9
 

Loading…
Cancel
Save