Initial commit: 上传完整代码
This commit is contained in:
Executable
+85
@@ -0,0 +1,85 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
env/
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
.env
|
||||
venv/
|
||||
myenv/
|
||||
.venv/
|
||||
|
||||
# Node.js
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Vue.js
|
||||
.DS_Store
|
||||
dist/
|
||||
dist-ssr/
|
||||
coverage/
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea/
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.db-journal
|
||||
devices_backup.json
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# System specific
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
**.vscode
|
||||
*.pid
|
||||
# Project specific
|
||||
backend/migrations/__pycache__/
|
||||
backend/models/__pycache__/
|
||||
frontend/.vite/
|
||||
frontend/coverage/
|
||||
frontend/cypress/videos/
|
||||
frontend/cypress/screenshots/
|
||||
frontend/package-lock.json
|
||||
frontend/package.json
|
||||
frontend/start.bat
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# 这个文件使 backend 目录成为一个 Python 包
|
||||
@@ -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"
|
||||
@@ -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("数据已恢复")
|
||||
@@ -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
@@ -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))
|
||||
@@ -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()
|
||||
@@ -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("迁移完成")
|
||||
@@ -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'
|
||||
]
|
||||
@@ -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)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
Generated
+576
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-free": "^6.7.2",
|
||||
"element-plus": "^2.9.7",
|
||||
"vue-router": "^4.5.0"
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -0,0 +1,31 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
*.json
|
||||
*.ts
|
||||
*.tsbuildinfo
|
||||
@@ -0,0 +1,33 @@
|
||||
# .
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
|
||||
|
||||
## Type Support for `.vue` Imports in TS
|
||||
|
||||
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
|
||||
|
||||
## Customize configuration
|
||||
|
||||
See [Vite Configuration Reference](https://vite.dev/config/).
|
||||
|
||||
## Project Setup
|
||||
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Type-Check, Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>测偏仪管理后台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,244 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { useRoute } from 'vue-router'
|
||||
import {
|
||||
Monitor,
|
||||
Connection,
|
||||
List,
|
||||
Setting,
|
||||
ArrowLeft,
|
||||
ArrowRight
|
||||
} from '@element-plus/icons-vue'
|
||||
|
||||
const systemInfo = ref(null)
|
||||
const networkInfo = ref(null)
|
||||
const isSidebarCollapsed = ref(false)
|
||||
const route = useRoute()
|
||||
|
||||
const currentRoute = computed(() => route.path)
|
||||
const activeMenu = computed(() => route.path)
|
||||
|
||||
const fetchSystemInfo = async () => {
|
||||
try {
|
||||
const response = await axios.get('/system/info')
|
||||
systemInfo.value = response.data
|
||||
} catch (error) {
|
||||
console.error('获取系统信息失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchNetworkInfo = async () => {
|
||||
try {
|
||||
const response = await axios.get('/system/network')
|
||||
networkInfo.value = response.data.interfaces
|
||||
} catch (error) {
|
||||
console.error('获取网络信息失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const getProgressClass = (value: number) => {
|
||||
if (value >= 90) return 'danger'
|
||||
if (value >= 70) return 'warning'
|
||||
return 'normal'
|
||||
}
|
||||
|
||||
const toggleSidebar = () => {
|
||||
isSidebarCollapsed.value = !isSidebarCollapsed.value
|
||||
}
|
||||
|
||||
// 页面加载时获取信息
|
||||
onMounted(() => {
|
||||
fetchSystemInfo()
|
||||
fetchNetworkInfo()
|
||||
// 每30秒更新一次系统信息
|
||||
setInterval(fetchSystemInfo, 30000)
|
||||
// 每60秒更新一次网络信息
|
||||
setInterval(fetchNetworkInfo, 60000)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app-container">
|
||||
<el-container>
|
||||
<el-aside :width="isSidebarCollapsed ? '64px' : '200px'">
|
||||
<div class="logo">
|
||||
<span v-if="!isSidebarCollapsed">树莓派设备管理系统</span>
|
||||
</div>
|
||||
<el-menu
|
||||
:default-active="activeMenu"
|
||||
class="el-menu-vertical"
|
||||
:collapse="isSidebarCollapsed"
|
||||
router
|
||||
>
|
||||
<el-menu-item index="/">
|
||||
<el-icon><Monitor /></el-icon>
|
||||
<template #title>仪表盘</template>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/devices">
|
||||
<el-icon><Connection /></el-icon>
|
||||
<template #title>设备管理</template>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/device-types">
|
||||
<el-icon><List /></el-icon>
|
||||
<template #title>设备类型</template>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/interfaces">
|
||||
<el-icon><List /></el-icon>
|
||||
<template #title>接口管理</template>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/services">
|
||||
<el-icon><Setting /></el-icon>
|
||||
<template #title>服务管理</template>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</el-aside>
|
||||
|
||||
<!-- 主内容区 -->
|
||||
<div class="main-container" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
|
||||
<header class="header">
|
||||
<h1>测偏仪管理后台</h1>
|
||||
</header>
|
||||
<main class="main-content">
|
||||
<div class="content-wrapper">
|
||||
<router-view></router-view>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</el-container>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.app-container {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
background-color: #f5f5f5;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
.el-container {
|
||||
width: 100%;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.el-aside {
|
||||
background-color: #304156;
|
||||
height: 100vh;
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
z-index: 1000;
|
||||
transition: width 0.3s;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
flex: 1;
|
||||
margin-left: 200px;
|
||||
transition: margin-left 0.3s;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.main-container.sidebar-collapsed {
|
||||
margin-left: 64px;
|
||||
}
|
||||
|
||||
.header {
|
||||
background-color: white;
|
||||
padding: 1rem 2rem;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
left: 200px;
|
||||
z-index: 900;
|
||||
transition: left 0.3s;
|
||||
}
|
||||
|
||||
.sidebar-collapsed + .header {
|
||||
left: 64px;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
padding: 2rem;
|
||||
margin-top: 60px;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
max-width: 1200px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
background-color: transparent;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 60px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 20px;
|
||||
background-color: #2b2f3a;
|
||||
color: #fff;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.el-menu {
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 1400px) {
|
||||
.content-wrapper {
|
||||
max-width: 1000px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.content-wrapper {
|
||||
max-width: 800px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.el-aside {
|
||||
position: fixed;
|
||||
height: 100vh;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.main-container.sidebar-collapsed {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.header {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.sidebar-collapsed + .header {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
max-width: 100%;
|
||||
padding: 0 1rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,86 @@
|
||||
/* color palette from <https://github.com/vuejs/theme> */
|
||||
:root {
|
||||
--vt-c-white: #ffffff;
|
||||
--vt-c-white-soft: #f8f8f8;
|
||||
--vt-c-white-mute: #f2f2f2;
|
||||
|
||||
--vt-c-black: #181818;
|
||||
--vt-c-black-soft: #222222;
|
||||
--vt-c-black-mute: #282828;
|
||||
|
||||
--vt-c-indigo: #2c3e50;
|
||||
|
||||
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
|
||||
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
|
||||
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
|
||||
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
|
||||
|
||||
--vt-c-text-light-1: var(--vt-c-indigo);
|
||||
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
|
||||
--vt-c-text-dark-1: var(--vt-c-white);
|
||||
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
|
||||
}
|
||||
|
||||
/* semantic color variables for this project */
|
||||
:root {
|
||||
--color-background: var(--vt-c-white);
|
||||
--color-background-soft: var(--vt-c-white-soft);
|
||||
--color-background-mute: var(--vt-c-white-mute);
|
||||
|
||||
--color-border: var(--vt-c-divider-light-2);
|
||||
--color-border-hover: var(--vt-c-divider-light-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-light-1);
|
||||
--color-text: var(--vt-c-text-light-1);
|
||||
|
||||
--section-gap: 160px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-background: var(--vt-c-black);
|
||||
--color-background-soft: var(--vt-c-black-soft);
|
||||
--color-background-mute: var(--vt-c-black-mute);
|
||||
|
||||
--color-border: var(--vt-c-divider-dark-2);
|
||||
--color-border-hover: var(--vt-c-divider-dark-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-dark-1);
|
||||
--color-text: var(--vt-c-text-dark-2);
|
||||
}
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
color: var(--color-text);
|
||||
background: var(--color-background);
|
||||
transition:
|
||||
color 0.5s,
|
||||
background-color 0.5s;
|
||||
line-height: 1.6;
|
||||
font-family:
|
||||
Inter,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
Oxygen,
|
||||
Ubuntu,
|
||||
Cantarell,
|
||||
'Fira Sans',
|
||||
'Droid Sans',
|
||||
'Helvetica Neue',
|
||||
sans-serif;
|
||||
font-size: 15px;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>
|
||||
|
After Width: | Height: | Size: 276 B |
@@ -0,0 +1,35 @@
|
||||
@import './base.css';
|
||||
|
||||
#app {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
a,
|
||||
.green {
|
||||
text-decoration: none;
|
||||
color: hsla(160, 100%, 37%, 1);
|
||||
transition: 0.4s;
|
||||
padding: 3px;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
a:hover {
|
||||
background-color: hsla(160, 100%, 37%, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
body {
|
||||
display: flex;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
#app {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
padding: 0 2rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
msg: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="greetings">
|
||||
<h1 class="green">{{ msg }}</h1>
|
||||
<h3>
|
||||
You’ve successfully created a project with
|
||||
<a href="https://vite.dev/" target="_blank" rel="noopener">Vite</a> +
|
||||
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
|
||||
</h3>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
h1 {
|
||||
font-weight: 500;
|
||||
font-size: 2.6rem;
|
||||
position: relative;
|
||||
top: -10px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.greetings h1,
|
||||
.greetings h3 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.greetings h1,
|
||||
.greetings h3 {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,94 @@
|
||||
<script setup lang="ts">
|
||||
import WelcomeItem from './WelcomeItem.vue'
|
||||
import DocumentationIcon from './icons/IconDocumentation.vue'
|
||||
import ToolingIcon from './icons/IconTooling.vue'
|
||||
import EcosystemIcon from './icons/IconEcosystem.vue'
|
||||
import CommunityIcon from './icons/IconCommunity.vue'
|
||||
import SupportIcon from './icons/IconSupport.vue'
|
||||
|
||||
const openReadmeInEditor = () => fetch('/__open-in-editor?file=README.md')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<DocumentationIcon />
|
||||
</template>
|
||||
<template #heading>Documentation</template>
|
||||
|
||||
Vue’s
|
||||
<a href="https://vuejs.org/" target="_blank" rel="noopener">official documentation</a>
|
||||
provides you with all information you need to get started.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<ToolingIcon />
|
||||
</template>
|
||||
<template #heading>Tooling</template>
|
||||
|
||||
This project is served and bundled with
|
||||
<a href="https://vite.dev/guide/features.html" target="_blank" rel="noopener">Vite</a>. The
|
||||
recommended IDE setup is
|
||||
<a href="https://code.visualstudio.com/" target="_blank" rel="noopener">VSCode</a>
|
||||
+
|
||||
<a href="https://github.com/johnsoncodehk/volar" target="_blank" rel="noopener">Volar</a>. If
|
||||
you need to test your components and web pages, check out
|
||||
<a href="https://vitest.dev/" target="_blank" rel="noopener">Vitest</a>
|
||||
and
|
||||
<a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a>
|
||||
/
|
||||
<a href="https://playwright.dev/" target="_blank" rel="noopener">Playwright</a>.
|
||||
|
||||
<br />
|
||||
|
||||
More instructions are available in
|
||||
<a href="javascript:void(0)" @click="openReadmeInEditor"><code>README.md</code></a
|
||||
>.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<EcosystemIcon />
|
||||
</template>
|
||||
<template #heading>Ecosystem</template>
|
||||
|
||||
Get official tools and libraries for your project:
|
||||
<a href="https://pinia.vuejs.org/" target="_blank" rel="noopener">Pinia</a>,
|
||||
<a href="https://router.vuejs.org/" target="_blank" rel="noopener">Vue Router</a>,
|
||||
<a href="https://test-utils.vuejs.org/" target="_blank" rel="noopener">Vue Test Utils</a>, and
|
||||
<a href="https://github.com/vuejs/devtools" target="_blank" rel="noopener">Vue Dev Tools</a>. If
|
||||
you need more resources, we suggest paying
|
||||
<a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">Awesome Vue</a>
|
||||
a visit.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<CommunityIcon />
|
||||
</template>
|
||||
<template #heading>Community</template>
|
||||
|
||||
Got stuck? Ask your question on
|
||||
<a href="https://chat.vuejs.org" target="_blank" rel="noopener">Vue Land</a>
|
||||
(our official Discord server), or
|
||||
<a href="https://stackoverflow.com/questions/tagged/vue.js" target="_blank" rel="noopener"
|
||||
>StackOverflow</a
|
||||
>. You should also follow the official
|
||||
<a href="https://bsky.app/profile/vuejs.org" target="_blank" rel="noopener">@vuejs.org</a>
|
||||
Bluesky account or the
|
||||
<a href="https://x.com/vuejs" target="_blank" rel="noopener">@vuejs</a>
|
||||
X account for latest news in the Vue world.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<SupportIcon />
|
||||
</template>
|
||||
<template #heading>Support Vue</template>
|
||||
|
||||
As an independent project, Vue relies on community backing for its sustainability. You can help
|
||||
us by
|
||||
<a href="https://vuejs.org/sponsor/" target="_blank" rel="noopener">becoming a sponsor</a>.
|
||||
</WelcomeItem>
|
||||
</template>
|
||||
@@ -0,0 +1,87 @@
|
||||
<template>
|
||||
<div class="item">
|
||||
<i>
|
||||
<slot name="icon"></slot>
|
||||
</i>
|
||||
<div class="details">
|
||||
<h3>
|
||||
<slot name="heading"></slot>
|
||||
</h3>
|
||||
<slot></slot>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.item {
|
||||
margin-top: 2rem;
|
||||
display: flex;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.details {
|
||||
flex: 1;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
|
||||
i {
|
||||
display: flex;
|
||||
place-items: center;
|
||||
place-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.4rem;
|
||||
color: var(--color-heading);
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.item {
|
||||
margin-top: 0;
|
||||
padding: 0.4rem 0 1rem calc(var(--section-gap) / 2);
|
||||
}
|
||||
|
||||
i {
|
||||
top: calc(50% - 25px);
|
||||
left: -26px;
|
||||
position: absolute;
|
||||
border: 1px solid var(--color-border);
|
||||
background: var(--color-background);
|
||||
border-radius: 8px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
.item:before {
|
||||
content: ' ';
|
||||
border-left: 1px solid var(--color-border);
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: calc(50% + 25px);
|
||||
height: calc(50% - 25px);
|
||||
}
|
||||
|
||||
.item:after {
|
||||
content: ' ';
|
||||
border-left: 1px solid var(--color-border);
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: calc(50% + 25px);
|
||||
height: calc(50% - 25px);
|
||||
}
|
||||
|
||||
.item:first-of-type:before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.item:last-of-type:after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
|
||||
<path
|
||||
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,19 @@
|
||||
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
|
||||
<template>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
aria-hidden="true"
|
||||
role="img"
|
||||
class="iconify iconify--mdi"
|
||||
width="24"
|
||||
height="24"
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
|
||||
fill="currentColor"
|
||||
></path>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,906 @@
|
||||
<template>
|
||||
<div class="device-management">
|
||||
<div class="toolbar">
|
||||
<button class="btn-primary" @click="showAddDeviceDialog = true">
|
||||
<i class="fas fa-plus"></i> 添加设备
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 设备列表 -->
|
||||
<div class="device-list">
|
||||
<div v-for="device in devices" :key="device.id" class="device-card">
|
||||
<div class="device-header">
|
||||
<h3>{{ device.name }}</h3>
|
||||
<div class="device-status-container">
|
||||
<div class="device-enabled" :class="device.enabled ? 'enabled' : 'disabled'">
|
||||
{{ device.enabled ? '已启用' : '已禁用' }}
|
||||
</div>
|
||||
<div class="device-status" :class="typeof device.status === 'object' && device.status.online ? 'online' : 'offline'">
|
||||
{{ typeof device.status === 'object' && device.status.online ? '在线' : '离线' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="device-info">
|
||||
<div class="info-item">
|
||||
<span class="label">代号:</span>
|
||||
<span>{{ device.code }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">设备类型:</span>
|
||||
<span>{{ device.device_type?.name || '未设置' }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">接口:</span>
|
||||
<span>{{ device.interface?.name || '未设置' }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">设备地址:</span>
|
||||
<span>0x{{ device.device_address.toString(16).padStart(2, '0').toUpperCase() }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">状态:</span>
|
||||
<span>
|
||||
<template v-if="typeof device.status === 'object'">
|
||||
<template v-if="device.device_type?.code === 'MTO'">
|
||||
电机状态: {{ device.status.state == 0 ? '正常': (device.status.state == 1 ?'上限位' : '下限位') }}
|
||||
电机位置: {{ device.status.location == 0 ? '未就绪': (device.status.location == 1 ? '上过渡段': (device.status.location == 2 ?'扫描段':'下过渡段') ) }}
|
||||
电机量程: {{ device.status.duration}}
|
||||
电机位置: {{ device.status.position.toFixed(2) }} mm
|
||||
电机速度: {{ device.status.velocity.toFixed(2) }} mm/s
|
||||
电机方向: {{ device.status.velocity < 0 ? '正向': '反向' }} <!-- 设备列表 device.status.direction == 1? '正向': '反向' -->
|
||||
</template>
|
||||
<template v-else-if="device.device_type?.code === 'HVS'">
|
||||
电压: {{ device.status.voltage }} V
|
||||
电流: {{ device.status.current }} A
|
||||
灯丝电流: {{ device.status.current_filament }} A
|
||||
内部温度: {{ device.status.internal_temperature }} ℃
|
||||
故障状态: {{ device.status.fault_status }}
|
||||
开关状态: {{ device.status.switch_status ? '开启' : '关闭' }}
|
||||
</template>
|
||||
<template v-if="device.device_type?.code === 'ALU'">
|
||||
灯光: {{ device.status.light ? '开启' : '关闭' }}
|
||||
</template>
|
||||
<template v-if="device.device_type?.code === 'WSU'">
|
||||
流量: {{ device.status.flow_rate }} L/min
|
||||
水温: {{ device.status.water_temp }} ℃
|
||||
</template>
|
||||
<template v-if="device.device_type?.code === 'OSU'">
|
||||
油温: {{ device.status.oil_temp }} ℃
|
||||
液位: <span :class="getOilLevelClass(device.status.oil_level)">{{ typeof device.status.oil_level === 'number' ? getOilLevelText(device.status.oil_level) : '未知' }}</span>
|
||||
</template>
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ device.status }}
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">最后更新:</span>
|
||||
<span>{{ new Date(device.last_update).toLocaleString() }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="device-actions">
|
||||
<template v-if="device.device_type?.code === 'ALU' || device.device_type?.code === 'HVS'">
|
||||
<el-button
|
||||
type="success"
|
||||
@click="controlDevice(device, true)"
|
||||
>关闭</el-button>
|
||||
<el-button
|
||||
type="warning"
|
||||
@click="controlDevice(device, false)"
|
||||
>打开</el-button>
|
||||
</template>
|
||||
<template v-if="device.device_type?.code === 'MTO'">
|
||||
<el-button
|
||||
type="success"
|
||||
@click="controlDevice2(device, 'switch', 1)"
|
||||
>启动</el-button>
|
||||
<el-button
|
||||
type="warning"
|
||||
@click="controlDevice2(device, 'switch', 0)"
|
||||
>停止</el-button>
|
||||
<el-button
|
||||
type="danger"
|
||||
@click="controlDevice2(device, 'emergency_stop', 0)"
|
||||
>急停</el-button>
|
||||
</template>
|
||||
<el-button type="primary" @click="editDevice(device)">编辑</el-button>
|
||||
<el-button type="danger" @click="deleteDevice(device)">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加设备对话框 -->
|
||||
<el-dialog
|
||||
v-model="showAddDeviceDialog"
|
||||
:title="editingDevice ? '编辑设备' : '添加设备'"
|
||||
width="500px"
|
||||
>
|
||||
<el-form
|
||||
ref="formRef"
|
||||
:model="deviceForm"
|
||||
:rules="rules"
|
||||
label-width="100px"
|
||||
>
|
||||
<el-form-item label="名称" prop="name">
|
||||
<el-input v-model="deviceForm.name" placeholder="请输入设备名称"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="代号" prop="code">
|
||||
<el-input v-model="deviceForm.code" placeholder="请输入设备代号" />
|
||||
</el-form-item>
|
||||
<el-form-item label="设备类型">
|
||||
<el-select v-model="deviceForm.device_type_id" placeholder="请选择设备类型">
|
||||
<el-option
|
||||
v-for="type in deviceTypes"
|
||||
:key="type.id"
|
||||
:label="type.name"
|
||||
:value="type.id"
|
||||
></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="接口" prop="interface_id">
|
||||
<el-select v-model="deviceForm.interface_id" placeholder="请选择接口">
|
||||
<el-option
|
||||
v-for="interfaceItem in interfaces"
|
||||
:key="interfaceItem.id"
|
||||
:label="interfaceItem.name"
|
||||
:value="interfaceItem.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="设备地址" prop="device_address">
|
||||
<el-input
|
||||
v-model="deviceForm.device_address"
|
||||
placeholder="0x00"
|
||||
@input="handleAddressInput($event)"
|
||||
@blur="handleAddressBlur($event)"
|
||||
></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-switch
|
||||
v-model="deviceForm.enabled"
|
||||
:active-text="'启用'"
|
||||
:inactive-text="'禁用'"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="showAddDeviceDialog = false">取消</el-button>
|
||||
<el-button type="primary" @click="saveDevice">确定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 寄存器表对话框 -->
|
||||
<el-dialog
|
||||
v-model="showRegistersDialog"
|
||||
title="寄存器管理"
|
||||
width="900px"
|
||||
>
|
||||
<div class="dialog-content">
|
||||
<!-- 寄存器表单 -->
|
||||
<div class="register-form" v-if="editingRegisterId !== null || registerForm.address !== undefined">
|
||||
<el-form :model="registerForm" label-width="100px">
|
||||
<el-form-item label="地址">
|
||||
<el-input-number
|
||||
v-model="registerForm.address"
|
||||
:min="0"
|
||||
:max="65535"
|
||||
placeholder="请输入寄存器地址"
|
||||
></el-input-number>
|
||||
</el-form-item>
|
||||
<el-form-item label="功能码">
|
||||
<el-select v-model="registerForm.functionCode" placeholder="请选择功能码">
|
||||
<el-option
|
||||
v-for="code in functionCodes"
|
||||
:key="code.value"
|
||||
:label="code.label"
|
||||
:value="code.value"
|
||||
></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="registerForm.name" placeholder="请输入寄存器名称"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注">
|
||||
<el-input
|
||||
v-model="registerForm.description"
|
||||
type="textarea"
|
||||
placeholder="请输入备注说明"
|
||||
></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="saveRegister">保存</el-button>
|
||||
<el-button @click="editingRegisterId = null; registerForm.address = ''">取消</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</div>
|
||||
|
||||
<!-- 寄存器列表 -->
|
||||
<div class="register-list">
|
||||
<div class="toolbar">
|
||||
<el-button type="primary" @click="addRegister" v-if="editingRegisterId === null && registerForm.address === ''">
|
||||
添加寄存器
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<el-table :data="currentDeviceRegisters" style="width: 100%">
|
||||
<el-table-column prop="address" label="地址" width="100">
|
||||
<template #default="{ row }">
|
||||
{{ row.address.toString(16).toUpperCase().padStart(4, '0') }}h
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="functionCode" label="功能码" width="150">
|
||||
<template #default="{ row }">
|
||||
{{ functionCodes.find(code => code.value === row.functionCode)?.label || row.functionCode }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="name" label="名称"></el-table-column>
|
||||
<el-table-column prop="description" label="备注"></el-table-column>
|
||||
<el-table-column prop="code" label="代号" width="120" />
|
||||
<el-table-column label="操作" width="150" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="editRegister(row)"
|
||||
:disabled="editingRegisterId !== null || registerForm.address !== ''"
|
||||
>编辑</el-button>
|
||||
<el-button
|
||||
type="danger"
|
||||
size="small"
|
||||
@click="deleteRegister(row)"
|
||||
:disabled="editingRegisterId !== null || registerForm.address !== ''"
|
||||
>删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</div>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import type { FormInstance } from 'element-plus'
|
||||
import type { DeviceTypeItem, InterfaceItem } from '../types'
|
||||
|
||||
// 修改设备类型定义
|
||||
interface DeviceItem {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
device_address: number;
|
||||
device_type_id: number | null;
|
||||
interface_id: number;
|
||||
enabled: boolean;
|
||||
status: string | {
|
||||
online?: boolean;
|
||||
light?: boolean;
|
||||
flow_rate?: number;
|
||||
water_temp?: number;
|
||||
oil_temp?: number; // 油温,单位:℃
|
||||
oil_level?: number; // 油位,范围:0-3
|
||||
[key: string]: any;
|
||||
};
|
||||
last_update: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
device_type?: {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
};
|
||||
interface?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
// 设备列表
|
||||
const devices = ref<DeviceItem[]>([])
|
||||
// 设备类型列表
|
||||
const deviceTypes = ref<DeviceTypeItem[]>([])
|
||||
// 接口列表
|
||||
const interfaces = ref<InterfaceItem[]>([])
|
||||
|
||||
// 对话框控制
|
||||
const showAddDeviceDialog = ref(false)
|
||||
const showRegistersDialog = ref(false)
|
||||
|
||||
// 表单引用
|
||||
const formRef = ref<FormInstance>()
|
||||
|
||||
// 表单数据
|
||||
const deviceForm = ref<Partial<DeviceItem>>({
|
||||
name: '',
|
||||
code: '',
|
||||
device_address: 1,
|
||||
device_type_id: undefined,
|
||||
interface_id: undefined,
|
||||
enabled: true // 默认启用
|
||||
})
|
||||
|
||||
// 当前编辑的设备
|
||||
const editingDevice = ref<DeviceItem | null>(null)
|
||||
// 当前设备的寄存器列表
|
||||
const currentDeviceRegisters = ref([])
|
||||
|
||||
// 寄存器相关
|
||||
const currentDeviceId = ref(null)
|
||||
const registerForm = ref({
|
||||
address: '',
|
||||
functionCode: '3', // 默认使用03功能码(读保持寄存器)
|
||||
name: '',
|
||||
description: ''
|
||||
})
|
||||
const editingRegisterId = ref(null)
|
||||
|
||||
// 功能码选项
|
||||
const functionCodes = [
|
||||
{ value: '1', label: '01 - 读线圈' },
|
||||
{ value: '2', label: '02 - 读离散输入' },
|
||||
{ value: '3', label: '03 - 读保持寄存器' },
|
||||
{ value: '4', label: '04 - 读输入寄存器' }
|
||||
]
|
||||
|
||||
// 在 data 中添加表单验证规则
|
||||
const rules = {
|
||||
name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
|
||||
code: [{ required: true, message: "请输入设备代号", trigger: "blur" }],
|
||||
device_address: [{ required: true, message: "请输入设备地址", trigger: "blur" }],
|
||||
interface_id: [{ required: true, message: "请选择接口", trigger: "change" }],
|
||||
};
|
||||
|
||||
// 获取设备类型列表
|
||||
const fetchDeviceTypes = async () => {
|
||||
try {
|
||||
const response = await axios.get('/device-types')
|
||||
deviceTypes.value = response.data
|
||||
} catch (error) {
|
||||
ElMessage.error('获取设备类型列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 获取设备列表
|
||||
const fetchDevices = async () => {
|
||||
try {
|
||||
const response = await axios.get<DeviceItem[]>('/devices')
|
||||
devices.value = response.data
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message)
|
||||
} else {
|
||||
ElMessage.error('获取设备列表失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取接口列表
|
||||
const fetchInterfaces = async () => {
|
||||
try {
|
||||
const response = await axios.get('/interfaces')
|
||||
interfaces.value = response.data
|
||||
} catch (error) {
|
||||
ElMessage.error('获取接口列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 保存设备
|
||||
const saveDevice = async () => {
|
||||
if (!formRef.value) return;
|
||||
|
||||
await formRef.value.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
try {
|
||||
const data = {
|
||||
name: deviceForm.value.name,
|
||||
code: deviceForm.value.code,
|
||||
device_address: Number(deviceForm.value.device_address),
|
||||
device_type_id: deviceForm.value.device_type_id || null,
|
||||
interface_id: deviceForm.value.interface_id,
|
||||
enabled: deviceForm.value.enabled
|
||||
};
|
||||
|
||||
if (editingDevice.value) {
|
||||
await axios.put(`/devices/${editingDevice.value.id}`, data);
|
||||
} else {
|
||||
await axios.post("/devices", data);
|
||||
}
|
||||
|
||||
ElMessage.success("保存成功");
|
||||
showAddDeviceDialog.value = false;
|
||||
fetchDevices();
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message);
|
||||
} else {
|
||||
ElMessage.error("保存失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 编辑设备
|
||||
const editDevice = (device: DeviceItem) => {
|
||||
editingDevice.value = device
|
||||
deviceForm.value = {
|
||||
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
|
||||
}
|
||||
showAddDeviceDialog.value = true
|
||||
}
|
||||
|
||||
// 删除设备
|
||||
const deleteDevice = (device: DeviceItem) => {
|
||||
ElMessageBox.confirm(
|
||||
'确定要删除这个设备吗?',
|
||||
'警告',
|
||||
{
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}
|
||||
).then(async () => {
|
||||
try {
|
||||
await axios.delete(`/devices/${device.id}`)
|
||||
ElMessage.success('设备删除成功')
|
||||
fetchDevices()
|
||||
} catch (error) {
|
||||
ElMessage.error('删除设备失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 查看寄存器
|
||||
const viewRegisters = async (device) => {
|
||||
currentDeviceId.value = device.id
|
||||
try {
|
||||
const response = await axios.get(`/devices/${device.id}/registers`)
|
||||
currentDeviceRegisters.value = response.data
|
||||
showRegistersDialog.value = true
|
||||
} catch (error) {
|
||||
ElMessage.error('获取寄存器列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 添加寄存器
|
||||
const addRegister = () => {
|
||||
editingRegisterId.value = null
|
||||
registerForm.value = {
|
||||
address: 0, // 设置默认值
|
||||
functionCode: '3',
|
||||
name: '',
|
||||
description: ''
|
||||
}
|
||||
// 确保表单显示
|
||||
showRegistersDialog.value = true
|
||||
}
|
||||
|
||||
// 编辑寄存器
|
||||
const editRegister = (register) => {
|
||||
editingRegisterId.value = register.id
|
||||
registerForm.value = { ...register }
|
||||
}
|
||||
|
||||
// 保存寄存器
|
||||
const saveRegister = async () => {
|
||||
try {
|
||||
if (editingRegisterId.value === null) {
|
||||
// 创建新寄存器
|
||||
await axios.post(
|
||||
`/devices/${currentDeviceId.value}/registers`,
|
||||
registerForm.value
|
||||
)
|
||||
ElMessage.success('寄存器添加成功')
|
||||
} else {
|
||||
// 更新现有寄存器
|
||||
await axios.put(
|
||||
`/devices/${currentDeviceId.value}/registers/${editingRegisterId.value}`,
|
||||
registerForm.value
|
||||
)
|
||||
ElMessage.success('寄存器更新成功')
|
||||
}
|
||||
// 重新加载寄存器列表
|
||||
const response = await axios.get(`/devices/${currentDeviceId.value}/registers`)
|
||||
currentDeviceRegisters.value = response.data
|
||||
editingRegisterId.value = null
|
||||
registerForm.value = {
|
||||
address: '',
|
||||
functionCode: '3',
|
||||
name: '',
|
||||
description: ''
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.response?.status === 400) {
|
||||
ElMessage.error(error.response.data.detail || '保存失败')
|
||||
} else {
|
||||
ElMessage.error('保存寄存器失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除寄存器
|
||||
const deleteRegister = async (register) => {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
'确定要删除该寄存器吗?',
|
||||
'警告',
|
||||
{
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}
|
||||
)
|
||||
|
||||
await axios.delete(
|
||||
`/devices/${currentDeviceId.value}/registers/${register.id}`
|
||||
)
|
||||
ElMessage.success('寄存器删除成功')
|
||||
|
||||
// 重新加载寄存器列表
|
||||
const response = await axios.get(`/devices/${currentDeviceId.value}/registers`)
|
||||
currentDeviceRegisters.value = response.data
|
||||
} catch (error) {
|
||||
if (error !== 'cancel') {
|
||||
ElMessage.error('删除寄存器失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理地址输入
|
||||
const handleAddressInput = (event: Event) => {
|
||||
const value = (event.target as HTMLInputElement).value
|
||||
// 移除所有空格
|
||||
const cleanValue = value.replace(/\s/g, '')
|
||||
|
||||
// 如果输入为空,设置为0
|
||||
if (!cleanValue) {
|
||||
deviceForm.value.device_address = 0
|
||||
return
|
||||
}
|
||||
|
||||
// 如果输入的是十六进制格式(以0x开头)
|
||||
if (cleanValue.toLowerCase().startsWith('0x')) {
|
||||
const hexValue = parseInt(cleanValue.slice(2), 16)
|
||||
if (!isNaN(hexValue) && hexValue >= 0 && hexValue <= 255) {
|
||||
deviceForm.value.device_address = hexValue
|
||||
}
|
||||
} else {
|
||||
// 如果输入的是十进制
|
||||
const decValue = parseInt(cleanValue, 10)
|
||||
if (!isNaN(decValue) && decValue >= 0 && decValue <= 255) {
|
||||
deviceForm.value.device_address = decValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理地址输入框失去焦点
|
||||
const handleAddressBlur = (event: FocusEvent) => {
|
||||
const value = (event.target as HTMLInputElement).value
|
||||
// 移除所有空格
|
||||
const cleanValue = value.replace(/\s/g, '')
|
||||
|
||||
// 如果输入为空,设置为0
|
||||
if (!cleanValue) {
|
||||
deviceForm.value.device_address = 0
|
||||
return
|
||||
}
|
||||
|
||||
// 如果输入的是十六进制格式(以0x开头)
|
||||
if (cleanValue.toLowerCase().startsWith('0x')) {
|
||||
const hexValue = parseInt(cleanValue.slice(2), 16)
|
||||
if (!isNaN(hexValue) && hexValue >= 0 && hexValue <= 255) {
|
||||
deviceForm.value.device_address = hexValue
|
||||
}
|
||||
} else {
|
||||
// 如果输入的是十进制
|
||||
const decValue = parseInt(cleanValue, 10)
|
||||
if (!isNaN(decValue) && decValue >= 0 && decValue <= 255) {
|
||||
deviceForm.value.device_address = decValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 修改控制设备的方法2
|
||||
const controlDevice2 = async (device: DeviceItem, command: string, value: number) => {
|
||||
try {
|
||||
await axios.post('/devices/control2', {
|
||||
device_id: device.id,
|
||||
command: command,
|
||||
value: value
|
||||
})
|
||||
ElMessage.success( '设备控制成功' )
|
||||
|
||||
// 等待一小段时间后重新获取设备状态
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const response = await axios.get<DeviceItem>(`/devices/${device.id}`)
|
||||
// 更新设备状态
|
||||
const updatedDevice = response.data
|
||||
const index = devices.value.findIndex(d => d.id === device.id)
|
||||
if (index !== -1) {
|
||||
devices.value[index] = updatedDevice
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取设备状态失败:', error)
|
||||
}
|
||||
}, 1000) // 等待1秒后获取最新状态
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message)
|
||||
} else {
|
||||
ElMessage.error('控制设备失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 修改控制设备的方法
|
||||
const controlDevice = async (device: DeviceItem, status: boolean) => {
|
||||
try {
|
||||
await axios.post('/devices/control', {
|
||||
device_id: device.id,
|
||||
command: 'set_status',
|
||||
status: !status // 反转状态值
|
||||
})
|
||||
ElMessage.success(!status ? '设备已打开' : '设备已关闭')
|
||||
|
||||
// 等待一小段时间后重新获取设备状态
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const response = await axios.get<DeviceItem>(`/devices/${device.id}`)
|
||||
// 更新设备状态
|
||||
const updatedDevice = response.data
|
||||
const index = devices.value.findIndex(d => d.id === device.id)
|
||||
if (index !== -1) {
|
||||
devices.value[index] = updatedDevice
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取设备状态失败:', error)
|
||||
}
|
||||
}, 1000) // 等待1秒后获取最新状态
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message)
|
||||
} else {
|
||||
ElMessage.error('控制设备失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加油位状态转换函数
|
||||
const getOilLevelText = (level: number) => {
|
||||
switch (level) {
|
||||
case 0:
|
||||
return '空'
|
||||
case 1:
|
||||
return '低'
|
||||
case 2:
|
||||
return '中'
|
||||
case 3:
|
||||
return '满'
|
||||
default:
|
||||
return '未知'
|
||||
}
|
||||
}
|
||||
|
||||
// 添加油位状态样式类获取函数
|
||||
const getOilLevelClass = (level: number) => {
|
||||
if (typeof level !== 'number') return '';
|
||||
if (level >= 2) return 'oil-level-high';
|
||||
if (level === 1) return 'oil-level-medium';
|
||||
if (level === 0) return 'oil-level-low';
|
||||
return '';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchDevices()
|
||||
fetchDeviceTypes()
|
||||
fetchInterfaces()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.device-management {
|
||||
padding: 20px;
|
||||
max-width: 1600px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.device-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.device-card {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 24px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
height: fit-content;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
min-width: 360px;
|
||||
}
|
||||
|
||||
.device-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.device-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.device-status-container {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.device-enabled {
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.device-enabled.enabled {
|
||||
background-color: #67C23A;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.device-enabled.disabled {
|
||||
background-color: #909399;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.device-status {
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.device-status.online {
|
||||
background-color: #67C23A;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.device-status.offline {
|
||||
background-color: #F56C6C;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.device-info {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.info-item .label {
|
||||
color: #666;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.device-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 8px 16px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.btn-text {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 4px 8px;
|
||||
cursor: pointer;
|
||||
color: #1976d2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.btn-text.danger {
|
||||
color: #f44336;
|
||||
}
|
||||
|
||||
.dialog-content {
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.register-form {
|
||||
margin-bottom: 20px;
|
||||
padding: 20px;
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
/* Element Plus 样式覆盖 */
|
||||
:deep(.el-dialog__body) {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
:deep(.el-form-item:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* 响应式布局调整 */
|
||||
@media (min-width: 1600px) {
|
||||
.device-list {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1599px) and (min-width: 1200px) {
|
||||
.device-list {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.device-list {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.device-card {
|
||||
min-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.status-online {
|
||||
color: #67C23A;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.status-offline {
|
||||
color: #F56C6C;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.oil-level-high {
|
||||
color: #67C23A;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.oil-level-medium {
|
||||
color: #E6A23C;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.oil-level-low {
|
||||
color: #F56C6C;
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,300 @@
|
||||
<template>
|
||||
<div class="device-type-management">
|
||||
<div class="toolbar">
|
||||
<el-button type="primary" @click="showAddDialog = true">
|
||||
<i class="fas fa-plus"></i> 添加设备类型
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 设备类型列表 -->
|
||||
<el-table :data="deviceTypes" style="width: 100%">
|
||||
<el-table-column prop="name" label="名称" width="150"></el-table-column>
|
||||
<el-table-column prop="code" label="代号" width="120"></el-table-column>
|
||||
<el-table-column label="地址范围" width="150">
|
||||
<template #default="{ row }">
|
||||
0x{{ row.address_range_start.toString(16).padStart(2, '0').toUpperCase() }} - 0x{{ row.address_range_end.toString(16).padStart(2, '0').toUpperCase() }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="chip_model" label="芯片型号" width="150"></el-table-column>
|
||||
<el-table-column prop="description" label="备注" min-width="250">
|
||||
<template #default="{ row }">
|
||||
<el-tooltip
|
||||
v-if="row.description"
|
||||
:content="row.description"
|
||||
placement="top"
|
||||
:show-after="500"
|
||||
>
|
||||
<div class="description-cell">{{ row.description }}</div>
|
||||
</el-tooltip>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="created_at" label="创建时间" width="180">
|
||||
<template #default="{ row }">
|
||||
{{ new Date(row.created_at).toLocaleString() }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="150" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="editDeviceType(row)"
|
||||
>编辑</el-button>
|
||||
<el-button
|
||||
type="danger"
|
||||
size="small"
|
||||
@click="confirmDelete(row)"
|
||||
>删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<!-- 添加/编辑对话框 -->
|
||||
<el-dialog
|
||||
v-model="showAddDialog"
|
||||
:title="editingType ? '编辑设备类型' : '添加设备类型'"
|
||||
width="500px"
|
||||
>
|
||||
<el-form :model="typeForm" label-width="100px">
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="typeForm.name" placeholder="请输入设备类型名称"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="代号">
|
||||
<el-input v-model="typeForm.code" placeholder="请输入设备类型代号"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="地址范围">
|
||||
<div class="address-range">
|
||||
<el-input
|
||||
v-model="typeForm.address_range_start"
|
||||
:min="0"
|
||||
:max="255"
|
||||
placeholder="0x00"
|
||||
@input="handleAddressInput('start', $event)"
|
||||
@blur="handleAddressBlur('start', $event)"
|
||||
></el-input>
|
||||
<span class="separator">-</span>
|
||||
<el-input
|
||||
v-model="typeForm.address_range_end"
|
||||
:min="0"
|
||||
:max="255"
|
||||
placeholder="0xFF"
|
||||
@input="handleAddressInput('end', $event)"
|
||||
@blur="handleAddressBlur('end', $event)"
|
||||
></el-input>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="芯片型号">
|
||||
<el-input v-model="typeForm.chip_model" placeholder="请输入芯片型号"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注">
|
||||
<el-input
|
||||
v-model="typeForm.description"
|
||||
type="textarea"
|
||||
placeholder="请输入备注说明"
|
||||
></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="showAddDialog = false">取消</el-button>
|
||||
<el-button type="primary" @click="saveDeviceType">确定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
|
||||
// 设备类型列表
|
||||
const deviceTypes = ref([])
|
||||
|
||||
// 对话框控制
|
||||
const showAddDialog = ref(false)
|
||||
const editingType = ref(null)
|
||||
|
||||
// 表单数据
|
||||
const typeForm = ref({
|
||||
name: '',
|
||||
code: '',
|
||||
address_range_start: 0,
|
||||
address_range_end: 0,
|
||||
chip_model: '',
|
||||
description: ''
|
||||
})
|
||||
|
||||
// 获取设备类型列表
|
||||
const fetchDeviceTypes = async () => {
|
||||
try {
|
||||
const response = await axios.get('/device-types')
|
||||
deviceTypes.value = response.data
|
||||
} catch (error) {
|
||||
ElMessage.error('获取设备类型列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 编辑设备类型
|
||||
const editDeviceType = (type) => {
|
||||
editingType.value = type
|
||||
typeForm.value = {
|
||||
...type,
|
||||
address_range_start: `0x${type.address_range_start.toString(16).padStart(2, '0').toUpperCase()}`,
|
||||
address_range_end: `0x${type.address_range_end.toString(16).padStart(2, '0').toUpperCase()}`
|
||||
}
|
||||
showAddDialog.value = true
|
||||
}
|
||||
|
||||
// 保存设备类型
|
||||
const saveDeviceType = async () => {
|
||||
try {
|
||||
// 确保地址范围为数字类型
|
||||
const formData = {
|
||||
...typeForm.value,
|
||||
address_range_start: Number(typeForm.value.address_range_start),
|
||||
address_range_end: Number(typeForm.value.address_range_end)
|
||||
}
|
||||
|
||||
if (editingType.value) {
|
||||
await axios.put(
|
||||
`/device-types/${editingType.value.id}`,
|
||||
formData
|
||||
)
|
||||
ElMessage.success('设备类型更新成功')
|
||||
} else {
|
||||
await axios.post('/device-types', formData)
|
||||
ElMessage.success('设备类型添加成功')
|
||||
}
|
||||
showAddDialog.value = false
|
||||
fetchDeviceTypes()
|
||||
} catch (error) {
|
||||
if (error.response?.status === 400) {
|
||||
ElMessage.error(error.response.data.detail || '保存失败')
|
||||
} else {
|
||||
ElMessage.error('保存设备类型失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除设备类型
|
||||
const confirmDelete = (type) => {
|
||||
ElMessageBox.confirm(
|
||||
'确定要删除该设备类型吗?',
|
||||
'警告',
|
||||
{
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}
|
||||
).then(async () => {
|
||||
try {
|
||||
await axios.delete(`/device-types/${type.id}`)
|
||||
ElMessage.success('设备类型删除成功')
|
||||
fetchDeviceTypes()
|
||||
} catch (error) {
|
||||
ElMessage.error('删除设备类型失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 处理地址输入
|
||||
const handleAddressInput = (type: 'start' | 'end', value: string) => {
|
||||
// 移除所有空格
|
||||
value = value.replace(/\s/g, '')
|
||||
|
||||
// 如果输入为空,设置为0
|
||||
if (!value) {
|
||||
typeForm.value[`address_range_${type}`] = 0
|
||||
return
|
||||
}
|
||||
|
||||
// 如果输入的是十六进制格式(以0x开头)
|
||||
if (value.toLowerCase().startsWith('0x')) {
|
||||
// 只更新显示值,不立即转换
|
||||
typeForm.value[`address_range_${type}`] = value
|
||||
} else {
|
||||
// 如果输入的是十进制
|
||||
const decValue = parseInt(value, 10)
|
||||
if (!isNaN(decValue) && decValue >= 0 && decValue <= 255) {
|
||||
typeForm.value[`address_range_${type}`] = decValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理地址输入框失去焦点
|
||||
const handleAddressBlur = (type: 'start' | 'end', value: string) => {
|
||||
// 移除所有空格
|
||||
value = value.replace(/\s/g, '')
|
||||
|
||||
// 如果输入为空,设置为0
|
||||
if (!value) {
|
||||
typeForm.value[`address_range_${type}`] = 0
|
||||
return
|
||||
}
|
||||
|
||||
// 如果输入的是十六进制格式(以0x开头)
|
||||
if (value.toLowerCase().startsWith('0x')) {
|
||||
const hexValue = parseInt(value.slice(2), 16)
|
||||
if (!isNaN(hexValue) && hexValue >= 0 && hexValue <= 255) {
|
||||
typeForm.value[`address_range_${type}`] = hexValue
|
||||
}
|
||||
} else {
|
||||
// 如果输入的是十进制
|
||||
const decValue = parseInt(value, 10)
|
||||
if (!isNaN(decValue) && decValue >= 0 && decValue <= 255) {
|
||||
typeForm.value[`address_range_${type}`] = decValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化地址显示
|
||||
const formatAddress = (value: number) => {
|
||||
return `0x${value.toString(16).padStart(2, '0').toUpperCase()}`
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchDeviceTypes()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.device-type-management {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.address-range {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.separator {
|
||||
color: #666;
|
||||
}
|
||||
|
||||
:deep(.el-form-item:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.description-cell {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
:deep(.el-table) {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
:deep(.el-table .cell) {
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,201 @@
|
||||
<template>
|
||||
<div class="dashboard">
|
||||
<div class="dashboard-grid">
|
||||
<!-- 系统状态卡片 -->
|
||||
<div class="card">
|
||||
<h2>系统状态</h2>
|
||||
<div class="status-grid">
|
||||
<div class="status-item">
|
||||
<div class="status-label">CPU 使用率</div>
|
||||
<div class="status-value">{{ cpu_usage || 0 }}%</div>
|
||||
<div class="progress-bar">
|
||||
<div :style="{ width: `${cpu_usage || 0}%` }" :class="getProgressClass(cpu_usage || 0)"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<div class="status-label">内存使用率</div>
|
||||
<div class="status-value">{{ memory_usage || 0 }}%</div>
|
||||
<div class="progress-bar">
|
||||
<div :style="{ width: `${memory_usage || 0}%` }" :class="getProgressClass(memory_usage || 0)"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<div class="status-label">磁盘使用率</div>
|
||||
<div class="status-value">{{ disk_usage || 0 }}%</div>
|
||||
<div class="progress-bar">
|
||||
<div :style="{ width: `${disk_usage || 0}%` }" :class="getProgressClass(disk_usage || 0)"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<div class="status-label">CPU 温度</div>
|
||||
<div class="status-value">{{ temperature || 0 }}°C</div>
|
||||
<div class="progress-bar">
|
||||
<div :style="{ width: `${(temperature || 0) * 2}%` }" :class="getTemperatureClass(temperature || 0)"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 网络信息卡片 -->
|
||||
<div class="card">
|
||||
<h2>网络信息</h2>
|
||||
<div class="network-list">
|
||||
<div v-for="(addresses, interfaceName) in network_info" :key="interfaceName" class="network-item">
|
||||
<div class="interface-name">{{ interfaceName }}</div>
|
||||
<div class="interface-addresses">
|
||||
<div v-for="address in addresses" :key="address">{{ address }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
const cpu_usage = ref(0)
|
||||
const memory_usage = ref(0)
|
||||
const disk_usage = ref(0)
|
||||
const network_info = ref<Record<string, string[]>>({})
|
||||
const temperature = ref(0)
|
||||
|
||||
const fetchSystemInfo = async () => {
|
||||
try {
|
||||
const response = await axios.get('/system/info')
|
||||
cpu_usage.value = response.data.cpu_usage
|
||||
memory_usage.value = response.data.memory_usage
|
||||
disk_usage.value = response.data.disk_usage
|
||||
network_info.value = response.data.network_info
|
||||
temperature.value = response.data.temperature
|
||||
} catch (error) {
|
||||
console.error('获取系统信息失败:', error)
|
||||
ElMessage.error('获取系统信息失败')
|
||||
}
|
||||
}
|
||||
|
||||
const getProgressClass = (value: number) => {
|
||||
if (value >= 90) return 'danger'
|
||||
if (value >= 70) return 'warning'
|
||||
return 'normal'
|
||||
}
|
||||
|
||||
const getTemperatureClass = (value: number) => {
|
||||
if (value >= 80) return 'danger'
|
||||
if (value >= 60) return 'warning'
|
||||
return 'normal'
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchSystemInfo()
|
||||
setInterval(fetchSystemInfo, 30000) // 每30秒更新一次系统信息
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dashboard {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.dashboard-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
margin-bottom: 20px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.status-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.status-item {
|
||||
padding: 15px;
|
||||
background: #f5f7fa;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.status-label {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.status-value {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 6px;
|
||||
background: #e4e7ed;
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-bar > div {
|
||||
height: 100%;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.normal {
|
||||
background: #67c23a;
|
||||
}
|
||||
|
||||
.warning {
|
||||
background: #e6a23c;
|
||||
}
|
||||
|
||||
.danger {
|
||||
background: #f56c6c;
|
||||
}
|
||||
|
||||
.network-list {
|
||||
display: grid;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.network-item {
|
||||
padding: 15px;
|
||||
background: #f5f7fa;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.interface-name {
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.interface-addresses {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.dashboard-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.status-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,532 @@
|
||||
<template>
|
||||
<div class="interface-management">
|
||||
<div class="toolbar">
|
||||
<el-button type="primary" @click="showAddInterfaceDialog = true">
|
||||
<i class="fas fa-plus"></i> 添加接口
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 接口列表 -->
|
||||
<div class="interface-list">
|
||||
<div v-for="item in interfaces" :key="item.id" class="interface-card">
|
||||
<div class="interface-header">
|
||||
<h3>{{ item.name }}</h3>
|
||||
<el-tag :type="item.type === 'CAN' ? 'primary' : 'success'">
|
||||
{{ item.type }}
|
||||
</el-tag>
|
||||
</div>
|
||||
<div class="interface-info">
|
||||
<div class="info-item">
|
||||
<span class="label">描述:</span>
|
||||
<span>{{ item.description || '无' }}</span>
|
||||
</div>
|
||||
<template v-if="item.type === 'CAN'">
|
||||
<div class="info-item">
|
||||
<span class="label">通道号:</span>
|
||||
<span>{{ item.can_channel }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">波特率:</span>
|
||||
<span>{{ item.can_baud_rate }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="item.type === 'Powerbus'">
|
||||
<div class="info-item">
|
||||
<span class="label">串口:</span>
|
||||
<span>{{ item.port }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="item.type === 'Modbus'">
|
||||
<div class="info-item">
|
||||
<span class="label">Modbus类型:</span>
|
||||
<span>{{ item.modbus_type === 'TCP' ? 'Modbus-TCP' : 'Modbus-RTU' }}</span>
|
||||
</div>
|
||||
<template v-if="item.modbus_type === 'TCP'">
|
||||
<div class="info-item">
|
||||
<span class="label">IP地址:</span>
|
||||
<span>{{ item.ip_address }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">端口号:</span>
|
||||
<span>{{ item.port }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="item.modbus_type === 'RTU'">
|
||||
<div class="info-item">
|
||||
<span class="label">串口:</span>
|
||||
<span>{{ item.port }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">波特率:</span>
|
||||
<span>{{ item.baud_rate }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">数据位:</span>
|
||||
<span>{{ item.data_bits }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">停止位:</span>
|
||||
<span>{{ item.stop_bits }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">校验位:</span>
|
||||
<span>{{ item.parity === 'N' ? '无' : item.parity === 'O' ? '奇校验' : '偶校验' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
<template v-else-if="item.type === 'Mqtt'">
|
||||
<div class="info-item">
|
||||
<span class="label">Broker地址:</span>
|
||||
<span>{{ item.broker_url }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">Broker端口:</span>
|
||||
<span>{{ item.broker_port }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="label">Topic:</span>
|
||||
<span>{{ item.topic }}</span>
|
||||
</div>
|
||||
<div v-if="item.username" class="info-item">
|
||||
<span class="label">用户名:</span>
|
||||
<span>{{ item.username }}</span>
|
||||
</div>
|
||||
<div v-if="item.client_id" class="info-item">
|
||||
<span class="label">Client ID:</span>
|
||||
<span>{{ item.client_id }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div class="interface-actions">
|
||||
<button class="btn-text" @click="editInterface(item)">
|
||||
<i class="fas fa-edit"></i> 编辑
|
||||
</button>
|
||||
<button class="btn-text danger" @click="confirmDelete(item)">
|
||||
<i class="fas fa-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加/编辑接口对话框 -->
|
||||
<el-dialog
|
||||
:title="editingInterface ? '编辑接口' : '添加接口'"
|
||||
v-model="showAddInterfaceDialog"
|
||||
width="500px"
|
||||
>
|
||||
<el-form :model="interfaceForm" label-width="100px">
|
||||
<el-form-item label="名称" required>
|
||||
<el-input v-model="interfaceForm.name" />
|
||||
</el-form-item>
|
||||
<el-form-item label="类型" required>
|
||||
<el-select v-model="interfaceForm.type" placeholder="请选择接口类型">
|
||||
<el-option label="CAN" value="CAN" />
|
||||
<el-option label="Powerbus" value="Powerbus" />
|
||||
<el-option label="Modbus" value="Modbus" />
|
||||
<el-option label="Mqtt" value="Mqtt" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="描述">
|
||||
<el-input v-model="interfaceForm.description" type="textarea" />
|
||||
</el-form-item>
|
||||
<template v-if="interfaceForm.type === 'CAN'">
|
||||
<el-form-item label="通道号" required>
|
||||
<el-input-number v-model="interfaceForm.can_channel" :min="0" :max="3" />
|
||||
</el-form-item>
|
||||
<el-form-item label="波特率" required>
|
||||
<el-select v-model="interfaceForm.can_baud_rate" placeholder="请选择波特率">
|
||||
<el-option label="125000" :value="125000" />
|
||||
<el-option label="250000" :value="250000" />
|
||||
<el-option label="500000" :value="500000" />
|
||||
<el-option label="1000000" :value="1000000" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</template>
|
||||
<template v-else-if="interfaceForm.type === 'Powerbus'">
|
||||
<el-form-item label="串口" required>
|
||||
<el-select v-model="interfaceForm.port" placeholder="请选择串口">
|
||||
<el-option
|
||||
v-for="port in serialPorts"
|
||||
:key="port.value"
|
||||
:label="port.label"
|
||||
:value="port.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="波特率" required>
|
||||
<el-select v-model="interfaceForm.baud_rate" placeholder="请选择波特率">
|
||||
<el-option label="4800" :value="4800" />
|
||||
<el-option label="9600" :value="9600" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</template>
|
||||
<template v-else-if="interfaceForm.type === 'Modbus'">
|
||||
<el-form-item label="Modbus类型" required>
|
||||
<el-select v-model="interfaceForm.modbus_type" placeholder="请选择Modbus类型">
|
||||
<el-option label="Modbus-TCP" value="TCP" />
|
||||
<el-option label="Modbus-RTU" value="RTU" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<template v-if="interfaceForm.modbus_type === 'TCP'">
|
||||
<el-form-item label="IP地址" required>
|
||||
<el-input v-model="interfaceForm.ip_address" placeholder="请输入IP地址" />
|
||||
</el-form-item>
|
||||
<el-form-item label="端口号" required>
|
||||
<el-input-number v-model="interfaceForm.port" :min="1" :max="65535" placeholder="默认502" />
|
||||
</el-form-item>
|
||||
</template>
|
||||
|
||||
<template v-else-if="interfaceForm.modbus_type === 'RTU'">
|
||||
<el-form-item label="串口" required>
|
||||
<el-select v-model="interfaceForm.port" placeholder="请选择串口">
|
||||
<el-option
|
||||
v-for="port in serialPorts"
|
||||
:key="port.value"
|
||||
:label="port.label"
|
||||
:value="port.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="波特率" required>
|
||||
<el-select v-model="interfaceForm.baud_rate" placeholder="请选择波特率">
|
||||
<el-option label="9600" :value="9600" />
|
||||
<el-option label="19200" :value="19200" />
|
||||
<el-option label="38400" :value="38400" />
|
||||
<el-option label="57600" :value="57600" />
|
||||
<el-option label="115200" :value="115200" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="数据位" required>
|
||||
<el-select v-model="interfaceForm.data_bits" placeholder="请选择数据位">
|
||||
<el-option label="7" :value="7" />
|
||||
<el-option label="8" :value="8" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="停止位" required>
|
||||
<el-select v-model="interfaceForm.stop_bits" placeholder="请选择停止位">
|
||||
<el-option label="1" :value="1" />
|
||||
<el-option label="2" :value="2" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="校验位" required>
|
||||
<el-select v-model="interfaceForm.parity" placeholder="请选择校验位">
|
||||
<el-option label="无" value="N" />
|
||||
<el-option label="奇校验" value="O" />
|
||||
<el-option label="偶校验" value="E" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</template>
|
||||
</template>
|
||||
<template v-else-if="interfaceForm.type === 'Mqtt'">
|
||||
<el-form-item label="Broker地址" required>
|
||||
<el-input v-model="interfaceForm.broker_url" />
|
||||
</el-form-item>
|
||||
<el-form-item label="Broker端口" required>
|
||||
<el-input-number v-model="interfaceForm.broker_port" :min="1" :max="65535" />
|
||||
</el-form-item>
|
||||
<el-form-item label="Topic" required>
|
||||
<el-input v-model="interfaceForm.topic" />
|
||||
</el-form-item>
|
||||
<el-form-item label="用户名">
|
||||
<el-input v-model="interfaceForm.username" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码">
|
||||
<el-input v-model="interfaceForm.password" type="password" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="Client ID">
|
||||
<el-input v-model="interfaceForm.client_id" />
|
||||
</el-form-item>
|
||||
</template>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<span class="dialog-footer">
|
||||
<el-button @click="showAddInterfaceDialog = false">取消</el-button>
|
||||
<el-button type="primary" @click="saveInterface">确定</el-button>
|
||||
</span>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
|
||||
interface InterfaceItem {
|
||||
id: number
|
||||
name: string
|
||||
type: 'CAN' | 'Powerbus' | 'Mqtt' | 'Modbus'
|
||||
description?: string
|
||||
modbus_type?: 'TCP' | 'RTU'
|
||||
ip_address?: string
|
||||
port?: number
|
||||
baud_rate?: number
|
||||
can_channel?: number
|
||||
can_baud_rate?: number
|
||||
broker_url?: string
|
||||
topic?: string
|
||||
broker_port?: number
|
||||
username?: string
|
||||
password?: string
|
||||
client_id?: string
|
||||
data_bits?: number
|
||||
stop_bits?: number
|
||||
parity?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
interface SerialPort {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
// 接口列表
|
||||
const interfaces = ref<InterfaceItem[]>([])
|
||||
const serialPorts = ref<SerialPort[]>([])
|
||||
|
||||
// 对话框控制
|
||||
const showAddInterfaceDialog = ref(false)
|
||||
const editingInterface = ref<InterfaceItem | null>(null)
|
||||
|
||||
// 表单数据
|
||||
const interfaceForm = ref<Partial<InterfaceItem>>({
|
||||
name: '',
|
||||
type: 'CAN',
|
||||
description: '',
|
||||
modbus_type: 'TCP',
|
||||
ip_address: undefined,
|
||||
port: undefined,
|
||||
baud_rate: undefined,
|
||||
can_channel: undefined,
|
||||
can_baud_rate: undefined,
|
||||
broker_url: undefined,
|
||||
topic: undefined,
|
||||
broker_port: undefined,
|
||||
username: undefined,
|
||||
password: undefined,
|
||||
client_id: undefined,
|
||||
data_bits: undefined,
|
||||
stop_bits: undefined,
|
||||
parity: undefined
|
||||
})
|
||||
|
||||
// 获取接口列表
|
||||
const fetchInterfaces = async () => {
|
||||
try {
|
||||
const response = await axios.get<InterfaceItem[]>('/interfaces')
|
||||
interfaces.value = response.data
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message)
|
||||
} else {
|
||||
ElMessage.error('获取接口列表失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取串口列表
|
||||
const fetchSerialPorts = async () => {
|
||||
try {
|
||||
const response = await axios.get<SerialPort[]>('/serial/ports')
|
||||
serialPorts.value = response.data
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message)
|
||||
} else {
|
||||
ElMessage.error('获取串口列表失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 保存接口
|
||||
const saveInterface = async () => {
|
||||
try {
|
||||
if (editingInterface.value) {
|
||||
await axios.put(
|
||||
`/interfaces/${editingInterface.value.id}`,
|
||||
interfaceForm.value
|
||||
)
|
||||
ElMessage.success('接口更新成功')
|
||||
} else {
|
||||
await axios.post('/interfaces', interfaceForm.value)
|
||||
ElMessage.success('接口添加成功')
|
||||
}
|
||||
showAddInterfaceDialog.value = false
|
||||
fetchInterfaces()
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message)
|
||||
} else if (typeof error === 'object' && error !== null && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: { detail?: string } } }
|
||||
ElMessage.error(axiosError.response?.data?.detail || '保存失败')
|
||||
} else {
|
||||
ElMessage.error('保存接口失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 编辑接口
|
||||
const editInterface = (interfaceItem: InterfaceItem) => {
|
||||
editingInterface.value = interfaceItem
|
||||
interfaceForm.value = { ...interfaceItem }
|
||||
showAddInterfaceDialog.value = true
|
||||
}
|
||||
|
||||
// 删除接口
|
||||
const confirmDelete = (interfaceItem: InterfaceItem) => {
|
||||
ElMessageBox.confirm(
|
||||
'确定要删除该接口吗?',
|
||||
'警告',
|
||||
{
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}
|
||||
).then(async () => {
|
||||
try {
|
||||
await axios.delete(`/interfaces/${interfaceItem.id}`)
|
||||
ElMessage.success('接口删除成功')
|
||||
fetchInterfaces()
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
ElMessage.error(error.message)
|
||||
} else if (typeof error === 'object' && error !== null && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: { detail?: string } } }
|
||||
ElMessage.error(axiosError.response?.data?.detail || '删除失败')
|
||||
} else {
|
||||
ElMessage.error('删除接口失败')
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 监听接口类型变化,重置相关字段
|
||||
watch(() => interfaceForm.value.type, (newType) => {
|
||||
if (!newType) return
|
||||
|
||||
// 重置所有相关字段
|
||||
interfaceForm.value.port = undefined
|
||||
interfaceForm.value.can_channel = undefined
|
||||
interfaceForm.value.can_baud_rate = undefined
|
||||
interfaceForm.value.ip_address = undefined
|
||||
interfaceForm.value.baud_rate = undefined
|
||||
interfaceForm.value.data_bits = undefined
|
||||
interfaceForm.value.stop_bits = undefined
|
||||
interfaceForm.value.parity = undefined
|
||||
|
||||
// 如果是Modbus类型,设置默认的modbus_type
|
||||
if (newType === 'Modbus') {
|
||||
interfaceForm.value.modbus_type = 'TCP'
|
||||
} else {
|
||||
interfaceForm.value.modbus_type = undefined
|
||||
}
|
||||
})
|
||||
|
||||
// 监听Modbus类型变化,重置相关字段
|
||||
watch(() => interfaceForm.value.modbus_type, (newModbusType) => {
|
||||
if (!newModbusType) return
|
||||
|
||||
// 重置Modbus相关字段
|
||||
interfaceForm.value.port = undefined
|
||||
interfaceForm.value.ip_address = undefined
|
||||
interfaceForm.value.baud_rate = undefined
|
||||
interfaceForm.value.data_bits = undefined
|
||||
interfaceForm.value.stop_bits = undefined
|
||||
interfaceForm.value.parity = undefined
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
fetchInterfaces()
|
||||
fetchSerialPorts()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.interface-management {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.interface-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.interface-card {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.interface-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.interface-header h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.interface-info {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.info-item .label {
|
||||
color: #909399;
|
||||
margin-right: 8px;
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.interface-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.btn-text {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #409EFF;
|
||||
cursor: pointer;
|
||||
padding: 5px 10px;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.btn-text:hover {
|
||||
color: #66b1ff;
|
||||
}
|
||||
|
||||
.btn-text.danger {
|
||||
color: #F56C6C;
|
||||
}
|
||||
|
||||
.btn-text.danger:hover {
|
||||
color: #f78989;
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,442 @@
|
||||
<template>
|
||||
<div class="service-management">
|
||||
<h2>服务管理</h2>
|
||||
|
||||
<!-- EMQX服务管理 -->
|
||||
<el-card class="service-card">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>EMQX服务</span>
|
||||
<el-tag :type="emqxStatus.toLowerCase() === 'running' ? 'success' : 'danger'">
|
||||
{{ emqxStatus.toLowerCase() === 'running' ? '运行中' : '已停止' }}
|
||||
</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="service-info">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="版本">{{ emqxInfo.version }}</el-descriptions-item>
|
||||
<el-descriptions-item label="节点">{{ emqxInfo.node }}</el-descriptions-item>
|
||||
<el-descriptions-item label="运行时间">{{ formatUptime(emqxInfo.uptime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="当前连接数">{{ emqxInfo.connections }}</el-descriptions-item>
|
||||
<el-descriptions-item label="内存使用">{{ emqxInfo.memory_used }} / {{ emqxInfo.memory_total }}</el-descriptions-item>
|
||||
<el-descriptions-item label="CPU负载">
|
||||
1分钟: {{ emqxInfo.load1 }} | 5分钟: {{ emqxInfo.load5 }} | 15分钟: {{ emqxInfo.load15 }}
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<!-- Powerbus设备通讯服务 -->
|
||||
<el-card class="service-card">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>Powerbus设备通讯服务</span>
|
||||
<el-tag :type="powerbusServiceStatus.available ? 'success' : 'danger'">
|
||||
{{ powerbusServiceStatus.available ? '运行中' : '已停止' }}
|
||||
</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="service-info">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="服务状态">{{ powerbusServiceStatus.available ? '可用' : '不可用' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="运行时间">{{ formatRunningTime(powerbusServiceStatus.running_time) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="service-actions">
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="controlLoading"
|
||||
@click="controlPowerbusService('start')"
|
||||
>
|
||||
启动
|
||||
</el-button>
|
||||
<el-button
|
||||
type="warning"
|
||||
:loading="controlLoading"
|
||||
@click="controlPowerbusService('stop')"
|
||||
>
|
||||
停止
|
||||
</el-button>
|
||||
<el-button
|
||||
type="danger"
|
||||
:loading="controlLoading"
|
||||
@click="controlPowerbusService('restart')"
|
||||
>
|
||||
重启
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
<!-- Modbus设备通讯服务 -->
|
||||
<el-card class="service-card">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>Modbus设备通讯服务</span>
|
||||
<el-tag :type="modbusServiceStatus.available ? 'success' : 'danger'">
|
||||
{{ modbusServiceStatus.available ? '运行中' : '已停止' }}
|
||||
</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="service-info">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="服务状态">{{ powerbusServiceStatus.available ? '可用' : '不可用' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="运行时间">{{ formatRunningTime(powerbusServiceStatus.running_time) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="service-actions">
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="controlLoading"
|
||||
@click="controlModbusService('start')"
|
||||
>
|
||||
启动
|
||||
</el-button>
|
||||
<el-button
|
||||
type="warning"
|
||||
:loading="controlLoading"
|
||||
@click="controlModbusService('stop')"
|
||||
>
|
||||
停止
|
||||
</el-button>
|
||||
<el-button
|
||||
type="danger"
|
||||
:loading="controlLoading"
|
||||
@click="controlModbusService('restart')"
|
||||
>
|
||||
重启
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
<!-- Motor设备通讯服务 -->
|
||||
<el-card class="service-card">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>Motor设备通讯服务</span>
|
||||
<el-tag :type="motorServiceStatus.available ? 'success' : 'danger'">
|
||||
{{ motorServiceStatus.available ? '运行中' : '已停止' }}
|
||||
</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="service-info">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="服务状态">{{ motorServiceStatus.available ? '可用' : '不可用' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="运行时间">{{ formatRunningTime(motorServiceStatus.running_time) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="service-actions">
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="controlLoading2"
|
||||
@click="controlMotorService('start')"
|
||||
>
|
||||
启动
|
||||
</el-button>
|
||||
<el-button
|
||||
type="warning"
|
||||
:loading="controlLoading2"
|
||||
@click="controlMotorService('stop')"
|
||||
>
|
||||
停止
|
||||
</el-button>
|
||||
<el-button
|
||||
type="danger"
|
||||
:loading="controlLoading2"
|
||||
@click="controlMotorService('restart')"
|
||||
>
|
||||
重启
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onActivated, onDeactivated } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
const emqxStatus = ref('unknown')
|
||||
const emqxInfo = ref({
|
||||
version: '',
|
||||
node: '',
|
||||
uptime: 0,
|
||||
connections: 0,
|
||||
memory_used: '',
|
||||
memory_total: '',
|
||||
load1: 0,
|
||||
load5: 0,
|
||||
load15: 0
|
||||
})
|
||||
|
||||
// Powerbus服务状态
|
||||
const powerbusServiceStatus = ref({
|
||||
available: false,
|
||||
running_time: 0
|
||||
})
|
||||
|
||||
const modbusServiceStatus = ref({
|
||||
available: false,
|
||||
running_time: 0
|
||||
})
|
||||
|
||||
// Motor服务状态
|
||||
const motorServiceStatus = ref({
|
||||
available: false,
|
||||
running_time: 0
|
||||
})
|
||||
|
||||
// 控制按钮加载状态
|
||||
const controlLoading = ref(false)
|
||||
const controlLoading2 = ref(false)
|
||||
|
||||
let refreshTimer: number | null = null
|
||||
|
||||
// 格式化运行时间
|
||||
const formatUptime = (ms: number) => {
|
||||
const seconds = Math.floor(ms / 1000)
|
||||
const days = Math.floor(seconds / 86400)
|
||||
const hours = Math.floor((seconds % 86400) / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
|
||||
return `${days}天${hours}小时${minutes}分钟`
|
||||
}
|
||||
|
||||
// 格式化Powerbus服务运行时间(秒)
|
||||
const formatRunningTime = (seconds: number) => {
|
||||
if (!seconds) return '0秒'
|
||||
|
||||
const days = Math.floor(seconds / 86400)
|
||||
const hours = Math.floor((seconds % 86400) / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
const secs = Math.floor(seconds % 60)
|
||||
|
||||
return `${days > 0 ? days + '天' : ''}${hours > 0 ? hours + '小时' : ''}${minutes > 0 ? minutes + '分钟' : ''}${secs}秒`
|
||||
}
|
||||
|
||||
const controlService = async (command: string, serviceName: string) => {
|
||||
controlLoading.value = true
|
||||
try {
|
||||
const response = await axios.post(`/services/control`, {
|
||||
service_name: serviceName,
|
||||
command: command
|
||||
})
|
||||
|
||||
if (response.data.status === 'success') {
|
||||
ElMessage.success(response.data.message)
|
||||
// 控制成功后立即刷新状态
|
||||
setTimeout(fetchServiceStatus, 1000)
|
||||
} else {
|
||||
ElMessage.error(response.data.message || '操作失败')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`控制${serviceName}服务失败:`, error)
|
||||
ElMessage.error(`控制${serviceName}服务失败`)
|
||||
} finally {
|
||||
controlLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 控制Modbus服务
|
||||
const controlModbusService = async (command: string) => {
|
||||
controlService(command, 'modbus_service')
|
||||
}
|
||||
|
||||
// 控制Powerbus服务
|
||||
const controlPowerbusService = async (command: string) => {
|
||||
controlService(command, 'powerbus_service')
|
||||
}
|
||||
|
||||
// 控制Motor服务
|
||||
const controlMotorService = async (command: string) => {
|
||||
controlService(command, 'motor_service')
|
||||
}
|
||||
|
||||
// 获取EMQX状态
|
||||
const fetchEmqxStatus = async () => {
|
||||
try {
|
||||
const response = await axios.get('/services/emqx/status')
|
||||
if (response.data.nodes && response.data.nodes.length > 0) {
|
||||
const node = response.data.nodes[0]
|
||||
emqxStatus.value = node.node_status
|
||||
emqxInfo.value = {
|
||||
version: node.version,
|
||||
node: node.node,
|
||||
uptime: node.uptime,
|
||||
connections: node.connections,
|
||||
memory_used: node.memory_used,
|
||||
memory_total: node.memory_total,
|
||||
load1: node.load1,
|
||||
load5: node.load5,
|
||||
load15: node.load15
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取EMQX状态失败:', error)
|
||||
ElMessage.error('获取EMQX状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 获取Powerbus服务状态
|
||||
const fetchPowerbusServiceStatus = async () => {
|
||||
try {
|
||||
const response = await axios.get('/services/status?service_name=powerbus_service')
|
||||
powerbusServiceStatus.value = response.data
|
||||
} catch (error) {
|
||||
console.error('获取Powerbus设备通讯服务状态失败:', error)
|
||||
ElMessage.error('获取Powerbus设备通讯服务状态失败')
|
||||
powerbusServiceStatus.value = {
|
||||
available: false,
|
||||
running_time: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fetchModbusServiceStatus = async () => {
|
||||
try {
|
||||
const response = await axios.get('/services/status?service_name=modbus_service')
|
||||
modbusServiceStatus.value = response.data
|
||||
} catch (error) {
|
||||
console.error('获取Modbus设备通讯服务状态失败:', error)
|
||||
ElMessage.error('获取Modbus设备通讯服务状态失败')
|
||||
modbusServiceStatus.value = {
|
||||
available: false,
|
||||
running_time: 0
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 获取Motor服务状态
|
||||
const fetchMotorServiceStatus = async () => {
|
||||
try {
|
||||
const response = await axios.get('/services/status?service_name=motor_service')
|
||||
motorServiceStatus.value = response.data
|
||||
} catch (error) {
|
||||
console.error('获取Motor设备通讯服务状态失败:', error)
|
||||
ElMessage.error('获取Motor设备通讯服务状态失败')
|
||||
motorServiceStatus.value = {
|
||||
available: false,
|
||||
running_time: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 启动定时刷新
|
||||
const startRefresh = () => {
|
||||
// 先立即获取一次数据
|
||||
fetchEmqxStatus()
|
||||
fetchPowerbusServiceStatus()
|
||||
fetchModbusServiceStatus()
|
||||
fetchMotorServiceStatus()
|
||||
|
||||
// 每30秒更新一次状态
|
||||
refreshTimer = window.setInterval(() => {
|
||||
fetchEmqxStatus()
|
||||
fetchModbusServiceStatus()
|
||||
fetchPowerbusServiceStatus()
|
||||
fetchMotorServiceStatus()
|
||||
}, 30000)
|
||||
}
|
||||
|
||||
// 停止定时刷新
|
||||
const stopRefresh = () => {
|
||||
if (refreshTimer) {
|
||||
clearInterval(refreshTimer)
|
||||
refreshTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载时获取状态
|
||||
onMounted(() => {
|
||||
startRefresh()
|
||||
})
|
||||
|
||||
// 页面激活时获取状态
|
||||
onActivated(() => {
|
||||
startRefresh()
|
||||
})
|
||||
|
||||
// 页面失活时停止刷新
|
||||
onDeactivated(() => {
|
||||
stopRefresh()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.service-management {
|
||||
padding: 20px;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
min-height: calc(100vh - 84px); /* 减去头部导航的高度 */
|
||||
background-color: #f5f7fa;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin-bottom: 24px;
|
||||
color: #1f2f3d;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.service-card {
|
||||
margin-bottom: 20px;
|
||||
width: 100%;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
transition: box-shadow 0.3s;
|
||||
}
|
||||
|
||||
.service-card:hover {
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
}
|
||||
|
||||
.service-info {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
/* 新增服务操作按钮样式 */
|
||||
.service-actions {
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
:deep(.el-descriptions) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
:deep(.el-descriptions__label) {
|
||||
width: 120px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
:deep(.el-descriptions__content) {
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
:deep(.el-card__header) {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
:deep(.el-card__body) {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
:deep(.el-tag) {
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,42 @@
|
||||
import json
|
||||
|
||||
# MQTT配置
|
||||
BROKER = "127.0.0.1"
|
||||
MQTT_PORT = 1883
|
||||
USER = "test"
|
||||
PWD = "test"
|
||||
|
||||
# Modbus配置
|
||||
TIMEOUT = 0.5
|
||||
BYTESIZE = 8
|
||||
PARITY = 'N'
|
||||
STOPBITS = 1
|
||||
|
||||
# 读取间隔(秒)
|
||||
READ_INTERVAL = 1
|
||||
|
||||
# MQTT主题
|
||||
DEVICE_STATUS_TOPIC = "device/status"
|
||||
DEVICE_CONTROL_TOPIC = "device/control"
|
||||
DEVICE_HVS_CONTROL_TOPIC = "device/hvs/control"
|
||||
DEVICE_API_TOPIC = "api/devices/hvs/response"
|
||||
SERVICE_STATUS_TOPIC = "service/status"
|
||||
|
||||
# 寄存器配置 - 根据实际设备修改
|
||||
INPUT_REGISTERS = {
|
||||
"start_address": 0,
|
||||
"count": 5
|
||||
}
|
||||
|
||||
COIL_REGISTERS = {
|
||||
"start_address": 0,
|
||||
"count": 10
|
||||
}
|
||||
|
||||
CONFIG_FILE = "/home/admin/.config/cpy/hvs.json"
|
||||
|
||||
try:
|
||||
with open(CONFIG_FILE, "r") as f:
|
||||
config = json.load(f)
|
||||
except FileNotFoundError:
|
||||
config = {}
|
||||
Executable
+242
@@ -0,0 +1,242 @@
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from modbus_client import ModbusClient
|
||||
from mqtt_client import mqtt_client
|
||||
from config import *
|
||||
from tcp_io_module import TcpIoModule
|
||||
import threading
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class HvService:
|
||||
def __init__(self):
|
||||
# 记录服务启动时间
|
||||
self.start_time = time.time()
|
||||
|
||||
# 创建线程池用于异步发布消息
|
||||
self.executor = ThreadPoolExecutor(max_workers=5)
|
||||
|
||||
# 初始化Modbus客户端
|
||||
self.modbus_client = ModbusClient()
|
||||
|
||||
# 初始化MQTT客户端
|
||||
self.mqtt_client = mqtt_client
|
||||
|
||||
# 设备列表
|
||||
self.hvs_devices = []
|
||||
|
||||
# 上次发布服务状态的时间
|
||||
self.last_service_status_time = 0
|
||||
|
||||
self.xray_on = [False, False]
|
||||
self.last_hvs_update_time = 0
|
||||
|
||||
self.exit_flag = False
|
||||
self.loop_thread = None
|
||||
|
||||
def handle_hvs_control_message(self, topic, payload):
|
||||
"""异步处理设备控制消息"""
|
||||
if topic == DEVICE_HVS_CONTROL_TOPIC:
|
||||
print(f"handle_hvs_control_message: {topic, payload}")
|
||||
self.executor.submit(self._process_hvs_control_message, payload)
|
||||
elif topic == DEVICE_CONTROL_TOPIC:
|
||||
dev_code = payload.get("device_code")
|
||||
if "HVS" in dev_code :
|
||||
print(f"handle_hvs_control_message: {topic, payload}")
|
||||
dev_id = int(dev_code.split('#')[0])
|
||||
command = payload.get("command")
|
||||
if command == "set_status":
|
||||
value = 1 if payload.get('status') else 0
|
||||
newpayload = {
|
||||
"command" : 'hv_switch',
|
||||
'device_id' : dev_id,
|
||||
'device_code' : dev_code,
|
||||
'value' : value
|
||||
}
|
||||
self.executor.submit(self._process_hvs_control_message, newpayload)
|
||||
|
||||
def _process_hvs_control_message(self, payload):
|
||||
"""处理设备控制消息"""
|
||||
try:
|
||||
logger.info(f"接收到控制消息: {payload}")
|
||||
command = payload.get("command")
|
||||
value = payload.get("value")
|
||||
device_code = payload.get("device_code")
|
||||
slave_id = payload.get("device_id")
|
||||
if not device_code:
|
||||
logger.error("控制消息缺少device_code")
|
||||
return
|
||||
|
||||
# 使用设备管理器控制设备
|
||||
if command == "hv_switch":
|
||||
if value == 1:
|
||||
self.modbus_client.write_coil(slave_id, 0x00, True)
|
||||
else:
|
||||
self.modbus_client.write_coil(slave_id, 0x00, False)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理控制消息失败: {e}")
|
||||
|
||||
def start(self):
|
||||
# 创建线程
|
||||
self.loop_thread = threading.Thread(target=self.loop)
|
||||
self.loop_thread.daemon = True
|
||||
self.loop_thread.start()
|
||||
|
||||
def stop(self):
|
||||
if not self.loop_thread:
|
||||
return
|
||||
"""停止服务"""
|
||||
self.exit_flag = True
|
||||
self.loop_thread.join()
|
||||
self.executor.shutdown(wait=True)
|
||||
|
||||
def loop(self):
|
||||
"""启动服务"""
|
||||
try:
|
||||
# 连接Modbus
|
||||
if not self.modbus_client.connect():
|
||||
logger.error("Modbus连接失败,程序退出")
|
||||
return
|
||||
print("Modbus连接成功")
|
||||
|
||||
# 订阅MQTT主题
|
||||
self.mqtt_client.subscribe(DEVICE_CONTROL_TOPIC, self.handle_hvs_control_message)
|
||||
self.mqtt_client.subscribe(DEVICE_HVS_CONTROL_TOPIC, self.handle_hvs_control_message)
|
||||
|
||||
while not self.mqtt_client.is_connected:
|
||||
time.sleep(1)
|
||||
logger.info("waiting for mqtt conn...")
|
||||
|
||||
logger.info("Modbus和MQTT连接成功,开始定时读取和发布数据...")
|
||||
|
||||
self.hvs_devices = config.get("devices", [])
|
||||
|
||||
if not self.hvs_devices or len(self.hvs_devices) == 0:
|
||||
logger.error("未找到HVS设备,程序退出")
|
||||
return
|
||||
|
||||
logger.info(f"找到 {len(self.hvs_devices)} 个HVS设备")
|
||||
|
||||
logger.info(f"hvs_devices: {json.dumps(self.hvs_devices, ensure_ascii=False)}")
|
||||
|
||||
# 主循环
|
||||
while self.exit_flag == False:
|
||||
# 计算当前时间
|
||||
current_time = time.time()
|
||||
|
||||
# 定期发布服务状态 (每10秒)
|
||||
if current_time - self.last_service_status_time >= 3:
|
||||
self._publish_service_status(current_time)
|
||||
# continue
|
||||
# 读取并发布所有HVS设备数据
|
||||
self.read_and_publish_devices_data()
|
||||
|
||||
# 等待指定间隔
|
||||
time.sleep(READ_INTERVAL)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.info("程序收到中断信号,正在退出...")
|
||||
finally:
|
||||
# 清理资源
|
||||
self.modbus_client.disconnect()
|
||||
logger.info("程序已退出")
|
||||
|
||||
def _publish_service_status(self, current_time):
|
||||
"""发布服务状态"""
|
||||
# 计算运行时间
|
||||
running_time = current_time - self.start_time
|
||||
|
||||
# 准备服务状态消息
|
||||
service_message = {
|
||||
"service_name": "modbus_service",
|
||||
"status": {
|
||||
"available": True,
|
||||
"running_time": running_time
|
||||
}
|
||||
}
|
||||
|
||||
# 发布消息
|
||||
self.mqtt_client.publish(SERVICE_STATUS_TOPIC, service_message)
|
||||
logger.debug(f"成功发布服务状态到 {SERVICE_STATUS_TOPIC}: {service_message}")
|
||||
self.last_service_status_time = current_time
|
||||
|
||||
def read_and_publish_devices_data(self):
|
||||
"""读取并发布所有设备数据"""
|
||||
# 确保Modbus连接正常
|
||||
if not self.modbus_client._ensure_connection():
|
||||
logger.error(f"无法连接到Modbus设备,跳过读取设备 {hvs_device.get('code')}")
|
||||
return
|
||||
|
||||
for hvs_device in self.hvs_devices:
|
||||
try:
|
||||
slave_id = int(hvs_device.get('address'))
|
||||
logger.info(f"开始读取设备 {hvs_device.get('code')} (从站ID: {slave_id}) 数据")
|
||||
|
||||
|
||||
# 读取输入寄存器
|
||||
input_regs = self.modbus_client.read_input_registers(
|
||||
slave_id=slave_id,
|
||||
address=INPUT_REGISTERS["start_address"],
|
||||
count=INPUT_REGISTERS["count"]
|
||||
)
|
||||
if input_regs is None:
|
||||
hvs_device["error_count"] = hvs_device.get("error_count", 10) + 1
|
||||
else:
|
||||
hvs_device["error_count"] = 0
|
||||
|
||||
# 短暂延迟,避免总线冲突
|
||||
time.sleep(0.1)
|
||||
|
||||
# 读取线圈
|
||||
coils = self.modbus_client.read_coils(
|
||||
slave_id=slave_id,
|
||||
address=COIL_REGISTERS["start_address"],
|
||||
count=COIL_REGISTERS["count"]
|
||||
)
|
||||
if coils is None:
|
||||
hvs_device["error_count"] = hvs_device.get("error_count", 10) + 1
|
||||
else:
|
||||
hvs_device["error_count"] = 0
|
||||
|
||||
if coils is not None:
|
||||
# print("coils:", coils)
|
||||
if coils[2]:
|
||||
self.xray_on[slave_id - 1] = True
|
||||
else:
|
||||
self.xray_on[slave_id - 1] = False
|
||||
# print(f"slave_id: {slave_id}, xray_on: {self.xray_on[slave_id - 1]}")
|
||||
self.last_hvs_update_time = time.time()
|
||||
|
||||
# 设备间添加延迟,避免总线冲突
|
||||
time.sleep(0.1)
|
||||
|
||||
# 准备发布的数据
|
||||
|
||||
data = {
|
||||
"device_id": hvs_device.get('id'),
|
||||
"device_code": hvs_device.get('code'),
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"status": {
|
||||
"online": hvs_device.get("error_count", 10) < 5,
|
||||
"voltage": input_regs[0] / 100.0 if input_regs and len(input_regs) > 0 else None,
|
||||
"current": input_regs[1] / 1000.0 if input_regs and len(input_regs) > 1 else None,
|
||||
"current_filament": input_regs[2] / 1000.0 if input_regs and len(input_regs) > 2 else None,
|
||||
"internal_temperature": input_regs[3] / 100.0 if input_regs and len(input_regs) > 3 else None,
|
||||
"fault_status": input_regs[4] if input_regs and len(input_regs) > 4 else None,
|
||||
"switch_status": coils[0] if coils and len(coils) > 0 else None,
|
||||
"xray_status": coils[2] if coils and len(coils) > 2 else None
|
||||
}
|
||||
}
|
||||
# 发布数据
|
||||
self.mqtt_client.publish(DEVICE_STATUS_TOPIC, data)
|
||||
if hvs_device.get("error_count", 10) > 5:
|
||||
logger.error(f"设备 {hvs_device.get('code')} 数据发布失败,错误次数超过5次")
|
||||
else:
|
||||
logger.info(f"成功发布设备数据: {data}")
|
||||
except Exception as e:
|
||||
logger.error(f"处理设备 {hvs_device.get('code')} 数据失败: {e}")
|
||||
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=Hvs Service
|
||||
After=emqx.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
WorkingDirectory=/home/admin/CPY/CPY_AdminPlatform_V3.5/hvs_service
|
||||
ExecStart=/home/admin/CPY/venv/bin/python /home/admin/CPY/CPY_AdminPlatform_V3.5/hvs_service/main.py
|
||||
Restart=always
|
||||
RestartSec=10s
|
||||
StartLimitBurst=5
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,53 @@
|
||||
import time
|
||||
|
||||
from config import *
|
||||
from tcp_io_module import TcpIoModule
|
||||
from hvs import HvService
|
||||
from mqtt_client import mqtt_client
|
||||
|
||||
def main():
|
||||
io_module = TcpIoModule(host='192.168.8.211', port=502)
|
||||
io_module.start()
|
||||
|
||||
hv_service = HvService()
|
||||
hv_service.start()
|
||||
|
||||
light_state = False
|
||||
light_new_state = False
|
||||
|
||||
light_state_update_time = 0.0
|
||||
xray_off_time = 0.0
|
||||
|
||||
while True:
|
||||
try:
|
||||
if time.time() - hv_service.last_hvs_update_time > 5.0:
|
||||
hv_service.xray_on = [False, False]
|
||||
if hv_service.xray_on[0] or hv_service.xray_on[1]:
|
||||
light_new_state = True
|
||||
else:
|
||||
if light_new_state == True:
|
||||
xray_off_time = time.time()
|
||||
light_new_state = False
|
||||
|
||||
if light_state != light_new_state and time.time() - light_state_update_time > 2 and time.time() - xray_off_time > 2:
|
||||
# if light_new_state == False:
|
||||
# if time.time() - xray_off_time > 12.0:
|
||||
# light_state = light_new_state
|
||||
# else:
|
||||
# light_state = light_new_state
|
||||
light_state = light_new_state
|
||||
io_module.control_light(8, light_state)
|
||||
mqtt_client.control_xray_light(light_state)
|
||||
light_state_update_time = time.time()
|
||||
|
||||
time.sleep(0.1)
|
||||
except KeyboardInterrupt:
|
||||
print("程序收到中断信号,正在退出...")
|
||||
io_module.stop()
|
||||
hv_service.stop()
|
||||
mqtt_client.stop()
|
||||
break
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import logging
|
||||
import threading
|
||||
from pymodbus.client import ModbusSerialClient
|
||||
from pymodbus.exceptions import ModbusException, ConnectionException
|
||||
import time
|
||||
from config import *
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RETRIES = 2
|
||||
RECONNECT_INTERVAL = 0.1 # 优化重连间隔时间(秒)
|
||||
|
||||
class ModbusClient:
|
||||
def __init__(self):
|
||||
self.client = None
|
||||
#使用普通锁
|
||||
self.serial_lock = threading.Lock()
|
||||
|
||||
try:
|
||||
port = config.get("interface", {}).get("port", "/dev/ttyModbus")
|
||||
if port:
|
||||
self.port = port
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
baudrate = config.get("interface", {}).get("baudrate", 115200)
|
||||
if baudrate:
|
||||
self.baudrate = baudrate
|
||||
except:
|
||||
pass
|
||||
|
||||
def acquire_lock(self):
|
||||
self.serial_lock.acquire()
|
||||
|
||||
def release_lock(self):
|
||||
self.serial_lock.release()
|
||||
|
||||
def connect(self):
|
||||
"""建立Modbus RTU连接"""
|
||||
try:
|
||||
# 连接操作也需要写锁保护
|
||||
self.acquire_lock()
|
||||
if self.client:
|
||||
try:
|
||||
self.client.close()
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
self.client = None
|
||||
try:
|
||||
self.client = ModbusSerialClient(
|
||||
port=self.port,
|
||||
baudrate=self.baudrate,
|
||||
bytesize=BYTESIZE,
|
||||
parity=PARITY,
|
||||
stopbits=STOPBITS,
|
||||
timeout=TIMEOUT
|
||||
)
|
||||
|
||||
if self.client.connect():
|
||||
logger.info(f"成功连接到Modbus串口: {self.port}")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Modbus串口连接失败: {self.port}")
|
||||
return False
|
||||
finally:
|
||||
self.release_lock()
|
||||
except Exception as e:
|
||||
logger.error(f"Modbus连接异常: {str(e)}")
|
||||
|
||||
return False
|
||||
|
||||
def disconnect(self):
|
||||
"""断开Modbus连接"""
|
||||
try:
|
||||
self.acquire_lock()
|
||||
try:
|
||||
if self.client:
|
||||
self.client.close()
|
||||
logger.info("已断开Modbus连接")
|
||||
finally:
|
||||
self.client = None
|
||||
self.release_lock()
|
||||
except Exception as e:
|
||||
logger.error(f"断开连接异常: {str(e)}")
|
||||
|
||||
|
||||
def read_input_registers(self, slave_id, address, count):
|
||||
"""读取输入寄存器,包含重试机制和线程锁保护"""
|
||||
|
||||
# 先确保连接正常,减少锁内操作
|
||||
if self.client is None or not self.client.is_socket_open():
|
||||
logger.error(f"无法确保Modbus连接,无法读取输入寄存器 (从站{slave_id}, 地址{address})")
|
||||
return None
|
||||
|
||||
try:
|
||||
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||
self.acquire_lock()
|
||||
try:
|
||||
response = self.client.read_input_registers(
|
||||
address=address,
|
||||
count=count,
|
||||
device_id=slave_id
|
||||
)
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
# 检查响应
|
||||
if response.isError():
|
||||
logger.error(f"读取输入寄存器错误: 从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES}, 错误: {response}")
|
||||
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||
|
||||
logger.debug(f"成功读取输入寄存器: 从站{slave_id}, 地址{address}, 值: {response.registers}")
|
||||
return response.registers
|
||||
except ModbusException as e:
|
||||
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"读取输入寄存器异常: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
return None
|
||||
|
||||
def read_coils(self, slave_id, address, count):
|
||||
"""读取线圈状态,包含重试机制和线程锁保护"""
|
||||
|
||||
# 先确保连接正常,减少锁内操作
|
||||
if self.client is None or not self.client.is_socket_open():
|
||||
logger.error(f"无法确保Modbus连接,无法读取线圈 (从站{slave_id}, 地址{address})")
|
||||
return None
|
||||
|
||||
try:
|
||||
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||
self.acquire_lock()
|
||||
try:
|
||||
response = self.client.read_coils(
|
||||
address=address,
|
||||
count=count,
|
||||
device_id=slave_id
|
||||
)
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
# 检查响应
|
||||
if response.isError():
|
||||
logger.error(f"读取线圈错误: 从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES}, 错误: {response}")
|
||||
|
||||
logger.debug(f"成功读取线圈: 从站{slave_id}, 地址{address}, 值: {response.bits[:count]}")
|
||||
return response.bits[:count]
|
||||
except ModbusException as e:
|
||||
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"读取线圈异常: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
return None
|
||||
def _ensure_connection(self) -> bool:
|
||||
"""确保Modbus连接正常
|
||||
|
||||
Returns:
|
||||
bool: 连接是否正常
|
||||
"""
|
||||
self.acquire_lock()
|
||||
try:
|
||||
if self.client and self.client.is_socket_open():
|
||||
return True
|
||||
return self.connect()
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
def write_coil(self, slave_id: int, address: int, value: bool) -> bool:
|
||||
"""写入线圈状态,带重试机制和线程锁保护
|
||||
|
||||
Args:
|
||||
slave_id: 从站地址
|
||||
address: 线圈地址
|
||||
value: 线圈状态(True/False)
|
||||
|
||||
Returns:
|
||||
bool: 写入是否成功
|
||||
"""
|
||||
# 先确保连接正常,减少锁内操作
|
||||
if not self._ensure_connection():
|
||||
logger.error(f"无法确保Modbus连接,无法写入线圈 (从站{slave_id}, 地址{address})")
|
||||
return False
|
||||
|
||||
for attempt in range(RETRIES):
|
||||
try:
|
||||
# 只在实际写操作时使用锁,减少锁持有时间
|
||||
self.acquire_lock()
|
||||
response = None
|
||||
try:
|
||||
logger.debug(f"发送写入线圈请求: 从站{slave_id}, 地址{address}, 状态{value}")
|
||||
response = self.client.write_coil(address, value, device_id=slave_id)
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
if response:
|
||||
# 检查响应
|
||||
if response.isError():
|
||||
logger.error(f"写入线圈错误响应: 从站{slave_id}, 地址{address} (尝试{attempt+1}/{RETRIES})")
|
||||
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05) # 使用更短的延迟
|
||||
continue
|
||||
else:
|
||||
logger.debug(f"接收到写入线圈响应: 长度{len(response.encode())}字节, 内容{response.encode().hex()}")
|
||||
|
||||
# 快速释放锁,减少其他操作等待时间
|
||||
|
||||
logger.info(f"成功写入线圈 {address}: {value} (尝试{attempt+1}/{RETRIES})")
|
||||
return True
|
||||
except ConnectionException as e:
|
||||
logger.error(f"连接中断错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
self.connected = False # 修正变量名
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05)
|
||||
except ModbusException as e:
|
||||
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05)
|
||||
except Exception as e:
|
||||
logger.error(f"写入线圈未知错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05)
|
||||
|
||||
logger.error(f"所有{RETRIES}次写入线圈尝试均失败: 从站{slave_id}, 地址{address}")
|
||||
return False
|
||||
@@ -0,0 +1,175 @@
|
||||
import paho.mqtt.client as mqtt
|
||||
import json
|
||||
import socket
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import time
|
||||
import socket
|
||||
from threading import Timer
|
||||
from config import *
|
||||
from typing import Dict, Any, List, Optional, Callable
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class MQTTClient():
|
||||
def __init__(self, broker: str, port: int = 1883, client_id: str = None):
|
||||
self.client = mqtt.Client(client_id = 'hv_service_' + self.random_string(6)) # 创建本地客户端
|
||||
self.client.username_pw_set(USER,PWD)
|
||||
self.broker = broker
|
||||
self.port = port
|
||||
self.callbacks: Dict[str, Callable] = {}
|
||||
self.received_messages = {}
|
||||
self.message_events = {}
|
||||
|
||||
self.is_connected = False
|
||||
|
||||
# 设置回调函数
|
||||
self.client.on_connect = self._on_connect
|
||||
self.client.on_message = self._on_message
|
||||
self.client.on_disconnect = self._on_disconnect
|
||||
|
||||
Timer(1, self.connTimerHandler).start()
|
||||
|
||||
def random_string(self, length=6):
|
||||
"""生成随机字符串"""
|
||||
import random
|
||||
import string
|
||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||
|
||||
def stop(self):
|
||||
"""停止服务"""
|
||||
self.client.loop_stop()
|
||||
self.client.disconnect()
|
||||
|
||||
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():
|
||||
self.client.connect(BROKER, MQTT_PORT) # 连接本地 MQTT 服务器
|
||||
self.client.loop_start() # 开始循环以处理网络流量
|
||||
else:
|
||||
print("local mqtt brokeris not ready")
|
||||
|
||||
Timer(1, self.connTimerHandler).start()
|
||||
|
||||
def connect(self):
|
||||
"""连接到MQTT代理并处理连接错误"""
|
||||
try:
|
||||
self.client.connect(self.broker, self.port)
|
||||
self.client.loop_start()
|
||||
logger.info(f"成功连接到MQTT代理: {self.broker}:{self.port}")
|
||||
return True
|
||||
except socket.gaierror:
|
||||
logger.error(f"MQTT代理地址解析失败: {self.broker}")
|
||||
except ConnectionRefusedError:
|
||||
logger.error(f"MQTT代理拒绝连接: {self.broker}:{self.port}")
|
||||
except Exception as e:
|
||||
logger.error(f"MQTT连接失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def disconnect(self):
|
||||
"""断开MQTT连接"""
|
||||
self.client.loop_stop()
|
||||
self.client.disconnect()
|
||||
|
||||
def subscribe(self, topic: str, callback: Callable):
|
||||
"""订阅主题并设置回调函数"""
|
||||
self.callbacks[topic] = callback
|
||||
|
||||
def publish(self, topic: str, message: Dict[str, Any]):
|
||||
"""发布消息到指定主题"""
|
||||
payload = json.dumps(message)
|
||||
self.client.publish(topic, payload)
|
||||
|
||||
|
||||
def control_xray_light(self, value):
|
||||
msg = {
|
||||
"device_code" : "1#ALU",
|
||||
"command" : "set_status",
|
||||
"status" : value
|
||||
}
|
||||
# print("publish", DEVICE_CONTROL_TOPIC, msg)
|
||||
self.publish(DEVICE_CONTROL_TOPIC, msg) # 发布数据到本地
|
||||
|
||||
def _on_connect(self, client, userdata, flags, rc):
|
||||
"""连接回调"""
|
||||
print(f"已连接到MQTT代理: {self.broker}")
|
||||
for topic in self.callbacks:
|
||||
self.client.subscribe(topic)
|
||||
self.is_connected = True
|
||||
|
||||
def _on_message(self, client, userdata, msg):
|
||||
"""消息接收回调"""
|
||||
print("mqtt msg:", msg.topic, msg.payload)
|
||||
topic = msg.topic
|
||||
try:
|
||||
payload = json.loads(msg.payload.decode())
|
||||
if topic in self.callbacks:
|
||||
self.callbacks[topic](topic, payload)
|
||||
|
||||
# 存储接收到的消息
|
||||
self.received_messages[topic] = msg
|
||||
|
||||
# 触发等待事件
|
||||
if topic in self.message_events:
|
||||
event = self.message_events.pop(topic)
|
||||
event.set()
|
||||
|
||||
except json.JSONDecodeError:
|
||||
print(f"无法解析消息: {msg.payload}")
|
||||
|
||||
def _on_disconnect(self, client, userdata, rc):
|
||||
"""断开连接回调"""
|
||||
print(f"已断开与MQTT代理的连接: {self.broker}")
|
||||
self.is_connected= False
|
||||
|
||||
def wait_for_message(self, topic: str, timeout: float = 5.0) -> Optional[mqtt.MQTTMessage]:
|
||||
"""等待接收指定主题的消息
|
||||
|
||||
Args:
|
||||
topic: 要等待的主题
|
||||
timeout: 超时时间(秒)
|
||||
|
||||
Returns:
|
||||
接收到的消息对象,如果超时则返回None
|
||||
"""
|
||||
import threading
|
||||
|
||||
# 检查是否已经有缓存的消息
|
||||
if topic in self.received_messages:
|
||||
return self.received_messages.pop(topic)
|
||||
|
||||
# 创建事件对象
|
||||
event = threading.Event()
|
||||
self.message_events[topic] = event
|
||||
|
||||
# 等待事件触发或超时
|
||||
event.wait(timeout)
|
||||
|
||||
# 移除事件对象
|
||||
if topic in self.message_events:
|
||||
self.message_events.pop(topic)
|
||||
|
||||
# 返回接收到的消息
|
||||
return self.received_messages.pop(topic, None)
|
||||
|
||||
|
||||
mqtt_client = MQTTClient(broker=BROKER, port=MQTT_PORT)
|
||||
@@ -0,0 +1,2 @@
|
||||
pymodbus>=3.5.0
|
||||
paho-mqtt>=2.1.0
|
||||
Executable
+209
@@ -0,0 +1,209 @@
|
||||
import time
|
||||
import threading
|
||||
from pymodbus.client import ModbusTcpClient
|
||||
class TcpIoModule():
|
||||
def __init__(self, host='localhost', port=502, timeout=3, retry_interval=1, max_retries=0):
|
||||
|
||||
"""
|
||||
初始化TCP IO模块
|
||||
:param host: 服务器IP地址
|
||||
:param port: 服务器端口
|
||||
:param timeout: 超时时间(秒)
|
||||
:param retry_interval: 重连间隔(秒)
|
||||
:param max_retries: 最大重连次数,0表示无限重试
|
||||
"""
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.timeout = timeout
|
||||
self.retry_interval = retry_interval
|
||||
self.max_retries = max_retries
|
||||
self.client = None
|
||||
self.is_connected = False
|
||||
self.is_running = False
|
||||
self.read_thread = None
|
||||
self.register_values = {}
|
||||
self.reconnect_count = 0
|
||||
self.reconnect_lock = threading.Lock()
|
||||
self.button_states = [False] * 10
|
||||
|
||||
def _connect(self):
|
||||
"""
|
||||
连接到Modbus服务器
|
||||
:return: 是否连接成功
|
||||
"""
|
||||
try:
|
||||
if self.client:
|
||||
self.client.close()
|
||||
self.client = ModbusTcpClient(host=self.host, port=self.port, timeout=self.timeout)
|
||||
self.is_connected = self.client.connect()
|
||||
if self.is_connected:
|
||||
print(f"成功连接到Modbus服务器: {self.host}:{self.port}")
|
||||
self.reconnect_count = 0
|
||||
else:
|
||||
print(f"连接Modbus服务器失败: {self.host}:{self.port}")
|
||||
return self.is_connected
|
||||
except Exception as e:
|
||||
print(f"连接失败: {e}")
|
||||
self.is_connected = False
|
||||
return False
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
启动Modbus客户端,开始读取寄存器
|
||||
:return: 是否启动成功
|
||||
"""
|
||||
|
||||
|
||||
self.is_running = True
|
||||
self.read_thread = threading.Thread(target=self._read_data_loop)
|
||||
self.read_thread.daemon = True
|
||||
self.read_thread.start()
|
||||
return True
|
||||
|
||||
def stop(self):
|
||||
"""
|
||||
停止Modbus客户端
|
||||
"""
|
||||
self.is_running = False
|
||||
if self.read_thread and self.read_thread.is_alive():
|
||||
self.read_thread.join(timeout=1.0)
|
||||
if self.client:
|
||||
self.client.close()
|
||||
self.is_connected = False
|
||||
print("Modbus客户端已停止")
|
||||
|
||||
def _read_data_loop(self):
|
||||
"""
|
||||
循环读取寄存器的内部方法
|
||||
"""
|
||||
while self.is_running:
|
||||
if not self.is_connected:
|
||||
# 连接断开,尝试重连
|
||||
with self.reconnect_lock:
|
||||
if not self.is_connected and self._auto_reconnect():
|
||||
print("连成功")
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
|
||||
try:
|
||||
# 这里实现读取寄存器的逻辑
|
||||
self.read_data()
|
||||
time.sleep(0.1) # 每秒读取一次
|
||||
except Exception as e:
|
||||
print(f"读取寄存器出错: {e}")
|
||||
# 读取错误可能是连接问题,标记为断开以便重连
|
||||
self.is_connected = False
|
||||
time.sleep(0.5)
|
||||
|
||||
def _auto_reconnect(self):
|
||||
"""
|
||||
自动重连机制
|
||||
:return: 是否重连成功
|
||||
"""
|
||||
# 只尝试一次重连,避免长时间持有锁
|
||||
if self.is_running and (self.max_retries == 0 or self.reconnect_count < self.max_retries):
|
||||
self.reconnect_count += 1
|
||||
|
||||
if self._connect():
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def read_data(self):
|
||||
"""
|
||||
读取寄存器的方法
|
||||
"""
|
||||
try:
|
||||
# 读取输入寄存器,起始地址为0,读取10个寄存器
|
||||
response = self.client.read_discrete_inputs(address=0, count= 4)
|
||||
if not response.isError():
|
||||
for idx, bit in enumerate(response.bits):
|
||||
if idx == 3:
|
||||
# 检测下降沿:从抬起(True)变为按下(False)
|
||||
previous_state = self.button_states[idx]
|
||||
current_state = bit
|
||||
|
||||
# 更新当前状态
|
||||
self.button_states[idx] = current_state
|
||||
|
||||
# 下降沿检测
|
||||
if previous_state == True and current_state == False:
|
||||
self.control_stop()
|
||||
print("=================control_stop")
|
||||
|
||||
else:
|
||||
if bit:
|
||||
print(f"寄存器 {idx} 的值是 {bit}")
|
||||
self.button_states[idx] = True
|
||||
|
||||
elif self.button_states[idx]:
|
||||
self.button_states[idx] = False
|
||||
if idx == 0:
|
||||
self.control_start()
|
||||
print("=================control_start")
|
||||
elif idx == 1:
|
||||
self.control_pause()
|
||||
print("=================control_pause")
|
||||
elif idx == 2:
|
||||
self.control_reset()
|
||||
print("=================control_reset")
|
||||
|
||||
else:
|
||||
print(f"读取寄存器出错: {response}")
|
||||
self.is_connected = False
|
||||
except Exception as e:
|
||||
print(f"读取寄存器出错: {e}")
|
||||
self.is_connected = False
|
||||
|
||||
def control_start(self):
|
||||
self.control_light(9, True)
|
||||
"""
|
||||
控制设备启动
|
||||
"""
|
||||
|
||||
def control_pause(self):
|
||||
self.control_light(9, False)
|
||||
"""
|
||||
控制设备暂停
|
||||
"""
|
||||
|
||||
def control_reset(self):
|
||||
"""
|
||||
控制设备复位
|
||||
"""
|
||||
|
||||
def control_stop(self):
|
||||
self.control_light(9, False)
|
||||
"""
|
||||
控制设备停止
|
||||
"""
|
||||
|
||||
def control_light(self, index, value):
|
||||
try:
|
||||
self.client.write_coil(index, value)
|
||||
except Exception as e:
|
||||
print(f"写入线圈出错: {e}")
|
||||
self.is_connected = False
|
||||
|
||||
def get_register_value(self, register_address):
|
||||
"""
|
||||
获取指定寄存器的值
|
||||
:param register_address: 寄存器地址
|
||||
:return: 寄存器值或None(如果不存在)
|
||||
"""
|
||||
return self.register_values.get(register_address)
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 示例用法
|
||||
modbus_client = TcpIoModule(host='192.168.8.211', port=502)
|
||||
if modbus_client.start():
|
||||
print("Modbus客户端已启动")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
print("停止Modbus客户端")
|
||||
modbus_client.stop()
|
||||
else:
|
||||
print("Modbus客户端启动失败")
|
||||
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
server {
|
||||
listen 80;
|
||||
root /home/admin/CPY/CPY_AdminPlatform_V3.5/frontend/dist/;
|
||||
index index.html;
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
location /api {
|
||||
proxy_pass http://localhost:8000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import json
|
||||
|
||||
# MQTT配置
|
||||
BROKER = "127.0.0.1"
|
||||
MQTT_PORT = 1883
|
||||
USER = "test"
|
||||
PWD = "test"
|
||||
|
||||
# Modbus配置
|
||||
TIMEOUT = 0.1
|
||||
BYTESIZE = 8
|
||||
PARITY = 'N'
|
||||
STOPBITS = 1
|
||||
|
||||
# MQTT主题
|
||||
DEVICE_STATUS_TOPIC = "device/status"
|
||||
DEVICE_CONTROL_TOPIC = "device/control"
|
||||
SERVICE_STATUS_TOPIC = "service/status"
|
||||
|
||||
CONFIG_FILE = "/home/admin/.config/cpy/sensor.json"
|
||||
|
||||
try:
|
||||
with open(CONFIG_FILE, "r") as f:
|
||||
config = json.load(f)
|
||||
except FileNotFoundError:
|
||||
config = {}
|
||||
@@ -0,0 +1,24 @@
|
||||
import time
|
||||
|
||||
from config import *
|
||||
from sensor import SensorService
|
||||
from mqtt_client import mqtt_client
|
||||
|
||||
def main():
|
||||
|
||||
sensor_service = SensorService()
|
||||
|
||||
sensor_service.start()
|
||||
|
||||
while True:
|
||||
try:
|
||||
time.sleep(0.1)
|
||||
except KeyboardInterrupt:
|
||||
print("程序收到中断信号,正在退出...")
|
||||
sensor_service.stop()
|
||||
mqtt_client.stop()
|
||||
break
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import logging
|
||||
import threading
|
||||
from pymodbus.client import ModbusSerialClient
|
||||
from pymodbus.exceptions import ModbusException, ConnectionException
|
||||
import time
|
||||
from config import *
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RETRIES = 2
|
||||
RECONNECT_INTERVAL = 0.1 # 优化重连间隔时间(秒)
|
||||
|
||||
class ModbusClient:
|
||||
def __init__(self):
|
||||
self.client = None
|
||||
#使用普通锁
|
||||
self.serial_lock = threading.Lock()
|
||||
|
||||
try:
|
||||
port = config.get("interface", {}).get("port", "/dev/ttyPowerbus")
|
||||
if port:
|
||||
self.port = port
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
baudrate = config.get("interface", {}).get("baudrate", 9600)
|
||||
if baudrate:
|
||||
self.baudrate = baudrate
|
||||
except:
|
||||
pass
|
||||
|
||||
def acquire_lock(self):
|
||||
self.serial_lock.acquire()
|
||||
|
||||
def release_lock(self):
|
||||
self.serial_lock.release()
|
||||
|
||||
def connect(self):
|
||||
"""建立Modbus RTU连接"""
|
||||
try:
|
||||
# 连接操作也需要写锁保护
|
||||
self.acquire_lock()
|
||||
if self.client:
|
||||
try:
|
||||
self.client.close()
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
self.client = None
|
||||
try:
|
||||
self.client = ModbusSerialClient(
|
||||
port=self.port,
|
||||
baudrate=self.baudrate,
|
||||
bytesize=BYTESIZE,
|
||||
parity=PARITY,
|
||||
stopbits=STOPBITS,
|
||||
retries=0,
|
||||
timeout=TIMEOUT
|
||||
)
|
||||
|
||||
if self.client.connect():
|
||||
logger.info(f"成功连接到Modbus串口: {self.port}")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Modbus串口连接失败: {self.port}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f"Modbus连接异常: {str(e)}")
|
||||
return False
|
||||
finally:
|
||||
self.release_lock()
|
||||
except Exception as e:
|
||||
logger.error(f"Modbus连接异常: {str(e)}")
|
||||
|
||||
return False
|
||||
|
||||
def disconnect(self):
|
||||
"""断开Modbus连接"""
|
||||
try:
|
||||
self.acquire_lock()
|
||||
try:
|
||||
if self.client:
|
||||
self.client.close()
|
||||
logger.info("已断开Modbus连接")
|
||||
finally:
|
||||
self.client = None
|
||||
self.release_lock()
|
||||
except Exception as e:
|
||||
logger.error(f"断开连接异常: {str(e)}")
|
||||
|
||||
|
||||
def read_input_registers(self, slave_id, address, count):
|
||||
"""读取输入寄存器,包含重试机制和线程锁保护"""
|
||||
|
||||
# 先确保连接正常,减少锁内操作
|
||||
if self.client is None or not self.client.is_socket_open():
|
||||
logger.error(f"无法确保Modbus连接,无法读取输入寄存器 (从站{slave_id}, 地址{address})")
|
||||
return None
|
||||
|
||||
try:
|
||||
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||
self.acquire_lock()
|
||||
try:
|
||||
response = self.client.read_input_registers(
|
||||
address=address,
|
||||
count=count,
|
||||
device_id=slave_id
|
||||
)
|
||||
except ModbusException as e:
|
||||
return None
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
# 检查响应
|
||||
if not response:
|
||||
logger.error(f"读取输入寄存器返回空响应: 从站{slave_id}, 地址{address}")
|
||||
return None
|
||||
|
||||
if response and response.isError():
|
||||
logger.error(f"读取输入寄存器错误: 从站{slave_id}, 地址{address}, 错误: {response}")
|
||||
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||
|
||||
logger.debug(f"成功读取输入寄存器: 从站{slave_id}, 地址{address}, 值: {response.registers}")
|
||||
return response.registers
|
||||
except ModbusException as e:
|
||||
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address})")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"读取输入寄存器异常: {str(e)} (从站{slave_id}, 地址{address})")
|
||||
|
||||
return None
|
||||
|
||||
def read_holding_registers(self, slave_id, address, count):
|
||||
"""读取保持寄存器,包含重试机制和线程锁保护"""
|
||||
# 先确保连接正常,减少锁内操作
|
||||
if self.client is None or not self.client.is_socket_open():
|
||||
logger.error(f"无法确保Modbus连接,无法读取保持寄存器 (从站{slave_id}, 地址{address})")
|
||||
return None
|
||||
|
||||
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||
self.acquire_lock()
|
||||
try:
|
||||
response = self.client.read_holding_registers(
|
||||
address=address,
|
||||
count=count,
|
||||
device_id=slave_id
|
||||
)
|
||||
except ModbusException as e:
|
||||
return None
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
if not response:
|
||||
logger.error(f"读取保持寄存器返回空响应: 从站{slave_id}, 地址{address}")
|
||||
return None
|
||||
|
||||
# 检查响应
|
||||
if response.isError():
|
||||
logger.error(f"读取保持寄存器错误: 从站{slave_id}, 地址{address},错误: {response}")
|
||||
return None
|
||||
|
||||
logger.debug(f"成功读取保持寄存器: 从站{slave_id}, 地址{address}, 值: {response.registers}")
|
||||
return response.registers
|
||||
|
||||
|
||||
def read_coils(self, slave_id, address, count):
|
||||
"""读取线圈状态,包含重试机制和线程锁保护"""
|
||||
|
||||
# 先确保连接正常,减少锁内操作
|
||||
if self.client is None or not self.client.is_socket_open():
|
||||
logger.error(f"无法确保Modbus连接,无法读取线圈 (从站{slave_id}, 地址{address})")
|
||||
return None
|
||||
|
||||
try:
|
||||
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||
self.acquire_lock()
|
||||
try:
|
||||
response = self.client.read_coils(
|
||||
address=address,
|
||||
count=count,
|
||||
device_id=slave_id
|
||||
)
|
||||
except ModbusException as e:
|
||||
return None
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
if not response:
|
||||
logger.error(f"读取线圈返回空响应: 从站{slave_id}, 地址{address}")
|
||||
return None
|
||||
|
||||
# 检查响应
|
||||
if response.isError():
|
||||
logger.error(f"读取线圈错误: 从站{slave_id}, 地址{address}, 错误: {response}")
|
||||
return None
|
||||
|
||||
logger.debug(f"成功读取线圈: 从站{slave_id}, 地址{address}, 值: {response.bits[:count]}")
|
||||
return response.bits[:count]
|
||||
except ModbusException as e:
|
||||
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address})")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"读取线圈异常: {str(e)} (从站{slave_id}, 地址{address})")
|
||||
|
||||
return None
|
||||
def _ensure_connection(self) -> bool:
|
||||
"""确保Modbus连接正常
|
||||
|
||||
Returns:
|
||||
bool: 连接是否正常
|
||||
"""
|
||||
self.acquire_lock()
|
||||
try:
|
||||
if self.client and self.client.is_socket_open():
|
||||
return True
|
||||
return self.connect()
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
def write_coil(self, slave_id: int, address: int, value: bool) -> bool:
|
||||
"""写入线圈状态,带重试机制和线程锁保护
|
||||
|
||||
Args:
|
||||
slave_id: 从站地址
|
||||
address: 线圈地址
|
||||
value: 线圈状态(True/False)
|
||||
|
||||
Returns:
|
||||
bool: 写入是否成功
|
||||
"""
|
||||
# 先确保连接正常,减少锁内操作
|
||||
if not self._ensure_connection():
|
||||
logger.error(f"无法确保Modbus连接,无法写入线圈 (从站{slave_id}, 地址{address})")
|
||||
return False
|
||||
|
||||
for attempt in range(RETRIES):
|
||||
try:
|
||||
# 只在实际写操作时使用锁,减少锁持有时间
|
||||
self.acquire_lock()
|
||||
response = None
|
||||
try:
|
||||
logger.debug(f"发送写入线圈请求: 从站{slave_id}, 地址{address}, 状态{value}")
|
||||
response = self.client.write_coil(address, value, device_id=slave_id)
|
||||
finally:
|
||||
self.release_lock()
|
||||
|
||||
if response:
|
||||
# 检查响应
|
||||
if response.isError():
|
||||
logger.error(f"写入线圈错误响应: 从站{slave_id}, 地址{address} (尝试{attempt+1}/{RETRIES})")
|
||||
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05) # 使用更短的延迟
|
||||
continue
|
||||
else:
|
||||
logger.debug(f"接收到写入线圈响应: 长度{len(response.encode())}字节, 内容{response.encode().hex()}")
|
||||
|
||||
# 快速释放锁,减少其他操作等待时间
|
||||
|
||||
logger.info(f"成功写入线圈 {address}: {value} (尝试{attempt+1}/{RETRIES})")
|
||||
return True
|
||||
except ConnectionException as e:
|
||||
logger.error(f"连接中断错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
self.connected = False # 修正变量名
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05)
|
||||
except ModbusException as e:
|
||||
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05)
|
||||
except Exception as e:
|
||||
logger.error(f"写入线圈未知错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||
|
||||
if attempt < RETRIES - 1:
|
||||
time.sleep(0.05)
|
||||
|
||||
logger.error(f"所有{RETRIES}次写入线圈尝试均失败: 从站{slave_id}, 地址{address}")
|
||||
return False
|
||||
@@ -0,0 +1,174 @@
|
||||
import paho.mqtt.client as mqtt
|
||||
import json
|
||||
import socket
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import time
|
||||
import socket
|
||||
from threading import Timer
|
||||
from config import *
|
||||
from typing import Dict, Any, List, Optional, Callable
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class MQTTClient():
|
||||
def __init__(self, broker: str, port: int = 1883, client_id: str = None):
|
||||
self.client = mqtt.Client(client_id = 'powerbus_service_' + self.random_string(6)) # 创建本地客户端
|
||||
self.client.username_pw_set(USER, PWD)
|
||||
self.broker = broker
|
||||
self.port = port
|
||||
self.callbacks: Dict[str, Callable] = {}
|
||||
self.received_messages = {}
|
||||
self.message_events = {}
|
||||
|
||||
self.is_connected = False
|
||||
|
||||
# 设置回调函数
|
||||
self.client.on_connect = self._on_connect
|
||||
self.client.on_message = self._on_message
|
||||
self.client.on_disconnect = self._on_disconnect
|
||||
|
||||
Timer(1, self.connTimerHandler).start()
|
||||
|
||||
def random_string(self, length=6):
|
||||
"""生成随机字符串"""
|
||||
import random
|
||||
import string
|
||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||
|
||||
def stop(self):
|
||||
"""停止服务"""
|
||||
self.client.loop_stop()
|
||||
self.client.disconnect()
|
||||
|
||||
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():
|
||||
logger.info("local mqtt broker is ready")
|
||||
self.connect()
|
||||
else:
|
||||
logger.info("local mqtt brokeris not ready")
|
||||
|
||||
Timer(1, self.connTimerHandler).start()
|
||||
|
||||
def connect(self):
|
||||
"""连接到MQTT代理并处理连接错误"""
|
||||
try:
|
||||
self.client.connect(self.broker, self.port)
|
||||
self.client.loop_start()
|
||||
logger.info(f"成功连接到MQTT代理: {self.broker}:{self.port}")
|
||||
return True
|
||||
except socket.gaierror:
|
||||
logger.error(f"MQTT代理地址解析失败: {self.broker}")
|
||||
except ConnectionRefusedError:
|
||||
logger.error(f"MQTT代理拒绝连接: {self.broker}:{self.port}")
|
||||
except Exception as e:
|
||||
logger.error(f"MQTT连接失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def disconnect(self):
|
||||
"""断开MQTT连接"""
|
||||
self.client.loop_stop()
|
||||
self.client.disconnect()
|
||||
|
||||
def subscribe(self, topic: str, callback: Callable):
|
||||
"""订阅主题并设置回调函数"""
|
||||
self.callbacks[topic] = callback
|
||||
|
||||
def publish(self, topic: str, message: Dict[str, Any]):
|
||||
"""发布消息到指定主题"""
|
||||
payload = json.dumps(message)
|
||||
self.client.publish(topic, payload)
|
||||
|
||||
def control_xray_light(self, value):
|
||||
msg = {
|
||||
"device_code" : "1#ALU",
|
||||
"command" : "set_status",
|
||||
"status" : value
|
||||
}
|
||||
logger.info(f"publish {DEVICE_CONTROL_TOPIC} {msg}")
|
||||
self.publish(DEVICE_CONTROL_TOPIC, msg) # 发布数据到本地
|
||||
|
||||
def _on_connect(self, client, userdata, flags, rc):
|
||||
"""连接回调"""
|
||||
logger.info(f"已连接到MQTT代理: {self.broker}")
|
||||
for topic in self.callbacks:
|
||||
self.client.subscribe(topic)
|
||||
self.is_connected = True
|
||||
|
||||
def _on_message(self, client, userdata, msg):
|
||||
"""消息接收回调"""
|
||||
logger.info(f"mqtt msg: {msg.topic} {msg.payload}")
|
||||
topic = msg.topic
|
||||
try:
|
||||
payload = json.loads(msg.payload.decode())
|
||||
if topic in self.callbacks:
|
||||
self.callbacks[topic](topic, payload)
|
||||
|
||||
# 存储接收到的消息
|
||||
self.received_messages[topic] = msg
|
||||
|
||||
# 触发等待事件
|
||||
if topic in self.message_events:
|
||||
event = self.message_events.pop(topic)
|
||||
event.set()
|
||||
|
||||
except json.JSONDecodeError:
|
||||
print(f"无法解析消息: {msg.payload}")
|
||||
|
||||
def _on_disconnect(self, client, userdata, rc):
|
||||
"""断开连接回调"""
|
||||
print(f"已断开与MQTT代理的连接: {self.broker}")
|
||||
self.is_connected= False
|
||||
|
||||
def wait_for_message(self, topic: str, timeout: float = 5.0) -> Optional[mqtt.MQTTMessage]:
|
||||
"""等待接收指定主题的消息
|
||||
|
||||
Args:
|
||||
topic: 要等待的主题
|
||||
timeout: 超时时间(秒)
|
||||
|
||||
Returns:
|
||||
接收到的消息对象,如果超时则返回None
|
||||
"""
|
||||
import threading
|
||||
|
||||
# 检查是否已经有缓存的消息
|
||||
if topic in self.received_messages:
|
||||
return self.received_messages.pop(topic)
|
||||
|
||||
# 创建事件对象
|
||||
event = threading.Event()
|
||||
self.message_events[topic] = event
|
||||
|
||||
# 等待事件触发或超时
|
||||
event.wait(timeout)
|
||||
|
||||
# 移除事件对象
|
||||
if topic in self.message_events:
|
||||
self.message_events.pop(topic)
|
||||
|
||||
# 返回接收到的消息
|
||||
return self.received_messages.pop(topic, None)
|
||||
|
||||
|
||||
mqtt_client = MQTTClient(broker=BROKER, port=MQTT_PORT)
|
||||
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=Powerbus Service
|
||||
After=emqx.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
WorkingDirectory=/home/admin/CPY/CPY_AdminPlatform_V3.5/powerbus_service
|
||||
ExecStart=/home/admin/CPY/venv/bin/python /home/admin/CPY/CPY_AdminPlatform_V3.5/powerbus_service/main.py
|
||||
Restart=always
|
||||
RestartSec=10s
|
||||
StartLimitBurst=5
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,2 @@
|
||||
pymodbus>=3.5.0
|
||||
paho-mqtt>=2.1.0
|
||||
@@ -0,0 +1,258 @@
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from modbus_client import ModbusClient
|
||||
from mqtt_client import mqtt_client
|
||||
from config import *
|
||||
import threading
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class SensorService:
|
||||
def __init__(self):
|
||||
# 记录服务启动时间
|
||||
self.start_time = time.time()
|
||||
|
||||
# 创建线程池用于异步发布消息
|
||||
self.executor = ThreadPoolExecutor(max_workers=5)
|
||||
|
||||
# 初始化Modbus客户端
|
||||
self.modbus_client = ModbusClient()
|
||||
|
||||
# 初始化MQTT客户端
|
||||
self.mqtt_client = mqtt_client
|
||||
|
||||
# 订阅MQTT主题
|
||||
self.mqtt_client.subscribe(DEVICE_CONTROL_TOPIC, self.handle_control_message)
|
||||
|
||||
# 设备列表
|
||||
self.devices = []
|
||||
|
||||
# 上次发布服务状态的时间
|
||||
self.last_service_status_time = 0
|
||||
|
||||
self.xray_on = [False, False]
|
||||
self.last_hvs_update_time = 0
|
||||
|
||||
self.exit_flag = False
|
||||
self.loop_thread = None
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def handle_control_message(self, topic, payload):
|
||||
"""异步处理设备控制消息"""
|
||||
if topic == DEVICE_CONTROL_TOPIC:
|
||||
dev_code = payload.get("device_code")
|
||||
if "ALU" in dev_code :
|
||||
print(f"handle_hvs_control_message: {topic, payload}")
|
||||
dev_id = int(dev_code.split('#')[0])
|
||||
command = payload.get("command")
|
||||
if command == "set_status":
|
||||
value = 1 if payload.get('status') else 0
|
||||
newpayload = {
|
||||
"command" : 'hv_switch',
|
||||
'device_id' : dev_id,
|
||||
'device_code' : dev_code,
|
||||
'value' : value
|
||||
}
|
||||
self.executor.submit(self._process_control_message, newpayload)
|
||||
|
||||
def _process_control_message(self, payload):
|
||||
"""处理设备控制消息"""
|
||||
try:
|
||||
logger.info(f"接收到控制消息: {payload}")
|
||||
command = payload.get("command")
|
||||
value = payload.get("value")
|
||||
device_code = payload.get("device_code")
|
||||
slave_id = 0x30
|
||||
if not device_code:
|
||||
logger.error("控制消息缺少device_code")
|
||||
return
|
||||
|
||||
# 使用设备管理器控制设备
|
||||
with self.lock:
|
||||
if command == "hv_switch":
|
||||
if value == 1:
|
||||
self.modbus_client.write_coil(slave_id, 0x00, True)
|
||||
else:
|
||||
self.modbus_client.write_coil(slave_id, 0x00, False)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理控制消息失败: {e}")
|
||||
|
||||
def start(self):
|
||||
# 创建线程
|
||||
self.loop_thread = threading.Thread(target=self.loop)
|
||||
self.loop_thread.daemon = True
|
||||
self.loop_thread.start()
|
||||
|
||||
def stop(self):
|
||||
if not self.loop_thread:
|
||||
return
|
||||
"""停止服务"""
|
||||
self.exit_flag = True
|
||||
self.loop_thread.join()
|
||||
self.executor.shutdown(wait=True)
|
||||
|
||||
def loop(self):
|
||||
"""启动服务"""
|
||||
try:
|
||||
# 连接Modbus
|
||||
if not self.modbus_client.connect():
|
||||
logger.error("Modbus连接失败,程序退出")
|
||||
return
|
||||
logger.info("Modbus连接成功")
|
||||
|
||||
while not self.mqtt_client.is_connected:
|
||||
logger.info("waiting for mqtt conn...")
|
||||
time.sleep(1)
|
||||
|
||||
logger.info("Modbus和MQTT连接成功,开始定时读取和发布数据...")
|
||||
|
||||
self.devices = config.get("devices", [])
|
||||
|
||||
if not self.devices or len(self.devices) == 0:
|
||||
logger.error("未找到HVS设备,程序退出")
|
||||
return
|
||||
|
||||
logger.info(f"找到 {len(self.devices)} 个sensor设备")
|
||||
|
||||
logger.info(f"sensor_devices: {json.dumps(self.devices, ensure_ascii=False)}")
|
||||
|
||||
# 主循环
|
||||
while self.exit_flag == False:
|
||||
# 计算当前时间
|
||||
current_time = time.time()
|
||||
|
||||
logger.info(f"loop... {current_time}")
|
||||
|
||||
# 定期发布服务状态 (每10秒)
|
||||
if current_time - self.last_service_status_time >= 3:
|
||||
logger.debug("publish service status")
|
||||
self._publish_service_status(current_time)
|
||||
|
||||
|
||||
# 读取并发布所有HVS设备数据
|
||||
self.read_and_publish_devices_data()
|
||||
|
||||
# 等待指定间隔
|
||||
time.sleep(config.get("poll_interval", 1))
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.info("程序收到中断信号,正在退出...")
|
||||
finally:
|
||||
# 清理资源
|
||||
self.modbus_client.disconnect()
|
||||
logger.info("程序已退出")
|
||||
|
||||
def _publish_service_status(self, current_time):
|
||||
"""发布服务状态"""
|
||||
# 计算运行时间
|
||||
running_time = current_time - self.start_time
|
||||
|
||||
# 准备服务状态消息
|
||||
service_message = {
|
||||
"service_name": "powerbus_service",
|
||||
"status": {
|
||||
"available": True,
|
||||
"running_time": running_time
|
||||
}
|
||||
}
|
||||
|
||||
# 发布消息
|
||||
self.mqtt_client.publish(SERVICE_STATUS_TOPIC, service_message)
|
||||
logger.info(f"成功发布服务状态到 {SERVICE_STATUS_TOPIC}: {service_message}")
|
||||
self.last_service_status_time = current_time
|
||||
|
||||
def read_and_publish_devices_data(self):
|
||||
"""读取并发布所有设备数据"""
|
||||
# 确保Modbus连接正常
|
||||
if not self.modbus_client._ensure_connection():
|
||||
logger.error(f"无法连接到Modbus设备")
|
||||
return
|
||||
|
||||
for device in self.devices:
|
||||
try:
|
||||
slave_id = int(device.get('address'))
|
||||
logger.info(f"开始读取设备 {device.get('code')} (从站ID: {slave_id}) 数据")
|
||||
|
||||
if device.get('type', '') == 'WSU':
|
||||
# 读取输入寄存器
|
||||
with self.lock:
|
||||
regs = self.modbus_client.read_holding_registers(
|
||||
slave_id=slave_id,
|
||||
address=0,
|
||||
count=2
|
||||
)
|
||||
if regs is None:
|
||||
device["error_count"] = device.get("error_count", 10) + 1
|
||||
else:
|
||||
device["error_count"] = 0
|
||||
device.update({
|
||||
"status" : {
|
||||
"online": device.get("error_count", 10) < 3,
|
||||
"flow_rate": regs[0] / 1000.0 if regs and len(regs) > 0 else None,
|
||||
"water_temp": regs[1] / 10.0 if regs and len(regs) > 1 else None,
|
||||
}
|
||||
})
|
||||
elif device.get('type', '') == 'OSU':
|
||||
# 读取输入寄存器
|
||||
with self.lock:
|
||||
regs = self.modbus_client.read_holding_registers(
|
||||
slave_id=slave_id,
|
||||
address=0,
|
||||
count=2
|
||||
)
|
||||
if regs is None:
|
||||
device["error_count"] = device.get("error_count", 10) + 1
|
||||
else:
|
||||
device["error_count"] = 0
|
||||
device.update({
|
||||
"status" : {
|
||||
"online": device.get("error_count", 10) < 3,
|
||||
"oil_temp": regs[1] / 10.0 if regs and len(regs) > 1 else None,
|
||||
"oil_level": regs[0] if regs and len(regs) > 0 else None,
|
||||
}
|
||||
})
|
||||
elif device.get('type', '') == 'ALU':
|
||||
# 读取线圈
|
||||
with self.lock:
|
||||
coils = self.modbus_client.read_coils(
|
||||
slave_id=slave_id,
|
||||
address=0,
|
||||
count=1
|
||||
)
|
||||
if coils is None:
|
||||
device["error_count"] = device.get("error_count", 10) + 1
|
||||
else:
|
||||
device["error_count"] = 0
|
||||
device.update({
|
||||
"status" : {
|
||||
"online": device.get("error_count", 10) < 3,
|
||||
"status": coils[0] if coils and len(coils) > 0 else None,
|
||||
}
|
||||
})
|
||||
if regs is None:
|
||||
logger.error(f"读取失败")
|
||||
else:
|
||||
logger.info(f"读取成功")
|
||||
# 短暂延迟,避免总线冲突
|
||||
time.sleep(0.1)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理设备 {device.get('code')} 数据失败: {e}")
|
||||
|
||||
# 准备发布的数据
|
||||
data = []
|
||||
for device in self.devices:
|
||||
data.append({
|
||||
"device_code": device.get('code'),
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"status": device.get("status", {})
|
||||
})
|
||||
|
||||
# 发布数据
|
||||
self.mqtt_client.publish(DEVICE_STATUS_TOPIC, data)
|
||||
logger.info(f"成功发布设备数据: {json.dumps(data, ensure_ascii=False)}")
|
||||
@@ -0,0 +1,209 @@
|
||||
import time
|
||||
import threading
|
||||
from pymodbus.client import ModbusTcpClient
|
||||
class TcpIoModule():
|
||||
def __init__(self, host='localhost', port=502, timeout=3, retry_interval=1, max_retries=0):
|
||||
|
||||
"""
|
||||
初始化TCP IO模块
|
||||
:param host: 服务器IP地址
|
||||
:param port: 服务器端口
|
||||
:param timeout: 超时时间(秒)
|
||||
:param retry_interval: 重连间隔(秒)
|
||||
:param max_retries: 最大重连次数,0表示无限重试
|
||||
"""
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.timeout = timeout
|
||||
self.retry_interval = retry_interval
|
||||
self.max_retries = max_retries
|
||||
self.client = None
|
||||
self.is_connected = False
|
||||
self.is_running = False
|
||||
self.read_thread = None
|
||||
self.register_values = {}
|
||||
self.reconnect_count = 0
|
||||
self.reconnect_lock = threading.Lock()
|
||||
self.button_states = [False] * 10
|
||||
|
||||
def _connect(self):
|
||||
"""
|
||||
连接到Modbus服务器
|
||||
:return: 是否连接成功
|
||||
"""
|
||||
try:
|
||||
if self.client:
|
||||
self.client.close()
|
||||
self.client = ModbusTcpClient(host=self.host, port=self.port, timeout=self.timeout)
|
||||
self.is_connected = self.client.connect()
|
||||
if self.is_connected:
|
||||
print(f"成功连接到Modbus服务器: {self.host}:{self.port}")
|
||||
self.reconnect_count = 0
|
||||
else:
|
||||
print(f"连接Modbus服务器失败: {self.host}:{self.port}")
|
||||
return self.is_connected
|
||||
except Exception as e:
|
||||
print(f"连接失败: {e}")
|
||||
self.is_connected = False
|
||||
return False
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
启动Modbus客户端,开始读取寄存器
|
||||
:return: 是否启动成功
|
||||
"""
|
||||
|
||||
|
||||
self.is_running = True
|
||||
self.read_thread = threading.Thread(target=self._read_data_loop)
|
||||
self.read_thread.daemon = True
|
||||
self.read_thread.start()
|
||||
return True
|
||||
|
||||
def stop(self):
|
||||
"""
|
||||
停止Modbus客户端
|
||||
"""
|
||||
self.is_running = False
|
||||
if self.read_thread and self.read_thread.is_alive():
|
||||
self.read_thread.join(timeout=1.0)
|
||||
if self.client:
|
||||
self.client.close()
|
||||
self.is_connected = False
|
||||
print("Modbus客户端已停止")
|
||||
|
||||
def _read_data_loop(self):
|
||||
"""
|
||||
循环读取寄存器的内部方法
|
||||
"""
|
||||
while self.is_running:
|
||||
if not self.is_connected:
|
||||
# 连接断开,尝试重连
|
||||
with self.reconnect_lock:
|
||||
if not self.is_connected and self._auto_reconnect():
|
||||
print("连成功")
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
|
||||
try:
|
||||
# 这里实现读取寄存器的逻辑
|
||||
self.read_data()
|
||||
time.sleep(0.1) # 每秒读取一次
|
||||
except Exception as e:
|
||||
print(f"读取寄存器出错: {e}")
|
||||
# 读取错误可能是连接问题,标记为断开以便重连
|
||||
self.is_connected = False
|
||||
time.sleep(0.5)
|
||||
|
||||
def _auto_reconnect(self):
|
||||
"""
|
||||
自动重连机制
|
||||
:return: 是否重连成功
|
||||
"""
|
||||
# 只尝试一次重连,避免长时间持有锁
|
||||
if self.is_running and (self.max_retries == 0 or self.reconnect_count < self.max_retries):
|
||||
self.reconnect_count += 1
|
||||
|
||||
if self._connect():
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def read_data(self):
|
||||
"""
|
||||
读取寄存器的方法
|
||||
"""
|
||||
try:
|
||||
# 读取输入寄存器,起始地址为0,读取10个寄存器
|
||||
response = self.client.read_discrete_inputs(address=0, count= 4)
|
||||
if not response.isError():
|
||||
for idx, bit in enumerate(response.bits):
|
||||
if idx == 3:
|
||||
# 检测下降沿:从抬起(True)变为按下(False)
|
||||
previous_state = self.button_states[idx]
|
||||
current_state = bit
|
||||
|
||||
# 更新当前状态
|
||||
self.button_states[idx] = current_state
|
||||
|
||||
# 下降沿检测
|
||||
if previous_state == True and current_state == False:
|
||||
self.control_stop()
|
||||
print("=================control_stop")
|
||||
|
||||
else:
|
||||
if bit:
|
||||
print(f"寄存器 {idx} 的值是 {bit}")
|
||||
self.button_states[idx] = True
|
||||
|
||||
elif self.button_states[idx]:
|
||||
self.button_states[idx] = False
|
||||
if idx == 0:
|
||||
self.control_start()
|
||||
print("=================control_start")
|
||||
elif idx == 1:
|
||||
self.control_pause()
|
||||
print("=================control_pause")
|
||||
elif idx == 2:
|
||||
self.control_reset()
|
||||
print("=================control_reset")
|
||||
|
||||
else:
|
||||
print(f"读取寄存器出错: {response}")
|
||||
self.is_connected = False
|
||||
except Exception as e:
|
||||
print(f"读取寄存器出错: {e}")
|
||||
self.is_connected = False
|
||||
|
||||
def control_start(self):
|
||||
self.control_light(9, True)
|
||||
"""
|
||||
控制设备启动
|
||||
"""
|
||||
|
||||
def control_pause(self):
|
||||
self.control_light(9, False)
|
||||
"""
|
||||
控制设备暂停
|
||||
"""
|
||||
|
||||
def control_reset(self):
|
||||
"""
|
||||
控制设备复位
|
||||
"""
|
||||
|
||||
def control_stop(self):
|
||||
self.control_light(9, False)
|
||||
"""
|
||||
控制设备停止
|
||||
"""
|
||||
|
||||
def control_light(self, index, value):
|
||||
try:
|
||||
self.client.write_coil(index, value)
|
||||
except Exception as e:
|
||||
print(f"写入线圈出错: {e}")
|
||||
self.is_connected = False
|
||||
|
||||
def get_register_value(self, register_address):
|
||||
"""
|
||||
获取指定寄存器的值
|
||||
:param register_address: 寄存器地址
|
||||
:return: 寄存器值或None(如果不存在)
|
||||
"""
|
||||
return self.register_values.get(register_address)
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 示例用法
|
||||
modbus_client = TcpIoModule(host='192.168.8.211', port=502)
|
||||
if modbus_client.start():
|
||||
print("Modbus客户端已启动")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
print("停止Modbus客户端")
|
||||
modbus_client.stop()
|
||||
else:
|
||||
print("Modbus客户端启动失败")
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
import os
|
||||
import math
|
||||
import time
|
||||
import threading
|
||||
import subprocess
|
||||
import re
|
||||
import json
|
||||
from config import *
|
||||
from PySide6.QtCore import *
|
||||
from PySide6.QtNetwork import QUdpSocket, QHostAddress
|
||||
import socket, struct
|
||||
|
||||
from PySide6.QtCore import QTimer
|
||||
|
||||
class ScannerState:
|
||||
STOP = 'stop'
|
||||
MOVING_UP = 'moving_up'
|
||||
MOVING_DOWN = 'moving_down'
|
||||
STOP_AT_UPPER = 'stop_at_upper'
|
||||
STOP_AT_BOTTOM = 'stop_at_bottom'
|
||||
STOP_AT_ORIGIN = 'stop_at_origin'
|
||||
UNKNOWN = 'unknown'
|
||||
|
||||
valid_states = [STOP, MOVING_UP, MOVING_DOWN,
|
||||
STOP_AT_UPPER, STOP_AT_BOTTOM,
|
||||
STOP_AT_ORIGIN, UNKNOWN]
|
||||
|
||||
class Scanner:
|
||||
def __init__(self, id):
|
||||
self.id = id
|
||||
self.config = {}
|
||||
self.state = ScannerState.UNKNOWN
|
||||
self.running = False
|
||||
self.last_update_time = 0
|
||||
self.location = 0
|
||||
self.velocity = 0
|
||||
|
||||
self.daq_info = {}
|
||||
|
||||
self.last_moving_time = 0
|
||||
self.last_idle_time = 0
|
||||
|
||||
self.run_flag = False
|
||||
|
||||
self.read_config()
|
||||
|
||||
self.ip = self.config.get("ip", "192.168.100.21")
|
||||
|
||||
def read_config(self):
|
||||
try:
|
||||
config = {}
|
||||
path = "/home/admin/.config/cpy/scanner.json"
|
||||
if not os.path.exists(path):
|
||||
return
|
||||
|
||||
with open(path, "r") as f:
|
||||
config = json.load(f)
|
||||
|
||||
self.config = config[f"scanner{self.id}"]
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
class MotorManager(QObject):
|
||||
update_location = Signal(int,int)
|
||||
update_direction = Signal(int,str)
|
||||
update_estimates = Signal(int, float, float)
|
||||
update_online_status = Signal(int, int)
|
||||
update_setting_velocity = Signal(int, float)
|
||||
update_duration = Signal(int,float)
|
||||
update_state = Signal(int, int)
|
||||
update_work_mode = Signal(str)
|
||||
|
||||
# 定义ID_MT1、ID_MT2两个常量为0x01, 0x02
|
||||
ID_MT1 = 0x01
|
||||
ID_MT2 = 0x02
|
||||
|
||||
UDP_STATUS_PORT = 11200
|
||||
UDP_CMD_PORT = 11300
|
||||
|
||||
def __init__(self, bus_id = 1):
|
||||
super().__init__()
|
||||
|
||||
self.scanners = [Scanner(self.ID_MT1),
|
||||
Scanner(self.ID_MT2)]
|
||||
|
||||
|
||||
self.mqtt_client = None
|
||||
|
||||
self.read_config()
|
||||
self.work_mode = "fast"
|
||||
print(self.config)
|
||||
|
||||
self.light_status = None
|
||||
self.last_light_on_time = 0
|
||||
self.start_scan_time = 0
|
||||
|
||||
self.online_status_update_time = 0
|
||||
self.moto_info_update_time = 0
|
||||
|
||||
self.udp_socket = QUdpSocket(self)
|
||||
self.udp_socket.bind(QHostAddress.Any, self.UDP_STATUS_PORT)
|
||||
self.udp_socket.readyRead.connect(self.udp_data_handle)
|
||||
|
||||
self.timer = QTimer(self)
|
||||
self.timer.setInterval(100)
|
||||
self.timer.timeout.connect(self.timer_callback)
|
||||
self.timer.start()
|
||||
|
||||
def scanner(self, index):
|
||||
return self.scanners[index - 1]
|
||||
|
||||
def send_udp_cmd(self, index, cmd):
|
||||
try:
|
||||
ip = self.scanner(index).ip
|
||||
self.udp_socket.writeDatagram(json.dumps(cmd).encode(), QHostAddress(ip), self.UDP_CMD_PORT)
|
||||
print("send to", ip, cmd)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
def start_scanning(self, index, count = 1, period = 6000):
|
||||
if self.scanner(index).run_flag == True:
|
||||
return
|
||||
|
||||
print("scanner", index, self.scanner(index).run_flag)
|
||||
|
||||
self.scanner(index).run_flag = True
|
||||
self.scanner(index).running = True
|
||||
self.send_udp_cmd(index, {"cmd": "start", "count": count, "period": period})
|
||||
|
||||
def stop_scanning(self, index):
|
||||
self.scanner(index).running = False
|
||||
self.send_udp_cmd(index, {"cmd": "stop"})
|
||||
|
||||
def stop_scanning_emer(self, index):
|
||||
self.scanner(index).running = False
|
||||
self.send_udp_cmd(index, {"cmd": "emer_stop"})
|
||||
|
||||
def reset_scanning(self, index):
|
||||
self.scanner(index).running = False
|
||||
self.send_udp_cmd(index, {"cmd": "reset"})
|
||||
|
||||
def update_motor_info(self):
|
||||
try:
|
||||
if time.time() > self.moto_info_update_time + 0.300:
|
||||
state_map = {
|
||||
ScannerState.STOP_AT_BOTTOM: 3,
|
||||
ScannerState.STOP_AT_UPPER: 1,
|
||||
ScannerState.STOP_AT_ORIGIN: 0,
|
||||
ScannerState.MOVING_UP: 2,
|
||||
ScannerState.MOVING_DOWN: 2,
|
||||
}
|
||||
|
||||
try:
|
||||
state = state_map[self.scanner(self.ID_MT1).state]
|
||||
self.update_location.emit(self.ID_MT1, state)
|
||||
self.update_estimates.emit(self.ID_MT1, self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
|
||||
# print(self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
try:
|
||||
state = state_map[self.scanner(self.ID_MT2).state]
|
||||
self.update_location.emit(self.ID_MT2, state)
|
||||
self.update_estimates.emit(self.ID_MT2, self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
|
||||
# print(self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
self.moto_info_update_time = time.time()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
self.moto_info_update_time = time.time()
|
||||
|
||||
def update_online_state(self):
|
||||
try:
|
||||
if time.time() > self.online_status_update_time + 1:
|
||||
online_state = {
|
||||
self.ID_MT1: time.time() < self.scanner(self.ID_MT1).last_update_time + 1,
|
||||
self.ID_MT2: time.time() < self.scanner(self.ID_MT2).last_update_time + 1,
|
||||
}
|
||||
self.update_online_status.emit(self.ID_MT1, online_state[self.ID_MT1])
|
||||
self.update_online_status.emit(self.ID_MT2, online_state[self.ID_MT2])
|
||||
self.online_status_update_time = time.time()
|
||||
# print("online state:", online_state)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
self.online_status_update_time = time.time()
|
||||
|
||||
@Slot(bytes)
|
||||
def udp_data_handle(self):
|
||||
while self.udp_socket.hasPendingDatagrams():
|
||||
datagram, addr, port = self.udp_socket.readDatagram(self.udp_socket.pendingDatagramSize())
|
||||
datagram = bytes(datagram.data())
|
||||
# print(f"Received datagram: {datagram} from {addr}:{port}")
|
||||
try:
|
||||
data = json.loads(datagram.decode())
|
||||
# print(f"Parsed JSON data: {data}")
|
||||
index = int(data['id'][0])
|
||||
|
||||
self.scanner(index).state = data['state']
|
||||
self.scanner(index).location = data['pos']
|
||||
self.scanner(index).velocity = data['speed']
|
||||
self.scanner(index).run_flag = data['run_flag']
|
||||
self.scanner(index).last_update_time = time.time()
|
||||
|
||||
if 'daq_temp' in data:
|
||||
self.scanner(index).daq_info['temp'] = data['daq_temp']
|
||||
if 'daq_online' in data:
|
||||
self.scanner(index).daq_info['online'] = data['daq_online']
|
||||
|
||||
if self.scanner(index).state in [ScannerState.MOVING_UP, ScannerState.MOVING_DOWN]:
|
||||
self.scanner(index).last_moving_time = time.time()
|
||||
|
||||
elif self.scanner(index).state in [ScannerState.STOP_AT_BOTTOM, ScannerState.STOP_AT_UPPER, ScannerState.STOP_AT_ORIGIN]:
|
||||
self.scanner(index).last_idle_time = time.time()
|
||||
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"JSON decode error: {e}")
|
||||
|
||||
def scanner_idle_time(self, index):
|
||||
return time.time() - self.scanner(index).last_moving_time
|
||||
|
||||
def scan(self):
|
||||
# print(self.scanner(self.ID_MT1).running, self.scanner(self.ID_MT2).running)
|
||||
# print(self.scanner(self.ID_MT1).last_moving_time, self.scanner(self.ID_MT2).last_moving_time)
|
||||
# print(time.time(), "\n")
|
||||
|
||||
if self.work_mode == "normal" and self.scan_count <= 0:
|
||||
idle_time = 60.0 * 1
|
||||
self.scan_count = 8
|
||||
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
|
||||
self.scan_count = 8
|
||||
elif self.work_mode == "slow" and self.scan_count <= 0:
|
||||
idle_time = 60.0 * 5
|
||||
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
|
||||
self.scan_count = 8
|
||||
elif self.work_mode == "fast":
|
||||
self.scan_count = 8
|
||||
|
||||
if self.scan_count <= 0:
|
||||
return
|
||||
|
||||
if time.time() - self.start_scan_time < 2.0:
|
||||
return
|
||||
|
||||
if self.scanner(self.ID_MT1).running and (not self.scanner(self.ID_MT2).running):
|
||||
if time.time() > self.scanner(self.ID_MT1).last_moving_time + 3.0:
|
||||
self.start_scanning(self.ID_MT1)
|
||||
print("start_scanning(self.ID_MT1)")
|
||||
self.scan_count -= 2
|
||||
self.start_scan_time = time.time()
|
||||
elif (not self.scanner(self.ID_MT1).running) and self.scanner(self.ID_MT2).running:
|
||||
if time.time() > self.scanner(self.ID_MT2).last_moving_time + 3.0:
|
||||
self.start_scanning(self.ID_MT2)
|
||||
self.scan_count -= 2
|
||||
self.start_scan_time = time.time()
|
||||
elif self.scanner(self.ID_MT1).running and self.scanner(self.ID_MT2).running:
|
||||
idle_time = 3.0
|
||||
if self.work_mode == "normal":
|
||||
idle_time = 18.0
|
||||
|
||||
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > 1.0:
|
||||
self.start_scanning(self.ID_MT1)
|
||||
self.scan_count -= 1
|
||||
self.start_scan_time = time.time()
|
||||
elif self.scanner_idle_time(self.ID_MT1) > 1.0 and self.scanner_idle_time(self.ID_MT2) > idle_time:
|
||||
self.start_scanning(self.ID_MT2)
|
||||
self.scan_count -= 1
|
||||
self.start_scan_time = time.time()
|
||||
|
||||
def update_daq_info(self):
|
||||
try:
|
||||
daq_index = self.daq_index
|
||||
if time.time() - self.daq_info_update_time < 1.0:
|
||||
return
|
||||
packet = {
|
||||
'id' : daq_index,
|
||||
'type' : "daq_info",
|
||||
'status' : self.scanner(daq_index).daq_info
|
||||
}
|
||||
self.udp_socket.writeDatagram(json.dumps(packet).encode(), QHostAddress("127.0.0.1"), 50009)
|
||||
self.daq_info_update_time = time.time()
|
||||
if daq_index == self.ID_MT1:
|
||||
self.daq_index = self.ID_MT2
|
||||
else:
|
||||
self.daq_index = self.ID_MT1
|
||||
except Exception as e:
|
||||
self.daq_index = self.ID_MT1
|
||||
self.daq_info_update_time = time.time()
|
||||
print(f"Error reading DAQ: {e}")
|
||||
|
||||
def timer_callback(self):
|
||||
self.update_online_state()
|
||||
self.update_motor_info()
|
||||
self.update_daq_info()
|
||||
|
||||
self.scan()
|
||||
|
||||
def write_config(self):
|
||||
with open("/home/admin/.config/cpy/config.json", "w") as f:
|
||||
json.dump(self.config, f)
|
||||
|
||||
def default_config(self):
|
||||
config = {
|
||||
|
||||
}
|
||||
self.config = config
|
||||
|
||||
return config
|
||||
|
||||
def read_config(self):
|
||||
config = {}
|
||||
path = "/home/admin/.config/cpy/config.json"
|
||||
if not os.path.exists(path):
|
||||
self.default_config()
|
||||
return self.config
|
||||
|
||||
with open(path, "r") as f:
|
||||
config = json.load(f)
|
||||
|
||||
self.config = config
|
||||
return config
|
||||
|
||||
def start(self, motor_index):
|
||||
if motor_index & self.ID_MT1:
|
||||
self.scanner(self.ID_MT1).running = True
|
||||
if self.scanner_idle_time(self.ID_MT1) > 3.0:
|
||||
self.scanner(self.ID_MT1).last_moving_time = 0.0
|
||||
if motor_index & self.ID_MT2:
|
||||
self.scanner(self.ID_MT2).running = True
|
||||
if self.scanner_idle_time(self.ID_MT2) > 3.0:
|
||||
self.scanner(self.ID_MT2).last_moving_time = 0.0
|
||||
|
||||
def emergency_stop(self, motor_index):
|
||||
|
||||
if motor_index & self.ID_MT1:
|
||||
self.stop_scanning_emer(self.ID_MT1)
|
||||
if motor_index & self.ID_MT2:
|
||||
self.stop_scanning_emer(self.ID_MT2)
|
||||
|
||||
def stop(self, motor_index):
|
||||
|
||||
if motor_index & self.ID_MT1:
|
||||
self.stop_scanning(self.ID_MT1)
|
||||
if motor_index & self.ID_MT2:
|
||||
self.stop_scanning(self.ID_MT2)
|
||||
|
||||
def destroy(self):
|
||||
pass
|
||||
|
||||
@Slot(int, str, str)
|
||||
def set_globaldev_value(self, motor_index, key, value):
|
||||
print("set_globaldev_value", motor_index, key, value)
|
||||
if motor_index == 3 and key == "sports_mode":
|
||||
self.work_mode = value
|
||||
print("self.work_mode =",self.work_mode)
|
||||
self.update_work_mode.emit(self.work_mode)
|
||||
if motor_index == 3 and key == "switch":
|
||||
try:
|
||||
val = int(value)
|
||||
|
||||
except ValueError:
|
||||
print("set_globaldev_value ValueError", motor_index, key, value)
|
||||
return
|
||||
|
||||
if val == 0:
|
||||
self.reset_scanning(self.ID_MT1)
|
||||
self.reset_scanning(self.ID_MT2)
|
||||
|
||||
@Slot(int, str, int)
|
||||
def set_value(self, motor_index, key, value):
|
||||
if key == "profileVelocity":
|
||||
return
|
||||
|
||||
if key == "emergency_stop":
|
||||
self.emergency_stop(motor_index)
|
||||
elif key == "switch":
|
||||
if value == 1:
|
||||
self.start(motor_index)
|
||||
else:
|
||||
if motor_index == 3:
|
||||
self.reset_scanning(self.ID_MT1)
|
||||
self.reset_scanning(self.ID_MT2)
|
||||
else:
|
||||
self.stop(motor_index)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
import os
|
||||
import math
|
||||
import time
|
||||
import threading
|
||||
import subprocess
|
||||
import re
|
||||
import json
|
||||
from config import *
|
||||
from PySide6.QtCore import *
|
||||
from PySide6.QtNetwork import QUdpSocket, QHostAddress
|
||||
import socket, struct
|
||||
|
||||
from PySide6.QtCore import QTimer
|
||||
|
||||
class ScannerState:
|
||||
STOP = 'stop'
|
||||
MOVING_UP = 'moving_up'
|
||||
MOVING_DOWN = 'moving_down'
|
||||
STOP_AT_UPPER = 'stop_at_upper'
|
||||
STOP_AT_BOTTOM = 'stop_at_bottom'
|
||||
STOP_AT_ORIGIN = 'stop_at_origin'
|
||||
UNKNOWN = 'unknown'
|
||||
|
||||
valid_states = [STOP, MOVING_UP, MOVING_DOWN,
|
||||
STOP_AT_UPPER, STOP_AT_BOTTOM,
|
||||
STOP_AT_ORIGIN, UNKNOWN]
|
||||
|
||||
class Scanner:
|
||||
def __init__(self, id):
|
||||
self.id = id
|
||||
self.config = {}
|
||||
self.state = ScannerState.UNKNOWN
|
||||
self.running = False
|
||||
self.last_update_time = 0
|
||||
self.location = 0
|
||||
self.velocity = 0
|
||||
|
||||
self.daq_info = {}
|
||||
|
||||
self.last_moving_time = 0
|
||||
self.last_idle_time = 0
|
||||
|
||||
self.run_flag = False
|
||||
|
||||
self.read_config()
|
||||
|
||||
self.ip = self.config.get("ip", "192.168.100.21")
|
||||
|
||||
def read_config(self):
|
||||
try:
|
||||
config = {}
|
||||
path = "/home/admin/.config/cpy/scanner.json"
|
||||
if not os.path.exists(path):
|
||||
return
|
||||
|
||||
with open(path, "r") as f:
|
||||
config = json.load(f)
|
||||
|
||||
self.config = config[f"scanner{self.id}"]
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
class MotorManager(QObject):
|
||||
update_location = Signal(int,int)
|
||||
update_direction = Signal(int,str)
|
||||
update_estimates = Signal(int, float, float)
|
||||
update_online_status = Signal(int, int)
|
||||
update_setting_velocity = Signal(int, float)
|
||||
update_duration = Signal(int,float)
|
||||
update_state = Signal(int, int)
|
||||
update_work_mode = Signal(str)
|
||||
|
||||
# 定义ID_MT1、ID_MT2两个常量为0x01, 0x02
|
||||
ID_MT1 = 0x01
|
||||
ID_MT2 = 0x02
|
||||
|
||||
UDP_STATUS_PORT = 11200
|
||||
UDP_CMD_PORT = 11300
|
||||
|
||||
def __init__(self, bus_id = 1):
|
||||
super().__init__()
|
||||
|
||||
self.scanners = [Scanner(self.ID_MT1),
|
||||
Scanner(self.ID_MT2)]
|
||||
|
||||
|
||||
self.mqtt_client = None
|
||||
|
||||
self.read_config()
|
||||
self.work_mode = "fast"
|
||||
print(self.config)
|
||||
|
||||
self.light_status = None
|
||||
self.last_light_on_time = 0
|
||||
self.start_scan_time = 0
|
||||
|
||||
self.online_status_update_time = 0
|
||||
self.moto_info_update_time = 0
|
||||
|
||||
self.udp_socket = QUdpSocket(self)
|
||||
self.udp_socket.bind(QHostAddress.Any, self.UDP_STATUS_PORT)
|
||||
self.udp_socket.readyRead.connect(self.udp_data_handle)
|
||||
|
||||
self.timer = QTimer(self)
|
||||
self.timer.setInterval(100)
|
||||
self.timer.timeout.connect(self.timer_callback)
|
||||
self.timer.start()
|
||||
|
||||
def scanner(self, index):
|
||||
return self.scanners[index - 1]
|
||||
|
||||
def send_udp_cmd(self, index, cmd):
|
||||
try:
|
||||
ip = self.scanner(index).ip
|
||||
self.udp_socket.writeDatagram(json.dumps(cmd).encode(), QHostAddress(ip), self.UDP_CMD_PORT)
|
||||
print("send to", ip, cmd)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
def start_scanning(self, index, count = 1, period = 6000):
|
||||
if self.scanner(index).run_flag == True:
|
||||
return
|
||||
|
||||
print("scanner", index, self.scanner(index).run_flag)
|
||||
|
||||
self.scanner(index).run_flag = True
|
||||
self.scanner(index).running = True
|
||||
self.send_udp_cmd(index, {"cmd": "start", "count": count, "period": period})
|
||||
|
||||
def stop_scanning(self, index):
|
||||
self.scanner(index).running = False
|
||||
self.send_udp_cmd(index, {"cmd": "stop"})
|
||||
|
||||
def stop_scanning_emer(self, index):
|
||||
self.scanner(index).running = False
|
||||
self.send_udp_cmd(index, {"cmd": "emer_stop"})
|
||||
|
||||
def reset_scanning(self, index):
|
||||
self.scanner(index).running = False
|
||||
self.send_udp_cmd(index, {"cmd": "reset"})
|
||||
|
||||
def update_motor_info(self):
|
||||
try:
|
||||
if time.time() > self.moto_info_update_time + 0.300:
|
||||
state_map = {
|
||||
ScannerState.STOP_AT_BOTTOM: 3,
|
||||
ScannerState.STOP_AT_UPPER: 1,
|
||||
ScannerState.STOP_AT_ORIGIN: 0,
|
||||
ScannerState.MOVING_UP: 2,
|
||||
ScannerState.MOVING_DOWN: 2,
|
||||
}
|
||||
|
||||
try:
|
||||
state = state_map[self.scanner(self.ID_MT1).state]
|
||||
self.update_location.emit(self.ID_MT1, state)
|
||||
self.update_estimates.emit(self.ID_MT1, self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
|
||||
# print(self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
try:
|
||||
state = state_map[self.scanner(self.ID_MT2).state]
|
||||
self.update_location.emit(self.ID_MT2, state)
|
||||
self.update_estimates.emit(self.ID_MT2, self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
|
||||
# print(self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
self.moto_info_update_time = time.time()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
self.moto_info_update_time = time.time()
|
||||
|
||||
def update_online_state(self):
|
||||
try:
|
||||
if time.time() > self.online_status_update_time + 1:
|
||||
online_state = {
|
||||
self.ID_MT1: time.time() < self.scanner(self.ID_MT1).last_update_time + 1,
|
||||
self.ID_MT2: time.time() < self.scanner(self.ID_MT2).last_update_time + 1,
|
||||
}
|
||||
self.update_online_status.emit(self.ID_MT1, online_state[self.ID_MT1])
|
||||
self.update_online_status.emit(self.ID_MT2, online_state[self.ID_MT2])
|
||||
self.online_status_update_time = time.time()
|
||||
# print("online state:", online_state)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
self.online_status_update_time = time.time()
|
||||
|
||||
@Slot(bytes)
|
||||
def udp_data_handle(self):
|
||||
while self.udp_socket.hasPendingDatagrams():
|
||||
datagram, addr, port = self.udp_socket.readDatagram(self.udp_socket.pendingDatagramSize())
|
||||
datagram = bytes(datagram.data())
|
||||
# print(f"Received datagram: {datagram} from {addr}:{port}")
|
||||
try:
|
||||
data = json.loads(datagram.decode())
|
||||
# print(f"Parsed JSON data: {data}")
|
||||
index = int(data['id'][0])
|
||||
|
||||
self.scanner(index).state = data['state']
|
||||
self.scanner(index).location = data['pos']
|
||||
self.scanner(index).velocity = data['speed']
|
||||
self.scanner(index).run_flag = data['run_flag']
|
||||
self.scanner(index).last_update_time = time.time()
|
||||
|
||||
if 'daq_temp' in data:
|
||||
self.scanner(index).daq_info['temp'] = data['daq_temp']
|
||||
if 'daq_online' in data:
|
||||
self.scanner(index).daq_info['online'] = data['daq_online']
|
||||
|
||||
if self.scanner(index).state in [ScannerState.MOVING_UP, ScannerState.MOVING_DOWN]:
|
||||
self.scanner(index).last_moving_time = time.time()
|
||||
|
||||
elif self.scanner(index).state in [ScannerState.STOP_AT_BOTTOM, ScannerState.STOP_AT_UPPER, ScannerState.STOP_AT_ORIGIN]:
|
||||
self.scanner(index).last_idle_time = time.time()
|
||||
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"JSON decode error: {e}")
|
||||
|
||||
def scanner_idle_time(self, index):
|
||||
return time.time() - self.scanner(index).last_moving_time
|
||||
|
||||
def scan(self):
|
||||
# print(self.scanner(self.ID_MT1).running, self.scanner(self.ID_MT2).running)
|
||||
# print(self.scanner(self.ID_MT1).last_moving_time, self.scanner(self.ID_MT2).last_moving_time)
|
||||
# print(time.time(), "\n")
|
||||
|
||||
if self.work_mode == "normal" and self.scan_count <= 0:
|
||||
idle_time = 60.0 * 1
|
||||
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
|
||||
self.scan_count = 8
|
||||
elif self.work_mode == "slow" and self.scan_count <= 0:
|
||||
idle_time = 60.0 * 5
|
||||
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
|
||||
self.scan_count = 8
|
||||
elif self.work_mode == "fast":
|
||||
self.scan_count = 8
|
||||
|
||||
if self.scan_count <= 0:
|
||||
return
|
||||
|
||||
if time.time() - self.start_scan_time < 2.0:
|
||||
return
|
||||
|
||||
if self.scanner(self.ID_MT1).running and (not self.scanner(self.ID_MT2).running):
|
||||
if time.time() > self.scanner(self.ID_MT1).last_moving_time + 3.0:
|
||||
self.start_scanning(self.ID_MT1)
|
||||
print("start_scanning(self.ID_MT1)")
|
||||
self.scan_count -= 2
|
||||
self.start_scan_time = time.time()
|
||||
elif (not self.scanner(self.ID_MT1).running) and self.scanner(self.ID_MT2).running:
|
||||
if time.time() > self.scanner(self.ID_MT2).last_moving_time + 3.0:
|
||||
self.start_scanning(self.ID_MT2)
|
||||
self.scan_count -= 2
|
||||
self.start_scan_time = time.time()
|
||||
elif self.scanner(self.ID_MT1).running and self.scanner(self.ID_MT2).running:
|
||||
idle_time = 3.0
|
||||
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
|
||||
self.start_scanning(self.ID_MT1)
|
||||
self.scan_count -= 1
|
||||
self.start_scan_time = time.time()
|
||||
elif (self.scanner_idle_time(self.ID_MT1) > 1.0) and (self.scanner_idle_time(self.ID_MT2) > 1.0):
|
||||
if self.scanner_idle_time(self.ID_MT1) > self.scanner_idle_time(self.ID_MT2):
|
||||
self.start_scanning(self.ID_MT1)
|
||||
self.scan_count -= 1
|
||||
self.start_scan_time = time.time()
|
||||
else:
|
||||
self.start_scanning(self.ID_MT2)
|
||||
self.scan_count -= 1
|
||||
self.start_scan_time = time.time()
|
||||
|
||||
def update_daq_info(self):
|
||||
try:
|
||||
daq_index = self.daq_index
|
||||
if time.time() - self.daq_info_update_time < 1.0:
|
||||
return
|
||||
packet = {
|
||||
'id' : daq_index,
|
||||
'type' : "daq_info",
|
||||
'status' : self.scanner(daq_index).daq_info
|
||||
}
|
||||
self.udp_socket.writeDatagram(json.dumps(packet).encode(), QHostAddress("127.0.0.1"), 50009)
|
||||
self.daq_info_update_time = time.time()
|
||||
if daq_index == self.ID_MT1:
|
||||
self.daq_index = self.ID_MT2
|
||||
else:
|
||||
self.daq_index = self.ID_MT1
|
||||
except Exception as e:
|
||||
self.daq_index = self.ID_MT1
|
||||
self.daq_info_update_time = time.time()
|
||||
print(f"Error reading DAQ: {e}")
|
||||
|
||||
def timer_callback(self):
|
||||
self.update_online_state()
|
||||
self.update_motor_info()
|
||||
self.update_daq_info()
|
||||
|
||||
self.scan()
|
||||
|
||||
def write_config(self):
|
||||
with open("/home/admin/.config/cpy/config.json", "w") as f:
|
||||
json.dump(self.config, f)
|
||||
|
||||
def default_config(self):
|
||||
config = {
|
||||
|
||||
}
|
||||
self.config = config
|
||||
|
||||
return config
|
||||
|
||||
def read_config(self):
|
||||
config = {}
|
||||
path = "/home/admin/.config/cpy/config.json"
|
||||
if not os.path.exists(path):
|
||||
self.default_config()
|
||||
return self.config
|
||||
|
||||
with open(path, "r") as f:
|
||||
config = json.load(f)
|
||||
|
||||
self.config = config
|
||||
return config
|
||||
|
||||
def start(self, motor_index):
|
||||
if motor_index & self.ID_MT1:
|
||||
self.scanner(self.ID_MT1).running = True
|
||||
if self.scanner_idle_time(self.ID_MT1) > 3.0:
|
||||
self.scanner(self.ID_MT1).last_moving_time = 0.0
|
||||
if motor_index & self.ID_MT2:
|
||||
self.scanner(self.ID_MT2).running = True
|
||||
if self.scanner_idle_time(self.ID_MT2) > 3.0:
|
||||
self.scanner(self.ID_MT2).last_moving_time = 0.0
|
||||
|
||||
def emergency_stop(self, motor_index):
|
||||
|
||||
if motor_index & self.ID_MT1:
|
||||
self.stop_scanning_emer(self.ID_MT1)
|
||||
if motor_index & self.ID_MT2:
|
||||
self.stop_scanning_emer(self.ID_MT2)
|
||||
|
||||
def stop(self, motor_index):
|
||||
|
||||
if motor_index & self.ID_MT1:
|
||||
self.stop_scanning(self.ID_MT1)
|
||||
if motor_index & self.ID_MT2:
|
||||
self.stop_scanning(self.ID_MT2)
|
||||
|
||||
def destroy(self):
|
||||
pass
|
||||
|
||||
@Slot(int, str, str)
|
||||
def set_globaldev_value(self, motor_index, key, value):
|
||||
print("set_globaldev_value", motor_index, key, value)
|
||||
if motor_index == 3 and key == "sports_mode":
|
||||
self.work_mode = value
|
||||
print("self.work_mode =",self.work_mode)
|
||||
self.update_work_mode.emit(self.work_mode)
|
||||
if motor_index == 3 and key == "switch":
|
||||
try:
|
||||
val = int(value)
|
||||
|
||||
except ValueError:
|
||||
print("set_globaldev_value ValueError", motor_index, key, value)
|
||||
return
|
||||
|
||||
if val == 0:
|
||||
self.reset_scanning(self.ID_MT1)
|
||||
self.reset_scanning(self.ID_MT2)
|
||||
|
||||
@Slot(int, str, int)
|
||||
def set_value(self, motor_index, key, value):
|
||||
if key == "profileVelocity":
|
||||
return
|
||||
|
||||
if key == "emergency_stop":
|
||||
self.emergency_stop(motor_index)
|
||||
elif key == "switch":
|
||||
if value == 1:
|
||||
self.start(motor_index)
|
||||
else:
|
||||
if motor_index == 3:
|
||||
self.reset_scanning(self.ID_MT1)
|
||||
self.reset_scanning(self.ID_MT2)
|
||||
else:
|
||||
self.stop(motor_index)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
BROKER = "127.0.0.1"
|
||||
PORT = 1883
|
||||
USER = "test"
|
||||
PWD = "test"
|
||||
PIN_CTRL_XRAY_1 = 22
|
||||
PIN_CTRL_XRAY_2 = 27
|
||||
PIN_CTRL_MOTOR = 18
|
||||
PIN_CTRL_DAQ = 17
|
||||
# BROKER = "127.0.0.1"
|
||||
# PORT = 1883
|
||||
# USER = "tgzz"
|
||||
# PWD = "Tgzz2025"
|
||||
@@ -0,0 +1,107 @@
|
||||
from PySide6.QtCore import *
|
||||
|
||||
class DataCenter(QObject):
|
||||
plcAlive = Signal(bool)
|
||||
dataReady = Signal(int, dict)
|
||||
readFinished = Signal()
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
|
||||
self.settings = QSettings("TGZZ", "TGX") # 设置存储位置
|
||||
self.device_object = {
|
||||
"scanner1":{
|
||||
"motor":{
|
||||
"online": False,
|
||||
"position": 0,
|
||||
"direction": 0,
|
||||
"duration": 0,
|
||||
"location": 0,
|
||||
"velocity": 0,
|
||||
"setting_velocity": 0,
|
||||
"usage_duration": 15,
|
||||
"useful_life": 365,
|
||||
"failure_status": 1,
|
||||
"failure_info": ""
|
||||
}
|
||||
},
|
||||
"scanner2":{
|
||||
|
||||
"motor":{
|
||||
"online": False,
|
||||
"position": 0,
|
||||
"direction": 0,
|
||||
"duration": 0,
|
||||
"location": 0,
|
||||
"velocity": 0,
|
||||
"setting_velocity": 0,
|
||||
"usage_duration": 15,
|
||||
"useful_life": 365,
|
||||
"failure_status": 1,
|
||||
"failure_info": ""
|
||||
}
|
||||
},
|
||||
"global_dev":{
|
||||
"device":{
|
||||
"sports_mode": "fast"
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Slot(str)
|
||||
def update_motor_sports_mode(self, sports_mode):
|
||||
self.device_object["global_dev"]["device"]["sports_mode"] = sports_mode
|
||||
print("self.device_object global_dev=",self.device_object["global_dev"])
|
||||
self.dataReady.emit(3, self.device_object["global_dev"]["device"]) # 更新全局设备数据
|
||||
|
||||
@Slot(int, int)
|
||||
def update_online_status(self, motor_index, status):
|
||||
result = False
|
||||
if status == 1:
|
||||
result = True
|
||||
else:
|
||||
result = False
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["online"] = result
|
||||
|
||||
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
|
||||
|
||||
@Slot(int, float, float)
|
||||
def update_motor_estimates(self, node_index, position, velocity):
|
||||
motor_index = node_index
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["position"] = position
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["velocity"] = velocity
|
||||
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
|
||||
# print(f"motor{motor_index}, position:{position}, velocity:{velocity}")
|
||||
|
||||
@Slot(int, int)
|
||||
def update_motor_location(self, motor_index, location):
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["location"] = location
|
||||
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
|
||||
# print(f"motor{motor_index}, location:{location}")
|
||||
|
||||
@Slot(int, str)
|
||||
def update_motor_direction(self, motor_index, direction):
|
||||
print(f"motor{motor_index}, direction:{direction}")
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["direction"] = direction
|
||||
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
|
||||
|
||||
@Slot(int, float)
|
||||
def update_motor_duration(self, motor_index, duration):
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["duration"] = duration
|
||||
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
|
||||
|
||||
@Slot(int,float)
|
||||
def update_motor_setting_velocity(self, motor_index, setting_velocity):
|
||||
if motor_index == 0:
|
||||
self.device_object["scanner1"]["motor"]["setting_velocity"] = setting_velocity
|
||||
self.device_object["scanner2"]["motor"]["setting_velocity"] = setting_velocity
|
||||
else:
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["setting_velocity"] = setting_velocity
|
||||
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
|
||||
|
||||
@Slot(int,int)
|
||||
def update_motor_state(self, motor_index, state):
|
||||
self.device_object[f"scanner{motor_index}"]["motor"]["state"] = state
|
||||
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
|
||||
Executable
+102
@@ -0,0 +1,102 @@
|
||||
# Draw.io 使用指南:绘制UML状态图并保存本地
|
||||
|
||||
## 一、进入绘制界面
|
||||
|
||||
1. 打开 [draw.io](https://app.diagrams.net/)
|
||||
2. 选择「Create New Diagram」(创建新图表)
|
||||
3. 选择存储位置:点击「Device」(设备)→ 暂时不保存
|
||||
4. 选择模板:点击「Blank Diagram」(空白图表)→ 点击「Create」
|
||||
|
||||
## 二、绘制UML状态图
|
||||
|
||||
### 1. 启用UML状态图工具
|
||||
|
||||
在左侧工具栏找到并点击「More Shapes」(更多形状):
|
||||
- 展开「Software」(软件)→ 勾选「UML」
|
||||
- 特别勾选「UML State Machine」(UML状态机)
|
||||
- 点击「Apply」(应用)
|
||||
|
||||
### 2. 绘制基本元素
|
||||
|
||||
#### 初始状态
|
||||
- 从左侧「UML State Machine」工具栏拖拽「Initial State」(实心圆)到画布
|
||||
|
||||
#### 普通状态
|
||||
- 拖拽「State」(圆角矩形)到画布
|
||||
- 双击状态框输入状态名称(如:`scanner1_scanning`)
|
||||
- 右键点击状态 → 「Edit Style」(编辑样式)可修改颜色、边框等
|
||||
|
||||
#### 状态转换
|
||||
- 从左侧工具栏拖拽「Transition」(带箭头的线)到画布
|
||||
- 连接两个状态(起点状态 → 终点状态)
|
||||
- 双击箭头输入触发事件(如:`scanner1_complete`)
|
||||
|
||||
#### 终止状态
|
||||
- 从左侧工具栏拖拽「Final State」(同心圆)到画布(如果需要)
|
||||
|
||||
### 3. 高级设置
|
||||
|
||||
#### 转换条件
|
||||
- 右键点击转换箭头 → 「Edit」(编辑)→ 「Add Condition」(添加条件)
|
||||
- 输入条件(如:`if position == upper_limit`)
|
||||
|
||||
#### 状态动作
|
||||
- 双击状态 → 进入编辑模式
|
||||
- 输入格式:`状态名称\n/进入动作\n退出动作`
|
||||
- 示例:`scanner1_scanning\n/on_scanner1_scanning_start()\non_scanner1_scanning_stop()`
|
||||
|
||||
#### 并行区域(可选)
|
||||
- 使用「Composite State」(复合状态)创建嵌套区域
|
||||
- 用于表示并发执行的状态
|
||||
|
||||
## 三、保存到本地
|
||||
|
||||
### 1. 保存为.drawio格式(可编辑)
|
||||
- 点击顶部菜单栏「File」(文件)→ 「Save As」(另存为)
|
||||
- 选择「Device」(设备)
|
||||
- 选择保存位置(推荐保存到 `motor_service` 目录)
|
||||
- 输入文件名(如:`scanner_state_machine.drawio`)
|
||||
- 点击「Save」(保存)
|
||||
|
||||
### 2. 导出为图片格式(用于查看)
|
||||
- 点击顶部菜单栏「File」(文件)→ 「Export As」(导出为)→ 「PNG」
|
||||
- 设置图片参数:
|
||||
- 「Include a border」(包含边框):可选
|
||||
- 「Zoom」(缩放):100%
|
||||
- 「Transparent Background」(透明背景):可选
|
||||
- 点击「Export」(导出)
|
||||
- 选择保存位置和文件名(如:`scanner_state_machine.png`)
|
||||
- 点击「Save」(保存)
|
||||
|
||||
### 3. 导出为PDF格式(用于文档)
|
||||
- 点击顶部菜单栏「File」(文件)→ 「Export As」(导出为)→ 「PDF」
|
||||
- 设置PDF参数后点击「Export」(导出)
|
||||
|
||||
## 四、绘制示例(扫描器状态图)
|
||||
|
||||
按照之前的设计指南,绘制以下状态:
|
||||
- 初始状态
|
||||
- `all_stopped`
|
||||
- `scanner1_scanning`
|
||||
- `scanner1_waiting`
|
||||
- `scanner2_scanning`
|
||||
- `scanner2_waiting`
|
||||
|
||||
并添加以下转换:
|
||||
- 初始状态 → `all_stopped`
|
||||
- `all_stopped` → `scanner1_scanning`(触发:`start_scanner1`)
|
||||
- `all_stopped` → `scanner2_scanning`(触发:`start_scanner2`)
|
||||
- `scanner1_scanning` → `scanner1_waiting`(触发:`scanner1_complete`)
|
||||
- `scanner2_scanning` → `scanner2_waiting`(触发:`scanner2_complete`)
|
||||
- `scanner1_waiting` → `scanner2_scanning`(触发:`start_scanner2`)
|
||||
- `scanner2_waiting` → `scanner1_scanning`(触发:`start_scanner1`)
|
||||
- 所有状态 → `all_stopped`(触发:`stop_all` 或 `emer_stop_all`)
|
||||
|
||||
## 五、注意事项
|
||||
|
||||
1. 定期保存:绘制过程中可按 Ctrl+S(Windows)或 Command+S(Mac)快速保存
|
||||
2. 命名规范:使用有意义的状态名称和事件名称
|
||||
3. 布局清晰:使用「Arrange」(排列)菜单调整状态布局
|
||||
4. 颜色区分:使用不同颜色表示不同类型的状态(如:运行状态用绿色,停止状态用红色)
|
||||
|
||||
绘制完成后,将 `.drawio` 文件保存到 `motor_service` 目录,然后告诉我,我将根据您的状态图实现代码。
|
||||
@@ -0,0 +1,76 @@
|
||||
from mqtt_client import MQTTClient
|
||||
from data_center import DataCenter
|
||||
from Manager.mwmotor_manager import MotorManager
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import signal
|
||||
from PySide6.QtCore import *
|
||||
|
||||
class Application(QCoreApplication):
|
||||
def __init__(self, argv):
|
||||
super().__init__(argv)
|
||||
self.motor_manager = None
|
||||
self.mqtt_client = None
|
||||
self._signal_received = False
|
||||
|
||||
# 创建定时器检查信号
|
||||
self.timer = QTimer()
|
||||
self.timer.timeout.connect(self.check_signals)
|
||||
self.timer.start(100) # 每100ms检查一次
|
||||
|
||||
def check_signals(self):
|
||||
if self._signal_received:
|
||||
self.timer.stop()
|
||||
self.cleanup()
|
||||
|
||||
def cleanup(self):
|
||||
print("\n正在清理资源...")
|
||||
# 停止电机
|
||||
if self.motor_manager:
|
||||
self.motor_manager.emergency_stop(MotorManager.ID_MT1 | MotorManager.ID_MT2)
|
||||
time.sleep(0.2)
|
||||
self.motor_manager.destroy()
|
||||
time.sleep(0.2)
|
||||
# 断开MQTT连接
|
||||
if self.mqtt_client:
|
||||
self.mqtt_client.quit()
|
||||
print("资源清理完成,程序退出")
|
||||
self.quit()
|
||||
|
||||
def signal_handler(signum, frame):
|
||||
app._signal_received = True
|
||||
|
||||
def exec_cmd(cmd):
|
||||
print("exec:", cmd)
|
||||
out = os.popen(cmd)
|
||||
print(out.readlines())
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = Application(sys.argv)
|
||||
|
||||
# 注册信号处理
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
|
||||
exec_cmd("sudo pinctrl set 17 op pn dl")
|
||||
|
||||
app.motor_manager = MotorManager()
|
||||
app.mqtt_client = MQTTClient()
|
||||
data_center = DataCenter()
|
||||
|
||||
app.motor_manager.mqtt_client = app.mqtt_client
|
||||
|
||||
app.motor_manager.update_online_status.connect(data_center.update_online_status)
|
||||
app.motor_manager.update_setting_velocity.connect(data_center.update_motor_setting_velocity)
|
||||
app.motor_manager.update_location.connect(data_center.update_motor_location)
|
||||
app.motor_manager.update_estimates.connect(data_center.update_motor_estimates)
|
||||
app.motor_manager.update_direction.connect(data_center.update_motor_direction)
|
||||
app.motor_manager.update_duration.connect(data_center.update_motor_duration)
|
||||
app.motor_manager.update_state.connect(data_center.update_motor_state)
|
||||
app.motor_manager.update_work_mode.connect(data_center.update_motor_sports_mode)
|
||||
data_center.dataReady.connect(app.mqtt_client.send_motor_status)
|
||||
app.mqtt_client.write_motor_data.connect(app.motor_manager.set_value)
|
||||
app.mqtt_client.write_motor_globaldev_data.connect(app.motor_manager.set_globaldev_value)
|
||||
|
||||
sys.exit(app.exec())
|
||||
@@ -0,0 +1,178 @@
|
||||
import paho.mqtt.client as mqtt
|
||||
import json
|
||||
from datetime import datetime
|
||||
import time
|
||||
import socket
|
||||
from threading import Timer
|
||||
from config import *
|
||||
from PySide6.QtCore import *
|
||||
from PySide6.QtCore import QTimer
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
#from PySide6.QtNetWork import *
|
||||
# 定义主题常量
|
||||
TOPICFIRST = "v1/cpy/"
|
||||
TOPICDEVICE = "/device"
|
||||
TOPICSTATUS = "/devstatus"
|
||||
TOPICCAL = "/calculation"
|
||||
TOPICCTRL = "/control"
|
||||
TOPICPRODUCT = "/product"
|
||||
TOPICCOLLECT = "/collect"
|
||||
startTime = time.time()
|
||||
|
||||
# 定义MQTT主题
|
||||
DEVICE_STATUS_TOPIC = "device/status"
|
||||
DEVICE_CONTROL_TOPIC = "device/control"
|
||||
SERVICE_STATUS_TOPIC = "service/status"
|
||||
DEVICE_API_TOPIC = "api/devices/response"
|
||||
|
||||
class MQTTClient(QObject):
|
||||
|
||||
write_motor_data = Signal(int, str, int)
|
||||
write_motor_globaldev_data = Signal(int, str, str)
|
||||
def __init__(self ):
|
||||
super().__init__()
|
||||
self.mqtt_client = mqtt.Client(client_id = 'scanner_service_' + self.random_string(6)) # 创建本地客户端
|
||||
self.mqtt_client.username_pw_set(USER, PWD)
|
||||
|
||||
# 设置回调函数
|
||||
self.mqtt_client.on_connect = self.on_connect
|
||||
self.mqtt_client.on_message = self.on_message
|
||||
self.mqtt_client.on_disconnect = self.on_disconnect
|
||||
self.is_connected = False
|
||||
self.conn_timer = QTimer(self)
|
||||
self.conn_timer.setInterval(1000)
|
||||
self.conn_timer.timeout.connect(self.connTimerHandler)
|
||||
self.conn_timer.start()
|
||||
|
||||
def random_string(self, length=6):
|
||||
"""生成随机字符串"""
|
||||
import random
|
||||
import string
|
||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||
|
||||
def checkLocalServer(self):
|
||||
host = '127.0.0.1'
|
||||
port = 1883
|
||||
timeout = 1
|
||||
print(f"Starting to check if {host}:{port} is available")
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
result = sock.connect_ex((host, port))
|
||||
if result == 0:
|
||||
print(f"Successfully connected to {host}:{port}")
|
||||
return True
|
||||
else:
|
||||
print(f"Failed to connect to {host}:{port}, error code: {result}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"An exception occurred while connecting to {host}:{port}: {e}")
|
||||
return False
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
def connTimerHandler(self):
|
||||
print("mqtt connect timer")
|
||||
self.conn_timer.stop()
|
||||
if self.checkLocalServer():
|
||||
self.mqtt_client.connect(BROKER, PORT) # 连接本地 MQTT 服务器
|
||||
self.mqtt_client.loop_start() # 开始循环以处理网络流量
|
||||
else:
|
||||
print("local mqtt brokeris not ready")
|
||||
self.conn_timer.start()
|
||||
|
||||
def quit(self):
|
||||
self.mqtt_client.loop_stop() # 停止循环
|
||||
self.mqtt_client.disconnect()
|
||||
|
||||
def on_connect(self, client, userdata, flags, rc):
|
||||
"""连接成功时调用"""
|
||||
print(f"Connected to MQTT broker with result code {rc}")
|
||||
client.subscribe(DEVICE_CONTROL_TOPIC) # 订阅命令主题
|
||||
|
||||
self.is_connected = True
|
||||
|
||||
def on_disconnect(self, client, userdata, rc):
|
||||
self.is_connected = False
|
||||
print("MQTT 已断开连接")
|
||||
|
||||
|
||||
def on_message(self, client, userdata, msg):
|
||||
"""处理接收到的消息"""
|
||||
if not 'MTO' in msg.payload.decode():
|
||||
return
|
||||
print(f"Message received on topic: {msg.topic} Message: {msg.payload.decode()}")
|
||||
# 解析 JSON
|
||||
try:
|
||||
json_obj = json.loads(msg.payload.decode())
|
||||
if msg.topic == DEVICE_CONTROL_TOPIC:
|
||||
self.handle_message(json_obj)
|
||||
except json.JSONDecodeError:
|
||||
print("Failed to decode JSON")
|
||||
|
||||
|
||||
def handle_message(self, json_obj):
|
||||
"""处理接收到的 JSON 消息"""
|
||||
motor_index = -1
|
||||
device_code = json_obj.get("device_code")
|
||||
device_id = json_obj.get("device_id")
|
||||
device_address = int(json_obj.get("device_address", 0))
|
||||
command = json_obj.get("command")
|
||||
if not 'MTO' in device_code:
|
||||
return
|
||||
print("device_code", device_code, "device_id", device_id, "device_address", device_address, "command", command)
|
||||
if device_code == "1#MTO" or device_code == "2#MTO" or device_code == "3#MTO":
|
||||
value = json_obj.get("value")
|
||||
if device_address == 1:
|
||||
print("motor",device_address, command, value)
|
||||
self.write_motor_data.emit(1, command, value)
|
||||
elif device_address == 2:
|
||||
print("motor",device_address, command, value)
|
||||
self.write_motor_data.emit(2, command, value)
|
||||
if device_address == 3:
|
||||
print("motor",device_address, command, value)
|
||||
self.write_motor_globaldev_data.emit(3, command, str(value))
|
||||
|
||||
def publish_msg(self, topic, msg):
|
||||
if isinstance(msg, dict):
|
||||
msg = json.dumps(msg)
|
||||
# print("publish_msg", topic, msg)
|
||||
self.mqtt_client.publish(topic, msg, qos=0)
|
||||
|
||||
def pusblish_service_status(self):
|
||||
global startTime
|
||||
runningTime = time.time() - startTime
|
||||
message = {
|
||||
"service_name" : "motor_service",
|
||||
"status": {
|
||||
"available": True,
|
||||
"running_time": runningTime
|
||||
}
|
||||
}
|
||||
self.publish_msg(SERVICE_STATUS_TOPIC, message)
|
||||
|
||||
def send_motor_status(self, motor_index, status):
|
||||
device_id = ""
|
||||
device_code = ""
|
||||
# print("send_motor_status", motor_index, status)
|
||||
|
||||
device_code = f"{motor_index}#MTO"
|
||||
self.publish_msg(DEVICE_STATUS_TOPIC, {
|
||||
"device_code": device_code, # 添加设备编码
|
||||
"status": status,
|
||||
"timestamp": datetime.now().isoformat()
|
||||
})
|
||||
|
||||
if hasattr(self, 'last_status_update'):
|
||||
if time.time() - self.last_status_update < 3.0:
|
||||
return
|
||||
self.last_status_update = time.time()
|
||||
self.pusblish_service_status()
|
||||
|
||||
def publish_cpy(self, topicname, data):
|
||||
topic = TOPICFIRST + self.device_id + topicname # 构建完整的主题名称
|
||||
json_data = json.dumps(data) # 将数据转换为 JSON 字符串
|
||||
self.mqtt_client.publish(topic, json_data) # 发布数据到本地
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
aiocoap==0.4.9
|
||||
altgraph==0.17.3
|
||||
astroid==3.0.1
|
||||
autograd==1.6.2
|
||||
autopep8==2.0.4
|
||||
bleak==0.20.2
|
||||
bleak-winrt==1.2.0
|
||||
blinker==1.7.0
|
||||
certifi==2023.7.22
|
||||
cffi==1.15.1
|
||||
charset-normalizer==3.2.0
|
||||
click==8.1.3
|
||||
clr-loader==0.2.5
|
||||
colorama==0.4.6
|
||||
colorlog==6.7.0
|
||||
comtypes==1.4.7
|
||||
contourpy==1.1.0
|
||||
CPU-temperature-monitor==0.2
|
||||
crcmod==1.7
|
||||
cycler==0.11.0
|
||||
dill==0.3.7
|
||||
docopt==0.6.2
|
||||
docstring-to-markdown==0.13
|
||||
et-xmlfile==1.1.0
|
||||
flake8==6.1.0
|
||||
Flask==3.0.0
|
||||
Flask-Cors==4.0.0
|
||||
fonttools==4.40.0
|
||||
future==0.18.3
|
||||
greenlet==2.0.2
|
||||
httpserver==1.1.0
|
||||
idna==3.4
|
||||
importlib-metadata==6.7.0
|
||||
influxdb==5.3.1
|
||||
influxdb-client==1.36.1
|
||||
iso8601==2.0.0
|
||||
isort==5.12.0
|
||||
isqdeployer==0.0.45
|
||||
isqtools==0.1.5
|
||||
itsdangerous==2.1.2
|
||||
jedi==0.19.1
|
||||
Jinja2==3.1.2
|
||||
joblib==1.3.2
|
||||
kiwisolver==1.4.4
|
||||
kneed==0.8.5
|
||||
Markdown==3.5.1
|
||||
markdown-it-py==3.0.0
|
||||
MarkupSafe==2.1.3
|
||||
matlab==0.1
|
||||
matlabengine==24.1
|
||||
matplotlib==3.7.1
|
||||
mccabe==0.7.0
|
||||
mdurl==0.1.2
|
||||
MouseInfo==0.1.3
|
||||
mplcursors==0.5.2
|
||||
msgpack==1.0.5
|
||||
mysql-connector-python==8.2.0
|
||||
numpy==1.25.0
|
||||
opencv-python==4.10.0.84
|
||||
opencv-python-headless==4.10.0.84
|
||||
openpyxl==3.1.2
|
||||
packaging==23.1
|
||||
paho-mqtt==1.6.1
|
||||
pandas==2.1.3
|
||||
parso==0.8.3
|
||||
pefile==2023.2.7
|
||||
Pillow==10.0.0
|
||||
platformdirs==3.7.0
|
||||
pluggy==1.3.0
|
||||
protobuf==4.21.12
|
||||
psutil==5.9.5
|
||||
pyasn1==0.6.0
|
||||
PyAutoGUI==0.9.54
|
||||
pycodestyle==2.11.1
|
||||
pycparser==2.21
|
||||
pycryptodome==3.16.0
|
||||
pydocstyle==6.3.0
|
||||
pyflakes==3.1.0
|
||||
PyGetWindow==0.0.9
|
||||
Pygments==2.15.1
|
||||
pyinstaller==6.2.0
|
||||
pyinstaller-hooks-contrib==2023.3
|
||||
pylint==3.0.2
|
||||
pymodbus==3.6.4
|
||||
PyMsgBox==1.0.9
|
||||
PyMySQL==1.1.0
|
||||
pyparsing==3.1.0
|
||||
pyperclip==1.9.0
|
||||
pypiwin32==223
|
||||
pyqt5-plugins==5.15.9.2.3
|
||||
PyQt5-Qt5==5.15.2
|
||||
PyQt5-sip==12.13.0
|
||||
pyqt5-tools==5.15.9.3.3
|
||||
PyQt6==6.6.0
|
||||
PyQt6-Charts==6.6.0
|
||||
PyQt6-Charts-Qt6==6.6.2
|
||||
PyQt6-QScintilla==2.14.1
|
||||
PyQt6-Qt6==6.6.0
|
||||
PyQt6-sip==13.6.0
|
||||
PyQt6-WebEngine==6.6.0
|
||||
PyQt6-WebEngine-Qt6==6.6.0
|
||||
PyQtChart==5.15.6
|
||||
PyQtChart-Qt5==5.15.2
|
||||
pyqtgraph==0.13.3
|
||||
PyRect==0.2.0
|
||||
pyscard==2.0.9
|
||||
PyScreeze==0.1.30
|
||||
pyserial==3.5
|
||||
pytesseract==0.3.10
|
||||
python-can==4.3.1
|
||||
python-dateutil==2.8.2
|
||||
python-dotenv==1.0.0
|
||||
python-lsp-jsonrpc==1.1.2
|
||||
python-lsp-server==1.9.0
|
||||
pythonnet==3.0.1
|
||||
pytoolconfig==1.2.6
|
||||
pytweening==1.2.0
|
||||
pytz==2023.3
|
||||
pywin32==306
|
||||
pywin32-ctypes==0.2.1
|
||||
PyYAML==6.0
|
||||
QCustomPlot_PyQt5==2.1.1.1
|
||||
qt5-applications==5.15.2.2.3
|
||||
qt5-tools==5.15.2.1.3
|
||||
qt6-applications==6.4.3.2.3
|
||||
qt6-tools==6.4.3.1.3
|
||||
reactivex==4.0.4
|
||||
requests==2.28.2
|
||||
rich==13.6.0
|
||||
rope==1.11.0
|
||||
scikit-learn==1.3.2
|
||||
scipy==1.11.1
|
||||
SCons==4.8.0
|
||||
serial==0.0.97
|
||||
six==1.16.0
|
||||
snowballstemmer==2.2.0
|
||||
SQLAlchemy==2.0.19
|
||||
threadpoolctl==3.2.0
|
||||
tkinterdnd2==0.4.2
|
||||
tomli==2.0.1
|
||||
tomlkit==0.12.3
|
||||
typing_extensions==4.7.1
|
||||
tzdata==2023.3
|
||||
ujson==5.8.0
|
||||
urllib3==1.26.18
|
||||
watchdog==3.0.0
|
||||
Werkzeug==3.0.1
|
||||
whatthepatch==1.0.5
|
||||
WMI==1.5.1
|
||||
wrapt==1.17.2
|
||||
xlwings==0.31.1
|
||||
yapf==0.40.1
|
||||
zipp==3.15.0
|
||||
transitions==0.9.0
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=Scanner Service
|
||||
After=emqx.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
WorkingDirectory=/home/admin/CPY/CPY_AdminPlatform_V3.5/scanner_service
|
||||
ExecStart=/home/admin/CPY/venv/bin/python /home/admin/CPY/CPY_AdminPlatform_V3.5/scanner_service/main.py
|
||||
Restart=always
|
||||
RestartSec=10s
|
||||
StartLimitBurst=5
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
# 状态机设计指南
|
||||
|
||||
## 一、状态图绘制指南
|
||||
|
||||
### 1. 状态图包含要素
|
||||
|
||||
为了确保状态图能准确转换为代码,请包含以下要素:
|
||||
|
||||
| 要素 | 说明 | 示例 |
|
||||
|------|------|------|
|
||||
| **状态名称** | 清晰描述系统状态 | `scanner1_scanning` |
|
||||
| **状态转换** | 状态间的变化路径 | `scanner1_scanning → scanner1_waiting` |
|
||||
| **触发事件** | 导致转换的信号 | `scanner1_complete` |
|
||||
| **转换条件** | 转换发生的条件 | `if position == upper_limit` |
|
||||
| **执行动作** | 转换时执行的操作 | `on_scanner1_scanning_start()` |
|
||||
| **初始状态** | 系统初始状态 | `all_stopped` |
|
||||
|
||||
### 2. 状态图绘制工具推荐
|
||||
|
||||
- **在线工具**:
|
||||
- [draw.io](https://app.diagrams.net/) - 免费、功能强大
|
||||
- [Lucidchart](https://www.lucidchart.com/) - 专业UML绘图
|
||||
- [PlantUML](https://plantuml.com/state-diagram) - 文本描述生成图形
|
||||
|
||||
- **本地工具**:
|
||||
- Microsoft Visio
|
||||
- StarUML
|
||||
- Visual Studio Code 插件 (如 PlantUML)
|
||||
|
||||
### 3. 绘制示例(PlantUML语法)
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
skinparam state {
|
||||
StartColor red
|
||||
EndColor silver
|
||||
BackgroundColor beige
|
||||
BorderColor gray
|
||||
FontName Helvetica
|
||||
}
|
||||
|
||||
[*] --> all_stopped
|
||||
|
||||
state all_stopped {
|
||||
}
|
||||
|
||||
state scanner1_scanning {
|
||||
}
|
||||
|
||||
state scanner1_waiting {
|
||||
}
|
||||
|
||||
state scanner2_scanning {
|
||||
}
|
||||
|
||||
state scanner2_waiting {
|
||||
}
|
||||
|
||||
all_stopped --> scanner1_scanning : start_scanner1
|
||||
transition all_stopped --> scanner2_scanning : start_scanner2
|
||||
scanner1_scanning --> scanner1_waiting : scanner1_complete
|
||||
scanner2_scanning --> scanner2_waiting : scanner2_complete
|
||||
scanner1_waiting --> scanner2_scanning : start_scanner2
|
||||
scanner2_waiting --> scanner1_scanning : start_scanner1
|
||||
|
||||
scanner1_scanning --> all_stopped : stop_all
|
||||
scanner1_waiting --> all_stopped : stop_all
|
||||
scanner2_scanning --> all_stopped : stop_all
|
||||
scanner2_waiting --> all_stopped : stop_all
|
||||
|
||||
@enduml
|
||||
```
|
||||
|
||||
## 二、代码实现对应关系
|
||||
|
||||
### 1. 状态映射
|
||||
|
||||
| 状态图要素 | 代码实现 |
|
||||
|------------|----------|
|
||||
| 状态 | `self.states = ['state1', 'state2', ...]` |
|
||||
| 转换 | `self.transitions = [{'trigger': 'event', 'source': 'from_state', 'dest': 'to_state'}]` |
|
||||
| 初始状态 | `Machine(initial='initial_state')` |
|
||||
| 动作 | `self.on_enter_state_name(action_function)` |
|
||||
|
||||
### 2. 事件处理
|
||||
|
||||
```python
|
||||
# 状态转换定义
|
||||
self.transitions = [
|
||||
{'trigger': 'start_scanner1', 'source': 'all_stopped', 'dest': 'scanner1_scanning'},
|
||||
{'trigger': 'scanner1_complete', 'source': 'scanner1_scanning', 'dest': 'scanner1_waiting'},
|
||||
# 更多转换...
|
||||
]
|
||||
|
||||
# 状态进入动作
|
||||
self.on_enter_scanner1_scanning(self.on_scanner1_scanning_start)
|
||||
|
||||
# 动作实现
|
||||
def on_scanner1_scanning_start(self):
|
||||
"""1号扫描开始时的回调"""
|
||||
self.start_scanning(self.ID_MT1)
|
||||
```
|
||||
|
||||
## 三、交付要求
|
||||
|
||||
请提供:
|
||||
|
||||
1. **状态图文件**:支持格式包括 PNG、JPG、SVG 或 PlantUML 文本
|
||||
2. **状态说明文档**:
|
||||
- 每个状态的含义
|
||||
- 每个事件的触发条件
|
||||
- 每个动作的具体功能
|
||||
3. **特殊需求说明**:
|
||||
- 超时处理
|
||||
- 错误恢复机制
|
||||
- 并发控制要求
|
||||
|
||||
## 四、示例状态图与代码对应
|
||||
|
||||
### 状态图
|
||||
|
||||
```
|
||||
[*] → all_stopped
|
||||
all_stopped → scanner1_scanning : start_scanner1
|
||||
scanner1_scanning → scanner1_waiting : scanner1_complete
|
||||
scanner1_waiting → scanner2_scanning : start_scanner2
|
||||
scanner2_scanning → scanner2_waiting : scanner2_complete
|
||||
scanner2_waiting → scanner1_scanning : start_scanner1
|
||||
```
|
||||
|
||||
### 对应代码
|
||||
|
||||
```python
|
||||
from transitions import Machine
|
||||
|
||||
class MotorManager:
|
||||
def __init__(self):
|
||||
# 定义状态
|
||||
self.states = ['all_stopped', 'scanner1_scanning', 'scanner1_waiting', 'scanner2_scanning', 'scanner2_waiting']
|
||||
|
||||
# 定义转换
|
||||
self.transitions = [
|
||||
{'trigger': 'start_scanner1', 'source': ['all_stopped', 'scanner2_waiting'], 'dest': 'scanner1_scanning'},
|
||||
{'trigger': 'scanner1_complete', 'source': 'scanner1_scanning', 'dest': 'scanner1_waiting'},
|
||||
{'trigger': 'start_scanner2', 'source': ['all_stopped', 'scanner1_waiting'], 'dest': 'scanner2_scanning'},
|
||||
{'trigger': 'scanner2_complete', 'source': 'scanner2_scanning', 'dest': 'scanner2_waiting'},
|
||||
]
|
||||
|
||||
# 初始化状态机
|
||||
self.machine = Machine(model=self, states=self.states, transitions=self.transitions, initial='all_stopped')
|
||||
|
||||
# 添加回调
|
||||
self.on_enter_scanner1_scanning(self.on_scanner1_scanning_start)
|
||||
self.on_enter_scanner2_scanning(self.on_scanner2_scanning_start)
|
||||
|
||||
def on_scanner1_scanning_start(self):
|
||||
print("1号扫描器开始扫描")
|
||||
|
||||
def on_scanner2_scanning_start(self):
|
||||
print("2号扫描器开始扫描")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
请完成状态图绘制后,将文件保存到 `y:\CPY\CPY_AdminPlatform_V3.5\motor_service\` 目录下,然后告知我开始实现代码。
|
||||
Reference in New Issue
Block a user