transfer.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # -*- coding: utf-8 -*-
  2. from enum import Enum
  3. from typing import Dict, List
  4. import arrow
  5. import numpy as np
  6. import pandas as pd
  7. from httpx import AsyncClient, URL
  8. from loguru import logger
  9. from app.core.config import settings
  10. from app.services.service import Service
  11. from app.utils.date import get_time_str, TIME_FMT
  12. from app.utils.math import round_half_up
  13. class Season(str, Enum):
  14. cooling = 'Cooling'
  15. heating = 'Warm'
  16. transition = 'Transition'
  17. class SpaceInfoService(Service):
  18. def __init__(
  19. self,
  20. client: AsyncClient,
  21. project_id: str,
  22. space_id: str,
  23. server_settings=settings
  24. ) -> None:
  25. super(SpaceInfoService, self).__init__(client)
  26. self._project_id = project_id
  27. self._space_id = space_id
  28. self._base_url = URL(server_settings.TRANSFER_HOST)
  29. self._now_time = get_time_str()
  30. def _common_parameters(self) -> Dict:
  31. return {'projectId': self._project_id, 'spaceId': self._space_id}
  32. async def is_customized(self) -> bool:
  33. url = self._base_url.join('duoduo-service/custom-service/custom/timetarget')
  34. time_str = arrow.get(arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp
  35. // 900 * 900).strftime('%Y%m%d%H%M%S')
  36. params = {
  37. 'projectId': self._project_id,
  38. 'objectId': self._space_id,
  39. 'timepoint': time_str,
  40. }
  41. raw_info = await self._get(url, params)
  42. flag = False
  43. if raw_info.get('data'):
  44. flag = True
  45. return flag
  46. async def is_temporary(self) -> bool:
  47. url = self._base_url.join('duoduo-service/transfer/environment/temp/target')
  48. params = self._common_parameters()
  49. params.update({'time': self._now_time})
  50. raw_info = await self._get(url, params)
  51. flag = False
  52. if raw_info.get('flag') == 1:
  53. flag = True
  54. return flag
  55. async def get_feedback(self, wechat_time: str) -> Dict:
  56. url = self._base_url.join('duoduo-service/transfer/environment/feedbackCount')
  57. params = self._common_parameters()
  58. params.update({'time': wechat_time})
  59. raw_info = await self._get(url, params)
  60. meaning_dict = {
  61. 'Id1': 'a little cold',
  62. 'Id2': 'so cold',
  63. 'Id3': 'a little hot',
  64. 'Id4': 'so hot',
  65. 'Id5': 'noisy or blowy',
  66. 'Id6': 'so stuffy',
  67. 'Id7': 'more sunshine',
  68. 'Id8': 'less sunshine',
  69. 'Id9': 'send a repairman',
  70. 'Id10': 'switch off',
  71. 'Id11': 'nice',
  72. 'Id12': 'switch on',
  73. }
  74. feedback_dic = {meaning_dict.get(k): v for k, v in raw_info.items() if k != 'result'}
  75. return feedback_dic
  76. async def get_custom_target(self) -> pd.DataFrame:
  77. url = self._base_url.join('duoduo-service/transfer/environment/target')
  78. params = self._common_parameters()
  79. params.update({'date': arrow.get(self._now_time, TIME_FMT).date().strftime('%Y%m%d')})
  80. raw_info = await self._get(url, params)
  81. try:
  82. custom_target_df = pd.DataFrame(raw_info.get('data'))
  83. custom_target_df.set_index('time', inplace=True)
  84. except KeyError:
  85. custom_target_df = pd.DataFrame()
  86. return custom_target_df
  87. async def get_current_temperature_target(self) -> float:
  88. current_targets = await self.get_custom_target()
  89. if len(current_targets) > 0:
  90. temp = arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp // (15 * 60) * (15 * 60)
  91. next_quarter_minutes = arrow.get(temp).time().strftime('%H%M%S')
  92. try:
  93. current_lower_target = current_targets['temperatureMin'].loc[next_quarter_minutes]
  94. current_upper_target = current_targets['temperatureMax'].loc[next_quarter_minutes]
  95. except KeyError:
  96. current_lower_target, current_upper_target = 0.0, 0.0
  97. else:
  98. current_lower_target, current_upper_target = np.NAN, np.NAN
  99. return round_half_up((current_lower_target + current_upper_target) / 2, 2)
  100. async def env_database_set(self, form: str, value: float) -> None:
  101. url = self._base_url.join('duoduo-service/transfer/environment/hispoint/set')
  102. params = self._common_parameters()
  103. time_str = arrow.get(arrow.get(self._now_time, TIME_FMT).timestamp // 900 * 900).strftime('%Y%m%d%H%M%S')
  104. params.update({'time': time_str, 'type': form, 'value': value})
  105. await self._get(url, params)
  106. async def env_database_get(self) -> Dict[str, pd.DataFrame]:
  107. url = self._base_url.join('duoduo-service/transfer/environment/hispoint/get')
  108. params = self._common_parameters()
  109. params.update({'date': arrow.get(self._now_time, TIME_FMT).date().strftime('%Y%m%d')})
  110. raw_info = await self._get(url, params)
  111. result = {}
  112. if raw_info.get('result') == 'success':
  113. for k, v in raw_info.items():
  114. if k != 'result':
  115. if len(v) > 0:
  116. temp = {}
  117. data = np.array(v)
  118. temp.update({'timestamp': data[:, 0]})
  119. temp.update({'value': data[:, 1].astype(np.float)})
  120. result.update({k: pd.DataFrame(temp)})
  121. else:
  122. result.update({k: pd.DataFrame()})
  123. return result
  124. async def set_custom_target(self, form: str, target_value: Dict[str, List[float]], flag: str = '1') -> None:
  125. url = self._base_url.join('duoduo-service/transfer/environment/target/setting')
  126. params = {
  127. 'projectId': self._project_id,
  128. 'spaceId': self._space_id,
  129. 'timepoint': self._now_time,
  130. 'type': form,
  131. 'flag': flag
  132. }
  133. await self._post(url, params=params, payload=target_value)
  134. async def set_temporary_custom(self) -> None:
  135. url = self._base_url.join('duoduo-service/transfer/environment/setServiceFlag')
  136. params = self._common_parameters()
  137. params.update({'time': self._now_time})
  138. await self._get(url, params)
  139. async def get_equipment(self) -> List[dict]:
  140. url = self._base_url.join('duoduo-service/object-service/object/equipment/findForServe')
  141. params = self._common_parameters()
  142. raw_info = await self._post(url, params)
  143. result = []
  144. for eq in raw_info.get('data'):
  145. result.append({'id': eq.get('id'), 'category': eq.get('equipmentCategory')})
  146. return result
  147. class Duoduo(Service):
  148. def __init__(self, client: AsyncClient, project_id: str, server_settings=settings):
  149. super(Duoduo, self).__init__(client)
  150. self._project_id = project_id
  151. self._base_url = URL(server_settings.TRANSFER_HOST)
  152. self._now_time = get_time_str()
  153. async def get_season(self) -> Season:
  154. url = self._base_url.join('duoduo-service/transfer/environment/getSeasonType')
  155. params = {
  156. 'projectId': self._project_id,
  157. 'date': self._now_time,
  158. }
  159. raw_info = await self._get(url, params)
  160. return Season(raw_info.get('data'))
  161. async def get_fill_rate(self):
  162. url = self._base_url.join('duoduo-service/review-service/space/report/quarter/query')
  163. payload = {
  164. 'criteria': {
  165. 'projectId': self._project_id,
  166. 'date': arrow.get(self._now_time, TIME_FMT).date().strftime('%Y%m%d')
  167. },
  168. 'orders': [
  169. {
  170. 'column': 'time',
  171. 'asc': False
  172. }
  173. ],
  174. 'page': 1,
  175. 'size': 1
  176. }
  177. raw_info = await self._post(url, payload=payload)
  178. try:
  179. content = raw_info.get('content')[-1]
  180. hot_rate = (content.get('hotNum')
  181. / (content.get('normalNum') + content.get('hotNum') + content.get('coldNum')))
  182. except KeyError and ZeroDivisionError:
  183. hot_rate = 0.0
  184. return hot_rate
  185. async def get_space_by_equipment(self, equipment_id: str) -> List[dict]:
  186. url = self._base_url.join('duoduo-service/object-service/object/space/findForServe')
  187. params = {
  188. 'projectId': self._project_id,
  189. 'objectId': equipment_id
  190. }
  191. raw_info = await self._post(url, params)
  192. result = []
  193. for sp in raw_info.get('data'):
  194. if sp.get('isControlled'):
  195. result.append({'id': sp.get('id')})
  196. return result
  197. async def get_system_by_equipment(self, equipment_id: str) -> List:
  198. url = self._base_url.join('duoduo-service/object-service/object/system/findForCompose')
  199. params = {
  200. 'projectId': self._project_id,
  201. 'equipmentId': equipment_id
  202. }
  203. raw_info = await self._post(url, params)
  204. system_list = []
  205. for sy in raw_info.get('data'):
  206. system_list.append({'id': sy.get('id')})
  207. return system_list
  208. async def get_day_type(self) -> Dict:
  209. url = self._base_url.join('duoduo-service/custom-service/custom/getDateInfo')
  210. params = {
  211. 'projectId': self._project_id,
  212. 'date': arrow.get(self._now_time, TIME_FMT).date().strftime('%Y%m%d')
  213. }
  214. raw_info = await self._get(url, params)
  215. result = {
  216. 'day_type': raw_info.get('dayType'),
  217. 'season': raw_info.get('seasonType')
  218. }
  219. return result