Projet de remplacement du "RPiPasserelle" d'Otec.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

variable_value.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. params = self.__dict__.copy()
  35. params.update({'type': str(params['type'])})
  36. DB.sql(
  37. """INSERT INTO var_value
  38. (type, address, value)
  39. VALUES
  40. (:type, :address, :value)""",
  41. params
  42. )
  43. return True
  44. except Exception as e:
  45. print(e)
  46. return False
  47. def get_value(self):
  48. return self.type.cast()(self.value)
  49. def equals(self, var_value):
  50. return self.get_value() == var_value.get_value()
  51. def set(self):
  52. if self.type == 'D':
  53. write_coil(self)
  54. else:
  55. write_holding_register(self)
  56. return self.insert()
  57. @staticmethod
  58. def get(type, address, time=datetime.now()):
  59. try:
  60. row = next(DB.sql(
  61. """SELECT * FROM var_value
  62. WHERE
  63. type = :type
  64. AND address = :address
  65. AND time <= :time
  66. ORDER BY time DESC
  67. LIMIT 1""", {
  68. 'type':str(type), 'address':address, 'time':int(time.strftime('%s'))+1
  69. }))
  70. return VariableValue(**dict(row))
  71. except StopIteration as e:
  72. raise e