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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. @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. commit()
  116. logger.info('Successfully read all variables')
  117. @click.option('--since', is_flag=True)
  118. @cli.command()
  119. def supervise(since):
  120. logger = logger_init()
  121. from .config import config, mac_address_init
  122. mac_address = config.get('heatpump','mac_address')
  123. if mac_address == 'None':
  124. mac_address = mac_address_init()
  125. from .models.heatpump import Heatpump
  126. last_update = None
  127. if since:
  128. last_update = int(datetime.now().strftime('%s')) - config.getint('supervisor', 'interval')
  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. if base_url['scheme'] == 'https':
  137. certificate = config.get('supervisor', 'certificate')
  138. if not os.path.isfile(certificate):
  139. raise Exception(f'Certificate not found :{certificate}')
  140. print(certificate)
  141. else:
  142. certificate = None
  143. post_url = {
  144. **base_url,
  145. **{'path': config.get('supervisor', 'post_path')}
  146. }
  147. logger.info(build_url(post_url))
  148. data = h.__dict__()
  149. try:
  150. logger.debug(json.dumps(data))
  151. except Exception as e:
  152. print(e)
  153. sys.exit(1)
  154. post_resp = requests.post(
  155. url=build_url(post_url),
  156. json=data,
  157. verify=False
  158. )
  159. if post_resp.status_code == 200:
  160. logger.info('POST to supervisor succeeded')
  161. get_path = '/'.join((
  162. config.get('supervisor', 'get_path'),
  163. h.macformat
  164. ))
  165. get_url = {
  166. **base_url,
  167. **{'path': get_path}
  168. }
  169. get_resp = requests.get(
  170. url=build_url(get_url),
  171. verify=False
  172. )
  173. control_data = get_resp.json()
  174. if h.control(control_data):
  175. commit()
  176. logger.info('GET to supervisor succeded : updated values')
  177. else:
  178. logger.warn('Unable to set data from supervisor\n{}'.format(control_data))