vav.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # -*- coding: utf-8 -*-
  2. from typing import Dict, List, Tuple
  3. import numpy as np
  4. from fastapi import HTTPException
  5. from httpx import AsyncClient
  6. from loguru import logger
  7. from sqlalchemy.orm import Session
  8. from app.controllers.equipment.controller import EquipmentController
  9. from app.crud.space.weight import get_weights_by_vav
  10. from app.schemas.equipment import VAVBox, FCU
  11. from app.schemas.sapce_weight import SpaceWeight
  12. from app.schemas.space import Space
  13. from app.services.platform import DataPlatformService
  14. from app.services.transfer import Duoduo, SpaceInfoService, Season
  15. from app.utils.date import get_time_str
  16. class VAVController(EquipmentController):
  17. def __init__(self, equipment: VAVBox):
  18. super(VAVController, self).__init__()
  19. self.equipment = equipment
  20. async def get_strategy(self):
  21. strategy = 'Plan A'
  22. for space in self.equipment.spaces:
  23. for eq in space.equipment:
  24. if isinstance(eq, FCU):
  25. strategy = 'Plan B'
  26. break
  27. return strategy
  28. async def build_virtual_temperature(self) -> Tuple[float, float]:
  29. target_list, realtime_list = [], []
  30. buffer_list = []
  31. strategy = await self.get_strategy()
  32. for space in self.equipment.spaces:
  33. if not np.isnan(space.temperature_target):
  34. target_list.append(space.temperature_target)
  35. realtime_list.append(space.realtime_temperature)
  36. if strategy == 'Plan B':
  37. for eq in space.equipment:
  38. if isinstance(eq, FCU):
  39. buffer = (4 - eq.air_valve_speed) / 4
  40. buffer_list.append(buffer)
  41. break
  42. logger.info(f'target list: {target_list}')
  43. logger.info(f'realtime list: {realtime_list}')
  44. logger.info(f'buffer list: {buffer_list}')
  45. total_target = buffer_list + target_list
  46. total_realtime = buffer_list + realtime_list
  47. if total_target and total_realtime:
  48. target_result = np.array(total_target).sum() / len(target_list)
  49. realtime_result = np.array(total_realtime).sum() / len(realtime_list)
  50. self.equipment.setting_temperature = target_result
  51. else:
  52. target_result, realtime_result = np.NAN, np.NAN
  53. return target_result, realtime_result
  54. async def get_supply_air_flow_set(self, temperature_set: float, temperature_realtime: float) -> float:
  55. if np.isnan(temperature_set) or np.isnan(temperature_realtime):
  56. supply_air_flow_set = 0.0
  57. else:
  58. temperature_supply = self.equipment.supply_air_temperature
  59. if np.isnan(temperature_supply):
  60. temperature_supply = 19.0
  61. supply_air_flow_set = self.equipment.supply_air_flow * ((temperature_supply - temperature_realtime)
  62. / (temperature_supply - temperature_set))
  63. supply_air_flow_set = max(self.equipment.supply_air_flow_lower_limit, supply_air_flow_set)
  64. supply_air_flow_set = min(self.equipment.supply_air_flow_upper_limit, supply_air_flow_set)
  65. self.equipment.supply_air_flow_set = supply_air_flow_set
  66. self.equipment.virtual_target_temperature = temperature_set
  67. self.equipment.virtual_realtime_temperature = temperature_realtime
  68. return supply_air_flow_set
  69. async def run(self):
  70. temperature_set, temperature_realtime = await self.build_virtual_temperature()
  71. await self.get_supply_air_flow_set(temperature_set, temperature_realtime)
  72. self.equipment.running_status = True
  73. def get_results(self):
  74. return self.equipment
  75. class VAVControllerV2(VAVController):
  76. def __init__(self, equipment: VAVBox, weights: List[SpaceWeight], season: Season):
  77. super(VAVControllerV2, self).__init__(equipment)
  78. # self.equipment = equipment
  79. self.weights = weights
  80. self.season = season
  81. async def build_virtual_temperature(self):
  82. valid_spaces = []
  83. weights = []
  84. for sp in self.equipment.spaces:
  85. if sp.realtime_temperature > 0.0 and sp.temperature_target > 0.0:
  86. valid_spaces.append(sp)
  87. for weight in self.weights:
  88. if weight.space_id == sp.id:
  89. weights.append(weight)
  90. if valid_spaces:
  91. weights = sorted(weights, key=lambda x: x.temporary_weight_update_time)
  92. if weights[-1].temporary_weight_update_time > get_time_str(60 * 60 * 2, flag='ago'):
  93. weight_dic = {weight.space_id: 0.0 for weight in weights}
  94. weight_dic.update({weights[-1].space_id: weights[-1].temporary_weight})
  95. else:
  96. weight_dic = {weight.space_id: weight.default_weight for weight in weights}
  97. total_weight_value = 0.0
  98. for v in weight_dic.values():
  99. total_weight_value += v
  100. if total_weight_value > 0:
  101. weight_dic = {k: v / total_weight_value for k, v in weight_dic.items()}
  102. else:
  103. weight_dic.update({list(weight_dic.keys())[0]: 1.0})
  104. try:
  105. virtual_target, virtual_realtime = 0.0, 0.0
  106. for sp in valid_spaces:
  107. virtual_target += sp.temperature_target * weight_dic.get(sp.id)
  108. virtual_realtime += sp.realtime_temperature * weight_dic.get(sp.id)
  109. except KeyError:
  110. logger.error(f'{self.equipment.id} has wrong vav-space relation')
  111. raise HTTPException(status_code=404, detail='This VAV box has wrong eq-sp relation')
  112. self.equipment.virtual_target_temperature = virtual_target
  113. self.equipment.virtual_realtime_temperature = virtual_realtime
  114. else:
  115. self.equipment.virtual_target_temperature = np.NAN
  116. self.equipment.virtual_realtime_temperature = np.NAN
  117. async def rectify(self) -> Tuple[float, float]:
  118. for sp in self.equipment.spaces:
  119. if sp.realtime_temperature < min(23.0, sp.temperature_target):
  120. if self.season == Season.heating:
  121. self.equipment.virtual_target_temperature = min(23.0, sp.temperature_target) + 0.5
  122. self.equipment.virtual_realtime_temperature = sp.realtime_temperature
  123. break
  124. elif sp.realtime_temperature > max(27.0, sp.temperature_target):
  125. if self.season == Season.cooling:
  126. self.equipment.virtual_target_temperature = max(27.0, sp.temperature_target)
  127. self.equipment.virtual_realtime_temperature = sp.realtime_temperature
  128. break
  129. return self.equipment.virtual_target_temperature, self.equipment.virtual_realtime_temperature
  130. async def run(self):
  131. await self.build_virtual_temperature()
  132. temperature_set, temperature_realtime = await self.rectify()
  133. await self.get_supply_air_flow_set(temperature_set, temperature_realtime)
  134. self.equipment.running_status = True
  135. async def fetch_vav_control_params(project_id: str, equipment_id: str) -> Dict:
  136. async with AsyncClient() as client:
  137. duo_duo = Duoduo(client, project_id)
  138. platform = DataPlatformService(client, project_id)
  139. _AHU_LIST = [
  140. 'Eq1101050030846e0a94670842109f7c8d8db0d44cf5',
  141. 'Eq1101050030b6b2f1db3d6944afa71e213e0d45d565'
  142. ]
  143. realtime_supply_air_temperature_list = []
  144. for eq in _AHU_LIST:
  145. realtime_supply_air_temperature_list.append(await platform.get_realtime_supply_air_temperature(eq))
  146. realtime_supply_air_temperature = np.array(realtime_supply_air_temperature_list).mean()
  147. realtime_supply_air_flow = await platform.get_realtime_supply_air_flow(equipment_id)
  148. lower_limit, upper_limit = await platform.get_air_flow_limit(equipment_id)
  149. season = await duo_duo.get_season()
  150. served_spaces = await duo_duo.get_space_by_equipment(equipment_id)
  151. space_objects = []
  152. for sp in served_spaces:
  153. sp_id = sp.get('id')
  154. transfer = SpaceInfoService(client, project_id, sp_id)
  155. current_target = await transfer.get_current_temperature_target()
  156. realtime_temperature = await platform.get_realtime_temperature(sp_id)
  157. related_equipment = await transfer.get_equipment()
  158. equipment_objects = []
  159. for eq in related_equipment:
  160. if eq.get('category') == 'ACATFC':
  161. speed = await platform.get_fan_speed(eq.get('id'))
  162. temp_fcu_params = {'id': eq.get('id'), 'air_valve_speed': speed}
  163. fcu = FCU(**temp_fcu_params)
  164. equipment_objects.append(fcu)
  165. temp_space_params = {
  166. 'id': sp_id,
  167. 'realtime_temperature': realtime_temperature,
  168. 'equipment': equipment_objects,
  169. 'temperature_target': current_target
  170. }
  171. space = Space(**temp_space_params)
  172. space_objects.append(space)
  173. vav_params = {
  174. 'id': equipment_id,
  175. 'spaces': space_objects,
  176. 'supply_air_temperature': realtime_supply_air_temperature,
  177. 'supply_air_flow': realtime_supply_air_flow,
  178. 'supply_air_flow_lower_limit': lower_limit,
  179. 'supply_air_flow_upper_limit': upper_limit,
  180. 'season': season
  181. }
  182. return vav_params
  183. @logger.catch()
  184. async def get_vav_control_v1(project: str, equipment_id: str) -> VAVBox:
  185. vav_params = await fetch_vav_control_params(project, equipment_id)
  186. vav = VAVBox(**vav_params)
  187. vav_controller = VAVController(vav)
  188. await vav_controller.run()
  189. regulated_vav = vav_controller.get_results()
  190. return regulated_vav
  191. @logger.catch()
  192. async def get_vav_control_v2(db: Session, project_id: str, equipment_id: str) -> VAVBox:
  193. vav_params = await fetch_vav_control_params(project_id, equipment_id)
  194. vav = VAVBox(**vav_params)
  195. weights = get_weights_by_vav(db, equipment_id)
  196. vav_controller = VAVControllerV2(vav, [SpaceWeight.from_orm(weight) for weight in weights], vav_params['season'])
  197. await vav_controller.run()
  198. regulated_vav = vav_controller.get_results()
  199. return regulated_vav