Browse Source

[get][post] /config/mac

Maxime Alves LIRMM@home 3 years ago
parent
commit
39d59badde
2 changed files with 53 additions and 12 deletions
  1. 1
    1
      pyheatpump/app.py
  2. 52
    11
      pyheatpump/config.py

+ 1
- 1
pyheatpump/app.py View File

@@ -4,7 +4,7 @@ from starlette.routing import Router, Mount, Route
4 4
 from starlette.responses import HTMLResponse
5 5
 from starlette.exceptions import HTTPException
6 6
 
7
-from pyheatpump.config import config
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 10
 from pyheatpump.variables import app as variables

+ 52
- 11
pyheatpump/config.py View File

@@ -1,5 +1,6 @@
1 1
 #!/usr/bin/env python3
2 2
 import os
3
+import re
3 4
 from datetime import datetime
4 5
 from configparser import ConfigParser
5 6
 from starlette.routing import Route, Router
@@ -39,11 +40,10 @@ default_config = {
39 40
 }
40 41
 
41 42
 CONFIG_FILES=[
42
-    './pyheatpump.ini',
43
-    '/etc/pyheatpump.ini']
43
+    '/etc/pyheatpump.ini',
44
+    './pyheatpump.ini']
44 45
 
45
-config = ConfigParser(
46
-    default_section='heatpump')
46
+config = ConfigParser()#default_section='heatpump')
47 47
 config.read_dict(default_config)
48 48
 config.read(filenames=CONFIG_FILES)
49 49
 
@@ -51,11 +51,20 @@ API_HOST=config.get('api', 'host')
51 51
 API_PORT=config.get('api', 'port')
52 52
 
53 53
 def save_config():
54
-    with open(CONFIG_FILES[0], 'w') as conf_file:
54
+    print(get_config_dict())
55
+    with open(CONFIG_FILES[1], 'w') as conf_file:
55 56
         config.write(conf_file)
56 57
 
58
+
59
+def get_mac():
60
+    config.read(filenames=CONFIG_FILES)
61
+    return config.get('heatpump', 'mac_address')
62
+
63
+
57 64
 def mac_address_init():
58 65
     from netifaces import gateways, ifaddresses, AF_INET, AF_LINK
66
+    global config
67
+
59 68
     interface = gateways()['default'][AF_INET][1]
60 69
     if len(ifaddresses(interface)) == 0:
61 70
         logger.error("Can't find interface")
@@ -71,16 +80,24 @@ def mac_address_init():
71 80
 
72 81
     return addr
73 82
 
83
+
84
+def get_config_dict():
85
+    c = config
86
+    return dict([ (s, dict([ (i, j) for i, j in c.items(s) ]) ) for s in c.sections() ])
87
+
88
+
74 89
 async def get_config(request):
75
-    items = dict([ (
76
-        section, dict([ (key, config.get(section, key)) for key in items ])
77
-        ) for section, items in config.items() ])
78
-    return JSONResponse(items)
90
+    return JSONResponse(get_config_dict())
91
+
79 92
 
80 93
 async def set_config(request):
81
-    body = json.loads(await request.json())
94
+    global config
95
+    body = await request.json()
96
+    #return PlainTextResponse(body)
82 97
 
83 98
     for sect in body.keys():
99
+        if type(body[sect]) is not dict:
100
+            continue
84 101
         for item in body[sect].keys():
85 102
             if not config.has_option(sect, item):
86 103
                 raise HTTPException(404, f'The option {sect}.{item} does not exists')
@@ -96,8 +113,32 @@ async def config_route(request, *args, **kwargs):
96 113
     elif request['method'] == 'POST':
97 114
         return await set_config(request)
98 115
 
116
+
117
+async def mac_route(request, *args, **kwargs):
118
+    global config
119
+    if request['method'] == 'GET':
120
+        return PlainTextResponse(get_mac())
121
+    elif request['method'] == 'POST':
122
+        body = await request.body()
123
+        mac_address = body.decode()
124
+        if len(mac_address) == 0:
125
+            mac_address = mac_address_init()
126
+
127
+        elif re.match('^([0-9a-f]{2}:?){6}$',
128
+            mac_address, re.I) is not None:
129
+
130
+            config.set('heatpump','mac_address',mac_address)
131
+            save_config()
132
+
133
+        return PlainTextResponse(' '.join((
134
+            'Current ->',
135
+            get_mac(),
136
+            ', New -> ', mac_address)))
137
+
138
+
99 139
 ROUTES=[
100
-    Route('/', config_route, methods=['GET', 'POST'])
140
+    Route('/', config_route, methods=['GET', 'POST']),
141
+    Route('/mac', mac_route, methods=['GET', 'POST'])
101 142
 ]
102 143
 
103 144
 app = Router(routes=ROUTES)

Loading…
Cancel
Save