vav.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. # -*- coding: utf-8 -*-
  2. from operator import attrgetter
  3. from typing import Dict, List, Optional, Tuple
  4. import numpy as np
  5. from fastapi import HTTPException
  6. from httpx import AsyncClient
  7. from loguru import logger
  8. from sqlalchemy.orm import Session
  9. from app.controllers.equipment.controller import EquipmentController
  10. from app.crud.space.weight import get_weights_by_vav
  11. from app.models.domain.devices import ACATVAInstructionsRequest
  12. from app.schemas.equipment import VAVBox, FCU
  13. from app.schemas.instructions import ACATVAInstructions
  14. from app.schemas.sapce_weight import SpaceWeight
  15. from app.schemas.space import Space
  16. from app.services.platform import DataPlatformService
  17. from app.services.transfer import Duoduo, SpaceInfoService, Season
  18. from app.utils.date import get_time_str
  19. class VAVController(EquipmentController):
  20. def __init__(self, equipment: VAVBox):
  21. super(VAVController, self).__init__()
  22. self.equipment = equipment
  23. async def get_strategy(self):
  24. strategy = 'Plan A'
  25. for space in self.equipment.spaces:
  26. for eq in space.equipment:
  27. if isinstance(eq, FCU):
  28. strategy = 'Plan B'
  29. break
  30. return strategy
  31. async def build_virtual_temperature(self) -> Tuple[float, float]:
  32. target_list, realtime_list = [], []
  33. buffer_list = []
  34. strategy = await self.get_strategy()
  35. for space in self.equipment.spaces:
  36. if not np.isnan(space.temperature_target):
  37. target_list.append(space.temperature_target)
  38. realtime_list.append(space.realtime_temperature)
  39. if strategy == 'Plan B':
  40. for eq in space.equipment:
  41. if isinstance(eq, FCU):
  42. buffer = (4 - eq.air_valve_speed) / 4
  43. buffer_list.append(buffer)
  44. break
  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. try:
  62. ratio = abs(1 + (temperature_realtime - temperature_set) / (temperature_set - temperature_supply))
  63. except ZeroDivisionError:
  64. ratio = 1
  65. supply_air_flow_set = self.equipment.supply_air_flow * ratio
  66. supply_air_flow_set = max(self.equipment.supply_air_flow_lower_limit, supply_air_flow_set)
  67. supply_air_flow_set = min(self.equipment.supply_air_flow_upper_limit, supply_air_flow_set)
  68. self.equipment.supply_air_flow_set = supply_air_flow_set
  69. self.equipment.virtual_target_temperature = temperature_set
  70. self.equipment.virtual_realtime_temperature = temperature_realtime
  71. return supply_air_flow_set
  72. async def run(self):
  73. temperature_set, temperature_realtime = await self.build_virtual_temperature()
  74. await self.get_supply_air_flow_set(temperature_set, temperature_realtime)
  75. self.equipment.running_status = True
  76. def get_results(self):
  77. return self.equipment
  78. class VAVControllerV2(VAVController):
  79. def __init__(self, equipment: VAVBox, weights: Optional[List[SpaceWeight]] = None, season: Optional[Season] = None):
  80. super(VAVControllerV2, self).__init__(equipment)
  81. self.weights = weights
  82. self.season = season
  83. async def build_virtual_temperature(self) -> None:
  84. valid_spaces = []
  85. weights = []
  86. for sp in self.equipment.spaces:
  87. if sp.realtime_temperature > 0.0 and sp.temperature_target > 0.0:
  88. valid_spaces.append(sp)
  89. for weight in self.weights:
  90. if weight.space_id == sp.id:
  91. weights.append(weight)
  92. if valid_spaces:
  93. weights = sorted(weights, key=lambda x: x.temporary_weight_update_time)
  94. if weights[-1].temporary_weight_update_time > get_time_str(60 * 60 * 2, flag='ago'):
  95. # If someone has submitted a feedback in past two hours, meet the need.
  96. weight_dic = {weight.space_id: 0.0 for weight in weights}
  97. weight_dic.update({weights[-1].space_id: weights[-1].temporary_weight})
  98. else:
  99. weight_dic = {weight.space_id: weight.default_weight for weight in weights}
  100. total_weight_value = 0.0
  101. for v in weight_dic.values():
  102. total_weight_value += v
  103. if total_weight_value > 0:
  104. weight_dic = {k: v / total_weight_value for k, v in weight_dic.items()}
  105. else:
  106. weight_dic.update({list(weight_dic.keys())[0]: 1.0})
  107. try:
  108. virtual_target, virtual_realtime = 0.0, 0.0
  109. for sp in valid_spaces:
  110. virtual_target += sp.temperature_target * weight_dic.get(sp.id)
  111. virtual_realtime += sp.realtime_temperature * weight_dic.get(sp.id)
  112. except KeyError:
  113. logger.error(f'{self.equipment.id} has wrong vav-space relation')
  114. raise HTTPException(status_code=404, detail='This VAV box has wrong eq-sp relation')
  115. self.equipment.virtual_target_temperature = virtual_target
  116. self.equipment.virtual_realtime_temperature = virtual_realtime
  117. else:
  118. self.equipment.virtual_target_temperature = np.NAN
  119. self.equipment.virtual_realtime_temperature = np.NAN
  120. async def rectify(self) -> Tuple[float, float]:
  121. bad_spaces = list()
  122. for sp in self.equipment.spaces:
  123. if (sp.realtime_temperature > max(27.0, sp.temperature_target) or
  124. sp.realtime_temperature < min(21.0, sp.temperature_target)):
  125. if sp.temperature_target > 0.0:
  126. bad_spaces.append(sp)
  127. if bad_spaces:
  128. virtual_diff = self.equipment.virtual_target_temperature - self.equipment.virtual_realtime_temperature
  129. if self.season == Season.cooling:
  130. bad_spaces = sorted(bad_spaces, key=attrgetter('diff'))
  131. worst = bad_spaces[0]
  132. if worst.diff <= 0:
  133. if worst.diff < virtual_diff:
  134. self.equipment.virtual_target_temperature = worst.temperature_target
  135. self.equipment.virtual_realtime_temperature = worst.realtime_temperature
  136. else:
  137. self.equipment.virtual_target_temperature = min(21.0, worst.temperature_target) + 0.5
  138. self.equipment.virtual_realtime_temperature = worst.realtime_temperature
  139. elif self.season == Season.heating:
  140. bad_spaces = sorted(bad_spaces, key=attrgetter('diff'), reverse=True)
  141. worst = bad_spaces[0]
  142. if worst.diff >= 0:
  143. if worst.diff > virtual_diff:
  144. self.equipment.virtual_target_temperature = worst.temperature_target
  145. self.equipment.virtual_realtime_temperature = worst.realtime_temperature
  146. else:
  147. self.equipment.virtual_target_temperature = max(27.0, worst.temperature_target) - 0.5
  148. self.equipment.virtual_realtime_temperature = worst.realtime_temperature
  149. return self.equipment.virtual_target_temperature, self.equipment.virtual_realtime_temperature
  150. async def run(self) -> None:
  151. await self.build_virtual_temperature()
  152. temperature_set, temperature_realtime = await self.rectify()
  153. await self.get_supply_air_flow_set(temperature_set, temperature_realtime)
  154. self.equipment.running_status = True
  155. class VAVControllerV3(VAVControllerV2):
  156. def __init__(self, vav_params: VAVBox, season: Season):
  157. super(VAVControllerV3, self).__init__(vav_params)
  158. self.season = season
  159. def get_valid_spaces(self) -> List:
  160. valid_spaces = list()
  161. for sp in self.equipment.spaces:
  162. if sp.realtime_temperature > 0.0 and sp.temperature_target > 22.0:
  163. valid_spaces.append(sp)
  164. return valid_spaces
  165. async def build_virtual_temperature(self) -> None:
  166. valid_spaces = self.get_valid_spaces()
  167. if not valid_spaces:
  168. virtual_realtime, virtual_target = np.NAN, np.NAN
  169. else:
  170. sorted_spaces = sorted(valid_spaces, key=lambda x: x.vav_temporary_update_time)
  171. if sorted_spaces[-1].vav_temporary_update_time > get_time_str(60 * 60 * 2, flag='ago'):
  172. virtual_realtime = sorted_spaces[-1].realtime_temperature
  173. virtual_target = sorted_spaces[-1].temperature_target
  174. else:
  175. virtual_realtime, virtual_target = 0.0, 0.0
  176. total_weight = 0.0
  177. for sp in valid_spaces:
  178. temp_weight = sp.vav_default_weight
  179. virtual_realtime += sp.realtime_temperature * temp_weight
  180. virtual_target += sp.temperature_target * temp_weight
  181. total_weight += temp_weight
  182. if total_weight == 0:
  183. for sp in valid_spaces:
  184. virtual_realtime += sp.realtime_temperature
  185. virtual_target += sp.temperature_target
  186. virtual_realtime /= len(valid_spaces)
  187. virtual_target /= len(valid_spaces)
  188. else:
  189. virtual_realtime /= total_weight
  190. virtual_target /= total_weight
  191. self.equipment.virtual_realtime_temperature = virtual_realtime
  192. self.equipment.virtual_target_temperature = virtual_target
  193. async def fetch_vav_control_params(project_id: str, equipment_id: str) -> Dict:
  194. async with AsyncClient() as client:
  195. duo_duo = Duoduo(client, project_id)
  196. platform = DataPlatformService(client, project_id)
  197. season = await duo_duo.get_season()
  198. served_spaces = await duo_duo.get_space_by_equipment(equipment_id)
  199. space_objects = []
  200. realtime_supply_air_temperature_list = []
  201. for sp in served_spaces:
  202. sp_id = sp.get('id')
  203. transfer = SpaceInfoService(client, project_id, sp_id)
  204. current_target = await transfer.get_current_temperature_target()
  205. realtime_temperature = await platform.get_realtime_temperature(sp_id)
  206. related_equipment = await transfer.get_equipment()
  207. equipment_objects = []
  208. for eq in related_equipment:
  209. if eq.get('category') == 'ACATFC':
  210. speed = await platform.get_fan_speed(eq.get('id'))
  211. temp_fcu_params = {'id': eq.get('id'), 'air_valve_speed': speed}
  212. fcu = FCU(**temp_fcu_params)
  213. equipment_objects.append(fcu)
  214. elif eq.get('category') == 'ACATAH':
  215. realtime_supply_air_temperature_list.append(
  216. await platform.get_realtime_supply_air_temperature(eq.get('id'))
  217. )
  218. temp_space_params = {
  219. 'id': sp_id,
  220. 'realtime_temperature': realtime_temperature,
  221. 'equipment': equipment_objects,
  222. 'temperature_target': current_target,
  223. 'diff': current_target - realtime_temperature
  224. }
  225. space = Space(**temp_space_params)
  226. space_objects.append(space)
  227. realtime_supply_air_temperature = np.array(realtime_supply_air_temperature_list).mean()
  228. realtime_supply_air_flow = await platform.get_realtime_supply_air_flow(equipment_id)
  229. lower_limit, upper_limit = await platform.get_air_flow_limit(equipment_id)
  230. vav_params = {
  231. 'id': equipment_id,
  232. 'spaces': space_objects,
  233. 'supply_air_temperature': realtime_supply_air_temperature,
  234. 'supply_air_flow': realtime_supply_air_flow,
  235. 'supply_air_flow_lower_limit': lower_limit,
  236. 'supply_air_flow_upper_limit': upper_limit,
  237. 'season': season
  238. }
  239. return vav_params
  240. @logger.catch()
  241. async def get_vav_control_v1(project: str, equipment_id: str) -> VAVBox:
  242. vav_params = await fetch_vav_control_params(project, equipment_id)
  243. vav = VAVBox(**vav_params)
  244. vav_controller = VAVController(vav)
  245. await vav_controller.run()
  246. regulated_vav = vav_controller.get_results()
  247. return regulated_vav
  248. @logger.catch()
  249. async def get_vav_control_v2(db: Session, project_id: str, equipment_id: str) -> VAVBox:
  250. vav_params = await fetch_vav_control_params(project_id, equipment_id)
  251. vav = VAVBox(**vav_params)
  252. weights = get_weights_by_vav(db, equipment_id)
  253. vav_controller = VAVControllerV2(vav, [SpaceWeight.from_orm(weight) for weight in weights], vav_params['season'])
  254. await vav_controller.run()
  255. regulated_vav = vav_controller.get_results()
  256. return regulated_vav
  257. @logger.catch()
  258. async def build_acatva_instructions(params: ACATVAInstructionsRequest) -> ACATVAInstructions:
  259. space_params = []
  260. for sp in params.spaces:
  261. temp_sp = Space(**sp.dict())
  262. temp_sp.diff = temp_sp.temperature_target - temp_sp.realtime_temperature
  263. space_params.append(temp_sp)
  264. if params.supply_air_temperature == -1:
  265. if params.acatah_supply_air_temperature == -1:
  266. supply_air_temperature = np.NAN
  267. else:
  268. supply_air_temperature = params.acatah_supply_air_temperature
  269. else:
  270. supply_air_temperature = params.supply_air_temperature
  271. vav_params = VAVBox(
  272. spaces=space_params,
  273. supply_air_temperature=supply_air_temperature,
  274. supply_air_flow=params.supply_air_flow,
  275. supply_air_flow_lower_limit=params.supply_air_flow_lower_limit,
  276. supply_air_flow_upper_limit=params.supply_air_flow_upper_limit
  277. )
  278. controller = VAVControllerV3(vav_params=vav_params, season=Season(params.season))
  279. await controller.run()
  280. regulated_vav = controller.get_results()
  281. instructions = ACATVAInstructions(
  282. supply_air_flow_set=regulated_vav.supply_air_flow_set,
  283. virtual_realtime_temperature=regulated_vav.virtual_realtime_temperature,
  284. virtual_temperature_target_set=regulated_vav.virtual_target_temperature
  285. )
  286. return instructions