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

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