Projet de remplacement du "RPiPasserelle" d'Otec.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. logger.debug(f'analog length : {len(res)}')
  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. logger.debug(f'integer length : {len(res)}')
  84. for r in range(len(res)):
  85. var = Variable(**{
  86. 'type': integer,
  87. 'address': r + integer.start_address})
  88. if not var.exists():
  89. logger.info('Insert variable {}:{}'.format(
  90. var.type, var.address))
  91. var.insert()
  92. val = VariableValue(**{
  93. 'type': var.type,
  94. 'address': var.address,
  95. 'value': res[r]})
  96. val.insert()
  97. # Digital - bool
  98. if 'Digital' in var_types.keys():
  99. digital = var_types['Digital']
  100. logger.info('Read digital variables in coils [{}, {}]'.format(
  101. digital.start_address, digital.end_address
  102. ))
  103. res = modbus.read_coils(digital.start_address, digital.end_address)
  104. logger.debug(f'digital length : {len(res)}')
  105. for r in range(len(res)):
  106. var = Variable(**{
  107. 'type': digital,
  108. 'address': r + digital.start_address})
  109. if not var.exists():
  110. logger.info('Insert variable {}:{}'.format(
  111. var.type, var.address))
  112. var.insert()
  113. val = VariableValue(**{
  114. 'type': var.type,
  115. 'address': var.address,
  116. 'value': res[r]})
  117. val.insert()
  118. logger.info('Successfully read all variables')
  119. @click.option('--since', is_flag=True)
  120. @cli.command()
  121. def supervise(since):
  122. logger = logger_init()
  123. from .config import config, mac_address_init, get_last_update, set_last_update
  124. mac_address = config.get('heatpump','mac_address')
  125. if not re.match('^(([0-9a-f]{2}):?){6}$', mac_address, re.I):
  126. mac_address = mac_address_init()
  127. from .models.heatpump import Heatpump
  128. if not since:
  129. last_update = 0
  130. else:
  131. last_update = get_last_update()
  132. h = Heatpump(mac_address, last_update)
  133. base_url = {
  134. 'scheme':config.get('supervisor', 'scheme'),
  135. 'hostname':config.get('supervisor', 'host'),
  136. 'port':config.getint('supervisor', 'port')
  137. }
  138. build_url = lambda d: '{scheme}://{hostname}:{port}{path}'.format(**d)
  139. """
  140. @TODO : Use a proper certificate
  141. if base_url['scheme'] == 'https':
  142. certificate = config.get('supervisor', 'certificate')
  143. if not os.path.isfile(certificate):
  144. raise Exception(f'Certificate not found :{certificate}')
  145. print(certificate)
  146. else:
  147. certificate = None
  148. """
  149. post_url = {
  150. **base_url,
  151. **{'path': config.get('supervisor', 'post_path')}
  152. }
  153. logger.info(build_url(post_url))
  154. data = h.__dict__()
  155. try:
  156. logger.debug(json.dumps(data))
  157. except Exception as e:
  158. print(e)
  159. sys.exit(1)
  160. logger.debug('Will send %s', data)
  161. post_resp = requests.post(
  162. url=build_url(post_url),
  163. json=data,
  164. verify=False
  165. )
  166. if post_resp.status_code == 200:
  167. logger.info('POST to supervisor succeeded')
  168. set_last_update(int(datetime.now().strftime('%s')))
  169. get_path = '/'.join((
  170. config.get('supervisor', 'get_path'),
  171. h.macformat
  172. ))
  173. get_url = {
  174. **base_url,
  175. **{'path': get_path}
  176. }
  177. get_resp = requests.get(
  178. url=build_url(get_url),
  179. verify=False
  180. )
  181. control_data = get_resp.json()
  182. if h.control(control_data):
  183. logger.info('GET to supervisor succeded : updated values')
  184. set_last_update(int(datetime.now().strftime('%s')))
  185. else:
  186. logger.warn('Unable to set data from supervisor\n{}'.format(control_data))