Projet de remplacement du "RPiPasserelle" d'Otec.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

variable.py 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. from pyheatpump.db import RowClass
  2. from pyheatpump.db import DB
  3. from datetime import date
  4. from pyheatpump.modbus import rtu
  5. from .variable_type import VariableType
  6. from .variable_value import VariableValue
  7. class Variable(RowClass):
  8. address: int = None
  9. unit: str = None
  10. last_update: date = None
  11. type: VariableType = None
  12. def __init__(self, **kwargs):
  13. if 'type' in kwargs.keys() and type(kwargs['type']) != VariableType:
  14. kwargs['type'] = VariableType.get(kwargs['type'])
  15. super().__init__(**kwargs)
  16. def insert(self):
  17. try:
  18. DB.sql(
  19. """INSERT INTO variable
  20. (type, address)
  21. VALUES
  22. (:type, :address)
  23. """, self.__dict__)
  24. return True
  25. except Exception as e:
  26. print(e)
  27. return False
  28. def exists(self):
  29. try:
  30. return bool(next(DB.sql(
  31. """SELECT 1 FROM variable
  32. WHERE type=:type AND address=:address
  33. """, self.__dict__)))
  34. except StopIteration:
  35. return False
  36. @staticmethod
  37. def getall():
  38. return dict([
  39. (str(row), Variable.getall_of_type(row))
  40. for _, row in VariableType.getall().items()
  41. ])
  42. @staticmethod
  43. def getall_of_type(type: VariableType) -> dict:
  44. return {
  45. row['address']: Variable(**dict(row))
  46. for row in DB.sql(
  47. """SELECT * FROM variable
  48. WHERE type = :slabel
  49. AND address >= :start_address
  50. AND address <= :end_address""",
  51. type.__dict__)
  52. }
  53. @staticmethod
  54. def getall_values_of_type(type: VariableType) -> dict:
  55. return Variable.getall_values_of_type_since(type, 0)
  56. @staticmethod
  57. def getall_values_of_type_since(type: VariableType, since: int) -> dict:
  58. floatcast = lambda x: round(float(x) / 10, 2)
  59. cast_fct = floatcast if type.slabel == 'A' else lambda x: x
  60. type.__dict__.update({'since': since})
  61. return {
  62. row['address']: cast_fct(row['value'])
  63. for row in DB.sql(
  64. """SELECT var.address as address, val.value
  65. FROM variable var
  66. LEFT JOIN var_value val ON
  67. var.type = val.type
  68. AND var.address = val.address
  69. AND var.last_update = val.time
  70. WHERE
  71. var.type = :slabel
  72. AND var.address >= :start_address
  73. AND var.address <= :end_address
  74. AND var.last_update > :since""",
  75. type.__dict__)
  76. }
  77. def modbus_update(self):
  78. if self.type == 'A':
  79. pass
  80. elif self.type == 'I':
  81. pass
  82. elif self.type == 'D':
  83. pass