from fastapi import FastAPI, HTTPException, Depends from fastapi.middleware.cors import CORSMiddleware from typing import List, Dict, Union, Optional, Any from sqlalchemy.orm import Session, joinedload import psutil import os import serial.tools.list_ports from datetime import datetime import subprocess import platform import httpx import time import sys import socket # import wmi import json from config import * from mqtt_client import mqtt_client import uvicorn from device_status import device_status_manager from service_status import service_status_manager from database import get_db, create_tables import models from schemas import DeviceType, Interface, Device, DeviceBase, DeviceTypeBase, InterfaceBase app = FastAPI(title="树莓派设备管理系统") # 配置 CORS app.add_middleware( CORSMiddleware, allow_origins=["*"],#["http://192.168.8.124","http://192.168.100.142", "http://localhost"], # Vue.js 开发服务器默认端口 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.on_event("startup") async def startup_event(): # 创建数据库表 create_tables() # 启动 MQTT 客户端 mqtt_client.connect() @app.on_event("shutdown") async def shutdown_event(): # 停止 MQTT 客户端 if mqtt_client.connected: mqtt_client.client.loop_stop() mqtt_client.client.disconnect() @app.get("/api") async def root(): return {"message": "Welcome to Raspberry Pi Device Management System"} # 设备管理接口 @app.get("/api/devices", response_model=List[Device]) async def get_devices(db: Session = Depends(get_db)): devices = db.query(models.Device).options( joinedload(models.Device.device_type), joinedload(models.Device.interface) ).all() print("devices", devices) # 添加设备状态信息 for device in devices: print("device id", device.id) print("device name", device.name) print("device code", device.code) status = device_status_manager.get_status(device.code) last_update = device_status_manager.get_last_update(device.code) if status: device.status = status else: device.status = {} if last_update: device.last_update = last_update else: device.last_update = None return devices @app.post("/api/devices", response_model=Device) async def create_device(device: DeviceBase, db: Session = Depends(get_db)): try: # 验证接口是否存在 interface = db.query(models.Interface).filter(models.Interface.id == device.interface_id).first() if interface is None: raise HTTPException(status_code=404, detail="选择的接口不存在") # 验证设备代号是否已存在 existing_device = db.query(models.Device).filter(models.Device.code == device.code).first() if existing_device: raise HTTPException(status_code=400, detail="设备代号已存在") # 验证设备地址是否在设备类型的地址范围内 if device.device_type_id: device_type = db.query(models.DeviceType).filter(models.DeviceType.id == device.device_type_id).first() if device_type: if device.device_address < device_type.address_range_start or device.device_address > device_type.address_range_end: raise HTTPException(status_code=400, detail="设备地址超出设备类型的地址范围") db_device = models.Device( name=device.name, code=device.code, device_address=device.device_address, device_type_id=device.device_type_id, interface_id=device.interface_id, enabled=device.enabled ) db.add(db_device) db.commit() db.refresh(db_device) return db_device except HTTPException as e: raise e except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/devices/{device_id}", response_model=Device) async def get_device(device_id: int, db: Session = Depends(get_db)): device = db.query(models.Device).filter(models.Device.id == device_id).first() if device is None: raise HTTPException(status_code=404, detail="设备不存在") # 添加设备状态信息 status = device_status_manager.get_status(device.code) last_update = device_status_manager.get_last_update(device.code) if status: device.status = status else: device.status = {} if last_update: device.last_update = last_update else: device.last_update = None return device @app.put("/api/devices/{device_id}", response_model=Device) async def update_device(device_id: int, device: DeviceBase, db: Session = Depends(get_db)): try: db_device = db.query(models.Device).filter(models.Device.id == device_id).first() if db_device is None: raise HTTPException(status_code=404, detail="设备不存在") # 验证设备代号是否已存在(排除当前设备) existing_device = db.query(models.Device).filter(models.Device.code == device.code, models.Device.id != device_id).first() if existing_device: raise HTTPException(status_code=400, detail="设备代号已存在") # 验证接口是否存在 interface = db.query(models.Interface).filter(models.Interface.id == device.interface_id).first() if interface is None: raise HTTPException(status_code=404, detail="选择的接口不存在") # 验证设备地址是否在设备类型的地址范围内 if device.device_type_id: device_type = db.query(models.DeviceType).filter(models.DeviceType.id == device.device_type_id).first() if device_type: if device.device_address < device_type.address_range_start or device.device_address > device_type.address_range_end: raise HTTPException(status_code=400, detail="设备地址超出设备类型的地址范围") # 更新设备信息 for key, value in device.dict().items(): setattr(db_device, key, value) db.commit() db.refresh(db_device) return db_device except HTTPException as e: raise e except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.delete("/api/devices/{device_id}") async def delete_device(device_id: int, db: Session = Depends(get_db)): device = db.query(models.Device).filter(models.Device.id == device_id).first() if device is None: raise HTTPException(status_code=404, detail="设备不存在") db.delete(device) db.commit() return {"message": "设备已删除"} @app.get("/api/serial/ports") async def get_serial_ports() -> List[Dict[str, str]]: """获取可用的串口列表""" ports = [] for port in serial.tools.list_ports.comports(): ports.append({ "value": port.device, "label": f"{port.device} - {port.description}" }) ports.append({ "value": "/dev/ttyAMA0", "label": "/dev/ttyAMA0" }) ports.append({ "value": "/dev/ttyUSB0", "label": "/dev/ttyUSB0" }) ports.append({ "value": "/dev/ttyUSB1", "label": "/dev/ttyUSB1" }) ports.append({ "value": "/dev/ttyPowerbus", "label": "/dev/ttyPowerbus" }) ports.append({ "value": "/dev/ttyModbus", "label": "/dev/ttyModbus" }) return ports # 系统信息缓存 system_info_cache = { "cpu_usage": 0, "memory_usage": 0, "disk_usage": 0, "temperature": 0, "network_info": {}, "last_update": 0 } # 系统信息更新间隔(秒) SYSTEM_INFO_UPDATE_INTERVAL = 30 # 增加到30秒 # EMQX API 客户端 emqx_client = None emqx_client_last_used = 0 EMQX_CLIENT_TIMEOUT = 300 # 5分钟超时 def get_emqx_client(): """获取或创建 EMQX API 客户端""" global emqx_client, emqx_client_last_used current_time = time.time() # 如果客户端不存在或已超时,创建新的客户端 if emqx_client is None or (current_time - emqx_client_last_used) > EMQX_CLIENT_TIMEOUT: if emqx_client is not None: emqx_client.close() emqx_client = httpx.Client( base_url=EMQX_API_BASE, auth=(EMQX_API_KEY, EMQX_API_SECRET), timeout=5.0 # 设置超时时间为5秒 ) emqx_client_last_used = current_time return emqx_client def get_cpu_temperature(): """获取CPU温度""" try: print(sys.platform) if sys.platform == "win32": # Windows系统下获取CPU温度 w = wmi.WMI(namespace="root\OpenHardwareMonitor") temperature_infos = w.Sensor() print(temperature_infos) for sensor in temperature_infos: if sensor.SensorType==u'Temperature' and 'CPU' in sensor.Name: return sensor.Value return 0 else: # Linux系统下获取CPU温度 temp = psutil.sensors_temperatures() if temp and 'cpu_thermal' in temp: return temp['cpu_thermal'][0].current return 0 except Exception as e: print(f"获取CPU温度失败: {e}") return 0 @app.get("/api/system/info") async def get_system_info(db: Session = Depends(get_db)): """获取系统信息""" current_time = time.time() # 获取最新的系统信息记录 system_info = db.query(models.SystemInfo).first() if system_info is None: system_info = models.SystemInfo( cpu_usage=0, memory_usage=0, disk_usage=0, temperature=0, network_info='{}', last_update=0 # 设置初始时间戳为0,确保第一次访问时会更新数据 ) db.add(system_info) db.commit() # 如果缓存未过期,直接返回缓存的数据 if current_time - system_info.last_update < SYSTEM_INFO_UPDATE_INTERVAL: return { "cpu_usage": system_info.cpu_usage, "memory_usage": system_info.memory_usage, "disk_usage": system_info.disk_usage, "temperature": system_info.temperature, "network_info": json.loads(system_info.network_info) } try: # 获取CPU使用率 cpu_usage = psutil.cpu_percent(interval=1) # 获取内存使用率 memory = psutil.virtual_memory() memory_usage = memory.percent # 获取磁盘使用率 disk = psutil.disk_usage('/') disk_usage = disk.percent # 获取CPU温度 temperature = get_cpu_temperature() # 获取网络信息 network_info = {} for interface, addrs in psutil.net_if_addrs().items(): if interface != 'lo': # 排除本地回环接口 network_info[interface] = [] for addr in addrs: if addr.family == socket.AF_INET: # IPv4 network_info[interface].append(addr.address) elif addr.family == socket.AF_INET6: # IPv6 network_info[interface].append(addr.address) # 更新数据库中的系统信息 system_info.cpu_usage = round(cpu_usage, 1) system_info.memory_usage = round(memory_usage, 1) system_info.disk_usage = round(disk_usage, 1) system_info.temperature = round(temperature, 1) system_info.network_info = json.dumps(network_info) system_info.last_update = current_time db.commit() return { "cpu_usage": system_info.cpu_usage, "memory_usage": system_info.memory_usage, "disk_usage": system_info.disk_usage, "temperature": system_info.temperature, "network_info": network_info } except Exception as e: print(f"获取系统信息失败: {e}") # 确保 last_update 不为 None if system_info.last_update is None: system_info.last_update = 0 db.commit() return { "cpu_usage": system_info.cpu_usage or 0, "memory_usage": system_info.memory_usage or 0, "disk_usage": system_info.disk_usage or 0, "temperature": system_info.temperature or 0, "network_info": json.loads(system_info.network_info) if system_info.network_info else {} } @app.get("/api/system/network") async def get_network_info() -> Dict[str, List[Dict[str, Union[str, List[str]]]]]: """获取网络信息""" network_info = [] for interface_name, addresses in psutil.net_if_addrs().items(): interface_addresses = [] for addr in addresses: # 只添加IPv4和IPv6地址 if addr.family in {2, 23}: # 2=IPv4, 23=IPv6 interface_addresses.append(addr.address) if interface_addresses: # 只添加有IP地址的接口 network_info.append({ "name": interface_name, "addresses": interface_addresses }) return {"interfaces": network_info} # 设备类型API @app.get("/api/device-types") async def get_device_types(db: Session = Depends(get_db)): return db.query(models.DeviceType).all() @app.post("/api/device-types") async def create_device_type(device_type: DeviceTypeBase, db: Session = Depends(get_db)): if device_type.address_range_start > device_type.address_range_end: raise HTTPException(status_code=400, detail="地址范围起始值不能大于结束值") if device_type.address_range_start < 0 or device_type.address_range_end > 247: raise HTTPException(status_code=400, detail="地址范围必须在0-247之间") db_device_type = models.DeviceType(**device_type.dict()) db.add(db_device_type) db.commit() db.refresh(db_device_type) return db_device_type @app.get("/api/device-types/{type_id}") async def get_device_type(type_id: int, db: Session = Depends(get_db)): device_type = db.query(models.DeviceType).filter(models.DeviceType.id == type_id).first() if device_type is None: raise HTTPException(status_code=404, detail="设备类型不存在") return device_type @app.put("/api/device-types/{type_id}") async def update_device_type(type_id: int, device_type: DeviceTypeBase, db: Session = Depends(get_db)): db_device_type = db.query(models.DeviceType).filter(models.DeviceType.id == type_id).first() if db_device_type is None: raise HTTPException(status_code=404, detail="设备类型不存在") if device_type.address_range_start > device_type.address_range_end: raise HTTPException(status_code=400, detail="地址范围起始值不能大于结束值") if device_type.address_range_start < 0 or device_type.address_range_end > 247: raise HTTPException(status_code=400, detail="地址范围必须在1-247之间") for key, value in device_type.dict().items(): setattr(db_device_type, key, value) db.commit() db.refresh(db_device_type) return db_device_type @app.delete("/api/device-types/{type_id}") async def delete_device_type(type_id: int, db: Session = Depends(get_db)): device_type = db.query(models.DeviceType).filter(models.DeviceType.id == type_id).first() if device_type is None: raise HTTPException(status_code=404, detail="设备类型不存在") db.delete(device_type) db.commit() return {"message": "设备类型已删除"} # EMQX服务管理API # EMQX_API_BASE = "http://192.168.8.200:18083/api/v5" # EMQX_API_KEY = "c7ad44cbad762a5d" # EMQX_API_SECRET = "iCaijduecUyAfMgfLhLQROcJynurMConLGKyrslxSyE" EMQX_API_BASE = f"http://{BROKER}:18083/api/v5" # EMQX_API_KEY = "10c101073a46a63f" # EMQX_API_SECRET = "i34MDpuD9AHYrmuh5wsx8ZQ6j8haHEzW9B3HZAd6nvwbO" # EMQX_API_KEY = "2bc5f394d6cef6a5" # EMQX_API_SECRET = "cI5r5bxVWsXgWYmreDqa69BwV9APtisHZwTUwAUiWnizK" # EMQX_API_KEY = "dddb9ec4c4ac04a2" # EMQX_API_SECRET = "XQqnA326bVmxndwtFhNc9AURABLXnkh8cI1d9AhZjOiVK" @app.get("/api/services/emqx/status") async def get_emqx_status(): """获取EMQX服务状态""" try: # 使用缓存的客户端 client = get_emqx_client() response = client.get("/nodes") print("EMQX状态", response.status_code, response.text) if response.status_code == 200: nodes = response.json() if nodes and len(nodes) > 0: return { "status": "running", "nodes": nodes } else: return {"status": "stopped", "nodes": []} else: print(f"检查EMQX状态失败: {response.text}") return {"status": "unknown", "nodes": []} except Exception as e: print(f"检查EMQX状态失败: {e}") return {"status": "unknown", "nodes": []} @app.get("/api/services/status") async def get_service_status(service_name: str): """获取服务状态""" return service_status_manager.get_status(service_name) #服务控制API,启动、停止、重启 @app.post("/api/services/control") async def control_service(control_data: dict): """控制服务""" service_name = control_data.get("service_name") command = control_data.get("command") if service_name is None or command is None: raise HTTPException(status_code=400, detail="缺少必要参数") return service_status_manager.control_service(service_name, command) # 接口管理API @app.get("/api/interfaces") async def get_interfaces(db: Session = Depends(get_db)): return db.query(models.Interface).all() @app.post("/api/interfaces") async def create_interface(interface: InterfaceBase, db: Session = Depends(get_db)): # 验证接口类型 if interface.type not in ['CAN', 'Powerbus','Mqtt','Modbus']: raise HTTPException(status_code=400, detail="接口类型必须是 CAN 或 Powerbus 或 Mqtt 或 Modbus") # 验证CAN接口参数 if interface.type == 'CAN': if interface.can_channel is None or interface.can_baud_rate is None: raise HTTPException(status_code=400, detail="CAN接口必须指定通道号和波特率") if interface.port is not None or interface.baud_rate is not None: raise HTTPException(status_code=400, detail="CAN接口不能指定串口和Powerbus波特率") # 验证Powerbus接口参数 elif interface.type == 'Powerbus': if interface.port is None: raise HTTPException(status_code=400, detail="Powerbus接口必须指定串口") if interface.baud_rate is None: raise HTTPException(status_code=400, detail="Powerbus接口必须指定波特率") if interface.baud_rate not in [4800, 9600]: raise HTTPException(status_code=400, detail="Powerbus接口波特率必须是4800或9600") if interface.can_channel is not None or interface.can_baud_rate is not None: raise HTTPException(status_code=400, detail="Powerbus接口不能指定CAN参数") db_interface = models.Interface(**interface.dict()) db.add(db_interface) db.commit() db.refresh(db_interface) return db_interface @app.get("/api/interfaces/{interface_id}") async def get_interface(interface_id: int, db: Session = Depends(get_db)): interface = db.query(models.Interface).filter(models.Interface.id == interface_id).first() if interface is None: raise HTTPException(status_code=404, detail="接口不存在") return interface @app.put("/api/interfaces/{interface_id}") async def update_interface(interface_id: int, interface: InterfaceBase, db: Session = Depends(get_db)): db_interface = db.query(models.Interface).filter(models.Interface.id == interface_id).first() if db_interface is None: raise HTTPException(status_code=404, detail="接口不存在") # 验证接口类型 if interface.type not in ['CAN', 'Powerbus', 'Modbus','Mqtt']: raise HTTPException(status_code=400, detail="接口类型必须是 CAN 或 Powerbus 或 Modbus 或 Mqtt") # 验证CAN接口参数 if interface.type == 'CAN': if interface.can_channel is None or interface.can_baud_rate is None: raise HTTPException(status_code=400, detail="CAN接口必须指定通道号和波特率") if interface.port is not None or interface.baud_rate is not None: raise HTTPException(status_code=400, detail="CAN接口不能指定串口和Powerbus波特率") # 验证Powerbus接口参数 elif interface.type == 'Powerbus': if interface.port is None: raise HTTPException(status_code=400, detail="Powerbus接口必须指定串口") if interface.baud_rate is None: raise HTTPException(status_code=400, detail="Powerbus接口必须指定波特率") if interface.baud_rate not in [4800, 9600]: raise HTTPException(status_code=400, detail="Powerbus接口波特率必须是4800或9600") if interface.can_channel is not None or interface.can_baud_rate is not None: raise HTTPException(status_code=400, detail="Powerbus接口不能指定CAN参数") for key, value in interface.dict().items(): setattr(db_interface, key, value) db.commit() db.refresh(db_interface) return db_interface @app.delete("/api/interfaces/{interface_id}") async def delete_interface(interface_id: int, db: Session = Depends(get_db)): interface = db.query(models.Interface).filter(models.Interface.id == interface_id).first() if interface is None: raise HTTPException(status_code=404, detail="接口不存在") db.delete(interface) db.commit() return {"message": "接口已删除"} # 添加控制设备的 API 端点 @app.post("/api/devices/control") async def control_device(control_data: dict, db: Session = Depends(get_db)): try: print("控制设备", control_data) device_id = control_data.get("device_id") command = control_data.get("command") status = control_data.get("status") print("device_id", device_id) print("command", command) print("status", status) # 修改参数验证逻辑 if device_id is None or command is None or status is None: print("缺少必要参数") raise HTTPException(status_code=400, detail="缺少必要参数") # 检查设备是否存在 device = db.query(models.Device).filter(models.Device.id == device_id).first() if not device: print("设备不存在") raise HTTPException(status_code=404, detail="设备不存在") # 检查设备是否启用 if not device.enabled: print("设备已禁用") raise HTTPException(status_code=400, detail="设备已禁用") # 确保MQTT客户端已连接 if not mqtt_client.is_connected(): try: mqtt_client.connect() except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to connect to MQTT broker: {str(e)}") # 发布控制消息到 MQTT message = { "device_id": str(device_id), "device_code": device.code, "device_address": str(device.device_address), "command": command, "status": status } print("控制消息", message) try: mqtt_client.publish(f"device/control", json.dumps(message)) print(f"已发送控制消息: {message}") return {"message": "控制命令已发送"} except Exception as e: print(f"发送 MQTT 消息失败: {e}") raise HTTPException(status_code=500, detail="发送控制命令失败") except HTTPException: raise except Exception as e: print(f"控制设备时发生错误: {e}") raise HTTPException(status_code=500, detail=str(e)) # 添加控制设备的 API 端点 @app.post("/api/devices/control2") async def control_device(control_data: dict, db: Session = Depends(get_db)): try: print("控制设备", control_data) device_id = control_data.get("device_id") command = control_data.get("command") value = control_data.get("value") print("device_id", device_id) print("command", command) print("value", value) # 修改参数验证逻辑 if device_id is None or command is None or value is None: print("缺少必要参数") raise HTTPException(status_code=400, detail="缺少必要参数") # 检查设备是否存在 device = db.query(models.Device).filter(models.Device.id == device_id).first() if not device: print("设备不存在") raise HTTPException(status_code=404, detail="设备不存在") # 检查设备是否启用 if not device.enabled: print("设备已禁用") raise HTTPException(status_code=400, detail="设备已禁用") # 确保MQTT客户端已连接 if not mqtt_client.is_connected(): try: mqtt_client.connect() except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to connect to MQTT broker: {str(e)}") # 发布控制消息到 MQTT message = { "device_id": str(device_id), "device_code": device.code, "device_address": str(device.device_address), "command": command, "value": value } print("控制消息", message) try: mqtt_client.publish(f"device/control", json.dumps(message)) print(f"已发送控制消息: {message}") return {"message": "控制命令已发送"} except Exception as e: print(f"发送 MQTT 消息失败: {e}") raise HTTPException(status_code=500, detail="发送控制命令失败") except HTTPException: raise except Exception as e: print(f"控制设备时发生错误: {e}") raise HTTPException(status_code=500, detail=str(e)) # 电源控制API - 控制HVS和Scanner的供电 @app.post("/api/powerctrl") async def power_control(power_data: dict): """ 控制HVS和Scanner的供电 参数: - device: 设备名称,可选值: 'hvs' 或 'scanner' - action: 操作,可选值: 'on' (打开) 或 'off' (关闭) 或 'status' (查询状态) """ try: device = power_data.get("device") action = power_data.get("action") if device is None or action is None: raise HTTPException(status_code=400, detail="缺少必要参数: device 和 action") # 验证设备类型 if device not in ['hvs', 'scanner']: raise HTTPException(status_code=400, detail="device 必须是 'hvs' 或 'scanner'") # 验证操作类型 if action not in ['on', 'off', 'status']: raise HTTPException(status_code=400, detail="action 必须是 'on'、'off' 或 'status'") # 定义GPIO引脚映射 gpio_pins = { 'hvs': 26, 'scanner': 17 } pin = gpio_pins[device] if action == 'status': # 查询状态 result = subprocess.run( ['pinctrl', 'get', str(pin)], capture_output=True, text=True ) if result.returncode != 0: return {"device": device, "status": "unknown", "error": result.stderr} output = result.stdout.strip() # 解析状态: "17: op dl pn | lo" 表示输出低电平(打开) # "17: op dh pn | hi" 表示输出高电平(关闭) if 'dl' in output or 'lo' in output.lower(): status = 'on' elif 'dh' in output or 'hi' in output.lower(): status = 'off' else: status = 'unknown' return {"device": device, "status": status, "raw_output": output} elif action == 'on': # 打开供电: pinctrl set op pn dl result = subprocess.run( ['pinctrl', 'set', str(pin), 'op', 'pn', 'dl'], capture_output=True, text=True ) if result.returncode != 0: raise HTTPException(status_code=500, detail=f"执行失败: {result.stderr}") return {"device": device, "action": action, "status": "success"} elif action == 'off': # 关闭供电: pinctrl set op pn dh result = subprocess.run( ['pinctrl', 'set', str(pin), 'op', 'pn', 'dh'], capture_output=True, text=True ) if result.returncode != 0: raise HTTPException(status_code=500, detail=f"执行失败: {result.stderr}") return {"device": device, "action": action, "status": "success"} except HTTPException: raise except Exception as e: print(f"电源控制时发生错误: {e}") raise HTTPException(status_code=500, detail=str(e)) # 扫描控制API - 控制Scanner的启动与停止 @app.post("/api/scanctrl") async def scan_control(scan_data: dict): """ 控制Scanner的启动与停止 参数: - action: 操作,可选值: 'start' (启动) 或 'stop' (停止) """ try: action = scan_data.get("action") # 验证操作类型 if action not in ['start', 'stop']: raise HTTPException(status_code=400, detail="action 必须是 'start' 或 'stop'") try: path = "/home/admin/.config/cpy/config.json" with open(path, "r") as f: config = json.load(f) sn = config.get('sn', "") if sn == "": raise HTTPException(status_code=400, detail="配置文件中缺少 sn 字段") except FileNotFoundError: raise HTTPException(status_code=400, detail="配置文件不存在") mqtt_client.publish(f"v1/cpy/{sn}/control", json.dumps({"method": "scan_control", "action": action})) return {"action": action, "status": "success"} except HTTPException: raise except Exception as e: print(f"扫描控制时发生错误: {e}") raise HTTPException(status_code=500, detail=str(e))