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.

variable_value.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from pyheatpump.db import DB, RowClass
  2. from datetime import datetime
  3. from .variable_type import VariableType
  4. from pyheatpump.logger import logger_init
  5. from pyheatpump.modbus import write_coil, write_holding_register
  6. logger = logger_init()
  7. class VariableValue(RowClass):
  8. type: VariableType = None
  9. address: int = None
  10. time: datetime = None
  11. value: int = None
  12. def __init__(self, **kwargs):
  13. if 'type' in kwargs.keys() and not isinstance(kwargs['type'], VariableType):
  14. kwargs['type'] = VariableType.get(kwargs['type'])
  15. super().__init__(**kwargs)
  16. def insert(self):
  17. try:
  18. old_value = VariableValue.get(
  19. self.type,
  20. self.address)
  21. if old_value.value == self.value:
  22. # last variable value is equal to current value
  23. # so do not insert
  24. return False
  25. except StopIteration:
  26. # variable value was never inserted
  27. pass
  28. try:
  29. params = self.__dict__.copy()
  30. params.update({'type': str(params['type'])})
  31. DB.sql(
  32. """INSERT INTO var_value
  33. (type, address, value)
  34. VALUES
  35. (:type, :address, :value)""",
  36. params
  37. )
  38. return True
  39. except Exception as e:
  40. logger.error('VariableValue.insert: %s', e)
  41. return False
  42. def get_value(self):
  43. return self.type.cast()(self.value)
  44. def equals(self, var_value):
  45. return self.get_value() == var_value.get_value()
  46. def set(self):
  47. if self.type == 'D':
  48. write_coil(self)
  49. else:
  50. write_holding_register(self)
  51. return self.insert()
  52. @staticmethod
  53. def get(var_type, address, time=datetime.now()):
  54. try:
  55. row = next(DB.sql(
  56. """SELECT * FROM var_value
  57. WHERE
  58. type = :type
  59. AND address = :address
  60. AND time <= :time
  61. ORDER BY time DESC
  62. LIMIT 1""", {
  63. 'type':str(var_type), 'address':address, 'time':int(time.strftime('%s'))+1
  64. }))
  65. return VariableValue(**{ **dict(row), **{ 'type': var_type } })
  66. except StopIteration as e:
  67. raise e