12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #!/usr/bin/env python3
- import os
- from datetime import datetime
- from configparser import ConfigParser
- from starlette.routing import Route, Router
- from starlette.responses import PlainTextResponse, JSONResponse
- from pprint import pprint
- import uvicorn
- import json
-
- default_config = {
- 'heatpump': {
- 'serial_port': '/dev/ttyUSB0',
- 'baudrate': 19200,
- 'mac_address': '00:00:00:00:00:00',
- 'ip_address': 'dhcp',
- 'read_only': 'False',
- 'database': '/var/run/pyheatpump/pyheatpump.sqlite3'
- },
- 'supervisor': {
- 'scheme': 'http',
- 'host': '127.0.0.1:8000',
- 'get_path': '/',
- 'post_path': '/',
- 'interval': 10000,
- 'auth': 'None',
- 'initialization': str(datetime.now()),
- 'heatpump_id': 'None'
- },
- 'api': {
- 'host': '127.0.0.1',
- 'port': 80
- }
- }
-
- CONFIG_FILES=[
- './pyheatpump.ini',
- '/etc/pyheatpump.ini']
-
- config = ConfigParser(
- default_section='heatpump')
- config.read_dict(default_config)
- config.read(filenames=CONFIG_FILES)
-
- API_HOST=config.get('api', 'host')
- API_PORT=config.get('api', 'port')
-
- async def get_config(request):
- items = dict([ (
- section, dict([ (key, config.get(section, key)) for key in items ])
- ) for section, items in config.items() ])
- return JSONResponse(items)
-
- async def set_config(request):
-
- body = json.loads(await request.json())
-
- for sect in body.keys():
- for item in body[sect].keys():
- if not config.has_option(sect, item):
- raise HTTPException(404, f'The option {sect}.{item} does not exists')
- else:
- config.set(sect, item, value=body[sect][item])
-
- with open(CONFIG_FILES[0], 'w') as conf_file:
- config.write(conf_file)
-
- return PlainTextResponse('OK')
-
- async def config_route(request, *args, **kwargs):
- if request['method'] == 'GET':
- return await get_config(request)
- elif request['method'] == 'POST':
- return await set_config(request)
-
- ROUTES=[
- Route('/', config_route, methods=['GET', 'POST'])
- ]
-
- app = Router(routes=ROUTES)
-
- if __name__ == '__main__':
- uvicorn.run('pyHeatpump:conf.app',
- host='127.0.0.1',
- port=8000)
|