瀏覽代碼

[get][post] /config/mac

Maxime Alves LIRMM@home 3 年之前
父節點
當前提交
39d59badde
共有 2 個檔案被更改,包括 53 行新增12 行删除
  1. 1
    1
      pyheatpump/app.py
  2. 52
    11
      pyheatpump/config.py

+ 1
- 1
pyheatpump/app.py 查看文件

4
 from starlette.responses import HTMLResponse
4
 from starlette.responses import HTMLResponse
5
 from starlette.exceptions import HTTPException
5
 from starlette.exceptions import HTTPException
6
 
6
 
7
-from pyheatpump.config import config
7
+from pyheatpump.config import app as config
8
 from pyheatpump.heatpump import app as heatpump
8
 from pyheatpump.heatpump import app as heatpump
9
 from pyheatpump.variable_types import app as types
9
 from pyheatpump.variable_types import app as types
10
 from pyheatpump.variables import app as variables
10
 from pyheatpump.variables import app as variables

+ 52
- 11
pyheatpump/config.py 查看文件

1
 #!/usr/bin/env python3
1
 #!/usr/bin/env python3
2
 import os
2
 import os
3
+import re
3
 from datetime import datetime
4
 from datetime import datetime
4
 from configparser import ConfigParser
5
 from configparser import ConfigParser
5
 from starlette.routing import Route, Router
6
 from starlette.routing import Route, Router
39
 }
40
 }
40
 
41
 
41
 CONFIG_FILES=[
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
 config.read_dict(default_config)
47
 config.read_dict(default_config)
48
 config.read(filenames=CONFIG_FILES)
48
 config.read(filenames=CONFIG_FILES)
49
 
49
 
51
 API_PORT=config.get('api', 'port')
51
 API_PORT=config.get('api', 'port')
52
 
52
 
53
 def save_config():
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
         config.write(conf_file)
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
 def mac_address_init():
64
 def mac_address_init():
58
     from netifaces import gateways, ifaddresses, AF_INET, AF_LINK
65
     from netifaces import gateways, ifaddresses, AF_INET, AF_LINK
66
+    global config
67
+
59
     interface = gateways()['default'][AF_INET][1]
68
     interface = gateways()['default'][AF_INET][1]
60
     if len(ifaddresses(interface)) == 0:
69
     if len(ifaddresses(interface)) == 0:
61
         logger.error("Can't find interface")
70
         logger.error("Can't find interface")
71
 
80
 
72
     return addr
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
 async def get_config(request):
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
 async def set_config(request):
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
     for sect in body.keys():
98
     for sect in body.keys():
99
+        if type(body[sect]) is not dict:
100
+            continue
84
         for item in body[sect].keys():
101
         for item in body[sect].keys():
85
             if not config.has_option(sect, item):
102
             if not config.has_option(sect, item):
86
                 raise HTTPException(404, f'The option {sect}.{item} does not exists')
103
                 raise HTTPException(404, f'The option {sect}.{item} does not exists')
96
     elif request['method'] == 'POST':
113
     elif request['method'] == 'POST':
97
         return await set_config(request)
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
 ROUTES=[
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
 app = Router(routes=ROUTES)
144
 app = Router(routes=ROUTES)

Loading…
取消
儲存