transfer.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from enum import Enum
  4. import arrow
  5. import httpx
  6. import numpy as np
  7. import pandas as pd
  8. from httpx import AsyncClient, URL
  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 = os.getenv("TRANSFER_HOST", 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_temporary(self) -> bool:
  33. url = URL(f"{self._base_url}/environment/temp/target")
  34. params = self._common_parameters()
  35. params.update({"time": self._now_time})
  36. raw_info = await self._get(url, params)
  37. flag = False
  38. if raw_info.get("flag") == 1:
  39. flag = True
  40. return flag
  41. async def get_custom_target(self) -> dict[str, pd.DataFrame]:
  42. url = URL(f"{self._base_url}/environment/normalAndPreDayTarget")
  43. params = self._common_parameters()
  44. params.update(
  45. {"date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d")}
  46. )
  47. raw_info = await self._get(url, params)
  48. try:
  49. pre_target_df = pd.DataFrame(raw_info.get("preTargets"))
  50. pre_target_df.set_index("time", inplace=True)
  51. except (KeyError, TypeError):
  52. pre_target_df = pd.DataFrame()
  53. try:
  54. normal_target_df = pd.DataFrame(raw_info.get("normalTargets"))
  55. normal_target_df.set_index("time", inplace=True)
  56. except (KeyError, TypeError):
  57. normal_target_df = pd.DataFrame()
  58. return {"pre_targets": pre_target_df, "normal_targets": normal_target_df}
  59. async def get_current_temperature_target(self) -> float:
  60. targets = await self.get_custom_target()
  61. if len(targets.get("pre_targets")) > 0:
  62. current_targets = targets.get("pre_targets").append(
  63. targets.get("normal_targets")
  64. )
  65. else:
  66. current_targets = targets.get("normal_targets")
  67. temp = (
  68. arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp()
  69. // (15 * 60)
  70. * (15 * 60)
  71. )
  72. next_quarter_minutes = arrow.get(temp).time().strftime("%H%M%S")
  73. try:
  74. current_lower_target = current_targets["temperatureMin"].loc[
  75. next_quarter_minutes
  76. ]
  77. current_upper_target = current_targets["temperatureMax"].loc[
  78. next_quarter_minutes
  79. ]
  80. except KeyError:
  81. current_lower_target, current_upper_target = np.NAN, np.NAN
  82. return round_half_up((current_lower_target + current_upper_target) / 2, 2)
  83. async def env_database_set(self, form: str, value: float) -> None:
  84. url = URL(f"{self._base_url}/environment/hispoint/set")
  85. params = self._common_parameters()
  86. time_str = arrow.get(
  87. arrow.get(self._now_time, TIME_FMT).timestamp() // 900 * 900
  88. ).strftime("%Y%m%d%H%M%S")
  89. params.update({"time": time_str, "type": form, "value": value})
  90. await self._get(url, params)
  91. async def env_database_get(self) -> dict[str, pd.DataFrame]:
  92. url = URL(f"{self._base_url}/environment/hispoint/get")
  93. params = self._common_parameters()
  94. params.update(
  95. {"date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d")}
  96. )
  97. raw_info = await self._get(url, params)
  98. result = {}
  99. if raw_info.get("result") == "success":
  100. for k, v in raw_info.items():
  101. if k != "result":
  102. if len(v) > 0:
  103. temp = {}
  104. data = np.array(v)
  105. temp.update({"timestamp": data[:, 0]})
  106. temp.update({"value": data[:, 1].astype(np.float)})
  107. result.update({k: pd.DataFrame(temp)})
  108. else:
  109. result.update({k: pd.DataFrame()})
  110. return result
  111. def set_custom_target(
  112. self, form: str, target_value: dict[str, list[float]], flag: str = "1"
  113. ) -> None:
  114. url = URL(f"{self._base_url}/environment/target/setting")
  115. params = {
  116. "projectId": self._project_id,
  117. "spaceId": self._space_id,
  118. "timepoint": self._now_time,
  119. "type": form,
  120. "flag": flag,
  121. }
  122. httpx.post(url, params=params, json=target_value)
  123. # await self._post(url, params=params, payload=target_value)
  124. async def set_temporary_custom(self) -> None:
  125. url = URL(f"{self._base_url}/environment/setServiceFlag")
  126. params = self._common_parameters()
  127. params.update({"time": self._now_time})
  128. await self._get(url, params)
  129. async def get_season(self) -> Season:
  130. url = URL(f"{self._base_url}/environment/getSeasonType")
  131. params = {
  132. "projectId": self._project_id,
  133. "date": self._now_time,
  134. }
  135. raw_info = await self._get(url, params)
  136. return Season(raw_info.get("data"))
  137. class Duoduo(Service):
  138. def __init__(self, client: AsyncClient, project_id: str, server_settings=settings):
  139. super(Duoduo, self).__init__(client)
  140. self._project_id = project_id
  141. self._base_url = URL(os.getenv("CUSTOM_HOST", server_settings.CUSTOM_HOST))
  142. self._now_time = get_time_str()
  143. async def is_customized(self, space_id: str) -> bool:
  144. url = URL(f"{self._base_url}/custom/timetarget")
  145. time_str = arrow.get(
  146. arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp()
  147. // 900
  148. * 900
  149. ).strftime("%Y%m%d%H%M%S")
  150. params = {
  151. "projectId": self._project_id,
  152. "objectId": space_id,
  153. "timepoint": time_str,
  154. }
  155. raw_info = await self._get(url, params)
  156. flag = False
  157. if raw_info.get("data"):
  158. flag = True
  159. return flag