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.

cli.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env python3
  2. # builtins
  3. import click
  4. import uvicorn
  5. import os
  6. import sys
  7. import re
  8. import importlib
  9. from pprint import pprint
  10. import urllib
  11. import requests
  12. import json
  13. from datetime import datetime
  14. from pyheatpump.logger import logger_init
  15. from pyheatpump.models import *
  16. from pyheatpump.db import commit
  17. CONTEXT_SETTINGS={
  18. 'default_map':{'run': {}}
  19. }
  20. @click.group(invoke_without_command=True, context_settings=CONTEXT_SETTINGS)
  21. @click.option('--version', is_flag=True)
  22. @click.pass_context
  23. def cli(ctx, version):
  24. if version:
  25. from pyheatpump import version
  26. return click.echo(pyheatpump.version())
  27. @click.option('--host', default=None)
  28. @click.option('--port', default=None)
  29. @cli.command()
  30. def run(host, port):
  31. logger = logger_init()
  32. from .config import (API_HOST, API_PORT)
  33. if not host:
  34. host = API_HOST
  35. if not port:
  36. port = API_PORT
  37. log_level = 'info'
  38. click.echo('Launching PyHeatpump application')
  39. uvicorn.run('pyheatpump.app:application',
  40. host=host,
  41. port=int(port),
  42. log_level=log_level,
  43. reload=True)
  44. @cli.command()
  45. def fetch():
  46. logger = logger_init()
  47. from pyheatpump import modbus
  48. var_types = VariableType.getall()
  49. # Analog - float
  50. analog = var_types['Analog']
  51. logger.info('Read analog variables in registers [{}, {}]'.format(
  52. analog.start_address, analog.end_address
  53. ))
  54. res = modbus.read_holding_registers(analog.start_address, analog.end_address)
  55. for r in range(len(res)):
  56. var = Variable(**{
  57. 'type': analog,
  58. 'address': r + analog.start_address})
  59. if not var.exists():
  60. logger.info('Insert variable {}:{}'.format(
  61. var.type, var.address))
  62. var.insert()
  63. val = VariableValue(**{
  64. 'type': var.type,
  65. 'address': var.address,
  66. 'value': res[r]})
  67. val.insert()
  68. # Integer - int
  69. integer = var_types['Integer']
  70. logger.info('Read integer variables in registers [{}, {}]'.format(
  71. integer.start_address, integer.end_address
  72. ))
  73. res = modbus.read_holding_registers(integer.start_address, integer.end_address)
  74. for r in range(len(res)):
  75. var = Variable(**{
  76. 'type': integer,
  77. 'address': r + integer.start_address})
  78. if not var.exists():
  79. logger.info('Insert variable {}:{}'.format(
  80. var.type, var.address))
  81. var.insert()
  82. val = VariableValue(**{
  83. 'type': var.type,
  84. 'address': var.address,
  85. 'value': res[r]})
  86. val.insert()
  87. # Digital - bool
  88. digital = var_types['Digital']
  89. logger.info('Read digital variables in coils [{}, {}]'.format(
  90. digital.start_address, digital.end_address
  91. ))
  92. res = modbus.read_coils(digital.start_address, digital.end_address)
  93. for r in range(len(res)):
  94. var = Variable(**{
  95. 'type': digital,
  96. 'address': r + digital.start_address})
  97. if not var.exists():
  98. logger.info('Insert variable {}:{}'.format(
  99. var.type, var.address))
  100. var.insert()
  101. val = VariableValue(**{
  102. 'type': var.type,
  103. 'address': var.address,
  104. 'value': res[r]})
  105. val.insert()
  106. commit()
  107. logger.info('Successfully read all variables')
  108. @click.option('--since', is_flag=True)
  109. @cli.command()
  110. def supervise(since):
  111. logger = logger_init()
  112. from .config import config
  113. from .models.heatpump import Heatpump
  114. last_update = None
  115. if since:
  116. last_update = int(datetime.now().strftime('%s')) - config.getint('supervisor', 'interval')
  117. h = Heatpump(config.get('heatpump','mac_address'), last_update)
  118. base_url = {
  119. 'scheme':config.get('supervisor', 'scheme'),
  120. 'hostname':config.get('supervisor', 'host'),
  121. 'port':config.getint('supervisor', 'port')
  122. }
  123. build_url = lambda d: '{scheme}://{hostname}:{port}{path}'.format(**d)
  124. if base_url['scheme'] == 'https':
  125. certificate = config.get('supervisor', 'certificate')
  126. if not os.path.isfile(certificate):
  127. raise Exception(f'Certificate not found :{certificate}')
  128. print(certificate)
  129. else:
  130. certificate = None
  131. post_url = {
  132. **base_url,
  133. **{'path': config.get('supervisor', 'post_path')}
  134. }
  135. logger.info(build_url(post_url))
  136. try:
  137. json.dumps(h.__dict__())
  138. except Exception as e:
  139. print(e)
  140. sys.exit(1)
  141. logger.debug(h.__dict__())
  142. post_req = requests.post(
  143. url=build_url(post_url),
  144. json=h.__dict__(),
  145. verify=False
  146. )
  147. if post_req.status_code == 200:
  148. logger.info('POST to supervisor succeeded')
  149. get_path = '/'.join((
  150. config.get('supervisor', 'get_path'),
  151. h.macformat
  152. ))
  153. get_url = {
  154. **base_url,
  155. **{'path': get_path}
  156. }
  157. get_req = requests.get(
  158. url=build_url(get_url),
  159. verify=False
  160. )