platform.py 11 KB

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