Projet de remplacement du "RPiPasserelle" d'Otec.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python3
  2. import os
  3. from datetime import datetime
  4. from configparser import ConfigParser
  5. from starlette.routing import Route, Router
  6. from starlette.responses import PlainTextResponse, JSONResponse
  7. from pprint import pprint
  8. import uvicorn
  9. import json
  10. default_config = {
  11. 'heatpump': {
  12. 'serial_port': '/dev/ttyUSB0',
  13. 'baudrate': 19200,
  14. 'mac_address': '00:00:00:00:00:00',
  15. 'ip_address': 'dhcp',
  16. 'read_only': 'False',
  17. 'database': '/var/run/pyheatpump/pyheatpump.sqlite3'
  18. },
  19. 'supervisor': {
  20. 'scheme': 'http',
  21. 'host': '127.0.0.1:8000',
  22. 'get_path': '/',
  23. 'post_path': '/',
  24. 'interval': 10000,
  25. 'auth': 'None',
  26. 'initialization': str(datetime.now()),
  27. 'heatpump_id': 'None'
  28. },
  29. 'api': {
  30. 'host': '127.0.0.1',
  31. 'port': 80
  32. }
  33. }
  34. CONFIG_FILES=[
  35. './pyheatpump.ini',
  36. '/etc/pyheatpump.ini']
  37. config = ConfigParser(
  38. default_section='heatpump')
  39. config.read_dict(default_config)
  40. config.read(filenames=CONFIG_FILES)
  41. API_HOST=config.get('api', 'host')
  42. API_PORT=config.get('api', 'port')
  43. async def get_config(request):
  44. items = dict([ (
  45. section, dict([ (key, config.get(section, key)) for key in items ])
  46. ) for section, items in config.items() ])
  47. return JSONResponse(items)
  48. async def set_config(request):
  49. body = json.loads(await request.json())
  50. for sect in body.keys():
  51. for item in body[sect].keys():
  52. if not config.has_option(sect, item):
  53. raise HTTPException(404, f'The option {sect}.{item} does not exists')
  54. else:
  55. config.set(sect, item, value=body[sect][item])
  56. with open(CONFIG_FILES[0], 'w') as conf_file:
  57. config.write(conf_file)
  58. return PlainTextResponse('OK')
  59. async def config_route(request, *args, **kwargs):
  60. if request['method'] == 'GET':
  61. return await get_config(request)
  62. elif request['method'] == 'POST':
  63. return await set_config(request)
  64. ROUTES=[
  65. Route('/', config_route, methods=['GET', 'POST'])
  66. ]
  67. app = Router(routes=ROUTES)
  68. if __name__ == '__main__':
  69. uvicorn.run('pyHeatpump:conf.app',
  70. host='127.0.0.1',
  71. port=8000)