Ver código fonte

modify host cofig of services

chenhaiyang 2 anos atrás
pai
commit
4b7e4374be

+ 3 - 2
.env_pro

@@ -1,7 +1,8 @@
-PLATFORM_HOST="http://api.sagacloud.cn"
+PLATFORM_HOST="http://api.sagacloud.cn/data-platform-3"
 PLATFORM_SECRET="saga123456"
 
-TRANSFER_HOST="http://api.sagacloud.cn"
+TRANSFER_HOST="http://api.sagacloud.cn/duoduo-service/transfer"
+CUSTOM_HOST="http://api.sagacloud.cn/duoduo-service/custom-service"
 
 TENCENT_NLP_ENDPOINT="nlp.tencentcloudapi.com"
 TENCENT_SECRET_ID_V1="AKIDH4x32k2xSpElCSIhv19B0ZrFwP68BcIh"

+ 2 - 2
app/controllers/targets/temperature.py

@@ -286,9 +286,9 @@ class TemperatureTargetCarrier(Carrier):
             targets = await transfer.get_custom_target()
             all_day_targets = targets.get("normal_targets")
             current_target = await transfer.get_current_temperature_target()
-            is_customized = await transfer.is_customized()
+            is_customized = await duoduo.is_customized(self.object_id)
             is_temporary = await transfer.is_temporary()
-            season = await duoduo.get_season()
+            season = await transfer.get_season()
 
         self.result = {
             "realtime_temperature": realtime_temperature,

+ 1 - 0
app/core/config.py

@@ -19,6 +19,7 @@ class Settings(BaseSettings):
     PLATFORM_HOST: AnyHttpUrl
     PLATFORM_SECRET: SecretStr
     TRANSFER_HOST: AnyHttpUrl
+    CUSTOM_HOST: AnyHttpUrl
     # WEATHER_HOST: AnyHttpUrl
 
     # HTTPS_PROXY: AnyHttpUrl

+ 3 - 203
app/services/platform.py

@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-
 
+import os
 from enum import Enum
 
 import arrow
@@ -16,7 +17,6 @@ from app.utils.math import round_half_up
 class InfoCode(str, Enum):
     temperature = "Tdb"
     co2 = "CO2"
-    hcho = "HCHO"
     pm2d5 = "PM2d5"
     humidity = "RH"
     supply_air_flow = "SupplyAirFlow"
@@ -48,7 +48,7 @@ class DataPlatformService(Service):
     def __init__(self, client: AsyncClient, project_id: str, server_settings=settings):
         super(DataPlatformService, self).__init__(client)
         self._project_id = project_id
-        self._base_url = URL(server_settings.PLATFORM_HOST)
+        self._base_url = os.getenv("PLATFORM_HOST", server_settings.PLATFORM_HOST)
         self._now_time = get_time_str()
         self._secret = server_settings.PLATFORM_SECRET
 
@@ -56,7 +56,7 @@ class DataPlatformService(Service):
         return {"projectId": self._project_id, "secret": self._secret}
 
     async def get_realtime_data(self, code: InfoCode, object_id: str) -> float:
-        url = self._base_url.join("data-platform-3/hisdata/query_by_obj")
+        url = URL(f"{self._base_url}/hisdata/query_by_obj")
         params = self._common_parameters()
         start_time = get_time_str(60 * 60, flag="ago")
         payload = {
@@ -86,205 +86,5 @@ class DataPlatformService(Service):
 
         return value
 
-    async def get_duration(
-            self, code: InfoCode, object_id: str, duration: int
-    ) -> list[dict]:
-        url = self._base_url.join("data-platform-3/hisdata/query_by_obj")
-        params = self._common_parameters()
-        start_time = get_time_str(duration, flag="ago")
-        payload = {
-            "criteria": {
-                "id": object_id,
-                "code": code.value,
-                "receivetime": {
-                    "$gte": start_time,
-                    "$lte": self._now_time,
-                },
-            }
-        }
-        raw_info = await self._post(url, params, payload)
-
-        try:
-            content = raw_info.get("Content")
-            latest_time = content[-1].get("receivetime")
-            if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(
-                    self._now_time, TIME_FMT
-            ):
-                result = []
-                logger.info(f"delayed data - {object_id}: ({latest_time})")
-            else:
-                result = [
-                    {"timestamp": item["receivetime"], "value": item["data"]}
-                    for item in content
-                ]
-        except (KeyError, TypeError, IndexError):
-            result = []
-
-        return result
-
-    async def get_past_data(
-            self, code: InfoCode, object_id: str, interval: int
-    ) -> float:
-        """
-        Query past data from data platform.
-        :param code: Info code
-        :param object_id:
-        :param interval: time interval(seconds) from now to past
-        :return: a past value
-        """
-        url = self._base_url.join("data-platform-3/hisdata/query_by_obj")
-        params = self._common_parameters()
-        start_time = get_time_str(60 * 60 + interval, flag="ago")
-        end_time = get_time_str(interval, flag="ago")
-        payload = {
-            "criteria": {
-                "id": object_id,
-                "code": code.value,
-                "receivetime": {
-                    "$gte": start_time,
-                    "$lte": end_time,
-                },
-            }
-        }
-        raw_info = await self._post(url, params, payload)
-
-        try:
-            latest_data = raw_info.get("Content")[-1].get("data")
-            latest_time = raw_info.get("Content")[-1].get("receivetime")
-            if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(
-                    end_time, TIME_FMT
-            ):
-                logger.info(
-                    f"delayed data - {object_id}: ({latest_time}, {latest_data})"
-                )
-            value = round_half_up(latest_data, 2)
-        except (KeyError, IndexError, TypeError):
-            value = np.NAN
-        except TypeError:
-            value = -1.0
-
-        return value
-
-    async def query_relations(
-            self,
-            from_id: str | None,
-            graph_id: str | None,
-            relation_type: str | None,
-    ) -> list[dict]:
-        url = self._base_url.join("data-platform-3/relation/query")
-        params = self._common_parameters()
-        criteria = dict()
-        if from_id:
-            criteria.update({"from_id": from_id})
-        if graph_id:
-            criteria.update({"graph_id": graph_id})
-        if relation_type:
-            criteria.update({"relation_type": relation_type})
-        payload = {"criteria": criteria}
-        raw_info = await self._post(url, params, payload)
-
-        return raw_info.get("Content")
-
     async def get_realtime_temperature(self, space_id: str) -> float:
         return await self.get_realtime_data(InfoCode.temperature, space_id)
-
-    async def get_past_temperature(self, space_id: str, interval: int) -> float:
-        return await self.get_past_data(InfoCode.temperature, space_id, interval)
-
-    async def get_realtime_co2(self, space_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.co2, space_id)
-
-    async def get_realtime_hcho(self, space_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.hcho, space_id)
-
-    async def get_realtime_pm2d5(self, space_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.pm2d5, space_id)
-
-    async def get_realtime_humidity(self, space_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.humidity, space_id)
-
-    async def get_realtime_supply_air_flow(self, equipment_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.supply_air_flow, equipment_id)
-
-    async def get_realtime_supply_air_temperature(self, equipment_id: str) -> float:
-        return await self.get_realtime_data(
-            InfoCode.supply_air_temperature, equipment_id
-        )
-
-    async def get_realtime_supply_air_temperature_set(self, equipment_id: str) -> float:
-        return await self.get_realtime_data(
-            InfoCode.supply_air_temperature_set, equipment_id
-        )
-
-    async def get_fan_speed(self, equipment_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.fan_speed, equipment_id)
-
-    async def get_static_info(self, code: str, object_id: str):
-        url = self._base_url.join("data-platform-3/object/batch_query")
-        params = self._common_parameters()
-        payload = {"customInfo": True, "criterias": [{"id": object_id}]}
-        raw_info = await self._post(url, params, payload)
-
-        try:
-            info = raw_info["Content"][0]["infos"][code]
-        except (KeyError, IndexError, TypeError) as e:
-            logger.error(f"id: {object_id}, details: {e}")
-            info = None
-
-        return info
-
-    async def get_air_flow_limit(self, equipment_id: str) -> tuple[float, float]:
-        lower = await self.get_static_info("MinAirFlow", equipment_id)
-        upper = await self.get_static_info("MaxAirFlow", equipment_id)
-        if lower is None:
-            lower = 150.0
-        if upper is None:
-            upper = 2000.0
-
-        return lower, upper
-
-    async def get_schedule(self, equipment_id: str) -> tuple[str, str]:
-        on_time = await self.get_static_info("ctm-OnTime", equipment_id)
-        off_time = await self.get_static_info("ctm-OffTime", equipment_id)
-        if not on_time:
-            on_time = "080000"
-        if not off_time:
-            off_time = "190000"
-
-        return on_time, off_time
-
-    async def get_realtime_fan_freq_set(self, equipment_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.fan_freq_set, equipment_id)
-
-    async def get_realtime_supply_static_press(self, system_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.supply_static_press, system_id)
-
-    async def get_realtime_supply_static_press_set(self, system_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.supply_static_press_set, system_id)
-
-    async def get_realtime_running_status(self, equipment_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.running_status, equipment_id)
-
-    async def get_cloud_status(self, equipment_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.cloud_status, equipment_id)
-
-    async def query_realtime_return_air_temperature(self, device_id: str) -> float:
-        return await self.get_realtime_data(InfoCode.return_air_temperature, device_id)
-
-    async def set_code_value(self, object_id: str, code: InfoCode, value: float):
-        url = self._base_url.join("data-platform-3/parameter/setting")
-        params = self._common_parameters()
-        payload = {"id": object_id, "code": code.value, "value": value}
-
-        await self._post(url, params, payload)
-
-    async def get_items_by_category(self, code) -> list:
-        url = self._base_url.join("data-platform-3/object/subset_query")
-        params = self._common_parameters()
-        payload = {"customInfo": True, "criteria": {"type": [code]}}
-
-        raw_info = await self._post(url, params, payload)
-        items = raw_info.get("Content")
-        results = items if items else []
-
-        return results

+ 28 - 187
app/services/transfer.py

@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-
 
+import os
 from enum import Enum
 
 import arrow
@@ -31,34 +32,14 @@ class SpaceInfoService(Service):
         super(SpaceInfoService, self).__init__(client)
         self._project_id = project_id
         self._space_id = space_id
-        self._base_url = URL(server_settings.TRANSFER_HOST)
+        self._base_url = os.getenv("TRANSFER_HOST", server_settings.TRANSFER_HOST)
         self._now_time = get_time_str()
 
     def _common_parameters(self) -> dict:
         return {"projectId": self._project_id, "spaceId": self._space_id}
 
-    async def is_customized(self) -> bool:
-        url = self._base_url.join("duoduo-service/custom-service/custom/timetarget")
-        time_str = arrow.get(
-            arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp()
-            // 900
-            * 900
-        ).strftime("%Y%m%d%H%M%S")
-        params = {
-            "projectId": self._project_id,
-            "objectId": self._space_id,
-            "timepoint": time_str,
-        }
-        raw_info = await self._get(url, params)
-
-        flag = False
-        if raw_info.get("data"):
-            flag = True
-
-        return flag
-
     async def is_temporary(self) -> bool:
-        url = self._base_url.join("duoduo-service/transfer/environment/temp/target")
+        url = URL(f"{self._base_url}/environment/temp/target")
         params = self._common_parameters()
         params.update({"time": self._now_time})
         raw_info = await self._get(url, params)
@@ -68,37 +49,8 @@ class SpaceInfoService(Service):
 
         return flag
 
-    async def get_feedback(self, wechat_time: str) -> dict:
-        url = self._base_url.join("duoduo-service/transfer/environment/feedbackCount")
-        params = self._common_parameters()
-        params.update({"time": wechat_time})
-        raw_info = await self._get(url, params)
-
-        meaning_dict = {
-            "Id1": "a little cold",
-            "Id2": "so cold",
-            "Id3": "a little hot",
-            "Id4": "so hot",
-            "Id5": "noisy or blowy",
-            "Id6": "so stuffy",
-            "Id7": "more sunshine",
-            "Id8": "less sunshine",
-            "Id9": "send a repairman",
-            "Id10": "switch off",
-            "Id11": "nice",
-            "Id12": "switch on",
-        }
-
-        feedback_dic = {
-            meaning_dict.get(k): v for k, v in raw_info.items() if k != "result"
-        }
-
-        return feedback_dic
-
     async def get_custom_target(self) -> dict[str, pd.DataFrame]:
-        url = self._base_url.join(
-            "duoduo-service/transfer/environment/normalAndPreDayTarget"
-        )
+        url = URL(f"{self._base_url}/environment/normalAndPreDayTarget")
         params = self._common_parameters()
         params.update(
             {"date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d")}
@@ -146,7 +98,7 @@ class SpaceInfoService(Service):
         return round_half_up((current_lower_target + current_upper_target) / 2, 2)
 
     async def env_database_set(self, form: str, value: float) -> None:
-        url = self._base_url.join("duoduo-service/transfer/environment/hispoint/set")
+        url = URL(f"{self._base_url}/environment/hispoint/set")
         params = self._common_parameters()
         time_str = arrow.get(
             arrow.get(self._now_time, TIME_FMT).timestamp() // 900 * 900
@@ -155,7 +107,7 @@ class SpaceInfoService(Service):
         await self._get(url, params)
 
     async def env_database_get(self) -> dict[str, pd.DataFrame]:
-        url = self._base_url.join("duoduo-service/transfer/environment/hispoint/get")
+        url = URL(f"{self._base_url}/environment/hispoint/get")
         params = self._common_parameters()
         params.update(
             {"date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d")}
@@ -180,7 +132,7 @@ class SpaceInfoService(Service):
     def set_custom_target(
             self, form: str, target_value: dict[str, list[float]], flag: str = "1"
     ) -> None:
-        url = self._base_url.join("duoduo-service/transfer/environment/target/setting")
+        url = URL(f"{self._base_url}/environment/target/setting")
         params = {
             "projectId": self._project_id,
             "spaceId": self._space_id,
@@ -192,34 +144,13 @@ class SpaceInfoService(Service):
         # await self._post(url, params=params, payload=target_value)
 
     async def set_temporary_custom(self) -> None:
-        url = self._base_url.join("duoduo-service/transfer/environment/setServiceFlag")
+        url = URL(f"{self._base_url}/environment/setServiceFlag")
         params = self._common_parameters()
         params.update({"time": self._now_time})
         await self._get(url, params)
 
-    async def get_equipment(self) -> list[dict]:
-        url = self._base_url.join(
-            "duoduo-service/object-service/object/equipment/findForServe"
-        )
-        params = self._common_parameters()
-        raw_info = await self._post(url, params)
-
-        result = []
-        for eq in raw_info.get("data"):
-            result.append({"id": eq.get("id"), "category": eq.get("equipmentCategory")})
-
-        return result
-
-
-class Duoduo(Service):
-    def __init__(self, client: AsyncClient, project_id: str, server_settings=settings):
-        super(Duoduo, self).__init__(client)
-        self._project_id = project_id
-        self._base_url = URL(server_settings.TRANSFER_HOST)
-        self._now_time = get_time_str()
-
     async def get_season(self) -> Season:
-        url = self._base_url.join("duoduo-service/transfer/environment/getSeasonType")
+        url = URL(f"{self._base_url}/environment/getSeasonType")
         params = {
             "projectId": self._project_id,
             "date": self._now_time,
@@ -228,120 +159,30 @@ class Duoduo(Service):
 
         return Season(raw_info.get("data"))
 
-    async def get_fill_count(self) -> dict:
-        url = self._base_url.join(
-            "duoduo-service/review-service/space/report/quarter/query"
-        )
-        payload = {
-            "criteria": {
-                "projectId": self._project_id,
-                "date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d"),
-            },
-            "orders": [{"column": "time", "asc": False}],
-            "page": 1,
-            "size": 1,
-        }
-
-        raw_info = await self._post(url, payload=payload)
 
-        try:
-            result = raw_info.get("content")[-1]
-        except (IndexError, TypeError):
-            result = {}
-
-        return result
-
-    async def get_space_by_equipment(self, equipment_id: str) -> list[dict]:
-        url = self._base_url.join(
-            "duoduo-service/object-service/object/space/findForServe"
-        )
-        params = {"projectId": self._project_id, "objectId": equipment_id}
-        raw_info = await self._post(url, params)
-
-        result = []
-        for sp in raw_info.get("data"):
-            if sp.get("isControlled"):
-                result.append({"id": sp.get("id")})
-
-        return result
-
-    async def get_system_by_equipment(self, equipment_id: str) -> list:
-        url = self._base_url.join(
-            "duoduo-service/object-service/object/system/findForCompose"
-        )
-        params = {"projectId": self._project_id, "equipmentId": equipment_id}
-        raw_info = await self._post(url, params)
-
-        system_list = []
-        for sy in raw_info.get("data"):
-            system_list.append({"id": sy.get("id")})
-
-        return system_list
+class Duoduo(Service):
+    def __init__(self, client: AsyncClient, project_id: str, server_settings=settings):
+        super(Duoduo, self).__init__(client)
+        self._project_id = project_id
+        self._base_url = URL(os.getenv("CUSTOM_HOST", server_settings.CUSTOM_HOST))
+        self._now_time = get_time_str()
 
-    async def get_day_type(self) -> dict:
-        url = self._base_url.join("duoduo-service/custom-service/custom/getDateInfo")
+    async def is_customized(self, space_id: str) -> bool:
+        url = URL(f"{self._base_url}/custom/timetarget")
+        time_str = arrow.get(
+            arrow.get(self._now_time, TIME_FMT).shift(minutes=15).timestamp()
+            // 900
+            * 900
+        ).strftime("%Y%m%d%H%M%S")
         params = {
             "projectId": self._project_id,
-            "date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d"),
+            "objectId": space_id,
+            "timepoint": time_str,
         }
         raw_info = await self._get(url, params)
 
-        result = {
-            "day_type": raw_info.get("dayType"),
-            "season": raw_info.get("seasonType"),
-        }
-
-        return result
-
-    async def query_device_virtual_data(self, device_id: str, info_code: str) -> float:
-        url = self._base_url.join("duoduo-service/review-service/equipment/order/query")
-        payload = {
-            "criteria": {
-                "projectId": self._project_id,
-                "objectId": device_id,
-                "date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d"),
-                "funcId": info_code,
-            }
-        }
-        raw_info = await self._post(url, payload=payload)
-
-        try:
-            latest_data = raw_info.get("data")[-1].get("value")
-            latest_time = raw_info.get("data")[-1].get("realTime")
-            if arrow.get(latest_time, TIME_FMT).shift(minutes=15) < arrow.get(
-                    self._now_time, TIME_FMT
-            ):
-                value = np.NAN
-            else:
-                value = latest_data
-        except (KeyError, TypeError, IndexError):
-            value = np.NAN
-
-        return value
-
-    async def query_fill_rate_by_device(self, device_id: str) -> [float, float]:
-        url = self._base_url.join(
-            "duoduo-service/review-service/space/quarter/getQueryByCategory"
-        )
-        payload = {
-            "criteria": {
-                "projectId": self._project_id,
-                "date": arrow.get(self._now_time, TIME_FMT).date().strftime("%Y%m%d"),
-                "eqId": device_id,
-            }
-        }
-
-        raw_info = await self._post(url, payload=payload)
-
-        try:
-            value_info = raw_info["content"][-1]
-            hot_count = value_info["hotSpaceNum"]
-            cold_count = value_info["coldSpaceNum"]
-            total = value_info["spaceNum"]
-
-            hot_rate = hot_count / total
-            cold_rate = cold_count / total
-        except (KeyError, IndexError, ZeroDivisionError):
-            hot_rate, cold_rate = np.NAN, np.NAN
+        flag = False
+        if raw_info.get("data"):
+            flag = True
 
-        return hot_rate, cold_rate
+        return flag