Compare commits
16
Commits
c884dce5bf
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d0f57763a | ||
|
|
bb9e546ccf | ||
|
|
3f8a6bd509 | ||
|
|
17233eb947 | ||
|
|
f3526e46f1 | ||
|
|
e7cbafa6eb | ||
|
|
5948dbaaf5 | ||
|
|
6e63361554 | ||
|
|
8ea65703a1 | ||
|
|
42b781aa03 | ||
|
|
98b0d71dc9 | ||
|
|
1e7b462c2c | ||
|
|
a3e2222388 | ||
|
|
36222e2675 | ||
|
|
add7f6c361 | ||
|
|
6f9d6ed0d6 |
@@ -777,3 +777,36 @@ async def power_control(power_data: dict):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"电源控制时发生错误: {e}")
|
print(f"电源控制时发生错误: {e}")
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
# 扫描控制API - 控制Scanner的启动与停止
|
||||||
|
@app.post("/api/scanctrl")
|
||||||
|
async def scan_control(scan_data: dict):
|
||||||
|
"""
|
||||||
|
控制Scanner的启动与停止
|
||||||
|
参数:
|
||||||
|
- action: 操作,可选值: 'start' (启动) 或 'stop' (停止)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
action = scan_data.get("action")
|
||||||
|
|
||||||
|
# 验证操作类型
|
||||||
|
if action not in ['start', 'stop']:
|
||||||
|
raise HTTPException(status_code=400, detail="action 必须是 'start' 或 'stop'")
|
||||||
|
|
||||||
|
try:
|
||||||
|
path = "/home/admin/.config/cpy/config.json"
|
||||||
|
with open(path, "r") as f:
|
||||||
|
config = json.load(f)
|
||||||
|
sn = config.get('sn', "")
|
||||||
|
if sn == "":
|
||||||
|
raise HTTPException(status_code=400, detail="配置文件中缺少 sn 字段")
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise HTTPException(status_code=400, detail="配置文件不存在")
|
||||||
|
|
||||||
|
mqtt_client.publish(f"v1/cpy/{sn}/control", json.dumps({"method": "scan_control", "action": action}))
|
||||||
|
return {"action": action, "status": "success"}
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
print(f"扫描控制时发生错误: {e}")
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|||||||
@@ -27,5 +27,4 @@ coverage
|
|||||||
*.sln
|
*.sln
|
||||||
*.sw?
|
*.sw?
|
||||||
*.json
|
*.json
|
||||||
*.ts
|
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
|
|||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
+31
-12
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, onMounted, computed } from 'vue'
|
import { ref, onMounted, onUnmounted, computed } from 'vue'
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import { useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import {
|
import {
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
Connection,
|
Connection,
|
||||||
List,
|
List,
|
||||||
Setting,
|
Setting,
|
||||||
Zap,
|
SwitchButton,
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
ArrowRight
|
ArrowRight
|
||||||
} from '@element-plus/icons-vue'
|
} from '@element-plus/icons-vue'
|
||||||
@@ -15,8 +15,18 @@ import {
|
|||||||
const systemInfo = ref(null)
|
const systemInfo = ref(null)
|
||||||
const networkInfo = ref(null)
|
const networkInfo = ref(null)
|
||||||
const isSidebarCollapsed = ref(false)
|
const isSidebarCollapsed = ref(false)
|
||||||
|
const isMobile = ref(false)
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
|
|
||||||
|
// 检测是否为移动设备
|
||||||
|
const checkMobile = () => {
|
||||||
|
isMobile.value = window.innerWidth <= 768
|
||||||
|
// 移动设备上默认折叠侧边栏
|
||||||
|
if (isMobile.value) {
|
||||||
|
isSidebarCollapsed.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const currentRoute = computed(() => route.path)
|
const currentRoute = computed(() => route.path)
|
||||||
const activeMenu = computed(() => route.path)
|
const activeMenu = computed(() => route.path)
|
||||||
|
|
||||||
@@ -50,6 +60,8 @@ const toggleSidebar = () => {
|
|||||||
|
|
||||||
// 页面加载时获取信息
|
// 页面加载时获取信息
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
|
checkMobile()
|
||||||
|
window.addEventListener('resize', checkMobile)
|
||||||
fetchSystemInfo()
|
fetchSystemInfo()
|
||||||
fetchNetworkInfo()
|
fetchNetworkInfo()
|
||||||
// 每30秒更新一次系统信息
|
// 每30秒更新一次系统信息
|
||||||
@@ -57,6 +69,10 @@ onMounted(() => {
|
|||||||
// 每60秒更新一次网络信息
|
// 每60秒更新一次网络信息
|
||||||
setInterval(fetchNetworkInfo, 60000)
|
setInterval(fetchNetworkInfo, 60000)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
window.removeEventListener('resize', checkMobile)
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -64,7 +80,7 @@ onMounted(() => {
|
|||||||
<el-container>
|
<el-container>
|
||||||
<el-aside :width="isSidebarCollapsed ? '64px' : '200px'">
|
<el-aside :width="isSidebarCollapsed ? '64px' : '200px'">
|
||||||
<div class="logo">
|
<div class="logo">
|
||||||
<span v-if="!isSidebarCollapsed">树莓派设备管理系统</span>
|
<span v-if="!isSidebarCollapsed">设备管理系统</span>
|
||||||
</div>
|
</div>
|
||||||
<el-menu
|
<el-menu
|
||||||
:default-active="activeMenu"
|
:default-active="activeMenu"
|
||||||
@@ -93,7 +109,7 @@ onMounted(() => {
|
|||||||
<template #title>服务管理</template>
|
<template #title>服务管理</template>
|
||||||
</el-menu-item>
|
</el-menu-item>
|
||||||
<el-menu-item index="/power-control">
|
<el-menu-item index="/power-control">
|
||||||
<el-icon><Zap /></el-icon>
|
<el-icon><SwitchButton /></el-icon>
|
||||||
<template #title>电源控制</template>
|
<template #title>电源控制</template>
|
||||||
</el-menu-item>
|
</el-menu-item>
|
||||||
</el-menu>
|
</el-menu>
|
||||||
@@ -101,9 +117,6 @@ onMounted(() => {
|
|||||||
|
|
||||||
<!-- 主内容区 -->
|
<!-- 主内容区 -->
|
||||||
<div class="main-container" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
|
<div class="main-container" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
|
||||||
<header class="header">
|
|
||||||
<h1>测偏仪管理后台</h1>
|
|
||||||
</header>
|
|
||||||
<main class="main-content">
|
<main class="main-content">
|
||||||
<div class="content-wrapper">
|
<div class="content-wrapper">
|
||||||
<router-view></router-view>
|
<router-view></router-view>
|
||||||
@@ -223,27 +236,33 @@ onMounted(() => {
|
|||||||
position: fixed;
|
position: fixed;
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
|
width: 64px !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main-container {
|
.main-container {
|
||||||
margin-left: 0;
|
margin-left: 64px !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main-container.sidebar-collapsed {
|
.main-container.sidebar-collapsed {
|
||||||
margin-left: 0;
|
margin-left: 64px !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.header {
|
.header {
|
||||||
left: 0;
|
left: 64px !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.sidebar-collapsed + .header {
|
.sidebar-collapsed + .header {
|
||||||
left: 0;
|
left: 64px !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.content-wrapper {
|
.content-wrapper {
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
padding: 0 1rem;
|
padding: 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
padding: 0;
|
||||||
|
justify-content: center;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import './assets/main.css'
|
||||||
|
|
||||||
|
import { createApp } from 'vue'
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router/index.ts'
|
||||||
|
import axios from 'axios'
|
||||||
|
|
||||||
|
// 配置 axios 默认值
|
||||||
|
// axios.defaults.baseURL = window.location.origin + ':8000/api'
|
||||||
|
// axios.defaults.baseURL = '/api'
|
||||||
|
axios.defaults.baseURL = `${window.location.protocol}//${window.location.hostname}/api`;
|
||||||
|
const app = createApp(App)
|
||||||
|
|
||||||
|
app.use(ElementPlus)
|
||||||
|
app.use(router)
|
||||||
|
|
||||||
|
app.mount('#app')
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import Home from '../views/Home.vue'
|
||||||
|
import DeviceManagement from '../views/DeviceManagement.vue'
|
||||||
|
import DeviceTypeManagement from '../views/DeviceTypeManagement.vue'
|
||||||
|
import ServiceManagement from '../views/ServiceManagement.vue'
|
||||||
|
import InterfaceManagement from '../views/InterfaceManagement.vue'
|
||||||
|
import PowerControl from '../views/PowerControl.vue'
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
|
routes: [
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
name: 'home',
|
||||||
|
component: Home
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/devices',
|
||||||
|
name: 'devices',
|
||||||
|
component: DeviceManagement
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/device-types',
|
||||||
|
name: 'device-types',
|
||||||
|
component: DeviceTypeManagement
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/services',
|
||||||
|
name: 'services',
|
||||||
|
component: ServiceManagement
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/interfaces',
|
||||||
|
name: 'interfaces',
|
||||||
|
component: InterfaceManagement
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/power-control',
|
||||||
|
name: 'power-control',
|
||||||
|
component: PowerControl
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
export interface DeviceTypeItem {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
code: string
|
||||||
|
address_range_start: number
|
||||||
|
address_range_end: number
|
||||||
|
chip_model: string
|
||||||
|
description?: string
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InterfaceItem {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
type: 'CAN' | 'Powerbus'
|
||||||
|
description?: string
|
||||||
|
port?: string
|
||||||
|
baud_rate?: number
|
||||||
|
can_channel?: number
|
||||||
|
can_baud_rate?: number
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeviceItem {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
device_address: number
|
||||||
|
device_type_id?: number
|
||||||
|
interface_id: number
|
||||||
|
status: string
|
||||||
|
created_at: string
|
||||||
|
device_type?: DeviceTypeItem
|
||||||
|
interface?: InterfaceItem
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
export interface DeviceStatus {
|
||||||
|
light?: boolean;
|
||||||
|
flow_rate?: number;
|
||||||
|
water_temp?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeviceItem {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
device_address: number;
|
||||||
|
device_type_id: number | null;
|
||||||
|
interface_id: number;
|
||||||
|
status?: DeviceStatus;
|
||||||
|
last_update?: string;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
device_type?: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
};
|
||||||
|
interface?: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeviceTypeItem {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
address_range_start: number;
|
||||||
|
address_range_end: number;
|
||||||
|
chip_model: string;
|
||||||
|
description?: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InterfaceItem {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
type: 'CAN' | 'Powerbus';
|
||||||
|
can_channel?: number;
|
||||||
|
can_baud_rate?: number;
|
||||||
|
port?: string;
|
||||||
|
baud_rate?: number;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
@@ -11,12 +11,18 @@
|
|||||||
<div v-for="device in devices" :key="device.id" class="device-card">
|
<div v-for="device in devices" :key="device.id" class="device-card">
|
||||||
<div class="device-header">
|
<div class="device-header">
|
||||||
<h3>{{ device.name }}</h3>
|
<h3>{{ device.name }}</h3>
|
||||||
<div class="device-status-container">
|
<div class="device-header-right">
|
||||||
<div class="device-enabled" :class="device.enabled ? 'enabled' : 'disabled'">
|
<div class="device-status-container">
|
||||||
{{ device.enabled ? '已启用' : '已禁用' }}
|
<span class="device-enabled" :class="device.enabled ? 'enabled' : 'disabled'">
|
||||||
|
{{ device.enabled ? '已启用' : '已禁用' }}
|
||||||
|
</span>
|
||||||
|
<span class="device-status" :class="typeof device.status === 'object' && device.status.online ? 'online' : 'offline'">
|
||||||
|
{{ typeof device.status === 'object' && device.status.online ? '在线' : '离线' }}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="device-status" :class="typeof device.status === 'object' && device.status.online ? 'online' : 'offline'">
|
<div class="device-header-actions">
|
||||||
{{ typeof device.status === 'object' && device.status.online ? '在线' : '离线' }}
|
<el-button type="text" @click="editDevice(device)">编辑</el-button>
|
||||||
|
<el-button type="text" @click="deleteDevice(device)">删除</el-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -104,8 +110,6 @@
|
|||||||
@click="controlDevice2(device, 'emergency_stop', 0)"
|
@click="controlDevice2(device, 'emergency_stop', 0)"
|
||||||
>急停</el-button>
|
>急停</el-button>
|
||||||
</template>
|
</template>
|
||||||
<el-button type="primary" @click="editDevice(device)">编辑</el-button>
|
|
||||||
<el-button type="danger" @click="deleteDevice(device)">删除</el-button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -749,41 +753,63 @@ onMounted(() => {
|
|||||||
margin-bottom: 15px;
|
margin-bottom: 15px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.device-header-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
.device-status-container {
|
.device-status-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-enabled {
|
.device-enabled {
|
||||||
padding: 4px 8px;
|
padding: 2px 6px;
|
||||||
border-radius: 4px;
|
border-radius: 2px;
|
||||||
font-size: 0.9rem;
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-enabled.enabled {
|
.device-enabled.enabled {
|
||||||
background-color: #67C23A;
|
background-color: #E8F5E9;
|
||||||
color: white;
|
color: #2E7D32;
|
||||||
|
border: 1px solid #C8E6C9;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-enabled.disabled {
|
.device-enabled.disabled {
|
||||||
background-color: #909399;
|
background-color: #F5F5F5;
|
||||||
color: white;
|
color: #757575;
|
||||||
|
border: 1px solid #E0E0E0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-status {
|
.device-status {
|
||||||
padding: 4px 8px;
|
padding: 2px 6px;
|
||||||
border-radius: 4px;
|
border-radius: 2px;
|
||||||
font-size: 0.9rem;
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-status.online {
|
.device-status.online {
|
||||||
background-color: #67C23A;
|
background-color: #E3F2FD;
|
||||||
color: white;
|
color: #1565C0;
|
||||||
|
border: 1px solid #BBDEFB;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-status.offline {
|
.device-status.offline {
|
||||||
background-color: #F56C6C;
|
background-color: #FFEBEE;
|
||||||
color: white;
|
color: #C62828;
|
||||||
|
border: 1px solid #FFCDD2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-header-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-header-actions .el-button--text {
|
||||||
|
padding: 4px 8px;
|
||||||
|
font-size: 0.85rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-info {
|
.device-info {
|
||||||
|
|||||||
@@ -0,0 +1,498 @@
|
|||||||
|
<template>
|
||||||
|
<div class="power-control-page">
|
||||||
|
<h2>电源与扫描控制</h2>
|
||||||
|
|
||||||
|
<!-- 电源状态概览 -->
|
||||||
|
<el-card class="status-card">
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>电源状态概览</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="status-grid">
|
||||||
|
<div class="status-item">
|
||||||
|
<div class="status-icon" :class="hvsPowerStatus">
|
||||||
|
<span class="icon-circle"></span>
|
||||||
|
</div>
|
||||||
|
<div class="status-info">
|
||||||
|
<h3>HVS 供电</h3>
|
||||||
|
<el-tag :type="hvsPowerStatus === 'on' ? 'success' : hvsPowerStatus === 'off' ? 'danger' : 'warning'">
|
||||||
|
{{ hvsPowerStatus === 'on' ? '已开启' : hvsPowerStatus === 'off' ? '已关闭' : '未知' }}
|
||||||
|
</el-tag>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="status-item">
|
||||||
|
<div class="status-icon" :class="scannerPowerStatus">
|
||||||
|
<span class="icon-circle"></span>
|
||||||
|
</div>
|
||||||
|
<div class="status-info">
|
||||||
|
<h3>Scanner 供电</h3>
|
||||||
|
<el-tag :type="scannerPowerStatus === 'on' ? 'success' : scannerPowerStatus === 'off' ? 'danger' : 'warning'">
|
||||||
|
{{ scannerPowerStatus === 'on' ? '已开启' : scannerPowerStatus === 'off' ? '已关闭' : '未知' }}
|
||||||
|
</el-tag>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- HVS电源控制 -->
|
||||||
|
<el-card class="control-card">
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>HVS 电源控制</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="control-content">
|
||||||
|
<div class="control-description">
|
||||||
|
<p>HVS(高压电源)用于为测偏仪的高压部件提供电力。</p>
|
||||||
|
<p>GPIO 引脚: <strong>GPIO26</strong></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="control-actions">
|
||||||
|
<el-button
|
||||||
|
type="primary"
|
||||||
|
:loading="hvsLoading"
|
||||||
|
@click="controlPower('hvs', 'on')"
|
||||||
|
>
|
||||||
|
<span class="btn-icon">▸</span> 打开供电
|
||||||
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
type="danger"
|
||||||
|
:loading="hvsLoading"
|
||||||
|
@click="controlPower('hvs', 'off')"
|
||||||
|
>
|
||||||
|
<span class="btn-icon">■</span> 关闭供电
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Scanner电源控制 -->
|
||||||
|
<el-card class="control-card">
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>Scanner 电源控制</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="control-content">
|
||||||
|
<div class="control-description">
|
||||||
|
<p>Scanner(扫描器)用于获取测量数据。</p>
|
||||||
|
<p>GPIO 引脚: <strong>GPIO17</strong></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="control-actions">
|
||||||
|
<el-button
|
||||||
|
type="primary"
|
||||||
|
:loading="scannerLoading"
|
||||||
|
@click="controlPower('scanner', 'on')"
|
||||||
|
>
|
||||||
|
<span class="btn-icon">▸</span> 打开供电
|
||||||
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
type="danger"
|
||||||
|
:loading="scannerLoading"
|
||||||
|
@click="controlPower('scanner', 'off')"
|
||||||
|
>
|
||||||
|
<span class="btn-icon">■</span> 关闭供电
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 扫描控制 -->
|
||||||
|
<el-card class="control-card scan-card">
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>扫描控制</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="control-content">
|
||||||
|
<div class="control-description">
|
||||||
|
<p>控制扫描过程的启动与停止。</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="control-actions">
|
||||||
|
<el-button
|
||||||
|
type="success"
|
||||||
|
:loading="scanLoading"
|
||||||
|
@click="controlScan('start')"
|
||||||
|
>
|
||||||
|
<span class="btn-icon">▶</span> 启动扫描
|
||||||
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
type="warning"
|
||||||
|
:loading="scanLoading"
|
||||||
|
@click="controlScan('stop')"
|
||||||
|
>
|
||||||
|
<span class="btn-icon">■</span> 停止扫描
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 操作日志 -->
|
||||||
|
<el-card class="log-card">
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>操作日志</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="log-container">
|
||||||
|
<div
|
||||||
|
v-for="(log, index) in operationLogs"
|
||||||
|
:key="index"
|
||||||
|
class="log-item"
|
||||||
|
:class="log.type"
|
||||||
|
>
|
||||||
|
<span class="log-time">{{ log.time }}</span>
|
||||||
|
<span class="log-content">{{ log.message }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="operationLogs.length === 0" class="empty-log">
|
||||||
|
暂无操作记录
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import axios from 'axios'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
// 电源状态
|
||||||
|
const hvsPowerStatus = ref('unknown')
|
||||||
|
const scannerPowerStatus = ref('unknown')
|
||||||
|
const hvsLoading = ref(false)
|
||||||
|
const scannerLoading = ref(false)
|
||||||
|
|
||||||
|
// 扫描状态
|
||||||
|
const scanLoading = ref(false)
|
||||||
|
|
||||||
|
// 操作日志
|
||||||
|
const operationLogs = ref<Array<{ time: string; message: string; type: string }>>([
|
||||||
|
{ time: new Date().toLocaleTimeString(), message: '系统已启动', type: 'info' }
|
||||||
|
])
|
||||||
|
|
||||||
|
// 获取电源状态
|
||||||
|
const fetchPowerStatus = async () => {
|
||||||
|
try {
|
||||||
|
// 获取HVS电源状态
|
||||||
|
const hvsResponse = await axios.post('/powerctrl', {
|
||||||
|
device: 'hvs',
|
||||||
|
action: 'status'
|
||||||
|
})
|
||||||
|
hvsPowerStatus.value = hvsResponse.data.status
|
||||||
|
|
||||||
|
// 获取Scanner电源状态
|
||||||
|
const scannerResponse = await axios.post('/powerctrl', {
|
||||||
|
device: 'scanner',
|
||||||
|
action: 'status'
|
||||||
|
})
|
||||||
|
scannerPowerStatus.value = scannerResponse.data.status
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取电源状态失败:', error)
|
||||||
|
hvsPowerStatus.value = 'unknown'
|
||||||
|
scannerPowerStatus.value = 'unknown'
|
||||||
|
addLog('error', '获取电源状态失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 控制电源
|
||||||
|
const controlPower = async (device: string, action: string) => {
|
||||||
|
const deviceName = device === 'hvs' ? 'HVS' : 'Scanner'
|
||||||
|
const actionText = action === 'on' ? '打开' : '关闭'
|
||||||
|
|
||||||
|
// 设置加载状态
|
||||||
|
if (device === 'hvs') {
|
||||||
|
hvsLoading.value = true
|
||||||
|
} else {
|
||||||
|
scannerLoading.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
addLog('info', `正在${actionText}${deviceName}电源...`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await axios.post('/powerctrl', {
|
||||||
|
device: device,
|
||||||
|
action: action
|
||||||
|
})
|
||||||
|
|
||||||
|
if (response.data.status === 'success') {
|
||||||
|
ElMessage.success(`${deviceName}电源${actionText}成功`)
|
||||||
|
addLog('success', `${deviceName}电源${actionText}成功`)
|
||||||
|
// 控制成功后立即刷新状态
|
||||||
|
setTimeout(fetchPowerStatus, 500)
|
||||||
|
} else {
|
||||||
|
ElMessage.error('操作失败')
|
||||||
|
addLog('error', `${deviceName}电源${actionText}失败`)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('控制电源失败:', error)
|
||||||
|
ElMessage.error('控制电源失败')
|
||||||
|
addLog('error', `${deviceName}电源${actionText}失败: ${error}`)
|
||||||
|
} finally {
|
||||||
|
// 清除加载状态
|
||||||
|
if (device === 'hvs') {
|
||||||
|
hvsLoading.value = false
|
||||||
|
} else {
|
||||||
|
scannerLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 控制扫描
|
||||||
|
const controlScan = async (action: 'start' | 'stop') => {
|
||||||
|
const actionText = action === 'start' ? '启动' : '停止'
|
||||||
|
|
||||||
|
scanLoading.value = true
|
||||||
|
addLog('info', `正在${actionText}扫描...`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await axios.post('/scanctrl', {
|
||||||
|
action: action
|
||||||
|
})
|
||||||
|
|
||||||
|
if (response.data.status === 'success') {
|
||||||
|
ElMessage.success(`扫描${actionText}成功`)
|
||||||
|
addLog('success', `扫描${actionText}成功`)
|
||||||
|
} else {
|
||||||
|
ElMessage.error('操作失败')
|
||||||
|
addLog('error', `扫描${actionText}失败`)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('扫描控制失败:', error)
|
||||||
|
ElMessage.error(`扫描${actionText}失败`)
|
||||||
|
addLog('error', `扫描${actionText}失败: ${error}`)
|
||||||
|
} finally {
|
||||||
|
scanLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加日志
|
||||||
|
const addLog = (type: string, message: string) => {
|
||||||
|
operationLogs.value.unshift({
|
||||||
|
time: new Date().toLocaleTimeString(),
|
||||||
|
message: message,
|
||||||
|
type: type
|
||||||
|
})
|
||||||
|
|
||||||
|
// 保留最近50条日志
|
||||||
|
if (operationLogs.value.length > 50) {
|
||||||
|
operationLogs.value.pop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面加载时获取状态
|
||||||
|
onMounted(() => {
|
||||||
|
fetchPowerStatus()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.power-control-page {
|
||||||
|
padding: 20px;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
min-height: calc(100vh - 84px);
|
||||||
|
background-color: #f5f7fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
color: #1f2f3d;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 16px 20px;
|
||||||
|
border-bottom: 1px solid #ebeef5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-card {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
background: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-grid {
|
||||||
|
display: flex;
|
||||||
|
gap: 20px;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-item {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 20px;
|
||||||
|
background: #f8f9fa;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-icon {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-icon.on {
|
||||||
|
background: #f0f9eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-icon.off {
|
||||||
|
background: #fff2f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-icon.unknown {
|
||||||
|
background: #fffbe6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-circle {
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-icon.on .icon-circle {
|
||||||
|
background: #67c23a;
|
||||||
|
box-shadow: 0 0 12px rgba(103, 194, 58, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-icon.off .icon-circle {
|
||||||
|
background: #f56c6c;
|
||||||
|
box-shadow: 0 0 12px rgba(245, 108, 108, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-icon.unknown .icon-circle {
|
||||||
|
background: #e6a23c;
|
||||||
|
box-shadow: 0 0 12px rgba(230, 162, 60, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-info h3 {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #303133;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-card {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
background: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scan-card {
|
||||||
|
border-left: 4px solid #409eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-content {
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-description {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-description p {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #606266;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-description strong {
|
||||||
|
color: #409eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-icon {
|
||||||
|
margin-right: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card {
|
||||||
|
background: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-container {
|
||||||
|
padding: 20px;
|
||||||
|
max-height: 300px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item {
|
||||||
|
padding: 10px 12px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item.info {
|
||||||
|
background: #f0f5ff;
|
||||||
|
color: #409eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item.success {
|
||||||
|
background: #f0f9eb;
|
||||||
|
color: #67c23a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item.error {
|
||||||
|
background: #fff2f0;
|
||||||
|
color: #f56c6c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-time {
|
||||||
|
margin-right: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-log {
|
||||||
|
text-align: center;
|
||||||
|
color: #909399;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-card__header) {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-card__body) {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-tag) {
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.status-grid {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { fileURLToPath, URL } from 'node:url'
|
||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
|
||||||
|
// https://vitejs.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
build:{
|
||||||
|
chunkSizeWarningLimit: 1500,
|
||||||
|
rollupOptions: {
|
||||||
|
output: {
|
||||||
|
manualChunks(id) {
|
||||||
|
if (id.includes('node_modules')) {
|
||||||
|
return 'vendor';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
plugins: [vue()
|
||||||
|
],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': fileURLToPath(new URL('./src', import.meta.url))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
host : '192.168.8.118',
|
||||||
|
port: 8001,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://192.168.8.118:8000',
|
||||||
|
changeOrigin: true,
|
||||||
|
rewrite: (path) => path.replace(/^\/api/, '')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// cors: true
|
||||||
|
},
|
||||||
|
base: '/'
|
||||||
|
})
|
||||||
@@ -39,4 +39,4 @@ try:
|
|||||||
with open(CONFIG_FILE, "r") as f:
|
with open(CONFIG_FILE, "r") as f:
|
||||||
config = json.load(f)
|
config = json.load(f)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
config = {}
|
config = {}
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import time
|
import time
|
||||||
|
import os
|
||||||
|
|
||||||
from config import *
|
from config import *
|
||||||
from tcp_io_module import TcpIoModule
|
from tcp_io_module import TcpIoModule
|
||||||
from hvs import HvService
|
from hvs import HvService
|
||||||
from mqtt_client import mqtt_client
|
from mqtt_client import mqtt_client
|
||||||
|
|
||||||
|
# pinctrl set 26 op pn dl
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
#通过pinctrl打开电源
|
||||||
|
os.system("pinctrl set 26 op pn dl")
|
||||||
|
|
||||||
io_module = TcpIoModule(host='192.168.8.211', port=502)
|
io_module = TcpIoModule(host='192.168.8.211', port=502)
|
||||||
io_module.start()
|
io_module.start()
|
||||||
|
|
||||||
|
|||||||
@@ -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 = 0.5
|
||||||
|
|
||||||
|
# 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": 2
|
||||||
|
}
|
||||||
|
|
||||||
|
COIL_REGISTERS = {
|
||||||
|
"start_address": 0,
|
||||||
|
"count": 4
|
||||||
|
}
|
||||||
|
|
||||||
|
CONFIG_FILE = "/home/admin/.config/cpy/hvs.json"
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(CONFIG_FILE, "r") as f:
|
||||||
|
config = json.load(f)
|
||||||
|
except FileNotFoundError:
|
||||||
|
config = {}
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
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
|
||||||
|
import socket
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
UDP_PORT = 62000
|
||||||
|
|
||||||
|
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.filament_info = [None, None]
|
||||||
|
self.xray_on = [False, False]
|
||||||
|
self.last_hvs_update_time = 0
|
||||||
|
|
||||||
|
self.exit_flag = False
|
||||||
|
self.loop_thread = None
|
||||||
|
|
||||||
|
# UDP socket,监听62000端口
|
||||||
|
self.udp_socket = None
|
||||||
|
self.udp_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 = 1 # 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)
|
||||||
|
self.modbus_client.write_coil(slave_id, 0x01, True)
|
||||||
|
self.modbus_client.write_holding_register(slave_id, 0x00, 6000)
|
||||||
|
else:
|
||||||
|
self.modbus_client.write_coil(slave_id, 0x01, 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()
|
||||||
|
|
||||||
|
# 启动UDP监听线程
|
||||||
|
self.udp_thread = threading.Thread(target=self._udp_listen)
|
||||||
|
self.udp_thread.daemon = True
|
||||||
|
self.udp_thread.start()
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
if not self.loop_thread:
|
||||||
|
return
|
||||||
|
"""停止服务"""
|
||||||
|
self.exit_flag = True
|
||||||
|
self.loop_thread.join()
|
||||||
|
if self.udp_thread:
|
||||||
|
self.udp_thread.join()
|
||||||
|
self.executor.shutdown(wait=True)
|
||||||
|
|
||||||
|
def _udp_listen(self):
|
||||||
|
"""UDP监听线程,监听62000端口"""
|
||||||
|
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
self.udp_socket.bind(("0.0.0.0", UDP_PORT))
|
||||||
|
self.udp_socket.settimeout(1.0)
|
||||||
|
logger.info(f"UDP监听已启动,端口: {UDP_PORT}")
|
||||||
|
while not self.exit_flag:
|
||||||
|
try:
|
||||||
|
data, addr = self.udp_socket.recvfrom(4096)
|
||||||
|
self.handle_udp_message(data, addr)
|
||||||
|
except socket.timeout:
|
||||||
|
continue
|
||||||
|
except OSError as e:
|
||||||
|
if not self.exit_flag:
|
||||||
|
logger.error(f"UDP接收数据失败: {e}")
|
||||||
|
self.udp_socket.close()
|
||||||
|
|
||||||
|
def handle_udp_message(self, data, addr):
|
||||||
|
"""处理UDP消息(留空,由外部实现)"""
|
||||||
|
try:
|
||||||
|
info = json.loads(data.decode())
|
||||||
|
#logger.info(f"收到UDP消息: {info}")
|
||||||
|
if 'id' in info:
|
||||||
|
id = int(info['id'][0])
|
||||||
|
self.filament_info[id - 1] = info
|
||||||
|
if 'work_state' in info:
|
||||||
|
self.xray_on[id - 1] = info['work_state'] == 2
|
||||||
|
self.last_hvs_update_time = time.time()
|
||||||
|
if "osu" in info:
|
||||||
|
osu = info['osu']
|
||||||
|
self.publish_osu_info(f"{id}#OSU", osu['temp'], osu['level'])
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.error("UDP消息不是JSON格式")
|
||||||
|
|
||||||
|
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_osu_info(self, dev_code, temp, level):
|
||||||
|
"""发布OSU信息"""
|
||||||
|
data = {
|
||||||
|
"device_id": None,
|
||||||
|
"device_code": dev_code,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"status": {
|
||||||
|
"online": True,
|
||||||
|
"oil_temp": temp / 10.0,
|
||||||
|
"oil_level": level,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.mqtt_client.publish(DEVICE_STATUS_TOPIC, data)
|
||||||
|
|
||||||
|
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=1,
|
||||||
|
address=INPUT_REGISTERS["start_address"],
|
||||||
|
count=INPUT_REGISTERS["count"]
|
||||||
|
)
|
||||||
|
print("------------------input_regs:", input_regs)
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 读取线圈
|
||||||
|
discrete = self.modbus_client.read_discrete(
|
||||||
|
slave_id=1,
|
||||||
|
address=COIL_REGISTERS["start_address"],
|
||||||
|
count=COIL_REGISTERS["count"]
|
||||||
|
)
|
||||||
|
print("discrete:", discrete)
|
||||||
|
if discrete is None:
|
||||||
|
hvs_device["error_count"] = hvs_device.get("error_count", 10) + 1
|
||||||
|
else:
|
||||||
|
hvs_device["error_count"] = 0
|
||||||
|
|
||||||
|
# 设备间添加延迟,避免总线冲突
|
||||||
|
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": self.filament_info[slave_id-1]['xray_current'] / 1000.0 if self.filament_info[slave_id-1] is not None else None,
|
||||||
|
"current_filament": self.filament_info[slave_id-1]['filament_current'] / 1000.0 if self.filament_info[slave_id-1] is not None else None,
|
||||||
|
"internal_temperature": self.filament_info[slave_id-1]['temp'] / 10.0 if self.filament_info[slave_id-1] is not None else None,
|
||||||
|
"fault_status": discrete[3] if discrete and len(discrete) > 3 else None,
|
||||||
|
"switch_status": discrete[1] if discrete and len(discrete) > 3 else None,
|
||||||
|
"xray_status": self.xray_on[slave_id-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# 发布数据
|
||||||
|
self.mqtt_client.publish(DEVICE_STATUS_TOPIC, data)
|
||||||
|
if hvs_device.get("error_count", 10) > 5:
|
||||||
|
logger.error(f"设备 {hvs_device.get('code')} 数据发布失败,错误次数超过5次")
|
||||||
|
else:
|
||||||
|
logger.info(f"成功发布设备数据: {data}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"处理设备 {hvs_device.get('code')} 数据失败: {e}")
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Hvs Service
|
||||||
|
After=emqx.service
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=root
|
||||||
|
Group=root
|
||||||
|
WorkingDirectory=/home/admin/CPY/CPY_AdminPlatform_V3.5/hvs_service
|
||||||
|
ExecStart=/home/admin/CPY/venv/bin/python /home/admin/CPY/CPY_AdminPlatform_V3.5/hvs_service/main.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10s
|
||||||
|
StartLimitBurst=5
|
||||||
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import time
|
||||||
|
import os
|
||||||
|
|
||||||
|
from config import *
|
||||||
|
from tcp_io_module import TcpIoModule
|
||||||
|
from hvs import HvService
|
||||||
|
from mqtt_client import mqtt_client
|
||||||
|
|
||||||
|
# pinctrl set 26 op pn dl
|
||||||
|
|
||||||
|
def main():
|
||||||
|
#通过pinctrl打开电源
|
||||||
|
os.system("pinctrl set 26 op pn dl")
|
||||||
|
|
||||||
|
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
|
||||||
|
last_valve_time = time.time()
|
||||||
|
|
||||||
|
if 'valve' in config:
|
||||||
|
valve_off_time = config['valve'][0]
|
||||||
|
valve_on_time = config['valve'][1]
|
||||||
|
else:
|
||||||
|
valve_off_time = 60.0
|
||||||
|
valve_on_time = 1.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)
|
||||||
|
|
||||||
|
if time.time() - last_valve_time > valve_off_time:
|
||||||
|
io_module.control_valve(11, True)
|
||||||
|
time.sleep(valve_on_time)
|
||||||
|
io_module.control_valve(11, False)
|
||||||
|
last_valve_time = time.time()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("程序收到中断信号,正在退出...")
|
||||||
|
io_module.control_valve(11, False)
|
||||||
|
io_module.stop()
|
||||||
|
hv_service.stop()
|
||||||
|
mqtt_client.stop()
|
||||||
|
break
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
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 read_discrete(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_discrete_inputs(
|
||||||
|
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
|
||||||
|
|
||||||
|
def write_holding_register(self, slave_id: int, address: int, value: int) -> bool:
|
||||||
|
"""写入保持寄存器,带重试机制和线程锁保护
|
||||||
|
|
||||||
|
Args:
|
||||||
|
slave_id: 从站地址
|
||||||
|
address: �保持寄存器地址
|
||||||
|
value: 保持寄存器值
|
||||||
|
|
||||||
|
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_register(address, value, device_id=slave_id)
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
|
||||||
|
if response:
|
||||||
|
# 检查响应
|
||||||
|
if response.isError():
|
||||||
|
logger.error(f"写入保持寄存器错误响应: 从站{slave_id}, 地址{address} (尝试{attempt+1}/{RETRIES})")
|
||||||
|
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05) # 使用更短的延迟
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
logger.debug(f"接收到写入保持寄存器响应: 长度{len(response.encode())}字节, 内容{response.encode().hex()}")
|
||||||
|
|
||||||
|
# 快速释放锁,减少其他操作等待时间
|
||||||
|
|
||||||
|
logger.info(f"成功写入保持寄存器 {address}: {value} (尝试{attempt+1}/{RETRIES})")
|
||||||
|
return True
|
||||||
|
except ConnectionException as e:
|
||||||
|
logger.error(f"连接中断错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
self.connected = False # 修正变量名
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
except ModbusException as e:
|
||||||
|
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"写入保持寄存器未知错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
logger.error(f"所有{RETRIES}次写入保持寄存器尝试均失败: 从站{slave_id}, 地址{address}")
|
||||||
|
return False
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import paho.mqtt.client as mqtt
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
import time
|
||||||
|
import socket
|
||||||
|
from threading import Timer
|
||||||
|
from config import *
|
||||||
|
from typing import Dict, Any, List, Optional, Callable
|
||||||
|
import requests
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class MQTTClient():
|
||||||
|
def __init__(self, broker: str, port: int = 1883, client_id: str = None):
|
||||||
|
self.client = mqtt.Client(client_id = 'hv_service_' + self.random_string(6)) # 创建本地客户端
|
||||||
|
self.client.username_pw_set(USER,PWD)
|
||||||
|
self.broker = broker
|
||||||
|
self.port = port
|
||||||
|
self.callbacks: Dict[str, Callable] = {}
|
||||||
|
self.received_messages = {}
|
||||||
|
self.message_events = {}
|
||||||
|
|
||||||
|
self.is_connected = False
|
||||||
|
|
||||||
|
# 设置回调函数
|
||||||
|
self.client.on_connect = self._on_connect
|
||||||
|
self.client.on_message = self._on_message
|
||||||
|
self.client.on_disconnect = self._on_disconnect
|
||||||
|
|
||||||
|
Timer(1, self.connTimerHandler).start()
|
||||||
|
|
||||||
|
def random_string(self, length=6):
|
||||||
|
"""生成随机字符串"""
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
"""停止服务"""
|
||||||
|
self.client.loop_stop()
|
||||||
|
self.client.disconnect()
|
||||||
|
|
||||||
|
def checkLocalServer(self):
|
||||||
|
host = '127.0.0.1'
|
||||||
|
port = 1883
|
||||||
|
timeout = 1
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
sock.settimeout(timeout)
|
||||||
|
try:
|
||||||
|
result = sock.connect_ex((host, port))
|
||||||
|
if result == 0:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
sock.close()
|
||||||
|
|
||||||
|
def connTimerHandler(self):
|
||||||
|
print("mqtt conn timer handler")
|
||||||
|
if self.checkLocalServer():
|
||||||
|
self.client.connect(BROKER, MQTT_PORT) # 连接本地 MQTT 服务器
|
||||||
|
self.client.loop_start() # 开始循环以处理网络流量
|
||||||
|
else:
|
||||||
|
print("local mqtt brokeris not ready")
|
||||||
|
|
||||||
|
Timer(1, self.connTimerHandler).start()
|
||||||
|
|
||||||
|
def connect(self):
|
||||||
|
"""连接到MQTT代理并处理连接错误"""
|
||||||
|
try:
|
||||||
|
self.client.connect(self.broker, self.port)
|
||||||
|
self.client.loop_start()
|
||||||
|
logger.info(f"成功连接到MQTT代理: {self.broker}:{self.port}")
|
||||||
|
return True
|
||||||
|
except socket.gaierror:
|
||||||
|
logger.error(f"MQTT代理地址解析失败: {self.broker}")
|
||||||
|
except ConnectionRefusedError:
|
||||||
|
logger.error(f"MQTT代理拒绝连接: {self.broker}:{self.port}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"MQTT连接失败: {str(e)}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def disconnect(self):
|
||||||
|
"""断开MQTT连接"""
|
||||||
|
self.client.loop_stop()
|
||||||
|
self.client.disconnect()
|
||||||
|
|
||||||
|
def subscribe(self, topic: str, callback: Callable):
|
||||||
|
"""订阅主题并设置回调函数"""
|
||||||
|
self.callbacks[topic] = callback
|
||||||
|
|
||||||
|
def publish(self, topic: str, message: Dict[str, Any]):
|
||||||
|
"""发布消息到指定主题"""
|
||||||
|
payload = json.dumps(message)
|
||||||
|
self.client.publish(topic, payload)
|
||||||
|
|
||||||
|
|
||||||
|
def control_xray_light(self, value):
|
||||||
|
msg = {
|
||||||
|
"device_code" : "1#ALU",
|
||||||
|
"command" : "set_status",
|
||||||
|
"status" : value
|
||||||
|
}
|
||||||
|
# print("publish", DEVICE_CONTROL_TOPIC, msg)
|
||||||
|
self.publish(DEVICE_CONTROL_TOPIC, msg) # 发布数据到本地
|
||||||
|
|
||||||
|
def _on_connect(self, client, userdata, flags, rc):
|
||||||
|
"""连接回调"""
|
||||||
|
print(f"已连接到MQTT代理: {self.broker}")
|
||||||
|
for topic in self.callbacks:
|
||||||
|
self.client.subscribe(topic)
|
||||||
|
self.is_connected = True
|
||||||
|
|
||||||
|
def _on_message(self, client, userdata, msg):
|
||||||
|
"""消息接收回调"""
|
||||||
|
print("mqtt msg:", msg.topic, msg.payload)
|
||||||
|
topic = msg.topic
|
||||||
|
try:
|
||||||
|
payload = json.loads(msg.payload.decode())
|
||||||
|
if topic in self.callbacks:
|
||||||
|
self.callbacks[topic](topic, payload)
|
||||||
|
|
||||||
|
# 存储接收到的消息
|
||||||
|
self.received_messages[topic] = msg
|
||||||
|
|
||||||
|
# 触发等待事件
|
||||||
|
if topic in self.message_events:
|
||||||
|
event = self.message_events.pop(topic)
|
||||||
|
event.set()
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
print(f"无法解析消息: {msg.payload}")
|
||||||
|
|
||||||
|
def _on_disconnect(self, client, userdata, rc):
|
||||||
|
"""断开连接回调"""
|
||||||
|
print(f"已断开与MQTT代理的连接: {self.broker}")
|
||||||
|
self.is_connected= False
|
||||||
|
|
||||||
|
def wait_for_message(self, topic: str, timeout: float = 5.0) -> Optional[mqtt.MQTTMessage]:
|
||||||
|
"""等待接收指定主题的消息
|
||||||
|
|
||||||
|
Args:
|
||||||
|
topic: 要等待的主题
|
||||||
|
timeout: 超时时间(秒)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
接收到的消息对象,如果超时则返回None
|
||||||
|
"""
|
||||||
|
import threading
|
||||||
|
|
||||||
|
# 检查是否已经有缓存的消息
|
||||||
|
if topic in self.received_messages:
|
||||||
|
return self.received_messages.pop(topic)
|
||||||
|
|
||||||
|
# 创建事件对象
|
||||||
|
event = threading.Event()
|
||||||
|
self.message_events[topic] = event
|
||||||
|
|
||||||
|
# 等待事件触发或超时
|
||||||
|
event.wait(timeout)
|
||||||
|
|
||||||
|
# 移除事件对象
|
||||||
|
if topic in self.message_events:
|
||||||
|
self.message_events.pop(topic)
|
||||||
|
|
||||||
|
# 返回接收到的消息
|
||||||
|
return self.received_messages.pop(topic, None)
|
||||||
|
|
||||||
|
|
||||||
|
mqtt_client = MQTTClient(broker=BROKER, port=MQTT_PORT)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
pymodbus>=3.5.0
|
||||||
|
paho-mqtt>=2.1.0
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
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 control_valve(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客户端启动失败")
|
||||||
|
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import math
|
||||||
import time
|
import time
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -166,6 +167,75 @@ class SensorService:
|
|||||||
logger.info(f"成功发布服务状态到 {SERVICE_STATUS_TOPIC}: {service_message}")
|
logger.info(f"成功发布服务状态到 {SERVICE_STATUS_TOPIC}: {service_message}")
|
||||||
self.last_service_status_time = current_time
|
self.last_service_status_time = current_time
|
||||||
|
|
||||||
|
# float get_temperature(float Rt)
|
||||||
|
# {
|
||||||
|
# const float Rp = 50000.0; ///< 10K NTC
|
||||||
|
# const float T2 = (273.15+25.0); ///< 10K NTC
|
||||||
|
# const float Bx = 3950.0; ///< 10K NTC
|
||||||
|
# const float Ka = 273.15; ///< 10K NTC
|
||||||
|
|
||||||
|
# float Temp = 0.0f;
|
||||||
|
# Temp = Rt / Rp;
|
||||||
|
# Temp = log(Temp);
|
||||||
|
# Temp /=Bx;
|
||||||
|
# Temp += (1 / T2);
|
||||||
|
# Temp = 1 / Temp;
|
||||||
|
# Temp -= Ka;
|
||||||
|
# return Temp;
|
||||||
|
# }
|
||||||
|
|
||||||
|
def wsu_get_temperature(self, Rt):
|
||||||
|
"""计算WSU温度"""
|
||||||
|
Rp = 50000.0
|
||||||
|
T2 = (273.15+25.0)
|
||||||
|
Bx = 3950.0
|
||||||
|
Ka = 273.15
|
||||||
|
|
||||||
|
Temp = 0.0
|
||||||
|
Temp = Rt / Rp
|
||||||
|
Temp = math.log10(Temp)
|
||||||
|
Temp /=Bx
|
||||||
|
Temp += (1 / T2)
|
||||||
|
Temp = 1 / Temp
|
||||||
|
Temp -= Ka
|
||||||
|
return Temp
|
||||||
|
|
||||||
|
def wsu_get_flow_rate_g1(self, freq):
|
||||||
|
"""计算WSU流量"""
|
||||||
|
if freq == 0:
|
||||||
|
return 0.0
|
||||||
|
return 50 * 1000.0 * 60 * 10 / 660 / freq
|
||||||
|
|
||||||
|
def wsu_get_flow_rate_g2(self, freq, factor):
|
||||||
|
"""计算WSU流量"""
|
||||||
|
if freq == 0:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
return freq * 60 / factor
|
||||||
|
|
||||||
|
def handle_wsu_data(self, device, regs):
|
||||||
|
"""处理WSU数据"""
|
||||||
|
|
||||||
|
if not regs or len(regs) < 2:
|
||||||
|
return 0, 0
|
||||||
|
|
||||||
|
generation = device.get("generation", "0")
|
||||||
|
flow_rate = regs[0]
|
||||||
|
water_temp = regs[1]
|
||||||
|
|
||||||
|
if generation == "0" and regs[1] < 500:
|
||||||
|
flow_rate = flow_rate / 1000.0
|
||||||
|
water_temp = water_temp / 10.0
|
||||||
|
elif generation == "1" and regs[1] >= 500:
|
||||||
|
flow_rate = self.wsu_get_flow_rate_g1(flow_rate)
|
||||||
|
water_temp = self.wsu_get_temperature(water_temp * 2)
|
||||||
|
elif generation == "2":
|
||||||
|
factor = device.get("factor", 6000)
|
||||||
|
flow_rate = self.wsu_get_flow_rate_g2(flow_rate, factor)
|
||||||
|
water_temp = self.wsu_get_temperature(water_temp * 2)
|
||||||
|
|
||||||
|
return flow_rate, water_temp
|
||||||
|
|
||||||
def read_and_publish_devices_data(self):
|
def read_and_publish_devices_data(self):
|
||||||
"""读取并发布所有设备数据"""
|
"""读取并发布所有设备数据"""
|
||||||
# 确保Modbus连接正常
|
# 确保Modbus连接正常
|
||||||
@@ -175,6 +245,9 @@ class SensorService:
|
|||||||
|
|
||||||
for device in self.devices:
|
for device in self.devices:
|
||||||
try:
|
try:
|
||||||
|
enabled = device.get("enabled", False)
|
||||||
|
if not enabled:
|
||||||
|
continue
|
||||||
slave_id = int(device.get('address'))
|
slave_id = int(device.get('address'))
|
||||||
logger.info(f"开始读取设备 {device.get('code')} (从站ID: {slave_id}) 数据")
|
logger.info(f"开始读取设备 {device.get('code')} (从站ID: {slave_id}) 数据")
|
||||||
|
|
||||||
@@ -190,12 +263,15 @@ class SensorService:
|
|||||||
device["error_count"] = device.get("error_count", 10) + 1
|
device["error_count"] = device.get("error_count", 10) + 1
|
||||||
else:
|
else:
|
||||||
device["error_count"] = 0
|
device["error_count"] = 0
|
||||||
|
|
||||||
|
flow_rate, water_temp = self.handle_wsu_data(device, regs)
|
||||||
|
|
||||||
device.update({
|
device.update({
|
||||||
"status" : {
|
"status" : {
|
||||||
"online": device.get("error_count", 10) < 3,
|
"online": device.get("error_count", 10) < 3,
|
||||||
"flow_rate": regs[0] / 1000.0 if regs and len(regs) > 0 else None,
|
"flow_rate": flow_rate,
|
||||||
"water_temp": regs[1] / 10.0 if regs and len(regs) > 1 else None,
|
"water_temp": water_temp
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
elif device.get('type', '') == 'OSU':
|
elif device.get('type', '') == 'OSU':
|
||||||
# 读取输入寄存器
|
# 读取输入寄存器
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import threading
|
|||||||
import subprocess
|
import subprocess
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
|
from copy import deepcopy
|
||||||
from config import *
|
from config import *
|
||||||
from PySide6.QtCore import *
|
from PySide6.QtCore import *
|
||||||
from PySide6.QtNetwork import QUdpSocket, QHostAddress
|
from PySide6.QtNetwork import QUdpSocket, QHostAddress
|
||||||
@@ -34,6 +35,7 @@ class Scanner:
|
|||||||
self.last_update_time = 0
|
self.last_update_time = 0
|
||||||
self.location = 0
|
self.location = 0
|
||||||
self.velocity = 0
|
self.velocity = 0
|
||||||
|
self.motor_power = 'on'
|
||||||
|
|
||||||
self.daq_info = {}
|
self.daq_info = {}
|
||||||
|
|
||||||
@@ -207,6 +209,16 @@ class MotorManager(QObject):
|
|||||||
self.scanner(index).daq_info['temp'] = data['daq_temp']
|
self.scanner(index).daq_info['temp'] = data['daq_temp']
|
||||||
if 'daq_online' in data:
|
if 'daq_online' in data:
|
||||||
self.scanner(index).daq_info['online'] = data['daq_online']
|
self.scanner(index).daq_info['online'] = data['daq_online']
|
||||||
|
if 'daq_power' in data:
|
||||||
|
self.scanner(index).daq_info['power'] = data['daq_power']
|
||||||
|
if 'filament_info' in data:
|
||||||
|
filament_info = deepcopy(data['filament_info'])
|
||||||
|
filament_info['id'] = data['id']
|
||||||
|
self.udp_socket.writeDatagram(QByteArray(json.dumps(filament_info).encode()) ,
|
||||||
|
QHostAddress("127.0.0.1"), 62000)
|
||||||
|
|
||||||
|
if 'motor_power' in data:
|
||||||
|
self.scanner(index).motor_power = data['motor_power']
|
||||||
|
|
||||||
if self.scanner(index).state in [ScannerState.MOVING_UP, ScannerState.MOVING_DOWN]:
|
if self.scanner(index).state in [ScannerState.MOVING_UP, ScannerState.MOVING_DOWN]:
|
||||||
self.scanner(index).last_moving_time = time.time()
|
self.scanner(index).last_moving_time = time.time()
|
||||||
|
|||||||
Reference in New Issue
Block a user