platform.py 11 KB

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