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