platform.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # -*- coding: utf-8 -*-
  2. from enum import Enum
  3. from typing import Dict, List, 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. supply_air_temperature_set = 'SupplyAirTempSet'
  21. fan_speed = 'FanGear'
  22. fan_freq = 'FanFreq'
  23. fan_freq_set = 'FanFreqSet'
  24. supply_static_press = 'SupplyStaticPress'
  25. supply_static_press_set = 'SupplyStaticPressSet'
  26. running_status = 'RunStatus'
  27. class DataPlatformService(Service):
  28. def __init__(
  29. self,
  30. client: AsyncClient,
  31. project_id: str,
  32. server_settings=settings
  33. ):
  34. super(DataPlatformService, self).__init__(client)
  35. self._project_id = project_id
  36. self._base_url = URL(server_settings.PLATFORM_HOST)
  37. self._now_time = get_time_str()
  38. self._secret = server_settings.PLATFORM_SECRET
  39. def _common_parameters(self) -> Dict:
  40. return {'projectId': self._project_id, 'secret': self._secret}
  41. async def get_realtime_data(self, code: InfoCode, object_id: str) -> float:
  42. url = self._base_url.join('data-platform-3/hisdata/query_by_obj')
  43. params = self._common_parameters()
  44. start_time = get_time_str(60 * 60, flag='ago')
  45. payload = {
  46. 'criteria': {
  47. 'id': object_id,
  48. 'code': code.value,
  49. 'receivetime': {
  50. '$gte': start_time,
  51. '$lte': self._now_time,
  52. }
  53. }
  54. }
  55. raw_info = await self._post(url, params, payload)
  56. try:
  57. latest_data = raw_info.get('Content')[-1].get('data')
  58. latest_time = raw_info.get('Content')[-1].get('receivetime')
  59. if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(self._now_time, TIME_FMT):
  60. logger.info(f'delayed data - {object_id}: ({latest_time}, {latest_data})')
  61. value = round_half_up(latest_data, 2)
  62. except KeyError and IndexError:
  63. value = np.NAN
  64. except TypeError:
  65. value = -1.0
  66. return value
  67. async def get_duration(self, code: InfoCode, object_id: str, duration: int) -> List[Dict]:
  68. url = self._base_url.join('data-platform-3/hisdata/query_by_obj')
  69. params = self._common_parameters()
  70. start_time = get_time_str(duration, flag='ago')
  71. payload = {
  72. 'criteria': {
  73. 'id': object_id,
  74. 'code': code.value,
  75. 'receivetime': {
  76. '$gte': start_time,
  77. '$lte': self._now_time,
  78. }
  79. }
  80. }
  81. raw_info = await self._post(url, params, payload)
  82. try:
  83. content = raw_info.get('Content')
  84. latest_time = content[-1].get('receivetime')
  85. if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(self._now_time, TIME_FMT):
  86. result = []
  87. logger.info(f'delayed data - {object_id}: ({latest_time})')
  88. else:
  89. result = [
  90. {
  91. 'timestamp': item['receivetime'],
  92. 'value': item['data']
  93. }
  94. for item in content
  95. ]
  96. except KeyError:
  97. result = []
  98. return result
  99. async def get_past_data(self, code: InfoCode, object_id: str, interval: int) -> float:
  100. """
  101. Query past data from data platform.
  102. :param code: Info code
  103. :param object_id:
  104. :param interval: time interval(seconds) from now to past
  105. :return: a past value
  106. """
  107. url = self._base_url.join('data-platform-3/hisdata/query_by_obj')
  108. params = self._common_parameters()
  109. start_time = get_time_str(60 * 60 + interval, flag='ago')
  110. end_time = get_time_str(interval, flag='ago')
  111. payload = {
  112. 'criteria': {
  113. 'id': object_id,
  114. 'code': code.value,
  115. 'receivetime': {
  116. '$gte': start_time,
  117. '$lte': end_time,
  118. }
  119. }
  120. }
  121. raw_info = await self._post(url, params, payload)
  122. try:
  123. latest_data = raw_info.get('Content')[-1].get('data')
  124. latest_time = raw_info.get('Content')[-1].get('receivetime')
  125. if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(end_time, TIME_FMT):
  126. logger.info(f'delayed data - {object_id}: ({latest_time}, {latest_data})')
  127. value = round_half_up(latest_data, 2)
  128. except KeyError and IndexError:
  129. value = np.NAN
  130. except TypeError:
  131. value = -1.0
  132. return value
  133. async def get_realtime_temperature(self, space_id: str) -> float:
  134. return await self.get_realtime_data(InfoCode.temperature, space_id)
  135. async def get_past_temperature(self, space_id: str, interval: int) -> float:
  136. return await self.get_past_data(InfoCode.temperature, space_id, interval)
  137. async def get_realtime_co2(self, space_id: str) -> float:
  138. return await self.get_realtime_data(InfoCode.co2, space_id)
  139. async def get_realtime_hcho(self, space_id: str) -> float:
  140. return await self.get_realtime_data(InfoCode.hcho, space_id)
  141. async def get_realtime_pm2d5(self, space_id: str) -> float:
  142. return await self.get_realtime_data(InfoCode.pm2d5, space_id)
  143. async def get_realtime_humidity(self, space_id: str) -> float:
  144. return await self.get_realtime_data(InfoCode.humidity, space_id)
  145. async def get_realtime_supply_air_flow(self, equipment_id: str) -> float:
  146. return await self.get_realtime_data(InfoCode.supply_air_flow, equipment_id)
  147. async def get_realtime_supply_air_temperature(self, equipment_id: str) -> float:
  148. return await self.get_realtime_data(InfoCode.supply_air_temperature, equipment_id)
  149. async def get_realtime_supply_air_temperature_set(self, equipment_id: str) -> float:
  150. return await self.get_realtime_data(InfoCode.supply_air_temperature_set, equipment_id)
  151. async def get_fan_speed(self, equipment_id: str) -> float:
  152. return await self.get_realtime_data(InfoCode.fan_speed, equipment_id)
  153. async def get_static_info(self, code: str, object_id: str):
  154. url = self._base_url.join('data-platform-3/object/batch_query')
  155. params = self._common_parameters()
  156. payload = {
  157. 'customInfo': True,
  158. 'criterias': [
  159. {
  160. 'id': object_id
  161. }
  162. ]
  163. }
  164. raw_info = await self._post(url, params, payload)
  165. try:
  166. info = raw_info['Content'][0]['infos'][code]
  167. except KeyError as e:
  168. logger.error(f'id: {object_id}, details: {e}')
  169. info = None
  170. return info
  171. async def get_air_flow_limit(self, equipment_id: str) -> Tuple[float, float]:
  172. lower = await self.get_static_info('MinAirFlow', equipment_id)
  173. upper = await self.get_static_info('MaxAirFlow', equipment_id)
  174. if not lower:
  175. lower = 150.0
  176. if not upper:
  177. upper = 2000.0
  178. return lower, upper
  179. async def get_schedule(self, equipment_id: str) -> Tuple[str, str]:
  180. on_time = await self.get_static_info('ctm-OnTime', equipment_id)
  181. off_time = await self.get_static_info('ctm-OffTime', equipment_id)
  182. if not on_time:
  183. on_time = '080000'
  184. if not off_time:
  185. off_time = '190000'
  186. return on_time, off_time
  187. async def get_realtime_fan_freq_set(self, equipment_id: str) -> float:
  188. return await self.get_realtime_data(InfoCode.fan_freq_set, equipment_id)
  189. async def get_realtime_supply_static_press(self, system_id: str) -> float:
  190. return await self.get_realtime_data(InfoCode.supply_static_press, system_id)
  191. async def get_realtime_supply_static_press_set(self, system_id: str) -> float:
  192. return await self.get_realtime_data(InfoCode.supply_static_press_set, system_id)
  193. async def get_realtime_running_status(self, equipment_id: str) -> float:
  194. return await self.get_realtime_data(InfoCode.running_status, equipment_id)
  195. async def set_code_value(self, object_id: str, code: InfoCode, value: float):
  196. url = self._base_url.join('data-platform-3/parameter/setting')
  197. params = self._common_parameters()
  198. payload = {
  199. 'id': object_id,
  200. 'code': code.value,
  201. 'value': value
  202. }
  203. await self._post(url, params, payload)