hvx 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hvx/__init__.py +27 -0
- hvx/__main__.py +7 -0
- hvx/app/__init__.py +7 -0
- hvx/app/analysis_runner.py +102 -0
- hvx/app/api.py +1030 -0
- hvx/app/main.py +345 -0
- hvx/app/state.py +270 -0
- hvx/building_csv.py +214 -0
- hvx/cli.py +349 -0
- hvx/connectors/__init__.py +3 -0
- hvx/connectors/climify.py +188 -0
- hvx/connectors/csv/__init__.py +29 -0
- hvx/connectors/csv/config.yaml +7 -0
- hvx/connectors/csv/data_loader.py +496 -0
- hvx/connectors/csv/portfolio_loader.py +850 -0
- hvx/connectors/dmi.py +124 -0
- hvx/core/__init__.py +257 -0
- hvx/core/access.py +80 -0
- hvx/core/aggregators.py +77 -0
- hvx/core/analysis.py +182 -0
- hvx/core/config/__init__.py +26 -0
- hvx/core/config/loader.py +74 -0
- hvx/core/data_quality.py +487 -0
- hvx/core/energy.py +451 -0
- hvx/core/energy_pricing.py +217 -0
- hvx/core/entities.py +2309 -0
- hvx/core/enums/__init__.py +52 -0
- hvx/core/enums/access.py +31 -0
- hvx/core/enums/analysis.py +49 -0
- hvx/core/enums/country.py +245 -0
- hvx/core/enums/energy.py +62 -0
- hvx/core/enums/rules.py +46 -0
- hvx/core/enums/sensors.py +96 -0
- hvx/core/enums/spatial.py +103 -0
- hvx/core/enums/timeseries.py +118 -0
- hvx/core/filters/__init__.py +17 -0
- hvx/core/filters/opening_hours_filter.py +117 -0
- hvx/core/filters/seasonal_filter.py +295 -0
- hvx/core/filters/time_filter.py +221 -0
- hvx/core/metering.py +310 -0
- hvx/core/py.typed +0 -0
- hvx/core/rules.py +161 -0
- hvx/core/schedules.py +322 -0
- hvx/core/semantics/__init__.py +57 -0
- hvx/core/semantics/brick.py +605 -0
- hvx/core/semantics/ieq.py +294 -0
- hvx/core/semantics/ifc.py +281 -0
- hvx/core/semantics/ifc_guid.py +69 -0
- hvx/core/semantics/mappings.py +254 -0
- hvx/core/semantics/namespaces.py +62 -0
- hvx/core/semantics/ontology/hvx_ieq.ttl +174 -0
- hvx/core/semantics/types.py +37 -0
- hvx/core/simulation.py +80 -0
- hvx/core/spacial_entity.py +1013 -0
- hvx/core/standards_registry.py +410 -0
- hvx/core/timeseries_aggregator.py +318 -0
- hvx/core/utils/calendar.py +55 -0
- hvx/live/__init__.py +41 -0
- hvx/live/base.py +106 -0
- hvx/live/bindings.py +79 -0
- hvx/live/chirpstack.py +373 -0
- hvx/live/limits.py +106 -0
- hvx/live/monitor.py +249 -0
- hvx/live/site.py +285 -0
- hvx/live/sources.py +171 -0
- hvx/mcp_server.py +421 -0
- hvx/reporting/__init__.py +77 -0
- hvx/reporting/aggregate.py +194 -0
- hvx/reporting/analysis.py +565 -0
- hvx/reporting/branding.py +102 -0
- hvx/reporting/brands/baw.yaml +18 -0
- hvx/reporting/builder.py +219 -0
- hvx/reporting/charts.py +480 -0
- hvx/reporting/config.py +158 -0
- hvx/reporting/frames.py +170 -0
- hvx/reporting/i18n.py +304 -0
- hvx/reporting/model.py +216 -0
- hvx/reporting/renderers/__init__.py +68 -0
- hvx/reporting/renderers/html.py +148 -0
- hvx/reporting/renderers/pdf.py +86 -0
- hvx/reporting/renderers/tabular.py +96 -0
- hvx/reporting/templates/report.html.j2 +531 -0
- hvx/simulations/__init__.py +50 -0
- hvx/simulations/config/__init__.py +22 -0
- hvx/simulations/config/registry.py +177 -0
- hvx/simulations/models/__init__.py +37 -0
- hvx/simulations/models/correlations/__init__.py +19 -0
- hvx/simulations/models/correlations/model.py +145 -0
- hvx/simulations/models/correlations/seasonal_thermal_analysis.py +198 -0
- hvx/simulations/models/correlations/solar_gain_analysis.py +291 -0
- hvx/simulations/models/occupancy/__init__.py +11 -0
- hvx/simulations/models/occupancy/config.yaml +77 -0
- hvx/simulations/models/occupancy/model.py +241 -0
- hvx/simulations/models/rc_thermal/__init__.py +13 -0
- hvx/simulations/models/rc_thermal/config.yaml +94 -0
- hvx/simulations/models/rc_thermal/model.py +347 -0
- hvx/simulations/models/real_epc/__init__.py +10 -0
- hvx/simulations/models/real_epc/config.yaml +57 -0
- hvx/simulations/models/real_epc/model.py +72 -0
- hvx/simulations/models/recommendations/__init__.py +20 -0
- hvx/simulations/models/recommendations/model.py +439 -0
- hvx/simulations/models/reporting/__init__.py +18 -0
- hvx/simulations/models/reporting/html_report_service.py +84 -0
- hvx/simulations/models/reporting/json_export_service.py +613 -0
- hvx/simulations/models/scenario/__init__.py +14 -0
- hvx/simulations/models/scenario/model.py +190 -0
- hvx/simulations/models/ventilation/__init__.py +11 -0
- hvx/simulations/models/ventilation/config.yaml +75 -0
- hvx/simulations/models/ventilation/model.py +198 -0
- hvx/simulations/registry.py +267 -0
- hvx/standards/__init__.py +4 -0
- hvx/standards/br18/analysis.py +288 -0
- hvx/standards/br18/config.yaml +234 -0
- hvx/standards/en16798/analysis.py +1499 -0
- hvx/standards/en16798/config.yaml +294 -0
- hvx/standards/tail/aggregate.py +83 -0
- hvx/standards/tail/analysis.py +350 -0
- hvx/standards/tail/calculator.py +1141 -0
- hvx/standards/tail/config.yaml +358 -0
- hvx/standards/tail/docs/TAIL_algorithm.txt +111 -0
- hvx/tail_label.py +303 -0
- hvx-0.5.0.dist-info/METADATA +509 -0
- hvx-0.5.0.dist-info/RECORD +127 -0
- hvx-0.5.0.dist-info/WHEEL +5 -0
- hvx-0.5.0.dist-info/entry_points.txt +2 -0
- hvx-0.5.0.dist-info/licenses/LICENSE +373 -0
- hvx-0.5.0.dist-info/top_level.txt +1 -0
hvx/app/api.py
ADDED
|
@@ -0,0 +1,1030 @@
|
|
|
1
|
+
# This Source Code Form is subject to the terms of the Mozilla Public
|
|
2
|
+
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
3
|
+
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
4
|
+
"""
|
|
5
|
+
FastAPI backend for the flow-editor frontend.
|
|
6
|
+
|
|
7
|
+
This API provides endpoints to:
|
|
8
|
+
- Create portfolio structures from the flow-editor
|
|
9
|
+
- Run analyses (EN 16798, TAIL, etc.)
|
|
10
|
+
- Retrieve results and statistics
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Dict, List, Optional
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
|
|
20
|
+
import tempfile
|
|
21
|
+
|
|
22
|
+
from fastapi import FastAPI, HTTPException, UploadFile, File
|
|
23
|
+
from fastapi.responses import Response
|
|
24
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
25
|
+
from pydantic import BaseModel
|
|
26
|
+
import pandas as pd
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
from hvx.app.state import PortfolioStore
|
|
30
|
+
from hvx.app.analysis_runner import run_en16798_for_rooms
|
|
31
|
+
from hvx.core import (
|
|
32
|
+
SpatialEntityType,
|
|
33
|
+
BuildingType,
|
|
34
|
+
RoomType,
|
|
35
|
+
MetricType,
|
|
36
|
+
SensorSourceType,
|
|
37
|
+
EnergyCarrier,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# Import standards
|
|
41
|
+
from hvx.standards.en16798 import analysis as en16798
|
|
42
|
+
from hvx.standards.tail import analysis as tail_analysis, calculator as tail_calc
|
|
43
|
+
from hvx.standards.br18 import analysis as br18
|
|
44
|
+
|
|
45
|
+
# Reporting and semantic interoperability
|
|
46
|
+
from hvx.reporting import MEDIA_TYPES, ReportBuilder, ReportConfig, render
|
|
47
|
+
from hvx.core.semantics.ieq import IEQAssessment
|
|
48
|
+
|
|
49
|
+
# Import simulations
|
|
50
|
+
from hvx.simulations import (
|
|
51
|
+
OccupancyCalculator,
|
|
52
|
+
VentilationCalculator,
|
|
53
|
+
RCThermalModel,
|
|
54
|
+
RCModelType,
|
|
55
|
+
calculate_epc_rating,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# Initialize FastAPI
|
|
60
|
+
app = FastAPI(
|
|
61
|
+
title="IEQ Analytics API",
|
|
62
|
+
description="Backend API for Indoor Environmental Quality Analytics",
|
|
63
|
+
version="1.0.0",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Configure CORS
|
|
67
|
+
app.add_middleware(
|
|
68
|
+
CORSMiddleware,
|
|
69
|
+
allow_origins=["http://localhost:3000"], # Next.js dev server
|
|
70
|
+
allow_credentials=True,
|
|
71
|
+
allow_methods=["*"],
|
|
72
|
+
allow_headers=["*"],
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
# Global store (in production, use database or session management)
|
|
76
|
+
_store = PortfolioStore()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# --- Pydantic Models for API ---
|
|
80
|
+
|
|
81
|
+
class PortfolioCreate(BaseModel):
|
|
82
|
+
name: str
|
|
83
|
+
country: Optional[str] = None
|
|
84
|
+
region: Optional[str] = None
|
|
85
|
+
description: Optional[str] = None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class BuildingCreate(BaseModel):
|
|
89
|
+
name: str
|
|
90
|
+
building_type: str = "office"
|
|
91
|
+
area_m2: float
|
|
92
|
+
city: Optional[str] = None
|
|
93
|
+
country: Optional[str] = None
|
|
94
|
+
heating_carrier: str = "district_heating"
|
|
95
|
+
cooling_carrier: str = "electricity"
|
|
96
|
+
dhw_carrier: str = "district_heating"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class FloorCreate(BaseModel):
|
|
100
|
+
building_id: str
|
|
101
|
+
name: str
|
|
102
|
+
floor_number: int
|
|
103
|
+
area_m2: float
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class RoomCreate(BaseModel):
|
|
107
|
+
building_id: str
|
|
108
|
+
floor_id: str
|
|
109
|
+
name: str
|
|
110
|
+
room_type: str = "office"
|
|
111
|
+
area_m2: float
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class SensorCreate(BaseModel):
|
|
115
|
+
entity_type: str
|
|
116
|
+
entity_id: str
|
|
117
|
+
parameter: str
|
|
118
|
+
metric_type: str
|
|
119
|
+
unit: str
|
|
120
|
+
source_type: str = "measured"
|
|
121
|
+
weight: float = 1.0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class PortfolioFromFlowEditor(BaseModel):
|
|
125
|
+
"""Structure sent from the flow-editor"""
|
|
126
|
+
name: str
|
|
127
|
+
metadata: Dict[str, Any]
|
|
128
|
+
buildings: List[Dict[str, Any]]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class AnalysisRequest(BaseModel):
|
|
132
|
+
room_ids: List[str]
|
|
133
|
+
season: str = "heating" # "heating" or "cooling"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class TimeSeriesUpload(BaseModel):
|
|
137
|
+
room_id: str
|
|
138
|
+
data: List[Dict[str, Any]] # List of {timestamp, temperature, co2, humidity, ...}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# --- API Endpoints ---
|
|
142
|
+
|
|
143
|
+
@app.get("/")
|
|
144
|
+
def read_root():
|
|
145
|
+
return {
|
|
146
|
+
"message": "IEQ Analytics API",
|
|
147
|
+
"version": "1.0.0",
|
|
148
|
+
"docs": "/docs",
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@app.get("/api/health")
|
|
153
|
+
def health_check():
|
|
154
|
+
return {"status": "healthy"}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# Portfolio endpoints
|
|
158
|
+
|
|
159
|
+
@app.post("/api/portfolio")
|
|
160
|
+
def create_portfolio(portfolio: PortfolioCreate):
|
|
161
|
+
"""Create a new portfolio"""
|
|
162
|
+
try:
|
|
163
|
+
_store.create_portfolio(
|
|
164
|
+
name=portfolio.name,
|
|
165
|
+
country=portfolio.country,
|
|
166
|
+
region=portfolio.region,
|
|
167
|
+
metadata={"description": portfolio.description} if portfolio.description else {},
|
|
168
|
+
)
|
|
169
|
+
return {"success": True, "portfolio": {"name": portfolio.name}}
|
|
170
|
+
except Exception as e:
|
|
171
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@app.get("/api/portfolio")
|
|
175
|
+
def get_portfolio():
|
|
176
|
+
"""Get current portfolio structure"""
|
|
177
|
+
if not _store.portfolio:
|
|
178
|
+
return {"portfolio": None}
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
"portfolio": {
|
|
182
|
+
"name": _store.portfolio.name,
|
|
183
|
+
"country": _store.portfolio.country,
|
|
184
|
+
"region": _store.portfolio.region,
|
|
185
|
+
"metadata": _store.portfolio.metadata,
|
|
186
|
+
"hierarchy": _store.hierarchy_dict(),
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@app.post("/api/portfolio/from-flow-editor")
|
|
192
|
+
def create_portfolio_from_flow_editor(data: PortfolioFromFlowEditor):
|
|
193
|
+
"""
|
|
194
|
+
Create portfolio structure from flow-editor.
|
|
195
|
+
This endpoint receives the structure from the ZIP wizard.
|
|
196
|
+
"""
|
|
197
|
+
try:
|
|
198
|
+
# Create portfolio
|
|
199
|
+
_store.create_portfolio(
|
|
200
|
+
name=data.name,
|
|
201
|
+
country=data.metadata.get("country"),
|
|
202
|
+
region=data.metadata.get("region"),
|
|
203
|
+
metadata=data.metadata,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Helper to convert string enums
|
|
207
|
+
def get_enum_value(enum_class, value: str, default):
|
|
208
|
+
try:
|
|
209
|
+
return getattr(enum_class, value.upper(), default)
|
|
210
|
+
except:
|
|
211
|
+
return default
|
|
212
|
+
|
|
213
|
+
# Create buildings
|
|
214
|
+
for building_data in data.buildings:
|
|
215
|
+
building = _store.add_building(
|
|
216
|
+
name=building_data["name"],
|
|
217
|
+
building_type=get_enum_value(
|
|
218
|
+
BuildingType, building_data.get("metadata", {}).get("building_type", "office"), BuildingType.OFFICE
|
|
219
|
+
),
|
|
220
|
+
area_m2=building_data.get("metadata", {}).get("area_m2", 1000.0),
|
|
221
|
+
city=building_data.get("metadata", {}).get("city"),
|
|
222
|
+
heating_carrier=get_enum_value(EnergyCarrier, "district_heating", EnergyCarrier.DISTRICT_HEATING),
|
|
223
|
+
cooling_carrier=get_enum_value(EnergyCarrier, "electricity", EnergyCarrier.ELECTRICITY),
|
|
224
|
+
dhw_carrier=get_enum_value(EnergyCarrier, "district_heating", EnergyCarrier.DISTRICT_HEATING),
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
# Create floors
|
|
228
|
+
for floor_data in building_data.get("floors", []):
|
|
229
|
+
# Skip default_floor if it exists
|
|
230
|
+
if floor_data.get("folder") == "default_floor":
|
|
231
|
+
# For flat structures, create one default floor
|
|
232
|
+
if floor_data.get("rooms"):
|
|
233
|
+
floor = _store.add_floor(
|
|
234
|
+
building_id=building.id,
|
|
235
|
+
name="Ground Floor",
|
|
236
|
+
floor_number=0,
|
|
237
|
+
area_m2=building_data.get("metadata", {}).get("area_m2", 1000.0),
|
|
238
|
+
)
|
|
239
|
+
# Create rooms
|
|
240
|
+
for room_data in floor_data.get("rooms", []):
|
|
241
|
+
room = _store.add_room(
|
|
242
|
+
building_id=building.id,
|
|
243
|
+
floor_id=floor.id,
|
|
244
|
+
name=room_data["name"],
|
|
245
|
+
room_type=get_enum_value(RoomType, room_data.get("metadata", {}).get("room_type", "office"), RoomType.OFFICE),
|
|
246
|
+
area_m2=room_data.get("metadata", {}).get("area_m2", 50.0),
|
|
247
|
+
)
|
|
248
|
+
continue
|
|
249
|
+
|
|
250
|
+
floor = _store.add_floor(
|
|
251
|
+
building_id=building.id,
|
|
252
|
+
name=floor_data["name"],
|
|
253
|
+
floor_number=floor_data.get("metadata", {}).get("floor_number", 0),
|
|
254
|
+
area_m2=floor_data.get("metadata", {}).get("area_m2", building.area_m2),
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# Create rooms
|
|
258
|
+
for room_data in floor_data.get("rooms", []):
|
|
259
|
+
room = _store.add_room(
|
|
260
|
+
building_id=building.id,
|
|
261
|
+
floor_id=floor.id,
|
|
262
|
+
name=room_data["name"],
|
|
263
|
+
room_type=get_enum_value(RoomType, room_data.get("metadata", {}).get("room_type", "office"), RoomType.OFFICE),
|
|
264
|
+
area_m2=room_data.get("metadata", {}).get("area_m2", 50.0),
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
# TODO: Load sensor data from CSV if available
|
|
268
|
+
# For now, sensors would need to be uploaded separately
|
|
269
|
+
|
|
270
|
+
return {
|
|
271
|
+
"success": True,
|
|
272
|
+
"portfolio": _store.hierarchy_dict(),
|
|
273
|
+
"message": f"Created portfolio '{data.name}' with {len(data.buildings)} buildings",
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
except Exception as e:
|
|
277
|
+
import traceback
|
|
278
|
+
traceback.print_exc()
|
|
279
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# Building endpoints
|
|
283
|
+
|
|
284
|
+
@app.post("/api/buildings")
|
|
285
|
+
def create_building(building: BuildingCreate):
|
|
286
|
+
"""Add a building to the portfolio"""
|
|
287
|
+
if not _store.portfolio:
|
|
288
|
+
raise HTTPException(status_code=400, detail="Create a portfolio first")
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
result = _store.add_building(
|
|
292
|
+
name=building.name,
|
|
293
|
+
building_type=getattr(BuildingType, building.building_type.upper(), BuildingType.OFFICE),
|
|
294
|
+
area_m2=building.area_m2,
|
|
295
|
+
city=building.city,
|
|
296
|
+
heating_carrier=getattr(EnergyCarrier, building.heating_carrier.upper(), EnergyCarrier.DISTRICT_HEATING),
|
|
297
|
+
cooling_carrier=getattr(EnergyCarrier, building.cooling_carrier.upper(), EnergyCarrier.ELECTRICITY),
|
|
298
|
+
dhw_carrier=getattr(EnergyCarrier, building.dhw_carrier.upper(), EnergyCarrier.DISTRICT_HEATING),
|
|
299
|
+
)
|
|
300
|
+
return {"success": True, "building_id": result.id}
|
|
301
|
+
except Exception as e:
|
|
302
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# Analysis endpoints
|
|
306
|
+
|
|
307
|
+
@app.post("/api/analysis/en16798")
|
|
308
|
+
def run_en16798_analysis(request: AnalysisRequest):
|
|
309
|
+
"""Run EN 16798 analysis on selected rooms"""
|
|
310
|
+
try:
|
|
311
|
+
# Get rooms
|
|
312
|
+
rooms = [_store.rooms[room_id] for room_id in request.room_ids if room_id in _store.rooms]
|
|
313
|
+
|
|
314
|
+
if not rooms:
|
|
315
|
+
raise HTTPException(status_code=400, detail="No valid rooms found")
|
|
316
|
+
|
|
317
|
+
# Filter rooms with data
|
|
318
|
+
rooms_with_data = [room for room in rooms if room.timeseries_data]
|
|
319
|
+
|
|
320
|
+
if not rooms_with_data:
|
|
321
|
+
raise HTTPException(status_code=400, detail="None of the selected rooms have timeseries data")
|
|
322
|
+
|
|
323
|
+
# Run analysis
|
|
324
|
+
results = run_en16798_for_rooms(
|
|
325
|
+
rooms_with_data,
|
|
326
|
+
season=request.season,
|
|
327
|
+
buildings=_store.buildings,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
"success": True,
|
|
332
|
+
"results": results,
|
|
333
|
+
"analyzed_rooms": len(rooms_with_data),
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
except Exception as e:
|
|
337
|
+
import traceback
|
|
338
|
+
traceback.print_exc()
|
|
339
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
@app.post("/api/rooms/{room_id}/timeseries")
|
|
343
|
+
def upload_room_timeseries(room_id: str, data: TimeSeriesUpload):
|
|
344
|
+
"""Upload timeseries data for a room"""
|
|
345
|
+
if room_id not in _store.rooms:
|
|
346
|
+
raise HTTPException(status_code=404, detail="Room not found")
|
|
347
|
+
|
|
348
|
+
try:
|
|
349
|
+
df = pd.DataFrame(data.data)
|
|
350
|
+
_store.load_room_timeseries(room_id, df)
|
|
351
|
+
return {
|
|
352
|
+
"success": True,
|
|
353
|
+
"message": f"Loaded {len(df)} records for room {room_id}",
|
|
354
|
+
}
|
|
355
|
+
except Exception as e:
|
|
356
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
@app.get("/api/stats")
|
|
360
|
+
def get_statistics():
|
|
361
|
+
"""Get portfolio statistics"""
|
|
362
|
+
return {
|
|
363
|
+
"portfolio": _store.portfolio.name if _store.portfolio else None,
|
|
364
|
+
"buildings": len(_store.buildings),
|
|
365
|
+
"floors": len(_store.floors),
|
|
366
|
+
"rooms": len(_store.rooms),
|
|
367
|
+
"rooms_with_data": sum(1 for room in _store.rooms.values() if room.timeseries_data),
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# ===== TAIL ANALYSIS ENDPOINTS =====
|
|
372
|
+
|
|
373
|
+
class TAILAnalysisRequest(BaseModel):
|
|
374
|
+
building_id: str
|
|
375
|
+
season: str = "heating" # "heating" or "cooling"
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
@app.post("/api/analysis/tail")
|
|
379
|
+
def run_tail_analysis(request: TAILAnalysisRequest):
|
|
380
|
+
"""
|
|
381
|
+
Run TAIL (Traffic Light) analysis for a building.
|
|
382
|
+
Returns color-coded ratings for all rooms.
|
|
383
|
+
"""
|
|
384
|
+
try:
|
|
385
|
+
if request.building_id not in _store.buildings:
|
|
386
|
+
raise HTTPException(status_code=404, detail="Building not found")
|
|
387
|
+
|
|
388
|
+
building = _store.buildings[request.building_id]
|
|
389
|
+
|
|
390
|
+
# Get all rooms in building with data
|
|
391
|
+
rooms_with_data = [
|
|
392
|
+
room for room in _store.rooms.values()
|
|
393
|
+
if room.building_id == building.id and room.timeseries_data
|
|
394
|
+
]
|
|
395
|
+
|
|
396
|
+
if not rooms_with_data:
|
|
397
|
+
raise HTTPException(status_code=400, detail="No rooms with data in this building")
|
|
398
|
+
|
|
399
|
+
# Run TAIL analysis
|
|
400
|
+
results = tail_analysis.run(
|
|
401
|
+
rooms=rooms_with_data,
|
|
402
|
+
season=request.season,
|
|
403
|
+
building=building,
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
return {
|
|
407
|
+
"success": True,
|
|
408
|
+
"building_id": building.id,
|
|
409
|
+
"building_name": building.name,
|
|
410
|
+
"analyzed_rooms": len(rooms_with_data),
|
|
411
|
+
"results": results,
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
except Exception as e:
|
|
415
|
+
import traceback
|
|
416
|
+
traceback.print_exc()
|
|
417
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
@app.post("/api/analysis/tail/calculator")
|
|
421
|
+
def calculate_tail_rating(data: Dict[str, Any]):
|
|
422
|
+
"""
|
|
423
|
+
Calculate TAIL rating from compliance percentages.
|
|
424
|
+
Input: {"temperature": 95.5, "co2": 88.2, "humidity": 92.0}
|
|
425
|
+
"""
|
|
426
|
+
try:
|
|
427
|
+
calculator = tail_calc.TAILCalculator()
|
|
428
|
+
|
|
429
|
+
# Convert input data to TAIL parameter results
|
|
430
|
+
param_results = {}
|
|
431
|
+
for param, compliance_pct in data.items():
|
|
432
|
+
param_results[param] = tail_calc.TAILParameterResult(
|
|
433
|
+
parameter=param,
|
|
434
|
+
compliance_percentage=compliance_pct,
|
|
435
|
+
rating=calculator._calculate_rating(compliance_pct),
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
# Calculate overall result
|
|
439
|
+
overall = calculator.calculate_overall(list(param_results.values()))
|
|
440
|
+
|
|
441
|
+
return {
|
|
442
|
+
"success": True,
|
|
443
|
+
"parameters": {k: v.dict() for k, v in param_results.items()},
|
|
444
|
+
"overall": overall.dict(),
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
except Exception as e:
|
|
448
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
# ===== BR18 ANALYSIS ENDPOINTS =====
|
|
452
|
+
|
|
453
|
+
class BR18AnalysisRequest(BaseModel):
|
|
454
|
+
room_ids: List[str]
|
|
455
|
+
season: str = "heating"
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
@app.post("/api/analysis/br18")
|
|
459
|
+
def run_br18_analysis(request: BR18AnalysisRequest):
|
|
460
|
+
"""
|
|
461
|
+
Run BR18 (Danish Building Regulations) analysis.
|
|
462
|
+
"""
|
|
463
|
+
try:
|
|
464
|
+
rooms = [_store.rooms[room_id] for room_id in request.room_ids if room_id in _store.rooms]
|
|
465
|
+
|
|
466
|
+
if not rooms:
|
|
467
|
+
raise HTTPException(status_code=400, detail="No valid rooms found")
|
|
468
|
+
|
|
469
|
+
rooms_with_data = [room for room in rooms if room.timeseries_data]
|
|
470
|
+
|
|
471
|
+
if not rooms_with_data:
|
|
472
|
+
raise HTTPException(status_code=400, detail="None of the selected rooms have data")
|
|
473
|
+
|
|
474
|
+
# Run BR18 analysis
|
|
475
|
+
results = br18.run(
|
|
476
|
+
rooms=rooms_with_data,
|
|
477
|
+
season=request.season,
|
|
478
|
+
buildings=_store.buildings,
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
return {
|
|
482
|
+
"success": True,
|
|
483
|
+
"analyzed_rooms": len(rooms_with_data),
|
|
484
|
+
"results": results,
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
except Exception as e:
|
|
488
|
+
import traceback
|
|
489
|
+
traceback.print_exc()
|
|
490
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
# ===== SIMULATION ENDPOINTS =====
|
|
494
|
+
|
|
495
|
+
class OccupancySimulationRequest(BaseModel):
|
|
496
|
+
room_id: str
|
|
497
|
+
co2_threshold: float = 800.0 # ppm
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@app.post("/api/simulations/occupancy")
|
|
501
|
+
def simulate_occupancy(request: OccupancySimulationRequest):
|
|
502
|
+
"""
|
|
503
|
+
Infer occupancy patterns from CO2 data.
|
|
504
|
+
"""
|
|
505
|
+
try:
|
|
506
|
+
if request.room_id not in _store.rooms:
|
|
507
|
+
raise HTTPException(status_code=404, detail="Room not found")
|
|
508
|
+
|
|
509
|
+
room = _store.rooms[request.room_id]
|
|
510
|
+
|
|
511
|
+
if not room.timeseries_data:
|
|
512
|
+
raise HTTPException(status_code=400, detail="Room has no timeseries data")
|
|
513
|
+
|
|
514
|
+
df = room.timeseries_data
|
|
515
|
+
|
|
516
|
+
# Check if CO2 column exists
|
|
517
|
+
co2_col = None
|
|
518
|
+
for col in df.columns:
|
|
519
|
+
if 'co2' in col.lower():
|
|
520
|
+
co2_col = col
|
|
521
|
+
break
|
|
522
|
+
|
|
523
|
+
if not co2_col:
|
|
524
|
+
raise HTTPException(status_code=400, detail="No CO2 data found")
|
|
525
|
+
|
|
526
|
+
# Run occupancy calculation
|
|
527
|
+
calculator = OccupancyCalculator()
|
|
528
|
+
result = calculator.infer_from_co2(
|
|
529
|
+
df[co2_col],
|
|
530
|
+
co2_threshold=request.co2_threshold,
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
return {
|
|
534
|
+
"success": True,
|
|
535
|
+
"room_id": room.id,
|
|
536
|
+
"room_name": room.name,
|
|
537
|
+
"occupancy_pattern": result.dict() if hasattr(result, 'dict') else str(result),
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
except Exception as e:
|
|
541
|
+
import traceback
|
|
542
|
+
traceback.print_exc()
|
|
543
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
class VentilationSimulationRequest(BaseModel):
|
|
547
|
+
room_id: str
|
|
548
|
+
room_volume_m3: float
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
@app.post("/api/simulations/ventilation")
|
|
552
|
+
def simulate_ventilation(request: VentilationSimulationRequest):
|
|
553
|
+
"""
|
|
554
|
+
Calculate ventilation rates from CO2 decay.
|
|
555
|
+
"""
|
|
556
|
+
try:
|
|
557
|
+
if request.room_id not in _store.rooms:
|
|
558
|
+
raise HTTPException(status_code=404, detail="Room not found")
|
|
559
|
+
|
|
560
|
+
room = _store.rooms[request.room_id]
|
|
561
|
+
|
|
562
|
+
if not room.timeseries_data:
|
|
563
|
+
raise HTTPException(status_code=400, detail="Room has no timeseries data")
|
|
564
|
+
|
|
565
|
+
df = room.timeseries_data
|
|
566
|
+
|
|
567
|
+
# Find CO2 column
|
|
568
|
+
co2_col = None
|
|
569
|
+
for col in df.columns:
|
|
570
|
+
if 'co2' in col.lower():
|
|
571
|
+
co2_col = col
|
|
572
|
+
break
|
|
573
|
+
|
|
574
|
+
if not co2_col:
|
|
575
|
+
raise HTTPException(status_code=400, detail="No CO2 data found")
|
|
576
|
+
|
|
577
|
+
# Run ventilation calculation
|
|
578
|
+
calculator = VentilationCalculator()
|
|
579
|
+
result = calculator.calculate_from_co2_decay(
|
|
580
|
+
df[co2_col],
|
|
581
|
+
room_volume=request.room_volume_m3,
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
return {
|
|
585
|
+
"success": True,
|
|
586
|
+
"room_id": room.id,
|
|
587
|
+
"room_name": room.name,
|
|
588
|
+
"ventilation_result": result.dict() if hasattr(result, 'dict') else str(result),
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
except Exception as e:
|
|
592
|
+
import traceback
|
|
593
|
+
traceback.print_exc()
|
|
594
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
class RCThermalSimulationRequest(BaseModel):
|
|
598
|
+
room_id: str
|
|
599
|
+
model_type: str = "2R2C" # "2R2C", "3R2C", etc.
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
@app.post("/api/simulations/rc-thermal")
|
|
603
|
+
def simulate_rc_thermal(request: RCThermalSimulationRequest):
|
|
604
|
+
"""
|
|
605
|
+
Fit RC thermal model to identify building thermal parameters.
|
|
606
|
+
"""
|
|
607
|
+
raise HTTPException(
|
|
608
|
+
status_code=501,
|
|
609
|
+
detail="RC thermal fitting is experimental and not available: the model has no fitting method yet "
|
|
610
|
+
"(2R2C/3R3C also run the 1R1C model).",
|
|
611
|
+
)
|
|
612
|
+
try:
|
|
613
|
+
if request.room_id not in _store.rooms:
|
|
614
|
+
raise HTTPException(status_code=404, detail="Room not found")
|
|
615
|
+
|
|
616
|
+
room = _store.rooms[request.room_id]
|
|
617
|
+
|
|
618
|
+
if not room.timeseries_data:
|
|
619
|
+
raise HTTPException(status_code=400, detail="Room has no timeseries data")
|
|
620
|
+
|
|
621
|
+
df = room.timeseries_data
|
|
622
|
+
|
|
623
|
+
# Find required columns
|
|
624
|
+
temp_col = None
|
|
625
|
+
for col in df.columns:
|
|
626
|
+
if 'temp' in col.lower():
|
|
627
|
+
temp_col = col
|
|
628
|
+
break
|
|
629
|
+
|
|
630
|
+
if not temp_col:
|
|
631
|
+
raise HTTPException(status_code=400, detail="No temperature data found")
|
|
632
|
+
|
|
633
|
+
# Run RC thermal model
|
|
634
|
+
model_type_enum = getattr(RCModelType, request.model_type.upper(), RCModelType.TWO_R_TWO_C)
|
|
635
|
+
model = RCThermalModel(model_type=model_type_enum)
|
|
636
|
+
|
|
637
|
+
result = model.fit(
|
|
638
|
+
indoor_temp=df[temp_col],
|
|
639
|
+
# Add outdoor_temp and heat_input if available
|
|
640
|
+
)
|
|
641
|
+
|
|
642
|
+
return {
|
|
643
|
+
"success": True,
|
|
644
|
+
"room_id": room.id,
|
|
645
|
+
"room_name": room.name,
|
|
646
|
+
"model_type": request.model_type,
|
|
647
|
+
"result": result.dict() if hasattr(result, 'dict') else str(result),
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
except Exception as e:
|
|
651
|
+
import traceback
|
|
652
|
+
traceback.print_exc()
|
|
653
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
@app.post("/api/simulations/epc")
|
|
657
|
+
def calculate_epc(building_id: str):
|
|
658
|
+
"""
|
|
659
|
+
Calculate EPC (Energy Performance Certificate) rating.
|
|
660
|
+
"""
|
|
661
|
+
raise HTTPException(
|
|
662
|
+
status_code=501,
|
|
663
|
+
detail="Operational EPC rating is experimental and not available: its thresholds file is not included yet.",
|
|
664
|
+
)
|
|
665
|
+
try:
|
|
666
|
+
if building_id not in _store.buildings:
|
|
667
|
+
raise HTTPException(status_code=404, detail="Building not found")
|
|
668
|
+
|
|
669
|
+
building = _store.buildings[building_id]
|
|
670
|
+
|
|
671
|
+
# Calculate EPC rating
|
|
672
|
+
rating = calculate_epc_rating(building)
|
|
673
|
+
|
|
674
|
+
return {
|
|
675
|
+
"success": True,
|
|
676
|
+
"building_id": building.id,
|
|
677
|
+
"building_name": building.name,
|
|
678
|
+
"epc_rating": rating,
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
except Exception as e:
|
|
682
|
+
import traceback
|
|
683
|
+
traceback.print_exc()
|
|
684
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
# ===== BATCH ANALYSIS ENDPOINT =====
|
|
688
|
+
|
|
689
|
+
class BatchAnalysisRequest(BaseModel):
|
|
690
|
+
building_ids: Optional[List[str]] = None # If None, analyze all buildings
|
|
691
|
+
analyses: List[str] = ["en16798", "tail", "br18"] # Which analyses to run
|
|
692
|
+
season: str = "heating"
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
@app.post("/api/analysis/batch")
|
|
696
|
+
def run_batch_analysis(request: BatchAnalysisRequest):
|
|
697
|
+
"""
|
|
698
|
+
Run multiple analyses on multiple buildings at once.
|
|
699
|
+
This is the main endpoint the flow-editor will call.
|
|
700
|
+
"""
|
|
701
|
+
try:
|
|
702
|
+
# Determine which buildings to analyze
|
|
703
|
+
if request.building_ids:
|
|
704
|
+
buildings = [_store.buildings[bid] for bid in request.building_ids if bid in _store.buildings]
|
|
705
|
+
else:
|
|
706
|
+
buildings = list(_store.buildings.values())
|
|
707
|
+
|
|
708
|
+
if not buildings:
|
|
709
|
+
raise HTTPException(status_code=400, detail="No valid buildings found")
|
|
710
|
+
|
|
711
|
+
results = {
|
|
712
|
+
"success": True,
|
|
713
|
+
"analyzed_buildings": len(buildings),
|
|
714
|
+
"building_results": {},
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
# Run analyses for each building
|
|
718
|
+
for building in buildings:
|
|
719
|
+
building_results = {
|
|
720
|
+
"building_id": building.id,
|
|
721
|
+
"building_name": building.name,
|
|
722
|
+
"analyses": {},
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
# Get rooms with data
|
|
726
|
+
rooms_with_data = [
|
|
727
|
+
room for room in _store.rooms.values()
|
|
728
|
+
if room.building_id == building.id and room.timeseries_data
|
|
729
|
+
]
|
|
730
|
+
|
|
731
|
+
if not rooms_with_data:
|
|
732
|
+
building_results["error"] = "No rooms with data"
|
|
733
|
+
results["building_results"][building.id] = building_results
|
|
734
|
+
continue
|
|
735
|
+
|
|
736
|
+
# Run EN 16798
|
|
737
|
+
if "en16798" in request.analyses:
|
|
738
|
+
try:
|
|
739
|
+
en16798_results = run_en16798_for_rooms(
|
|
740
|
+
rooms_with_data,
|
|
741
|
+
season=request.season,
|
|
742
|
+
buildings=_store.buildings,
|
|
743
|
+
)
|
|
744
|
+
building_results["analyses"]["en16798"] = en16798_results
|
|
745
|
+
except Exception as e:
|
|
746
|
+
building_results["analyses"]["en16798"] = {"error": str(e)}
|
|
747
|
+
|
|
748
|
+
# Run TAIL
|
|
749
|
+
if "tail" in request.analyses:
|
|
750
|
+
try:
|
|
751
|
+
tail_results = tail_analysis.run(
|
|
752
|
+
rooms=rooms_with_data,
|
|
753
|
+
season=request.season,
|
|
754
|
+
building=building,
|
|
755
|
+
)
|
|
756
|
+
building_results["analyses"]["tail"] = tail_results
|
|
757
|
+
except Exception as e:
|
|
758
|
+
building_results["analyses"]["tail"] = {"error": str(e)}
|
|
759
|
+
|
|
760
|
+
# Run BR18
|
|
761
|
+
if "br18" in request.analyses:
|
|
762
|
+
try:
|
|
763
|
+
br18_results = br18.run(
|
|
764
|
+
rooms=rooms_with_data,
|
|
765
|
+
season=request.season,
|
|
766
|
+
buildings=_store.buildings,
|
|
767
|
+
)
|
|
768
|
+
building_results["analyses"]["br18"] = br18_results
|
|
769
|
+
except Exception as e:
|
|
770
|
+
building_results["analyses"]["br18"] = {"error": str(e)}
|
|
771
|
+
|
|
772
|
+
results["building_results"][building.id] = building_results
|
|
773
|
+
|
|
774
|
+
return results
|
|
775
|
+
|
|
776
|
+
except Exception as e:
|
|
777
|
+
import traceback
|
|
778
|
+
traceback.print_exc()
|
|
779
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
# --- Reporting -------------------------------------------------------------
|
|
783
|
+
|
|
784
|
+
_SEASON_ALIASES = {"heating": "winter", "cooling": "summer"}
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
class ReportRequest(BaseModel):
|
|
788
|
+
format: str = "json" # json | html | csv | pdf
|
|
789
|
+
language: str = "en" # en | da
|
|
790
|
+
seasons: List[str] = ["winter"] # winter | summer | all_year (heating/cooling accepted)
|
|
791
|
+
target_category: str = "II"
|
|
792
|
+
building_ids: Optional[List[str]] = None
|
|
793
|
+
top_n_rooms: int = 15
|
|
794
|
+
include_simulations: bool = True
|
|
795
|
+
title: Optional[str] = None
|
|
796
|
+
brand: Optional[str] = None # built-in brand name (e.g. "baw"); None: white-label
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
def _require_portfolio() -> None:
|
|
800
|
+
if _store.portfolio is None:
|
|
801
|
+
raise HTTPException(status_code=400, detail="No portfolio loaded")
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def _report_config(request: ReportRequest) -> ReportConfig:
|
|
805
|
+
from hvx.reporting import available_brands
|
|
806
|
+
from hvx.reporting.branding import WHITE_LABEL
|
|
807
|
+
|
|
808
|
+
# Only built-in brands over HTTP: a file path would let callers read server files.
|
|
809
|
+
if request.brand and request.brand.lower() not in WHITE_LABEL and request.brand.lower() not in available_brands():
|
|
810
|
+
raise HTTPException(status_code=422, detail=f"brand must be one of {available_brands()} or omitted")
|
|
811
|
+
try:
|
|
812
|
+
return ReportConfig(
|
|
813
|
+
title=request.title,
|
|
814
|
+
branding=request.brand.lower() if request.brand else None,
|
|
815
|
+
language=request.language,
|
|
816
|
+
seasons=tuple(_SEASON_ALIASES.get(s.lower(), s.lower()) for s in request.seasons),
|
|
817
|
+
target_category=request.target_category,
|
|
818
|
+
top_n_rooms=request.top_n_rooms,
|
|
819
|
+
include_simulations=request.include_simulations,
|
|
820
|
+
)
|
|
821
|
+
except ValueError as exc:
|
|
822
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
@app.post("/api/reports")
|
|
826
|
+
def create_report(request: ReportRequest):
|
|
827
|
+
"""
|
|
828
|
+
Build an IEQ report for the loaded portfolio.
|
|
829
|
+
|
|
830
|
+
`format=json` returns the structured report (schema `hvx.ieq-report/2.0`);
|
|
831
|
+
`html` returns a self-contained page; `csv` returns one row per room.
|
|
832
|
+
"""
|
|
833
|
+
_require_portfolio()
|
|
834
|
+
fmt = request.format.lower()
|
|
835
|
+
if fmt not in MEDIA_TYPES:
|
|
836
|
+
raise HTTPException(status_code=422, detail=f"format must be one of {sorted(MEDIA_TYPES)}")
|
|
837
|
+
report = ReportBuilder(_report_config(request)).build(
|
|
838
|
+
_store.portfolio, _store.buildings, _store.floors, _store.rooms, building_ids=request.building_ids
|
|
839
|
+
)
|
|
840
|
+
try:
|
|
841
|
+
body = render(report, fmt)
|
|
842
|
+
except ImportError as exc:
|
|
843
|
+
raise HTTPException(status_code=501, detail=str(exc)) from exc
|
|
844
|
+
headers = {}
|
|
845
|
+
if fmt != "json":
|
|
846
|
+
headers["Content-Disposition"] = f'attachment; filename="ieq-report.{fmt}"'
|
|
847
|
+
return Response(content=body, media_type=MEDIA_TYPES[fmt], headers=headers)
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
# --- Semantic interoperability (Brick / IFC) --------------------------------
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
@app.get("/api/semantics/brick")
|
|
854
|
+
def export_brick_model(with_assessments: bool = False, season: str = "winter"):
|
|
855
|
+
"""Export the portfolio as a Brick 1.4 model (Turtle), optionally with IEQ assessments."""
|
|
856
|
+
from hvx.core.semantics.brick import BrickExporter
|
|
857
|
+
|
|
858
|
+
_require_portfolio()
|
|
859
|
+
assessments = scores = None
|
|
860
|
+
if with_assessments:
|
|
861
|
+
report = ReportBuilder(
|
|
862
|
+
ReportConfig(seasons=(_SEASON_ALIASES.get(season, season),), include_simulations=False)
|
|
863
|
+
).build(_store.portfolio, _store.buildings, _store.floors, _store.rooms)
|
|
864
|
+
assessments = {r.room_id: [IEQAssessment(**a) for a in r.assessments] for r in report.rooms}
|
|
865
|
+
scores = {r.room_id: r.ieq_score for r in report.rooms if r.ieq_score is not None}
|
|
866
|
+
try:
|
|
867
|
+
ttl = BrickExporter().serialize(
|
|
868
|
+
_store.portfolio, _store.buildings, _store.floors, _store.rooms,
|
|
869
|
+
assessments=assessments, ieq_scores=scores,
|
|
870
|
+
)
|
|
871
|
+
except ImportError as exc:
|
|
872
|
+
raise HTTPException(status_code=501, detail=str(exc)) from exc
|
|
873
|
+
return Response(content=ttl, media_type="text/turtle")
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
async def _upload_to_tempfile(file: UploadFile, suffix: str) -> Path:
|
|
877
|
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
|
|
878
|
+
with tmp:
|
|
879
|
+
tmp.write(await file.read())
|
|
880
|
+
return Path(tmp.name)
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
@app.post("/api/semantics/brick/import")
|
|
884
|
+
async def import_brick_model(file: UploadFile = File(...)):
|
|
885
|
+
"""Replace the loaded portfolio with the spaces and points of a Brick model."""
|
|
886
|
+
from hvx.core.semantics.brick import import_brick
|
|
887
|
+
|
|
888
|
+
path = await _upload_to_tempfile(file, Path(file.filename or "model.ttl").suffix or ".ttl")
|
|
889
|
+
try:
|
|
890
|
+
result = import_brick(path)
|
|
891
|
+
except ImportError as exc:
|
|
892
|
+
raise HTTPException(status_code=501, detail=str(exc)) from exc
|
|
893
|
+
except Exception as exc:
|
|
894
|
+
raise HTTPException(status_code=422, detail=f"Could not parse Brick model: {exc}") from exc
|
|
895
|
+
finally:
|
|
896
|
+
path.unlink(missing_ok=True)
|
|
897
|
+
_store.load_import(result)
|
|
898
|
+
return {"success": True, **result.summary()}
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
@app.post("/api/semantics/ifc/import")
|
|
902
|
+
async def import_ifc_model(file: UploadFile = File(...)):
|
|
903
|
+
"""Replace the loaded portfolio with the spatial structure of an IFC file."""
|
|
904
|
+
from hvx.core.semantics.ifc import load_ifc
|
|
905
|
+
|
|
906
|
+
path = await _upload_to_tempfile(file, ".ifc")
|
|
907
|
+
try:
|
|
908
|
+
result = load_ifc(path, portfolio_name=Path(file.filename or "model").stem)
|
|
909
|
+
except ImportError as exc:
|
|
910
|
+
raise HTTPException(status_code=501, detail=str(exc)) from exc
|
|
911
|
+
except Exception as exc:
|
|
912
|
+
raise HTTPException(status_code=422, detail=f"Could not read IFC file: {exc}") from exc
|
|
913
|
+
finally:
|
|
914
|
+
path.unlink(missing_ok=True)
|
|
915
|
+
result.portfolio.metadata["ifc_file"] = file.filename
|
|
916
|
+
_store.load_import(result)
|
|
917
|
+
return {"success": True, **result.summary()}
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
# --- Live monitoring and ChirpStack webhook ---------------------------------
|
|
921
|
+
|
|
922
|
+
import hmac # noqa: E402
|
|
923
|
+
import os # noqa: E402
|
|
924
|
+
from dataclasses import asdict # noqa: E402
|
|
925
|
+
|
|
926
|
+
from fastapi import Header, Request # noqa: E402
|
|
927
|
+
|
|
928
|
+
_live: Dict[str, Any] = {"monitor": None, "webhook_sources": {}}
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def _live_monitor():
|
|
932
|
+
monitor = _live["monitor"]
|
|
933
|
+
if monitor is None:
|
|
934
|
+
raise HTTPException(status_code=400, detail="No live site loaded; POST /api/live/site first")
|
|
935
|
+
return monitor
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
@app.post("/api/live/site")
|
|
939
|
+
def load_live_site(site: Dict[str, Any], window_days: float = 7.0):
|
|
940
|
+
"""
|
|
941
|
+
Load a site description (same schema as the YAML site files) and start monitoring.
|
|
942
|
+
`chirpstack-http` sources are fed by POST /api/integrations/chirpstack.
|
|
943
|
+
"""
|
|
944
|
+
from datetime import timedelta
|
|
945
|
+
|
|
946
|
+
from hvx.live import LiveMonitor, load_site
|
|
947
|
+
from hvx.live.sources import InMemorySource
|
|
948
|
+
|
|
949
|
+
try:
|
|
950
|
+
loaded = load_site(site)
|
|
951
|
+
sources = loaded.build_sources()
|
|
952
|
+
for source in sources.values():
|
|
953
|
+
source.start()
|
|
954
|
+
except Exception as exc:
|
|
955
|
+
raise HTTPException(status_code=422, detail=f"Invalid site: {exc}") from exc
|
|
956
|
+
old = _live["monitor"]
|
|
957
|
+
if old is not None:
|
|
958
|
+
for source in old.sources.values():
|
|
959
|
+
source.close()
|
|
960
|
+
_live["monitor"] = LiveMonitor(*loaded.entities, sources=sources, window=timedelta(days=window_days), timezone=loaded.timezone)
|
|
961
|
+
_live["webhook_sources"] = {
|
|
962
|
+
name: src
|
|
963
|
+
for name, src in sources.items()
|
|
964
|
+
if isinstance(src, InMemorySource) and str(loaded.source_configs[name].get("type", "")).lower() == "chirpstack-http"
|
|
965
|
+
}
|
|
966
|
+
_store.load_import(loaded)
|
|
967
|
+
return {"success": True, "rooms": len(loaded.rooms), "points": len(_live["monitor"].bindings), "webhook_sources": list(_live["webhook_sources"])}
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
@app.get("/api/live/snapshot")
|
|
971
|
+
def live_snapshot():
|
|
972
|
+
"""Refresh from all sources and return current values, alerts and the rolling assessment."""
|
|
973
|
+
from hvx.reporting.renderers.tabular import _clean
|
|
974
|
+
|
|
975
|
+
monitor = _live_monitor()
|
|
976
|
+
monitor.refresh()
|
|
977
|
+
snapshot = monitor.snapshot()
|
|
978
|
+
return _clean({**asdict(snapshot), "alerts": snapshot.alerts})
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
@app.post("/api/live/report")
|
|
982
|
+
def live_report(request: ReportRequest):
|
|
983
|
+
"""Report over the live window (same options as /api/reports)."""
|
|
984
|
+
monitor = _live_monitor()
|
|
985
|
+
fmt = request.format.lower()
|
|
986
|
+
if fmt not in MEDIA_TYPES:
|
|
987
|
+
raise HTTPException(status_code=422, detail=f"format must be one of {sorted(MEDIA_TYPES)}")
|
|
988
|
+
monitor.refresh()
|
|
989
|
+
report = monitor.report(_report_config(request))
|
|
990
|
+
return Response(content=render(report, fmt), media_type=MEDIA_TYPES[fmt])
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
@app.post("/api/integrations/chirpstack")
|
|
994
|
+
async def chirpstack_webhook(
|
|
995
|
+
request: Request,
|
|
996
|
+
event: str = "up",
|
|
997
|
+
source: Optional[str] = None,
|
|
998
|
+
authorization: Optional[str] = Header(default=None),
|
|
999
|
+
):
|
|
1000
|
+
"""
|
|
1001
|
+
Target for ChirpStack's HTTP integration (JSON or Protobuf encoding).
|
|
1002
|
+
|
|
1003
|
+
Configure the integration URL as `https://<hvx>/api/integrations/chirpstack` and add the
|
|
1004
|
+
header `Authorization: Bearer <HVX_WEBHOOK_TOKEN>`. Without HVX_WEBHOOK_TOKEN set, the
|
|
1005
|
+
endpoint refuses all deliveries.
|
|
1006
|
+
"""
|
|
1007
|
+
from hvx.live.chirpstack import handle_http_event
|
|
1008
|
+
|
|
1009
|
+
expected = os.environ.get("HVX_WEBHOOK_TOKEN")
|
|
1010
|
+
if not expected:
|
|
1011
|
+
raise HTTPException(status_code=503, detail="Set HVX_WEBHOOK_TOKEN to enable the ChirpStack webhook")
|
|
1012
|
+
given = (authorization or "").removeprefix("Bearer ").strip()
|
|
1013
|
+
if not hmac.compare_digest(given, expected):
|
|
1014
|
+
raise HTTPException(status_code=401, detail="Invalid webhook token")
|
|
1015
|
+
targets = _live["webhook_sources"]
|
|
1016
|
+
if source:
|
|
1017
|
+
targets = {source: targets[source]} if source in targets else {}
|
|
1018
|
+
if not targets:
|
|
1019
|
+
raise HTTPException(status_code=409, detail="No chirpstack-http source in the loaded live site")
|
|
1020
|
+
body = await request.body()
|
|
1021
|
+
try:
|
|
1022
|
+
stored = sum(handle_http_event(src, event, body, request.headers.get("content-type")) for src in targets.values())
|
|
1023
|
+
except ValueError as exc:
|
|
1024
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
1025
|
+
return {"success": True, "event": event, "readings": stored}
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
if __name__ == "__main__":
|
|
1029
|
+
import uvicorn
|
|
1030
|
+
uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)
|