commit 78b5898da2b5ad2d93e3d3c1cdc12412f11a1229 Author: leon Date: Fri Jun 19 20:47:06 2026 +0800 Initial commit: 上传完整代码 diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..70be789 --- /dev/null +++ b/.gitignore @@ -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 + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..78fc0c9 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# CPY_IPC_admin + diff --git a/backend/__init__.py b/backend/__init__.py new file mode 100644 index 0000000..69f0e39 --- /dev/null +++ b/backend/__init__.py @@ -0,0 +1 @@ +# 这个文件使 backend 目录成为一个 Python 包 \ No newline at end of file diff --git a/backend/config.py b/backend/config.py new file mode 100644 index 0000000..68928fd --- /dev/null +++ b/backend/config.py @@ -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" \ No newline at end of file diff --git a/backend/database.py b/backend/database.py new file mode 100644 index 0000000..9c70400 --- /dev/null +++ b/backend/database.py @@ -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("数据已恢复") diff --git a/backend/device_status.py b/backend/device_status.py new file mode 100644 index 0000000..03c30d1 --- /dev/null +++ b/backend/device_status.py @@ -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() \ No newline at end of file diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000..ed62bc0 --- /dev/null +++ b/backend/main.py @@ -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)) diff --git a/backend/migrate.py b/backend/migrate.py new file mode 100644 index 0000000..882c7c5 --- /dev/null +++ b/backend/migrate.py @@ -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() \ No newline at end of file diff --git a/backend/migrations/add_device_enabled.py b/backend/migrations/add_device_enabled.py new file mode 100644 index 0000000..0bfbdba --- /dev/null +++ b/backend/migrations/add_device_enabled.py @@ -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("迁移完成") \ No newline at end of file diff --git a/backend/models/__init__.py b/backend/models/__init__.py new file mode 100644 index 0000000..58c68ba --- /dev/null +++ b/backend/models/__init__.py @@ -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' +] \ No newline at end of file diff --git a/backend/models/base.py b/backend/models/base.py new file mode 100644 index 0000000..eeebe88 --- /dev/null +++ b/backend/models/base.py @@ -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) \ No newline at end of file diff --git a/backend/models/device.py b/backend/models/device.py new file mode 100644 index 0000000..71650fe --- /dev/null +++ b/backend/models/device.py @@ -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 + } \ No newline at end of file diff --git a/backend/models/device_type.py b/backend/models/device_type.py new file mode 100644 index 0000000..75f99b4 --- /dev/null +++ b/backend/models/device_type.py @@ -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 + } \ No newline at end of file diff --git a/backend/models/interface.py b/backend/models/interface.py new file mode 100644 index 0000000..e7217fe --- /dev/null +++ b/backend/models/interface.py @@ -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 + } \ No newline at end of file diff --git a/backend/models/register.py b/backend/models/register.py new file mode 100644 index 0000000..608fb8b --- /dev/null +++ b/backend/models/register.py @@ -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") \ No newline at end of file diff --git a/backend/models/system_info.py b/backend/models/system_info.py new file mode 100644 index 0000000..4ed5482 --- /dev/null +++ b/backend/models/system_info.py @@ -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) \ No newline at end of file diff --git a/backend/mqtt_client.py b/backend/mqtt_client.py new file mode 100644 index 0000000..26fd39a --- /dev/null +++ b/backend/mqtt_client.py @@ -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() \ No newline at end of file diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000..e9dab29 --- /dev/null +++ b/backend/package-lock.json @@ -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" + } + } + } +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..069af9a --- /dev/null +++ b/backend/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "@fortawesome/fontawesome-free": "^6.7.2", + "element-plus": "^2.9.7", + "vue-router": "^4.5.0" + } +} diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..04079b3 --- /dev/null +++ b/backend/requirements.txt @@ -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 diff --git a/backend/run.py b/backend/run.py new file mode 100644 index 0000000..55f792d --- /dev/null +++ b/backend/run.py @@ -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) \ No newline at end of file diff --git a/backend/schemas.py b/backend/schemas.py new file mode 100644 index 0000000..a290103 --- /dev/null +++ b/backend/schemas.py @@ -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 \ No newline at end of file diff --git a/backend/service_status.py b/backend/service_status.py new file mode 100644 index 0000000..6bcfefc --- /dev/null +++ b/backend/service_status.py @@ -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() diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..91f7558 --- /dev/null +++ b/frontend/.gitignore @@ -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 diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..f7a5d43 --- /dev/null +++ b/frontend/README.md @@ -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 +``` diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..d30d101 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + 测偏仪管理后台 + + +
+ + + diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico new file mode 100644 index 0000000..df36fcf Binary files /dev/null and b/frontend/public/favicon.ico differ diff --git a/frontend/src/App.vue b/frontend/src/App.vue new file mode 100644 index 0000000..7d9ce89 --- /dev/null +++ b/frontend/src/App.vue @@ -0,0 +1,244 @@ + + + + + diff --git a/frontend/src/assets/base.css b/frontend/src/assets/base.css new file mode 100644 index 0000000..8816868 --- /dev/null +++ b/frontend/src/assets/base.css @@ -0,0 +1,86 @@ +/* color palette from */ +: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; +} diff --git a/frontend/src/assets/logo.svg b/frontend/src/assets/logo.svg new file mode 100644 index 0000000..7565660 --- /dev/null +++ b/frontend/src/assets/logo.svg @@ -0,0 +1 @@ + diff --git a/frontend/src/assets/main.css b/frontend/src/assets/main.css new file mode 100644 index 0000000..36fb845 --- /dev/null +++ b/frontend/src/assets/main.css @@ -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; + } +} diff --git a/frontend/src/components/HelloWorld.vue b/frontend/src/components/HelloWorld.vue new file mode 100644 index 0000000..a2eabd1 --- /dev/null +++ b/frontend/src/components/HelloWorld.vue @@ -0,0 +1,41 @@ + + + + + diff --git a/frontend/src/components/TheWelcome.vue b/frontend/src/components/TheWelcome.vue new file mode 100644 index 0000000..ae6eec3 --- /dev/null +++ b/frontend/src/components/TheWelcome.vue @@ -0,0 +1,94 @@ + + + diff --git a/frontend/src/components/WelcomeItem.vue b/frontend/src/components/WelcomeItem.vue new file mode 100644 index 0000000..6d7086a --- /dev/null +++ b/frontend/src/components/WelcomeItem.vue @@ -0,0 +1,87 @@ + + + diff --git a/frontend/src/components/icons/IconCommunity.vue b/frontend/src/components/icons/IconCommunity.vue new file mode 100644 index 0000000..2dc8b05 --- /dev/null +++ b/frontend/src/components/icons/IconCommunity.vue @@ -0,0 +1,7 @@ + diff --git a/frontend/src/components/icons/IconDocumentation.vue b/frontend/src/components/icons/IconDocumentation.vue new file mode 100644 index 0000000..6d4791c --- /dev/null +++ b/frontend/src/components/icons/IconDocumentation.vue @@ -0,0 +1,7 @@ + diff --git a/frontend/src/components/icons/IconEcosystem.vue b/frontend/src/components/icons/IconEcosystem.vue new file mode 100644 index 0000000..c3a4f07 --- /dev/null +++ b/frontend/src/components/icons/IconEcosystem.vue @@ -0,0 +1,7 @@ + diff --git a/frontend/src/components/icons/IconSupport.vue b/frontend/src/components/icons/IconSupport.vue new file mode 100644 index 0000000..7452834 --- /dev/null +++ b/frontend/src/components/icons/IconSupport.vue @@ -0,0 +1,7 @@ + diff --git a/frontend/src/components/icons/IconTooling.vue b/frontend/src/components/icons/IconTooling.vue new file mode 100644 index 0000000..660598d --- /dev/null +++ b/frontend/src/components/icons/IconTooling.vue @@ -0,0 +1,19 @@ + + diff --git a/frontend/src/views/DeviceManagement.vue b/frontend/src/views/DeviceManagement.vue new file mode 100644 index 0000000..a266d57 --- /dev/null +++ b/frontend/src/views/DeviceManagement.vue @@ -0,0 +1,906 @@ + + + + + \ No newline at end of file diff --git a/frontend/src/views/DeviceTypeManagement.vue b/frontend/src/views/DeviceTypeManagement.vue new file mode 100644 index 0000000..7dca34a --- /dev/null +++ b/frontend/src/views/DeviceTypeManagement.vue @@ -0,0 +1,300 @@ + + + + + \ No newline at end of file diff --git a/frontend/src/views/Home.vue b/frontend/src/views/Home.vue new file mode 100644 index 0000000..574ec94 --- /dev/null +++ b/frontend/src/views/Home.vue @@ -0,0 +1,201 @@ + + + + + \ No newline at end of file diff --git a/frontend/src/views/InterfaceManagement.vue b/frontend/src/views/InterfaceManagement.vue new file mode 100644 index 0000000..93a949f --- /dev/null +++ b/frontend/src/views/InterfaceManagement.vue @@ -0,0 +1,532 @@ + + + + + \ No newline at end of file diff --git a/frontend/src/views/ServiceManagement.vue b/frontend/src/views/ServiceManagement.vue new file mode 100644 index 0000000..a167fbd --- /dev/null +++ b/frontend/src/views/ServiceManagement.vue @@ -0,0 +1,442 @@ + + + + + \ No newline at end of file diff --git a/hvs_service/config.py b/hvs_service/config.py new file mode 100644 index 0000000..e4eac95 --- /dev/null +++ b/hvs_service/config.py @@ -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 = {} \ No newline at end of file diff --git a/hvs_service/hvs.py b/hvs_service/hvs.py new file mode 100755 index 0000000..2ad3a6c --- /dev/null +++ b/hvs_service/hvs.py @@ -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}") \ No newline at end of file diff --git a/hvs_service/hvs.service b/hvs_service/hvs.service new file mode 100644 index 0000000..8432835 --- /dev/null +++ b/hvs_service/hvs.service @@ -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 \ No newline at end of file diff --git a/hvs_service/main.py b/hvs_service/main.py new file mode 100644 index 0000000..f3846e9 --- /dev/null +++ b/hvs_service/main.py @@ -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() + diff --git a/hvs_service/modbus_client.py b/hvs_service/modbus_client.py new file mode 100644 index 0000000..1b19960 --- /dev/null +++ b/hvs_service/modbus_client.py @@ -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 diff --git a/hvs_service/mqtt_client.py b/hvs_service/mqtt_client.py new file mode 100644 index 0000000..c349f1c --- /dev/null +++ b/hvs_service/mqtt_client.py @@ -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) \ No newline at end of file diff --git a/hvs_service/requirements.txt b/hvs_service/requirements.txt new file mode 100644 index 0000000..5fbe897 --- /dev/null +++ b/hvs_service/requirements.txt @@ -0,0 +1,2 @@ +pymodbus>=3.5.0 +paho-mqtt>=2.1.0 \ No newline at end of file diff --git a/hvs_service/tcp_io_module.py b/hvs_service/tcp_io_module.py new file mode 100755 index 0000000..60e2b5d --- /dev/null +++ b/hvs_service/tcp_io_module.py @@ -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客户端启动失败") + diff --git a/nginx.conf b/nginx.conf new file mode 100755 index 0000000..3039686 --- /dev/null +++ b/nginx.conf @@ -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; + } +} diff --git a/powerbus_service/config.py b/powerbus_service/config.py new file mode 100644 index 0000000..4fb28b5 --- /dev/null +++ b/powerbus_service/config.py @@ -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 = {} diff --git a/powerbus_service/main.py b/powerbus_service/main.py new file mode 100644 index 0000000..90d7afc --- /dev/null +++ b/powerbus_service/main.py @@ -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() + diff --git a/powerbus_service/modbus_client.py b/powerbus_service/modbus_client.py new file mode 100644 index 0000000..aded482 --- /dev/null +++ b/powerbus_service/modbus_client.py @@ -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 diff --git a/powerbus_service/mqtt_client.py b/powerbus_service/mqtt_client.py new file mode 100644 index 0000000..976cf0b --- /dev/null +++ b/powerbus_service/mqtt_client.py @@ -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) \ No newline at end of file diff --git a/powerbus_service/powerbus.service b/powerbus_service/powerbus.service new file mode 100644 index 0000000..2ccdf30 --- /dev/null +++ b/powerbus_service/powerbus.service @@ -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 \ No newline at end of file diff --git a/powerbus_service/requirements.txt b/powerbus_service/requirements.txt new file mode 100644 index 0000000..5fbe897 --- /dev/null +++ b/powerbus_service/requirements.txt @@ -0,0 +1,2 @@ +pymodbus>=3.5.0 +paho-mqtt>=2.1.0 \ No newline at end of file diff --git a/powerbus_service/sensor.py b/powerbus_service/sensor.py new file mode 100644 index 0000000..c8070e5 --- /dev/null +++ b/powerbus_service/sensor.py @@ -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)}") diff --git a/powerbus_service/tcp_io_module.py b/powerbus_service/tcp_io_module.py new file mode 100644 index 0000000..60e2b5d --- /dev/null +++ b/powerbus_service/tcp_io_module.py @@ -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客户端启动失败") + diff --git a/scanner_service/Manager/mwmotor_manager.py b/scanner_service/Manager/mwmotor_manager.py new file mode 100644 index 0000000..1e49c55 --- /dev/null +++ b/scanner_service/Manager/mwmotor_manager.py @@ -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) + + + diff --git a/scanner_service/Manager/mwmotor_manager.py_backup b/scanner_service/Manager/mwmotor_manager.py_backup new file mode 100644 index 0000000..796def7 --- /dev/null +++ b/scanner_service/Manager/mwmotor_manager.py_backup @@ -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) + + + diff --git a/scanner_service/config.py b/scanner_service/config.py new file mode 100644 index 0000000..c04a728 --- /dev/null +++ b/scanner_service/config.py @@ -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" \ No newline at end of file diff --git a/scanner_service/data_center.py b/scanner_service/data_center.py new file mode 100644 index 0000000..4ff22f5 --- /dev/null +++ b/scanner_service/data_center.py @@ -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"]) diff --git a/scanner_service/drawio_usage_guide.md b/scanner_service/drawio_usage_guide.md new file mode 100755 index 0000000..58619df --- /dev/null +++ b/scanner_service/drawio_usage_guide.md @@ -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` 目录,然后告诉我,我将根据您的状态图实现代码。 \ No newline at end of file diff --git a/scanner_service/main.py b/scanner_service/main.py new file mode 100644 index 0000000..d9ae2c2 --- /dev/null +++ b/scanner_service/main.py @@ -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()) \ No newline at end of file diff --git a/scanner_service/mqtt_client.py b/scanner_service/mqtt_client.py new file mode 100644 index 0000000..a6c8673 --- /dev/null +++ b/scanner_service/mqtt_client.py @@ -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) # 发布数据到本地 + + diff --git a/scanner_service/requirements.txt b/scanner_service/requirements.txt new file mode 100644 index 0000000..1c8c74c --- /dev/null +++ b/scanner_service/requirements.txt @@ -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 \ No newline at end of file diff --git a/scanner_service/scanner.service b/scanner_service/scanner.service new file mode 100755 index 0000000..6b269f6 --- /dev/null +++ b/scanner_service/scanner.service @@ -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 \ No newline at end of file diff --git a/scanner_service/state_machine_design_guide.md b/scanner_service/state_machine_design_guide.md new file mode 100755 index 0000000..6bb2841 --- /dev/null +++ b/scanner_service/state_machine_design_guide.md @@ -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\` 目录下,然后告知我开始实现代码。 \ No newline at end of file