Initial commit: 上传完整代码

This commit is contained in:
2026-06-19 20:47:06 +08:00
commit 78b5898da2
71 changed files with 8767 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
# 这个文件使 backend 目录成为一个 Python 包
+8
View File
@@ -0,0 +1,8 @@
BROKER = "127.0.0.1"
USER = "test"
PWD = "test"
PORT = 1883
# EMQX_API_KEY = "5423e75c67920883"
# EMQX_API_SECRET = "iZcgvxXAU3xGqt9Ca8DvVIWYnyj0WzYgfSFctRTpARfC"
EMQX_API_KEY = "79df0d17e0a8d2e8"
EMQX_API_SECRET = "9Aaz8KuCxj0wjh7zMYzMioGyT5henEfSBJbx7K7hcFHO"
+90
View File
@@ -0,0 +1,90 @@
from sqlalchemy import create_engine, Column, Integer, String, Float, ForeignKey, DateTime, Boolean, JSON, inspect
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
import os
import sqlite3
import json
# 创建数据库引擎
SQLALCHEMY_DATABASE_URL = "sqlite:///./cpy_admin.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 创建基类
Base = declarative_base()
# 获取数据库会话
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def backup_data():
"""备份数据库中的数据"""
if not os.path.exists("cpy_admin.db"):
return {}
conn = sqlite3.connect("cpy_admin.db")
cursor = conn.cursor()
# 获取所有表的数据
tables_data = {}
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
for table in tables:
table_name = table[0]
cursor.execute(f"SELECT * FROM {table_name}")
columns = [description[0] for description in cursor.description]
rows = cursor.fetchall()
tables_data[table_name] = [dict(zip(columns, row)) for row in rows]
conn.close()
return tables_data
def restore_data(tables_data):
"""恢复数据到数据库"""
conn = sqlite3.connect("cpy_admin.db")
cursor = conn.cursor()
for table_name, rows in tables_data.items():
if not rows:
continue
columns = rows[0].keys()
placeholders = ','.join(['?' for _ in columns])
insert_sql = f"INSERT INTO {table_name} ({','.join(columns)}) VALUES ({placeholders})"
for row in rows:
values = [row[col] for col in columns]
cursor.execute(insert_sql, values)
conn.commit()
conn.close()
# 创建数据库表
def create_tables():
# 检查数据库文件是否存在
db_exists = os.path.exists("cpy_admin.db")
# 如果数据库存在,备份数据
if db_exists:
tables_data = backup_data()
# 删除数据库文件
os.remove("cpy_admin.db")
# 创建所有表
Base.metadata.create_all(bind=engine)
print("数据库表已创建")
# 如果之前有数据,恢复数据
if db_exists:
restore_data(tables_data)
print("数据已恢复")
+36
View File
@@ -0,0 +1,36 @@
from datetime import datetime
from typing import Dict, Any, Optional
class DeviceStatusManager:
def __init__(self):
self._status: Dict[int, Dict[str, Any]] = {}
self._last_update: Dict[int, datetime] = {}
def update_status(self, device_id: int, status: Dict[str, Any]) -> None:
"""更新设备状态"""
self._status[device_id] = status
self._last_update[device_id] = datetime.utcnow()
def get_status(self, device_code: str) -> Optional[Dict[str, Any]]:
"""获取设备状态"""
status = self._status.get(device_code)
if status:
tim = self.get_last_update(device_code)
# 如果最后更新时间大于1分钟,则认为设备离线
if tim:
if (datetime.utcnow() - tim).total_seconds() > 60:
status["online"] = False
else:
return status
else:
return {}
else:
return {}
def get_last_update(self, device_code: str) -> Optional[datetime]:
"""获取设备最后更新时间"""
return self._last_update.get(device_code)
# 创建全局状态管理器实例
device_status_manager = DeviceStatusManager()
+695
View File
@@ -0,0 +1,695 @@
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))
+35
View File
@@ -0,0 +1,35 @@
from database import Base, engine, backup_data, restore_data
from models.device import Device
from models.device_type import DeviceType
from models.interface import Interface
from models.register import Register
from models.system_info import SystemInfo
import os
def migrate():
# 检查数据库文件是否存在
db_exists = os.path.exists("cpy_admin.db")
# 如果数据库存在,备份数据
if db_exists:
print("正在备份数据...")
tables_data = backup_data()
print("数据备份完成")
# 删除旧表
print("正在删除旧表...")
Base.metadata.drop_all(engine)
# 创建新表
print("正在创建新表...")
Base.metadata.create_all(engine)
print("新表创建完成")
# 如果之前有数据,恢复数据
if db_exists:
print("正在恢复数据...")
restore_data(tables_data)
print("数据恢复完成")
if __name__ == "__main__":
migrate()
+56
View File
@@ -0,0 +1,56 @@
from sqlalchemy import create_engine, text
import json
import os
# 数据库连接配置
DATABASE_URL = "sqlite:///./cpy_admin.db" # 修改为正确的数据库文件名
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
def backup_data():
"""备份现有数据"""
if not os.path.exists("cpy_admin.db"): # 检查数据库文件是否存在
print("数据库文件不存在,跳过备份")
return []
with engine.connect() as conn:
result = conn.execute(text("SELECT id FROM devices"))
devices = []
for row in result:
devices.append({"id": row[0]})
return devices
def migrate():
"""执行迁移"""
try:
# 备份现有数据
devices = backup_data()
with engine.connect() as conn:
try:
# 添加 enabled 列
conn.execute(text("ALTER TABLE devices ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT 1"))
conn.commit()
print("已添加 enabled 字段")
# 恢复数据
for device in devices:
conn.execute(
text("UPDATE devices SET enabled = :enabled WHERE id = :id"),
{"enabled": True, "id": device['id']}
)
conn.commit()
print("已更新现有设备的 enabled 状态")
except Exception as e:
if "duplicate column name" in str(e).lower():
print("enabled 字段已存在,跳过添加")
else:
raise e
except Exception as e:
print(f"迁移过程中出错: {str(e)}")
return
if __name__ == "__main__":
migrate()
print("迁移完成")
+12
View File
@@ -0,0 +1,12 @@
from .device_type import DeviceType
from .interface import Interface
from .device import Device
from .system_info import SystemInfo
# 导出所有模型
__all__ = [
'DeviceType',
'Interface',
'Device',
'SystemInfo'
]
+9
View File
@@ -0,0 +1,9 @@
from sqlalchemy import Column, Integer, DateTime
from datetime import datetime
from database import Base
class BaseModel(Base):
__abstract__ = True
id = Column(Integer, primary_key=True, index=True)
created_at = Column(DateTime, default=datetime.utcnow)
+40
View File
@@ -0,0 +1,40 @@
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, JSON, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime
from database import Base
class Device(Base):
__tablename__ = "devices"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
code = Column(String, nullable=False, unique=True)
device_address = Column(Integer, nullable=False)
device_type_id = Column(Integer, ForeignKey("device_types.id"), nullable=True)
interface_id = Column(Integer, ForeignKey("interfaces.id"), nullable=True)
enabled = Column(Boolean, nullable=False, default=True)
status = Column(JSON, nullable=True, default=dict)
last_update = Column(DateTime, nullable=True)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
# 关系
device_type = relationship("DeviceType", back_populates="devices")
interface = relationship("Interface", back_populates="devices")
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"code": self.code,
"device_address": self.device_address,
"device_type_id": self.device_type_id,
"interface_id": self.interface_id,
"enabled": self.enabled,
"status": self.status,
"last_update": self.last_update.isoformat() if self.last_update else None,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
"device_type": self.device_type.to_dict() if self.device_type else None,
"interface": self.interface.to_dict() if self.interface else None
}
+27
View File
@@ -0,0 +1,27 @@
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import relationship
from .base import BaseModel
class DeviceType(BaseModel):
__tablename__ = "device_types"
name = Column(String, index=True)
code = Column(String, unique=True)
address_range_start = Column(Integer)
address_range_end = Column(Integer)
chip_model = Column(String)
description = Column(String, nullable=True)
# 关系
devices = relationship("Device", back_populates="device_type")
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"code": self.code,
"address_range_start": self.address_range_start,
"address_range_end": self.address_range_end,
"chip_model": self.chip_model,
"description": self.description
}
+29
View File
@@ -0,0 +1,29 @@
from sqlalchemy import Column, String, Integer, JSON
from sqlalchemy.orm import relationship
from .base import BaseModel
class Interface(BaseModel):
__tablename__ = "interfaces"
name = Column(String, index=True)
type = Column(String) # 'CAN' 或 'Powerbus'
description = Column(String, nullable=True)
port = Column(String, nullable=True)
baud_rate = Column(Integer, nullable=True)
can_channel = Column(Integer, nullable=True)
can_baud_rate = Column(Integer, nullable=True)
# 关系
devices = relationship("Device", back_populates="interface")
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"type": self.type,
"description": self.description,
"port": self.port,
"baud_rate": self.baud_rate,
"can_channel": self.can_channel,
"can_baud_rate": self.can_baud_rate
}
+15
View File
@@ -0,0 +1,15 @@
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship
from .base import BaseModel
class Register(BaseModel):
__tablename__ = "registers"
address = Column(Integer)
function_code = Column(String)
name = Column(String)
description = Column(String, nullable=True)
device_id = Column(Integer, ForeignKey("devices.id"))
# 关系
device = relationship("Device", back_populates="registers")
+12
View File
@@ -0,0 +1,12 @@
from sqlalchemy import Column, Float, String
from .base import BaseModel
class SystemInfo(BaseModel):
__tablename__ = "system_info"
cpu_usage = Column(Float)
memory_usage = Column(Float)
disk_usage = Column(Float)
temperature = Column(Float)
network_info = Column(String) # JSON 字符串
last_update = Column(Float)
+188
View File
@@ -0,0 +1,188 @@
import socket
from threading import Timer
import paho.mqtt.client as mqtt
import json
import threading
import paho.mqtt.client as mqtt
from config import *
# 确保config.py中包含MQTT_USERNAME和MQTT_PASSWORD配置
from datetime import datetime
from device_status import device_status_manager
from service_status import service_status_manager
import time
from database import get_db
import models
from sqlalchemy.orm import joinedload
class MQTTClient:
def __init__(self):
self.client = mqtt.Client(client_id = 'backend_' + self.random_string(6)) # 创建本地客户端
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.on_disconnect = self.on_disconnect
self.connected = False
self.reconnect_delay = 1
self.max_reconnect_delay = 60
def random_string(self, length=6):
import random
import string
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def is_connected(self):
return self.connected
def publish(self, topic, payload):
try:
self.client.publish(topic, payload)
except Exception as e:
print(f"发送 MQTT 消息失败: {e}")
self.schedule_reconnect()
def checkLocalServer(self):
host = '127.0.0.1'
port = 1883
timeout = 1
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
result = sock.connect_ex((host, port))
if result == 0:
return True
else:
return False
except Exception as e:
print(e)
return False
finally:
sock.close()
def connTimerHandler(self):
print("mqtt conn timer handler")
if self.checkLocalServer():
print("local mqtt broker is ready")
self.__connect()
else:
print("local mqtt brokeris not ready")
Timer(1, self.connTimerHandler).start()
def connect(self):
Timer(1, self.connTimerHandler).start()
def __connect(self):
try:
self.client.username_pw_set(username=USER,password=PWD)
self.client.connect(BROKER, PORT, 60)
self.client.loop_start()
print("MQTT 客户端已启动")
except Exception as e:
print(f"MQTT 连接失败: {e}")
self.schedule_reconnect()
def disconnect(self):
self.client.loop_stop()
self.client.disconnect()
self.connected = False
print("MQTT 客户端已停止")
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
self.connected = True
self.reconnect_delay = 1
print("MQTT 已连接")
self.client.subscribe("device/status")
self.client.subscribe("service/status")
self.client.subscribe("api/devices/#")
self.client.subscribe("api/interfaces")
else:
print(f"MQTT 连接失败,错误码: {rc}")
self.schedule_reconnect()
def on_disconnect(self, client, userdata, rc):
self.connected = False
print("MQTT 已断开连接")
self.schedule_reconnect()
def update_device_status(self, device_code, status):
device_status_manager.update_status(device_code, status)
def on_message(self, client, userdata, msg):
try:
topic = msg.topic
payload = json.loads(msg.payload.decode())
if topic.startswith("api/devices"):
print(f"接收到 MQTT 消息: {topic} - {payload}")
# 验证payload是否为字典类型
if not (isinstance(payload, dict) or isinstance(payload, list)):
print("payload", payload)
print(f"MQTT消息格式错误: 预期字典类型, 实际为{type(payload)}")
print(f"MQTT消息内容: {json.dumps(payload)}")
return
# print(f"接收到 MQTT 消息: {topic} - {payload}")
if topic == "device/status":
if isinstance(payload, list):
for item in payload:
device_code = item.get("device_code")
status = item.get("status", {})
if device_code is not None:
self.update_device_status(device_code, status)
else:
device_code = payload.get("device_code")
status = payload.get("status", {})
if device_code is not None:
self.update_device_status(device_code, status)
print(f"设备 {device_code} 状态已更新: {status}")
elif topic == "service/status":
service_name = payload.get("service_name")
status = payload.get("status", {})
if service_name is not None:
service_status_manager.update_status(service_name, status)
# print(f"服务 {service_name} 状态已更新: {status}")
elif topic == "api/interfaces":
print("接收到接口请求")
db = next(get_db())
interfaces = db.query(models.Interface).all()
print(f"查询到接口: {interfaces}")
self.publish("api/interfaces/response", json.dumps([interface.to_dict() for interface in interfaces]))
db.close()
except Exception as e:
print(f"处理 MQTT 消息时出错: {e}")
def schedule_reconnect(self):
if not self.connected:
print(f"尝试重新连接 MQTT,延迟: {self.reconnect_delay} 秒")
def attempt_reconnect():
self.client.loop_stop()
# 确保重连时重新设置用户名密码
self.client.username_pw_set(username=USER, password=PWD)
# 等待延迟时间后再重连
time.sleep(self.reconnect_delay)
try:
self.client.connect(BROKER, PORT, 60)
self.client.loop_start()
print("MQTT 重连已启动")
except Exception as e:
print(f"重连失败: {e}")
# 重连失败后,启动新的重连尝试
self.reconnect_delay = min(self.reconnect_delay * 2, self.max_reconnect_delay)
threading.Timer(self.reconnect_delay, attempt_reconnect).start()
# 在单独的线程中执行重连,避免阻塞主线程
threading.Thread(target=attempt_reconnect).start()
def ensure_connected(self):
"""确保 MQTT 客户端已连接"""
if not self.connected:
print("MQTT 未连接,尝试重新连接")
self.connect()
# 等待连接完成
time.sleep(1)
return self.connected
# 创建全局 MQTT 客户端实例
mqtt_client = MQTTClient()
+576
View File
@@ -0,0 +1,576 @@
{
"name": "backend",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"@fortawesome/fontawesome-free": "^6.7.2",
"element-plus": "^2.9.7",
"vue-router": "^4.5.0"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.25.9",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz",
"integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.25.9",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz",
"integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.26.10",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.10.tgz",
"integrity": "sha512-6aQR2zGE/QFi8JpDLjUZEPYOs7+mhKXm86VaKFiLP35JQwQb6bwUE+XbvkH0EptsYhbNBSUGaUBLKqxH1xSgsA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/types": "^7.26.10"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.26.10",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.10.tgz",
"integrity": "sha512-emqcG3vHrpxUKTrxcblR36dcrcoRDvKmnL/dCL6ZsHaShW80qxCAcNhzQZrpeM765VzEos+xOi4s+r4IXzTwdQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/helper-string-parser": "^7.25.9",
"@babel/helper-validator-identifier": "^7.25.9"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@ctrl/tinycolor": {
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-3.6.1.tgz",
"integrity": "sha512-SITSV6aIXsuVNV3f3O0f2n/cgyEDWoSqtZMYiAmcsYHydcKrOz3gUxB/iXd/Qf08+IZX4KpgNbvUdMBmWz+kcA==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/@element-plus/icons-vue": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@element-plus/icons-vue/-/icons-vue-2.3.1.tgz",
"integrity": "sha512-XxVUZv48RZAd87ucGS48jPf6pKu0yV5UCg9f4FFwtrYxXOwWuVJo6wOvSLKEoMQKjv8GsX/mhP6UsC1lRwbUWg==",
"license": "MIT",
"peerDependencies": {
"vue": "^3.2.0"
}
},
"node_modules/@floating-ui/core": {
"version": "1.6.9",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.9.tgz",
"integrity": "sha512-uMXCuQ3BItDUbAMhIXw7UPXRfAlOAvZzdK9BWpE60MCn+Svt3aLn9jsPTi/WNGlRUu2uI0v5S7JiIUsbsvh3fw==",
"license": "MIT",
"dependencies": {
"@floating-ui/utils": "^0.2.9"
}
},
"node_modules/@floating-ui/dom": {
"version": "1.6.13",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.13.tgz",
"integrity": "sha512-umqzocjDgNRGTuO7Q8CU32dkHkECqI8ZdMZ5Swb6QAM0t5rnlrN3lGo1hdpscRd3WS8T6DKYK4ephgIH9iRh3w==",
"license": "MIT",
"dependencies": {
"@floating-ui/core": "^1.6.0",
"@floating-ui/utils": "^0.2.9"
}
},
"node_modules/@floating-ui/utils": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.9.tgz",
"integrity": "sha512-MDWhGtE+eHw5JW7lq4qhc5yRLS11ERl1c7Z6Xd0a58DozHES6EnNNwUWbMiG4J9Cgj053Bhk8zvlhFYKVhULwg==",
"license": "MIT"
},
"node_modules/@fortawesome/fontawesome-free": {
"version": "6.7.2",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-6.7.2.tgz",
"integrity": "sha512-JUOtgFW6k9u4Y+xeIaEiLr3+cjoUPiAuLXoyKOJSia6Duzb7pq+A76P9ZdPDoAoxHdHzq6gE9/jKBGXlZT8FbA==",
"license": "(CC-BY-4.0 AND OFL-1.1 AND MIT)",
"engines": {
"node": ">=6"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz",
"integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==",
"license": "MIT",
"peer": true
},
"node_modules/@popperjs/core": {
"name": "@sxzz/popperjs-es",
"version": "2.11.7",
"resolved": "https://registry.npmjs.org/@sxzz/popperjs-es/-/popperjs-es-2.11.7.tgz",
"integrity": "sha512-Ccy0NlLkzr0Ex2FKvh2X+OyERHXJ88XJ1MXtsI9y9fGexlaXaVTPzBCRBwIxFkORuOb+uBqeu+RqnpgYTEZRUQ==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@types/lodash": {
"version": "4.17.16",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.16.tgz",
"integrity": "sha512-HX7Em5NYQAXKW+1T+FiuG27NGwzJfCX3s1GjOa7ujxZa52kjJLOr4FUxT+giF6Tgxv1e+/czV/iTtBw27WTU9g==",
"license": "MIT"
},
"node_modules/@types/lodash-es": {
"version": "4.17.12",
"resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz",
"integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
"license": "MIT",
"dependencies": {
"@types/lodash": "*"
}
},
"node_modules/@types/web-bluetooth": {
"version": "0.0.16",
"resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.16.tgz",
"integrity": "sha512-oh8q2Zc32S6gd/j50GowEjKLoOVOwHP/bWVjKJInBwQqdOYMdPrf1oVlelTlyfFK3CKxL1uahMDAr+vy8T7yMQ==",
"license": "MIT"
},
"node_modules/@vue/compiler-core": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.13.tgz",
"integrity": "sha512-oOdAkwqUfW1WqpwSYJce06wvt6HljgY3fGeM9NcVA1HaYOij3mZG9Rkysn0OHuyUAGMbEbARIpsG+LPVlBJ5/Q==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/parser": "^7.25.3",
"@vue/shared": "3.5.13",
"entities": "^4.5.0",
"estree-walker": "^2.0.2",
"source-map-js": "^1.2.0"
}
},
"node_modules/@vue/compiler-dom": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.13.tgz",
"integrity": "sha512-ZOJ46sMOKUjO3e94wPdCzQ6P1Lx/vhp2RSvfaab88Ajexs0AHeV0uasYhi99WPaogmBlRHNRuly8xV75cNTMDA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-core": "3.5.13",
"@vue/shared": "3.5.13"
}
},
"node_modules/@vue/compiler-sfc": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.13.tgz",
"integrity": "sha512-6VdaljMpD82w6c2749Zhf5T9u5uLBWKnVue6XWxprDobftnletJ8+oel7sexFfM3qIxNmVE7LSFGTpv6obNyaQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/parser": "^7.25.3",
"@vue/compiler-core": "3.5.13",
"@vue/compiler-dom": "3.5.13",
"@vue/compiler-ssr": "3.5.13",
"@vue/shared": "3.5.13",
"estree-walker": "^2.0.2",
"magic-string": "^0.30.11",
"postcss": "^8.4.48",
"source-map-js": "^1.2.0"
}
},
"node_modules/@vue/compiler-ssr": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.13.tgz",
"integrity": "sha512-wMH6vrYHxQl/IybKJagqbquvxpWCuVYpoUJfCqFZwa/JY1GdATAQ+TgVtgrwwMZ0D07QhA99rs/EAAWfvG6KpA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.13",
"@vue/shared": "3.5.13"
}
},
"node_modules/@vue/devtools-api": {
"version": "6.6.4",
"resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
"license": "MIT"
},
"node_modules/@vue/reactivity": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.13.tgz",
"integrity": "sha512-NaCwtw8o48B9I6L1zl2p41OHo/2Z4wqYGGIK1Khu5T7yxrn+ATOixn/Udn2m+6kZKB/J7cuT9DbWWhRxqixACg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/shared": "3.5.13"
}
},
"node_modules/@vue/runtime-core": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.13.tgz",
"integrity": "sha512-Fj4YRQ3Az0WTZw1sFe+QDb0aXCerigEpw418pw1HBUKFtnQHWzwojaukAs2X/c9DQz4MQ4bsXTGlcpGxU/RCIw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/reactivity": "3.5.13",
"@vue/shared": "3.5.13"
}
},
"node_modules/@vue/runtime-dom": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.13.tgz",
"integrity": "sha512-dLaj94s93NYLqjLiyFzVs9X6dWhTdAlEAciC3Moq7gzAc13VJUdCnjjRurNM6uTLFATRHexHCTu/Xp3eW6yoog==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/reactivity": "3.5.13",
"@vue/runtime-core": "3.5.13",
"@vue/shared": "3.5.13",
"csstype": "^3.1.3"
}
},
"node_modules/@vue/server-renderer": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.13.tgz",
"integrity": "sha512-wAi4IRJV/2SAW3htkTlB+dHeRmpTiVIK1OGLWV1yeStVSebSQQOwGwIq0D3ZIoBj2C2qpgz5+vX9iEBkTdk5YA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-ssr": "3.5.13",
"@vue/shared": "3.5.13"
},
"peerDependencies": {
"vue": "3.5.13"
}
},
"node_modules/@vue/shared": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.13.tgz",
"integrity": "sha512-/hnE/qP5ZoGpol0a5mDi45bOd7t3tjYJBjsgCsivow7D48cJeV5l05RD82lPqi7gRiphZM37rnhW1l6ZoCNNnQ==",
"license": "MIT",
"peer": true
},
"node_modules/@vueuse/core": {
"version": "9.13.0",
"resolved": "https://registry.npmjs.org/@vueuse/core/-/core-9.13.0.tgz",
"integrity": "sha512-pujnclbeHWxxPRqXWmdkKV5OX4Wk4YeK7wusHqRwU0Q7EFusHoqNA/aPhB6KCh9hEqJkLAJo7bb0Lh9b+OIVzw==",
"license": "MIT",
"dependencies": {
"@types/web-bluetooth": "^0.0.16",
"@vueuse/metadata": "9.13.0",
"@vueuse/shared": "9.13.0",
"vue-demi": "*"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@vueuse/core/node_modules/vue-demi": {
"version": "0.14.10",
"resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz",
"integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==",
"hasInstallScript": true,
"license": "MIT",
"bin": {
"vue-demi-fix": "bin/vue-demi-fix.js",
"vue-demi-switch": "bin/vue-demi-switch.js"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^3.0.0-0 || ^2.6.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/@vueuse/metadata": {
"version": "9.13.0",
"resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-9.13.0.tgz",
"integrity": "sha512-gdU7TKNAUVlXXLbaF+ZCfte8BjRJQWPCa2J55+7/h+yDtzw3vOoGQDRXzI6pyKyo6bXFT5/QoPE4hAknExjRLQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@vueuse/shared": {
"version": "9.13.0",
"resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-9.13.0.tgz",
"integrity": "sha512-UrnhU+Cnufu4S6JLCPZnkWh0WwZGUp72ktOF2DFptMlOs3TOdVv8xJN53zhHGARmVOsz5KqOls09+J1NR6sBKw==",
"license": "MIT",
"dependencies": {
"vue-demi": "*"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@vueuse/shared/node_modules/vue-demi": {
"version": "0.14.10",
"resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz",
"integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==",
"hasInstallScript": true,
"license": "MIT",
"bin": {
"vue-demi-fix": "bin/vue-demi-fix.js",
"vue-demi-switch": "bin/vue-demi-switch.js"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^3.0.0-0 || ^2.6.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/async-validator": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/async-validator/-/async-validator-4.2.5.tgz",
"integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
"license": "MIT",
"peer": true
},
"node_modules/dayjs": {
"version": "1.11.13",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz",
"integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==",
"license": "MIT"
},
"node_modules/element-plus": {
"version": "2.9.7",
"resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.9.7.tgz",
"integrity": "sha512-6vjZh5SXBncLhUwJGTVKS5oDljfgGMh6J4zVTeAZK3YdMUN76FgpvHkwwFXocpJpMbii6rDYU3sgie64FyPerQ==",
"license": "MIT",
"dependencies": {
"@ctrl/tinycolor": "^3.4.1",
"@element-plus/icons-vue": "^2.3.1",
"@floating-ui/dom": "^1.0.1",
"@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.7",
"@types/lodash": "^4.14.182",
"@types/lodash-es": "^4.17.6",
"@vueuse/core": "^9.1.0",
"async-validator": "^4.2.5",
"dayjs": "^1.11.13",
"escape-html": "^1.0.3",
"lodash": "^4.17.21",
"lodash-es": "^4.17.21",
"lodash-unified": "^1.0.2",
"memoize-one": "^6.0.0",
"normalize-wheel-es": "^1.2.0"
},
"peerDependencies": {
"vue": "^3.2.0"
}
},
"node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"license": "BSD-2-Clause",
"peer": true,
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/estree-walker": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
"license": "MIT",
"peer": true
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"license": "MIT"
},
"node_modules/lodash-es": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
"license": "MIT"
},
"node_modules/lodash-unified": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/lodash-unified/-/lodash-unified-1.0.3.tgz",
"integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==",
"license": "MIT",
"peerDependencies": {
"@types/lodash-es": "*",
"lodash": "*",
"lodash-es": "*"
}
},
"node_modules/magic-string": {
"version": "0.30.17",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
"integrity": "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0"
}
},
"node_modules/memoize-one": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-6.0.0.tgz",
"integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==",
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
"integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"peer": true,
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/normalize-wheel-es": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz",
"integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==",
"license": "BSD-3-Clause"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC",
"peer": true
},
"node_modules/postcss": {
"version": "8.5.3",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.3.tgz",
"integrity": "sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"license": "BSD-3-Clause",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/vue": {
"version": "3.5.13",
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.13.tgz",
"integrity": "sha512-wmeiSMxkZCSc+PM2w2VRsOYAZC8GdipNFRTsLSfodVqI9mbejKeXEGr8SckuLnrQPGe3oJN5c3K0vpoU9q/wCQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.13",
"@vue/compiler-sfc": "3.5.13",
"@vue/runtime-dom": "3.5.13",
"@vue/server-renderer": "3.5.13",
"@vue/shared": "3.5.13"
},
"peerDependencies": {
"typescript": "*"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/vue-router": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.5.0.tgz",
"integrity": "sha512-HDuk+PuH5monfNuY+ct49mNmkCRK4xJAV9Ts4z9UFc4rzdDnxQLyCMGGc8pKhZhHTVzfanpNwB/lwqevcBwI4w==",
"license": "MIT",
"dependencies": {
"@vue/devtools-api": "^6.6.4"
},
"funding": {
"url": "https://github.com/sponsors/posva"
},
"peerDependencies": {
"vue": "^3.2.0"
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"dependencies": {
"@fortawesome/fontawesome-free": "^6.7.2",
"element-plus": "^2.9.7",
"vue-router": "^4.5.0"
}
}
+24
View File
@@ -0,0 +1,24 @@
annotated-types==0.7.0
anyio==4.9.0
certifi==2025.1.31
click==8.1.8
colorama==0.4.6
fastapi==0.115.12
greenlet==3.1.1
h11==0.14.0
httpcore==1.0.7
httpx==0.28.1
idna==3.10
paho-mqtt==2.1.0
psutil==7.0.0
pydantic==2.10.6
pydantic_core==2.27.2
pyserial==3.5
python-dotenv==1.0.1
pywin32==310
sniffio==1.3.1
SQLAlchemy==2.0.39
starlette==0.46.1
typing_extensions==4.12.2
uvicorn==0.34.0
WMI==1.5.1
+8
View File
@@ -0,0 +1,8 @@
import os
import signal
import subprocess
import sys
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
+66
View File
@@ -0,0 +1,66 @@
from pydantic import BaseModel
from typing import Optional, List, Union, Dict, Any
from datetime import datetime
class DeviceTypeBase(BaseModel):
name: str
code: str
address_range_start: int
address_range_end: int
chip_model: str
description: Optional[str] = None
class DeviceType(DeviceTypeBase):
id: int
created_at: datetime
class Config:
from_attributes = True
class InterfaceBase(BaseModel):
name: str
type: str
description: Optional[str] = None
port: Optional[str] = None
baud_rate: Optional[int] = None
can_channel: Optional[int] = None
can_baud_rate: Optional[int] = None
class Interface(InterfaceBase):
id: int
created_at: datetime
class Config:
from_attributes = True
class DeviceBase(BaseModel):
name: str
code: str
device_address: int
device_type_id: Optional[int] = None
interface_id: int
enabled: bool = True # 默认启用
class Device(DeviceBase):
id: int
status: Union[str, Dict[str, Any]] = "offline"
last_update: Optional[datetime] = None
created_at: datetime
updated_at: datetime
device_type: Optional[DeviceType] = None
interface: Optional[Interface] = None
class Config:
from_attributes = True
class SystemInfo(BaseModel):
id: int
cpu_usage: float
memory_usage: float
disk_usage: float
temperature: float
network_info: str
last_update: float
class Config:
from_attributes = True
+83
View File
@@ -0,0 +1,83 @@
from datetime import datetime
import subprocess
from typing import Dict, Any, Optional
from config import *
import paho.mqtt.publish as publish
class ServiceStatusManager:
def __init__(self):
self._status: Dict[str, Dict[str, Any]] = {}
self._last_update: Dict[str, datetime] = {}
self.proc = None
def update_status(self, service_name: str, status: Dict[str, Any]) -> None:
"""更新服务状态"""
self._status[service_name] = status
self._last_update[service_name] = datetime.utcnow()
def get_status(self, service_name: str) -> Optional[Dict[str, Any]]:
"""获取服务状态"""
status = self._status.get(service_name)
if status:
tim = self.get_last_update(service_name)
# 如果最后更新时间大于10秒钟,则认为服务不可用
if tim:
if (datetime.utcnow() - tim).total_seconds() > 10:
status["available"] = False
return status
else:
return {
'available': False,
'running_time': 0
}
else:
return {
'available': False,
'running_time': 0
}
def get_last_update(self, service_name: str) -> Optional[datetime]:
"""获取服务最后更新时间"""
return self._last_update.get(service_name)
def get_all_status(self) -> Dict[str, Dict[str, Any]]:
"""获取所有服务状态"""
return self._status
def get_all_last_update(self) -> Dict[str, datetime]:
"""获取所有服务最后更新时间"""
return self._last_update
def control_service(self, service_name: str, command: str) -> Dict[str, Any]:
"""处理服务控制命令"""
if service_name in ["powerbus_service", "motor_service", "modbus_service"]:
service_map = {
"powerbus_service": "powerbus.service",
"motor_service": "scanner.service",
"modbus_service": "hvs.service"
}
systemd_service = service_map[service_name]
else:
return {"status": "error", "message": "无效的服务名称"}
if command == "start":
print(f"启动{service_name}服务")
proc = subprocess.Popen(["systemctl", "start", systemd_service])
return {"status": "success", "message": f"{systemd_service}服务启动成功"}
elif command == "stop":
print(f"停止{service_name}服务")
proc = subprocess.Popen(["systemctl", "stop", systemd_service])
proc.wait()
return {"status": "success", "message": f"{systemd_service}服务停止成功"}
elif command == "restart":
print(f"重启{service_name}服务")
proc = subprocess.Popen(["systemctl", "restart", systemd_service])
proc.wait()
return {"status": "success", "message": f"{systemd_service}服务重启成功"}
else:
return {"status": "error", "message": "无效的命令"}
# 创建全局服务状态管理器实例
service_status_manager = ServiceStatusManager()