platform.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # -*- coding: utf-8 -*-
  2. from enum import Enum
  3. from typing import Dict, Tuple
  4. import arrow
  5. import numpy as np
  6. from httpx import AsyncClient, URL
  7. from loguru import logger
  8. from app.core.config import settings
  9. from app.services.service import Service
  10. from app.utils.date import get_time_str, TIME_FMT
  11. from app.utils.math import round_half_up
  12. class InfoCode(str, Enum):
  13. temperature = 'Tdb'
  14. co2 = 'CO2'
  15. hcho = 'HCHO'
  16. pm2d5 = 'PM2d5'
  17. humidity = 'RH'
  18. supply_air_flow = 'SupplyAirFlow'
  19. supply_air_temperature = 'SupplyAirTemp'
  20. fan_speed = 'FanGear'
  21. class DataPlatformService(Service):
  22. def __init__(
  23. self,
  24. client: AsyncClient,
  25. project_id: str,
  26. server_settings=settings
  27. ):
  28. super(DataPlatformService, self).__init__(client)
  29. self._project_id = project_id
  30. self._base_url = URL(server_settings.PLATFORM_HOST)
  31. self._now_time = get_time_str()
  32. self._secret = server_settings.PLATFORM_SECRET
  33. def _common_parameters(self) -> Dict:
  34. return {'projectId': self._project_id, 'secret': self._secret}
  35. async def get_realtime_data(self, code: InfoCode, object_id: str) -> float:
  36. url = self._base_url.join('data-platform-3/hisdata/query_by_obj')
  37. params = self._common_parameters()
  38. start_time = get_time_str(60 * 60, flag='ago')
  39. payload = {
  40. 'criteria': {
  41. 'id': object_id,
  42. 'code': code.value,
  43. 'receivetime': {
  44. '$gte': start_time,
  45. '$lte': self._now_time,
  46. }
  47. }
  48. }
  49. raw_info = await self._post(url, params, payload)
  50. try:
  51. latest_data = raw_info.get('Content')[-1].get('data')
  52. latest_time = raw_info.get('Content')[-1].get('receivetime')
  53. if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(self._now_time, TIME_FMT):
  54. logger.info(f'delayed data - {object_id}: ({latest_time}, {latest_data})')
  55. value = round_half_up(latest_data, 2)
  56. except KeyError and IndexError:
  57. value = np.NAN
  58. except TypeError:
  59. value = -1.0
  60. return value
  61. async def get_past_data(self, code: InfoCode, object_id: str, interval: int) -> float:
  62. """
  63. Query past data from data platform.
  64. :param code: Info code
  65. :param object_id:
  66. :param interval: time interval(seconds) from now to past
  67. :return: a past value
  68. """
  69. url = self._base_url.join('data-platform-3/hisdata/query_by_obj')
  70. params = self._common_parameters()
  71. start_time = get_time_str(60 * 60 + interval, flag='ago')
  72. end_time = get_time_str(interval, flag='ago')
  73. payload = {
  74. 'criteria': {
  75. 'id': object_id,
  76. 'code': code.value,
  77. 'receivetime': {
  78. '$gte': start_time,
  79. '$lte': end_time,
  80. }
  81. }
  82. }
  83. raw_info = await self._post(url, params, payload)
  84. try:
  85. latest_data = raw_info.get('Content')[-1].get('data')
  86. latest_time = raw_info.get('Content')[-1].get('receivetime')
  87. if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(end_time, TIME_FMT):
  88. logger.info(f'delayed data - {object_id}: ({latest_time}, {latest_data})')
  89. value = round_half_up(latest_data, 2)
  90. except KeyError and IndexError:
  91. value = np.NAN
  92. except TypeError:
  93. value = -1.0
  94. return value
  95. async def get_realtime_temperature(self, space_id: str) -> float:
  96. return await self.get_realtime_data(InfoCode.temperature, space_id)
  97. async def get_past_temperature(self, space_id: str, interval: int) -> float:
  98. return await self.get_past_data(InfoCode.temperature, space_id, interval)
  99. async def get_realtime_co2(self, space_id: str) -> float:
  100. return await self.get_realtime_data(InfoCode.co2, space_id)
  101. async def get_realtime_hcho(self, space_id: str) -> float:
  102. return await self.get_realtime_data(InfoCode.hcho, space_id)
  103. async def get_realtime_pm2d5(self, space_id: str) -> float:
  104. return await self.get_realtime_data(InfoCode.pm2d5, space_id)
  105. async def get_realtime_humidity(self, space_id: str) -> float:
  106. return await self.get_realtime_data(InfoCode.humidity, space_id)
  107. async def get_realtime_supply_air_flow(self, equipment_id: str) -> float:
  108. return await self.get_realtime_data(InfoCode.supply_air_flow, equipment_id)
  109. async def get_realtime_supply_air_temperature(self, equipment_id: str) -> float:
  110. return await self.get_realtime_data(InfoCode.supply_air_temperature, equipment_id)
  111. async def get_fan_speed(self, equipment_id: str) -> float:
  112. return await self.get_realtime_data(InfoCode.fan_speed, equipment_id)
  113. async def get_static_info(self, code: str, object_id: str):
  114. url = self._base_url.join('data-platform-3/object/batch_query')
  115. params = self._common_parameters()
  116. payload = {
  117. 'customInfo': True,
  118. 'criterias': [
  119. {
  120. 'id': object_id
  121. }
  122. ]
  123. }
  124. raw_info = await self._post(url, params, payload)
  125. try:
  126. info = raw_info['Content'][0]['infos'][code]
  127. except KeyError as e:
  128. logger.error(f'id: {object_id}, details: {e}')
  129. info = None
  130. return info
  131. async def get_air_flow_limit(self, equipment_id: str) -> Tuple[float, float]:
  132. lower = await self.get_static_info('MinAirFlow', equipment_id)
  133. upper = await self.get_static_info('MaxAirFlow', equipment_id)
  134. if not lower:
  135. lower = 150.0
  136. if not upper:
  137. upper = 2000.0
  138. return lower, upper