Projet de remplacement du "RPiPasserelle" d'Otec.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

cli.py 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. CONTEXT_SETTINGS={
  17. 'default_map':{'run': {}}
  18. }
  19. @click.group(invoke_without_command=True, context_settings=CONTEXT_SETTINGS)
  20. @click.option('--version', is_flag=True)
  21. @click.pass_context
  22. def cli(ctx, version):
  23. if version:
  24. from pyheatpump import version
  25. return click.echo(pyheatpump.version())
  26. @click.option('--host', default=None)
  27. @click.option('--port', default=None)
  28. @cli.command()
  29. def run(host, port):
  30. logger = logger_init()
  31. from .config import (API_HOST, API_PORT)
  32. if not host:
  33. host = API_HOST
  34. if not port:
  35. port = API_PORT
  36. log_level = 'info'
  37. click.echo('Launching PyHeatpump application')
  38. uvicorn.run('pyheatpump.app:application',
  39. host=host,
  40. port=int(port),
  41. log_level=log_level,
  42. workers=1)
  43. @click.option('--type', '-t', default=None, multiple=True)
  44. @cli.command()
  45. def fetch(type):
  46. logger = logger_init()
  47. from pyheatpump import modbus
  48. if type is None:
  49. var_types = VariableType.getall()
  50. else:
  51. var_types = {}
  52. for label, var_type in VariableType.getall().items():
  53. if label in type or var_type.slabel in type:
  54. var_types[label] = var_type
  55. # Analog - float
  56. if 'Analog' in var_types.keys():
  57. analog = var_types['Analog']
  58. logger.info('Read analog variables in registers [{}, {}]'.format(
  59. analog.start_address, analog.end_address
  60. ))
  61. res = modbus.read_holding_registers(analog.start_address, analog.end_address)
  62. for r in range(len(res)):
  63. var = Variable(**{
  64. 'type': analog,
  65. 'address': r + analog.start_address})
  66. if not var.exists():
  67. logger.info('Insert variable {}:{}'.format(
  68. var.type, var.address))
  69. var.insert()
  70. val = VariableValue(**{
  71. 'type': var.type,
  72. 'address': var.address,
  73. 'value': res[r]})
  74. val.insert()
  75. # Integer - int
  76. if 'Integer' in var_types.keys():
  77. integer = var_types['Integer']
  78. logger.info('Read integer variables in registers [{}, {}]'.format(
  79. integer.start_address, integer.end_address
  80. ))
  81. res = modbus.read_holding_registers(integer.start_address, integer.end_address)
  82. for r in range(len(res)):
  83. var = Variable(**{
  84. 'type': integer,
  85. 'address': r + integer.start_address})
  86. if not var.exists():
  87. logger.info('Insert variable {}:{}'.format(
  88. var.type, var.address))
  89. var.insert()
  90. val = VariableValue(**{
  91. 'type': var.type,
  92. 'address': var.address,
  93. 'value': res[r]})
  94. val.insert()
  95. # Digital - bool
  96. if 'Digital' in var_types.keys():
  97. digital = var_types['Digital']
  98. logger.info('Read digital variables in coils [{}, {}]'.format(
  99. digital.start_address, digital.end_address
  100. ))
  101. res = modbus.read_coils(digital.start_address, digital.end_address)
  102. for r in range(len(res)):
  103. var = Variable(**{
  104. 'type': digital,
  105. 'address': r + digital.start_address})
  106. if not var.exists():
  107. logger.info('Insert variable {}:{}'.format(
  108. var.type, var.address))
  109. var.insert()
  110. val = VariableValue(**{
  111. 'type': var.type,
  112. 'address': var.address,
  113. 'value': res[r]})
  114. val.insert()
  115. logger.info('Successfully read all variables')
  116. @click.option('--since', is_flag=True)
  117. @cli.command()
  118. def supervise(since):
  119. logger = logger_init()
  120. from .config import config, mac_address_init, get_last_update, set_last_update
  121. mac_address = config.get('heatpump','mac_address')
  122. if mac_address == 'None':
  123. mac_address = mac_address_init()
  124. from .models.heatpump import Heatpump
  125. if not since:
  126. last_update = 0
  127. else:
  128. last_update = get_last_update()
  129. h = Heatpump(mac_address, last_update)
  130. base_url = {
  131. 'scheme':config.get('supervisor', 'scheme'),
  132. 'hostname':config.get('supervisor', 'host'),
  133. 'port':config.getint('supervisor', 'port')
  134. }
  135. build_url = lambda d: '{scheme}://{hostname}:{port}{path}'.format(**d)
  136. """
  137. @TODO : Use a proper certificate
  138. if base_url['scheme'] == 'https':
  139. certificate = config.get('supervisor', 'certificate')
  140. if not os.path.isfile(certificate):
  141. raise Exception(f'Certificate not found :{certificate}')
  142. print(certificate)
  143. else:
  144. certificate = None
  145. """
  146. post_url = {
  147. **base_url,
  148. **{'path': config.get('supervisor', 'post_path')}
  149. }
  150. logger.info(build_url(post_url))
  151. data = h.__dict__()
  152. try:
  153. logger.debug(json.dumps(data))
  154. except Exception as e:
  155. print(e)
  156. sys.exit(1)
  157. post_resp = requests.post(
  158. url=build_url(post_url),
  159. json=data,
  160. verify=False
  161. )
  162. if post_resp.status_code == 200:
  163. logger.info('POST to supervisor succeeded')
  164. set_last_update(int(datetime.now().strftime('%s')))
  165. get_path = '/'.join((
  166. config.get('supervisor', 'get_path'),
  167. h.macformat
  168. ))
  169. get_url = {
  170. **base_url,
  171. **{'path': get_path}
  172. }
  173. get_resp = requests.get(
  174. url=build_url(get_url),
  175. verify=False
  176. )
  177. control_data = get_resp.json()
  178. if h.control(control_data):
  179. logger.info('GET to supervisor succeded : updated values')
  180. set_last_update(int(datetime.now().strftime('%s')))
  181. else:
  182. logger.warn('Unable to set data from supervisor\n{}'.format(control_data))