123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #!/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'
- }
- }
-
- CONFIG_FILES=[
- './pyheatpump.ini',
- '/etc/pyheatpump.ini']
-
- config = ConfigParser(
- default_section='heatpump')
- config.read_dict(default_config)
- config.read(filenames=CONFIG_FILES)
-
- 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)
|