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 6.1KB

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