transfer.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 = pd.concat([targets.get("pre_targets"), targets.get("normal_targets")])
  63. else:
  64. current_targets = targets.get("normal_targets")
  65. temp = (
  66. arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp()
  67. // (15 * 60)
  68. * (15 * 60)
  69. )
  70. next_quarter_minutes = arrow.get(temp).time().strftime("%H%M%S")
  71. try:
  72. current_lower_target = current_targets["temperatureMin"].loc[
  73. next_quarter_minutes
  74. ]
  75. current_upper_target = current_targets["temperatureMax"].loc[
  76. next_quarter_minutes
  77. ]
  78. except KeyError:
  79. current_lower_target, current_upper_target = np.NAN, np.NAN
  80. return round_half_up((current_lower_target + current_upper_target) / 2, 2)
  81. async def env_database_set(self, form: str, value: float) -> None:
  82. url = URL(f"{self._base_url}/environment/hispoint/set")
  83. params = self._common_parameters()
  84. time_str = arrow.get(
  85. arrow.get(self._now_time, TIME_FMT).timestamp() // 900 * 900
  86. ).strftime("%Y%m%d%H%M%S")
  87. params.update({"time": time_str, "type": form, "value": value})
  88. await self._get(url, params)
  89. async def env_database_get(self) -> dict[str, pd.DataFrame]:
  90. url = URL(f"{self._base_url}/environment/hispoint/get")
  91. params = self._common_parameters()
  92. params.update(
  93. {"date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d")}
  94. )
  95. raw_info = await self._get(url, params)
  96. result = {}
  97. if raw_info.get("result") == "success":
  98. for k, v in raw_info.items():
  99. if k != "result":
  100. if len(v) > 0:
  101. temp = {}
  102. time_stamp = [item[0] for item in v]
  103. value = [item[1] for item in v]
  104. temp.update({"timestamp": time_stamp})
  105. temp.update({"value": value})
  106. result.update({k: pd.DataFrame(temp)})
  107. else:
  108. result.update({k: pd.DataFrame()})
  109. return result
  110. def set_custom_target(
  111. self, form: str, target_value: dict[str, list[float]], flag: str = "1"
  112. ) -> None:
  113. url = URL(f"{self._base_url}/environment/target/setting")
  114. params = {
  115. "projectId": self._project_id,
  116. "spaceId": self._space_id,
  117. "timepoint": self._now_time,
  118. "type": form,
  119. "flag": flag,
  120. }
  121. httpx.post(url, params=params, json=target_value)
  122. # await self._post(url, params=params, payload=target_value)
  123. async def set_temporary_custom(self) -> None:
  124. url = URL(f"{self._base_url}/environment/setServiceFlag")
  125. params = self._common_parameters()
  126. params.update({"time": self._now_time})
  127. await self._get(url, params)
  128. async def get_season(self) -> Season:
  129. url = URL(f"{self._base_url}/environment/getSeasonType")
  130. params = {
  131. "projectId": self._project_id,
  132. "date": self._now_time,
  133. }
  134. raw_info = await self._get(url, params)
  135. return Season(raw_info.get("data"))
  136. class Duoduo(Service):
  137. def __init__(self, client: AsyncClient, project_id: str, server_settings=settings):
  138. super(Duoduo, self).__init__(client)
  139. self._project_id = project_id
  140. self._base_url = URL(os.getenv("CUSTOM_HOST", server_settings.CUSTOM_HOST))
  141. self._now_time = get_time_str()
  142. async def is_customized(self, space_id: str) -> bool:
  143. url = URL(f"{self._base_url}/custom/timetarget")
  144. time_str = arrow.get(
  145. arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp()
  146. // 900
  147. * 900
  148. ).strftime("%Y%m%d%H%M%S")
  149. params = {
  150. "projectId": self._project_id,
  151. "objectId": space_id,
  152. "timepoint": time_str,
  153. }
  154. raw_info = await self._get(url, params)
  155. flag = False
  156. if raw_info.get("data"):
  157. flag = True
  158. return flag