2026-04-02 18:46:42 +08:00
|
|
|
import logging
|
2026-04-01 13:36:06 +08:00
|
|
|
from contextlib import asynccontextmanager
|
2026-04-02 18:46:42 +08:00
|
|
|
from typing import Optional
|
|
|
|
|
|
2026-04-01 13:36:06 +08:00
|
|
|
from fastapi import FastAPI
|
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
from app.api.router import api_router
|
2026-04-02 18:46:42 +08:00
|
|
|
from app.api.v1.websocket import start_broadcast_task, stop_broadcast_task
|
2026-04-01 13:36:06 +08:00
|
|
|
from app.core.config import get_settings
|
|
|
|
|
from app.services.simulator import DataSimulator
|
2026-04-02 18:46:42 +08:00
|
|
|
from app.collectors.manager import CollectorManager
|
2026-04-01 13:36:06 +08:00
|
|
|
|
|
|
|
|
settings = get_settings()
|
|
|
|
|
simulator = DataSimulator()
|
2026-04-02 18:46:42 +08:00
|
|
|
collector_manager: Optional[CollectorManager] = None
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger("app")
|
2026-04-01 13:36:06 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan(app: FastAPI):
|
2026-04-02 18:46:42 +08:00
|
|
|
global collector_manager
|
|
|
|
|
if settings.USE_SIMULATOR:
|
|
|
|
|
logger.info("Starting in SIMULATOR mode")
|
|
|
|
|
await simulator.start()
|
|
|
|
|
else:
|
|
|
|
|
logger.info("Starting in COLLECTOR mode (real IoT devices)")
|
|
|
|
|
collector_manager = CollectorManager()
|
|
|
|
|
await collector_manager.start()
|
|
|
|
|
start_broadcast_task()
|
2026-04-01 13:36:06 +08:00
|
|
|
yield
|
2026-04-02 18:46:42 +08:00
|
|
|
stop_broadcast_task()
|
|
|
|
|
if settings.USE_SIMULATOR:
|
|
|
|
|
await simulator.stop()
|
|
|
|
|
else:
|
|
|
|
|
if collector_manager:
|
|
|
|
|
await collector_manager.stop()
|
|
|
|
|
collector_manager = None
|
2026-04-01 13:36:06 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
app = FastAPI(
|
|
|
|
|
title="天普零碳园区智慧能源管理平台",
|
|
|
|
|
description="Tianpu Zero-Carbon Park Smart Energy Management System",
|
|
|
|
|
version="1.0.0",
|
|
|
|
|
lifespan=lifespan,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=["http://localhost:3000", "http://localhost:5173", "http://127.0.0.1:3000", "http://127.0.0.1:5173"],
|
|
|
|
|
allow_credentials=True,
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
app.include_router(api_router)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/health")
|
|
|
|
|
async def health():
|
|
|
|
|
return {"status": "ok", "app": settings.APP_NAME}
|