fix:修复设备ws订阅逻辑,切花设备后订阅逻辑完善
This commit is contained in:
@@ -172,6 +172,9 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
const [wsConnected, setWsConnected] = useState(false);
|
const [wsConnected, setWsConnected] = useState(false);
|
||||||
const reconnectTimerRef = useRef<NodeJS.Timeout>();
|
const reconnectTimerRef = useRef<NodeJS.Timeout>();
|
||||||
const heartbeatTimerRef = useRef<NodeJS.Timeout>();
|
const heartbeatTimerRef = useRef<NodeJS.Timeout>();
|
||||||
|
const [currentSubscribedDevice, setCurrentSubscribedDevice] = useState<string>('all');
|
||||||
|
// 添加订阅ID跟踪
|
||||||
|
const [currentSubscriptions, setCurrentSubscriptions] = useState<string[]>([]);
|
||||||
|
|
||||||
// token自动续期相关
|
// token自动续期相关
|
||||||
const tokenCache = {
|
const tokenCache = {
|
||||||
@@ -301,6 +304,20 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
if (heartbeatTimerRef.current) {
|
if (heartbeatTimerRef.current) {
|
||||||
clearInterval(heartbeatTimerRef.current);
|
clearInterval(heartbeatTimerRef.current);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 取消所有订阅
|
||||||
|
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN && currentSubscriptions.length > 0) {
|
||||||
|
console.log('页面卸载,取消所有订阅:', currentSubscriptions);
|
||||||
|
currentSubscriptions.forEach(subId => {
|
||||||
|
const unsubMessage = {
|
||||||
|
type: 'unsub',
|
||||||
|
id: subId,
|
||||||
|
};
|
||||||
|
console.log('发送取消订阅请求:', JSON.stringify(unsubMessage, null, 2));
|
||||||
|
wsRef.current?.send(JSON.stringify(unsubMessage));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (wsRef.current) {
|
if (wsRef.current) {
|
||||||
wsRef.current.close();
|
wsRef.current.close();
|
||||||
}
|
}
|
||||||
@@ -372,109 +389,165 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
// 处理属性上报
|
// 处理属性上报
|
||||||
const handlePropertyReport = (deviceSn: string, payload: any) => {
|
const handlePropertyReport = (deviceSn: string, payload: any) => {
|
||||||
console.log('处理属性上报:', deviceSn, payload);
|
console.log('处理属性上报:', deviceSn, payload);
|
||||||
|
|
||||||
|
// 提取设备数据,可能在不同的位置
|
||||||
|
let deviceData = null;
|
||||||
|
if (payload.data && payload.data.data) {
|
||||||
|
deviceData = payload.data.data;
|
||||||
|
console.log('从payload.data.data中提取设备数据:', JSON.stringify(deviceData, null, 2));
|
||||||
|
} else if (payload.properties) {
|
||||||
|
deviceData = payload.properties;
|
||||||
|
console.log('从payload.properties中提取设备数据:', JSON.stringify(deviceData, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!deviceData) {
|
||||||
|
console.log('未找到设备数据');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 更新性能指标数据
|
// 更新性能指标数据
|
||||||
if (payload.properties) {
|
const newMetrics: DeviceMetrics[] = [];
|
||||||
const newMetrics: DeviceMetrics[] = [];
|
const time = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||||
const time = moment().format('YYYY-MM-DD HH:mm:ss');
|
|
||||||
|
|
||||||
if (payload.properties.cpu_usage !== undefined) {
|
// 处理环境数据
|
||||||
newMetrics.push({
|
if (deviceData.temperature !== undefined) {
|
||||||
time,
|
newMetrics.push({
|
||||||
value: payload.properties.cpu_usage,
|
time,
|
||||||
type: 'CPU使用率',
|
value: deviceData.temperature,
|
||||||
});
|
type: '温度',
|
||||||
}
|
|
||||||
|
|
||||||
if (payload.properties.memory_usage !== undefined) {
|
|
||||||
newMetrics.push({
|
|
||||||
time,
|
|
||||||
value: payload.properties.memory_usage,
|
|
||||||
type: '内存使用率',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (payload.properties.temperature !== undefined) {
|
|
||||||
newMetrics.push({
|
|
||||||
time,
|
|
||||||
value: payload.properties.temperature,
|
|
||||||
type: '温度',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 新增:同步更新 deviceList 里对应设备的 metrics 字段
|
|
||||||
setDeviceList(prev => {
|
|
||||||
// 检查设备是否已存在
|
|
||||||
const existingDevice = prev.find(d => d.deviceSn === deviceSn);
|
|
||||||
|
|
||||||
if (!existingDevice) {
|
|
||||||
console.log('设备不存在,创建新设备记录:', deviceSn);
|
|
||||||
// 如果设备不存在,创建一个新的设备记录
|
|
||||||
const newDevice: Device = {
|
|
||||||
deviceSn: deviceSn,
|
|
||||||
deviceName: deviceSn, // 使用设备编号作为名称
|
|
||||||
deviceType: 1, // 默认类型
|
|
||||||
boundStatus: 1,
|
|
||||||
createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
|
|
||||||
loginTime: moment().format('YYYY-MM-DD HH:mm:ss'),
|
|
||||||
metrics: {
|
|
||||||
temperature: payload.properties.temperature ?? 0,
|
|
||||||
humidity: payload.properties.humidity ?? 0,
|
|
||||||
windSpeed: payload.properties.wind_speed ?? 0,
|
|
||||||
rainfall: payload.properties.rainfall ?? 0,
|
|
||||||
environmentTemperature: payload.properties.environment_temperature ?? 0,
|
|
||||||
positionQuality: payload.properties.position_state?.quality ?? 0,
|
|
||||||
networkQuality: payload.properties.network_state?.quality ?? 0,
|
|
||||||
droneInDock: payload.properties.drone_in_dock ?? 0,
|
|
||||||
batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? 0,
|
|
||||||
batteryState: payload.properties.drone_charge_state?.state ?? 0,
|
|
||||||
workingVoltage: 0,
|
|
||||||
workingCurrent: 0,
|
|
||||||
acdcPowerInput: 0,
|
|
||||||
backupBatteryVoltage: 0,
|
|
||||||
flightTaskStep: 0,
|
|
||||||
tiltAngle: 0,
|
|
||||||
sdrUpQuality: 0,
|
|
||||||
sdrDownQuality: 0,
|
|
||||||
wirelessLinkState: 0,
|
|
||||||
wirelessLinkQuality: 0,
|
|
||||||
'4gLinkState': 0,
|
|
||||||
'4gLinkQuality': 0,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
console.log('创建的新设备:', JSON.stringify(newDevice, null, 2));
|
|
||||||
return [...prev, newDevice];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果设备存在,更新现有设备
|
|
||||||
return prev.map(d =>
|
|
||||||
d.deviceSn === deviceSn
|
|
||||||
? {
|
|
||||||
...d,
|
|
||||||
metrics: {
|
|
||||||
...d.metrics,
|
|
||||||
temperature: payload.properties.temperature ?? d.metrics.temperature,
|
|
||||||
humidity: payload.properties.humidity ?? d.metrics.humidity,
|
|
||||||
windSpeed: payload.properties.wind_speed ?? d.metrics.windSpeed,
|
|
||||||
rainfall: payload.properties.rainfall ?? d.metrics.rainfall,
|
|
||||||
environmentTemperature: payload.properties.environment_temperature ?? d.metrics.environmentTemperature,
|
|
||||||
positionQuality: payload.properties.position_state?.quality ?? d.metrics.positionQuality,
|
|
||||||
networkQuality: payload.properties.network_state?.quality ?? d.metrics.networkQuality,
|
|
||||||
droneInDock: payload.properties.drone_in_dock ?? d.metrics.droneInDock,
|
|
||||||
batteryCapacity: payload.properties.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity,
|
|
||||||
batteryState: payload.properties.drone_charge_state?.state ?? d.metrics.batteryState,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
: d
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (newMetrics.length > 0) {
|
if (deviceData.humidity !== undefined) {
|
||||||
console.log('新的性能指标:', JSON.stringify(newMetrics, null, 2));
|
newMetrics.push({
|
||||||
setMetricsMap(prev => ({
|
time,
|
||||||
...prev,
|
value: deviceData.humidity,
|
||||||
[deviceSn]: [...(prev[deviceSn] || []), ...newMetrics].slice(-72)
|
type: '湿度',
|
||||||
}));
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deviceData.environment_temperature !== undefined) {
|
||||||
|
newMetrics.push({
|
||||||
|
time,
|
||||||
|
value: deviceData.environment_temperature,
|
||||||
|
type: '环境温度',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deviceData.wind_speed !== undefined) {
|
||||||
|
newMetrics.push({
|
||||||
|
time,
|
||||||
|
value: deviceData.wind_speed,
|
||||||
|
type: '风速',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deviceData.rainfall !== undefined) {
|
||||||
|
newMetrics.push({
|
||||||
|
time,
|
||||||
|
value: deviceData.rainfall,
|
||||||
|
type: '降雨量',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理设备状态数据
|
||||||
|
if (deviceData.drone_charge_state?.capacity_percent !== undefined) {
|
||||||
|
newMetrics.push({
|
||||||
|
time,
|
||||||
|
value: deviceData.drone_charge_state.capacity_percent,
|
||||||
|
type: '电池电量',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deviceData.position_state?.quality !== undefined) {
|
||||||
|
newMetrics.push({
|
||||||
|
time,
|
||||||
|
value: deviceData.position_state.quality,
|
||||||
|
type: '定位质量',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deviceData.network_state?.quality !== undefined) {
|
||||||
|
newMetrics.push({
|
||||||
|
time,
|
||||||
|
value: deviceData.network_state.quality,
|
||||||
|
type: '网络质量',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 同步更新 deviceList 里对应设备的 metrics 字段
|
||||||
|
setDeviceList(prev => {
|
||||||
|
// 检查设备是否已存在
|
||||||
|
const existingDevice = prev.find(d => d.deviceSn === deviceSn);
|
||||||
|
|
||||||
|
if (!existingDevice) {
|
||||||
|
console.log('设备不存在,创建新设备记录:', deviceSn);
|
||||||
|
// 如果设备不存在,创建一个新的设备记录
|
||||||
|
const newDevice: Device = {
|
||||||
|
deviceSn: deviceSn,
|
||||||
|
deviceName: deviceSn, // 使用设备编号作为名称
|
||||||
|
deviceType: 1, // 默认类型
|
||||||
|
boundStatus: 1,
|
||||||
|
createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||||
|
loginTime: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||||
|
metrics: {
|
||||||
|
temperature: deviceData.temperature ?? 0,
|
||||||
|
humidity: deviceData.humidity ?? 0,
|
||||||
|
windSpeed: deviceData.wind_speed ?? 0,
|
||||||
|
rainfall: deviceData.rainfall ?? 0,
|
||||||
|
environmentTemperature: deviceData.environment_temperature ?? 0,
|
||||||
|
positionQuality: deviceData.position_state?.quality ?? 0,
|
||||||
|
networkQuality: deviceData.network_state?.quality ?? 0,
|
||||||
|
droneInDock: deviceData.drone_in_dock ?? 0,
|
||||||
|
batteryCapacity: deviceData.drone_charge_state?.capacity_percent ?? 0,
|
||||||
|
batteryState: deviceData.drone_charge_state?.state ?? 0,
|
||||||
|
workingVoltage: 0,
|
||||||
|
workingCurrent: 0,
|
||||||
|
acdcPowerInput: 0,
|
||||||
|
backupBatteryVoltage: 0,
|
||||||
|
flightTaskStep: 0,
|
||||||
|
tiltAngle: 0,
|
||||||
|
sdrUpQuality: 0,
|
||||||
|
sdrDownQuality: 0,
|
||||||
|
wirelessLinkState: 0,
|
||||||
|
wirelessLinkQuality: 0,
|
||||||
|
'4gLinkState': 0,
|
||||||
|
'4gLinkQuality': 0,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
console.log('创建的新设备:', JSON.stringify(newDevice, null, 2));
|
||||||
|
return [...prev, newDevice];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 如果设备存在,更新现有设备
|
||||||
|
return prev.map(d =>
|
||||||
|
d.deviceSn === deviceSn
|
||||||
|
? {
|
||||||
|
...d,
|
||||||
|
metrics: {
|
||||||
|
...d.metrics,
|
||||||
|
temperature: deviceData.temperature ?? d.metrics.temperature,
|
||||||
|
humidity: deviceData.humidity ?? d.metrics.humidity,
|
||||||
|
windSpeed: deviceData.wind_speed ?? d.metrics.windSpeed,
|
||||||
|
rainfall: deviceData.rainfall ?? d.metrics.rainfall,
|
||||||
|
environmentTemperature: deviceData.environment_temperature ?? d.metrics.environmentTemperature,
|
||||||
|
positionQuality: deviceData.position_state?.quality ?? d.metrics.positionQuality,
|
||||||
|
networkQuality: deviceData.network_state?.quality ?? d.metrics.networkQuality,
|
||||||
|
droneInDock: deviceData.drone_in_dock ?? d.metrics.droneInDock,
|
||||||
|
batteryCapacity: deviceData.drone_charge_state?.capacity_percent ?? d.metrics.batteryCapacity,
|
||||||
|
batteryState: deviceData.drone_charge_state?.state ?? d.metrics.batteryState,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: d
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (newMetrics.length > 0) {
|
||||||
|
console.log('新的性能指标:', JSON.stringify(newMetrics, null, 2));
|
||||||
|
setMetricsMap(prev => ({
|
||||||
|
...prev,
|
||||||
|
[deviceSn]: [...(prev[deviceSn] || []), ...newMetrics].slice(-72)
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -655,6 +728,8 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
// topic: /device/{productId}/{deviceSn}/message/event/fire_alarm
|
// topic: /device/{productId}/{deviceSn}/message/event/fire_alarm
|
||||||
const deviceSn = topicParts[3];
|
const deviceSn = topicParts[3];
|
||||||
console.log('从主题中提取的设备编号:', deviceSn);
|
console.log('从主题中提取的设备编号:', deviceSn);
|
||||||
|
console.log('消息主题:', topic);
|
||||||
|
console.log('消息负载:', JSON.stringify(payload, null, 2));
|
||||||
|
|
||||||
// 处理设备在线状态
|
// 处理设备在线状态
|
||||||
if (topic.endsWith('/online')) {
|
if (topic.endsWith('/online')) {
|
||||||
@@ -682,9 +757,36 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
} else if (data.type === 'error') {
|
} else if (data.type === 'error') {
|
||||||
console.error('WebSocket消息错误:', data);
|
console.error('WebSocket消息错误:', data);
|
||||||
message.error(data.message || '消息处理错误');
|
message.error(data.message || '消息处理错误');
|
||||||
|
} else if (data.type === 'sub') {
|
||||||
|
// 处理订阅响应
|
||||||
|
console.log('收到订阅响应:', JSON.stringify(data, null, 2));
|
||||||
|
if (data.success) {
|
||||||
|
console.log('订阅成功:', data.id);
|
||||||
|
} else {
|
||||||
|
console.error('订阅失败:', data.id, data.message);
|
||||||
|
}
|
||||||
|
} else if (data.type === 'unsub') {
|
||||||
|
// 处理取消订阅响应
|
||||||
|
console.log('收到取消订阅响应:', JSON.stringify(data, null, 2));
|
||||||
|
if (data.success) {
|
||||||
|
console.log('取消订阅成功:', data.id);
|
||||||
|
} else {
|
||||||
|
console.error('取消订阅失败:', data.id, data.message);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log('未处理的WebSocket消息类型:', data.type);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 添加订阅状态检查
|
||||||
|
const checkSubscriptionStatus = () => {
|
||||||
|
console.log('当前订阅状态:');
|
||||||
|
console.log('- 当前订阅的设备:', currentSubscribedDevice);
|
||||||
|
console.log('- 当前订阅列表:', currentSubscriptions);
|
||||||
|
console.log('- WebSocket连接状态:', wsRef.current?.readyState);
|
||||||
|
console.log('- 设备列表:', deviceList.map(d => ({ deviceSn: d.deviceSn, deviceName: d.deviceName })));
|
||||||
|
};
|
||||||
|
|
||||||
// 订阅设备消息
|
// 订阅设备消息
|
||||||
const subscribeDeviceMessages = (deviceSn?: string) => {
|
const subscribeDeviceMessages = (deviceSn?: string) => {
|
||||||
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
|
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
|
||||||
@@ -694,73 +796,129 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
|
|
||||||
console.log('开始订阅设备消息:', deviceSn);
|
console.log('开始订阅设备消息:', deviceSn);
|
||||||
|
|
||||||
// 取消所有现有订阅
|
try {
|
||||||
const unsubAll = {
|
// 生成唯一的时间戳作为ID前缀
|
||||||
type: 'unsub',
|
const timestamp = Date.now();
|
||||||
topic: '/device/*',
|
const newSubscriptions: string[] = [];
|
||||||
id: 'unsub-all',
|
|
||||||
};
|
|
||||||
console.log('取消所有订阅:', JSON.stringify(unsubAll, null, 2));
|
|
||||||
wsRef.current.send(JSON.stringify(unsubAll));
|
|
||||||
|
|
||||||
if (deviceSn) {
|
// 先取消所有当前订阅
|
||||||
// 订阅指定设备的消息
|
if (currentSubscriptions.length > 0) {
|
||||||
const subscriptions = [
|
console.log('取消当前订阅:', currentSubscriptions);
|
||||||
{
|
currentSubscriptions.forEach(subId => {
|
||||||
type: 'sub',
|
const unsubMessage = {
|
||||||
topic: `/device/*/${deviceSn}/online`,
|
type: 'unsub',
|
||||||
id: 'online-sub',
|
id: subId,
|
||||||
},
|
};
|
||||||
{
|
console.log('发送取消订阅请求:', JSON.stringify(unsubMessage, null, 2));
|
||||||
type: 'sub',
|
wsRef.current?.send(JSON.stringify(unsubMessage));
|
||||||
topic: `/device/*/${deviceSn}/offline`,
|
});
|
||||||
id: 'offline-sub',
|
// 清空当前订阅列表
|
||||||
},
|
setCurrentSubscriptions([]);
|
||||||
{
|
}
|
||||||
type: 'sub',
|
|
||||||
topic: `/device/*/${deviceSn}/message/property/report`,
|
// 等待一段时间让服务器处理取消订阅
|
||||||
id: 'property-sub',
|
setTimeout(() => {
|
||||||
},
|
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
|
||||||
{
|
console.log('WebSocket连接已断开,取消订阅');
|
||||||
type: 'sub',
|
return;
|
||||||
topic: `/device/*/${deviceSn}/message/event/fire_alarm`,
|
}
|
||||||
id: 'fire-alarm-sub',
|
|
||||||
},
|
if (deviceSn) {
|
||||||
];
|
// 订阅指定设备的消息,每个订阅使用唯一的ID
|
||||||
subscriptions.forEach(sub => {
|
const subscriptions = [
|
||||||
console.log('发送订阅请求:', JSON.stringify(sub, null, 2));
|
{
|
||||||
wsRef.current?.send(JSON.stringify(sub));
|
type: 'sub',
|
||||||
});
|
topic: `/device/*/${deviceSn}/online`,
|
||||||
} else {
|
id: `online-sub-${timestamp}-${deviceSn}`,
|
||||||
// 订阅所有设备的在线状态
|
},
|
||||||
const onlineSub = {
|
{
|
||||||
type: 'sub',
|
type: 'sub',
|
||||||
topic: '/device/*/online',
|
topic: `/device/*/${deviceSn}/offline`,
|
||||||
id: 'online-sub',
|
id: `offline-sub-${timestamp}-${deviceSn}`,
|
||||||
};
|
},
|
||||||
console.log('发送在线状态订阅请求:', JSON.stringify(onlineSub, null, 2));
|
{
|
||||||
wsRef.current.send(JSON.stringify(onlineSub));
|
type: 'sub',
|
||||||
|
topic: `/device/*/${deviceSn}/message/property/report`,
|
||||||
|
id: `property-sub-${timestamp}-${deviceSn}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'sub',
|
||||||
|
topic: `/device/*/${deviceSn}/message/event/fire_alarm`,
|
||||||
|
id: `fire-alarm-sub-${timestamp}-${deviceSn}`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
console.log('准备发送设备订阅请求:', JSON.stringify(subscriptions, null, 2));
|
||||||
|
|
||||||
|
// 逐个发送订阅请求,确保每个请求都被正确处理
|
||||||
|
const sendSubscriptions = (index: number) => {
|
||||||
|
if (index >= subscriptions.length) {
|
||||||
|
console.log('所有订阅请求已发送完成');
|
||||||
|
// 更新当前订阅列表
|
||||||
|
setCurrentSubscriptions(newSubscriptions);
|
||||||
|
console.log('设备消息订阅请求已发送,当前订阅:', newSubscriptions);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sub = subscriptions[index];
|
||||||
|
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
||||||
|
console.log(`发送订阅请求 ${index + 1}/${subscriptions.length}:`, JSON.stringify(sub, null, 2));
|
||||||
|
wsRef.current.send(JSON.stringify(sub));
|
||||||
|
newSubscriptions.push(sub.id);
|
||||||
|
|
||||||
|
// 延迟发送下一个订阅请求
|
||||||
|
setTimeout(() => {
|
||||||
|
sendSubscriptions(index + 1);
|
||||||
|
}, 200);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 开始发送订阅请求
|
||||||
|
sendSubscriptions(0);
|
||||||
|
} else {
|
||||||
|
// 订阅所有设备的在线状态,修正topic格式
|
||||||
|
const onlineSub = {
|
||||||
|
type: 'sub',
|
||||||
|
topic: '/device/*/*/online',
|
||||||
|
id: `online-sub-${timestamp}-all`,
|
||||||
|
};
|
||||||
|
console.log('发送在线状态订阅请求:', JSON.stringify(onlineSub, null, 2));
|
||||||
|
wsRef.current.send(JSON.stringify(onlineSub));
|
||||||
|
newSubscriptions.push(onlineSub.id);
|
||||||
|
|
||||||
|
// 更新当前订阅列表
|
||||||
|
setCurrentSubscriptions(newSubscriptions);
|
||||||
|
console.log('设备消息订阅请求已发送,当前订阅:', newSubscriptions);
|
||||||
|
}
|
||||||
|
}, 500); // 等待500ms让服务器处理取消订阅
|
||||||
|
} catch (error) {
|
||||||
|
console.error('订阅设备消息失败:', error);
|
||||||
}
|
}
|
||||||
console.log('设备消息订阅请求已发送');
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 修改 WebSocket 连接初始化
|
// 修改 WebSocket 连接初始化
|
||||||
const initWebSocket = async () => {
|
const initWebSocket = async () => {
|
||||||
try {
|
try {
|
||||||
console.log('开始初始化WebSocket连接...');
|
console.log('开始初始化WebSocket连接...');
|
||||||
const token = await getToken();
|
|
||||||
console.log('获取到WebSocket token:', token);
|
|
||||||
|
|
||||||
// 如果已经存在连接,且未关闭,不重复建立
|
// 如果已经存在连接,且未关闭,不重复建立
|
||||||
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||||
console.log('WebSocket已连接,无需重复建立');
|
console.log('WebSocket已连接,无需重复建立');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 如果存在连接但状态不是OPEN,先关闭
|
||||||
if (wsRef.current) {
|
if (wsRef.current) {
|
||||||
console.log('关闭已存在的WebSocket连接');
|
console.log('关闭已存在的WebSocket连接');
|
||||||
wsRef.current.close();
|
wsRef.current.close();
|
||||||
|
wsRef.current = null;
|
||||||
|
// 等待一小段时间确保连接完全关闭
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const token = await getToken();
|
||||||
|
console.log('获取到WebSocket token:', token);
|
||||||
|
|
||||||
// 建立WebSocket连接
|
// 建立WebSocket连接
|
||||||
const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`;
|
const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`;
|
||||||
console.log('正在连接WebSocket:', wsUrl);
|
console.log('正在连接WebSocket:', wsUrl);
|
||||||
@@ -772,14 +930,19 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
setWsConnected(true);
|
setWsConnected(true);
|
||||||
// 启动心跳检测
|
// 启动心跳检测
|
||||||
startHeartbeat();
|
startHeartbeat();
|
||||||
// 根据当前选中的设备订阅消息
|
|
||||||
if (selectedDevice !== 'all') {
|
// 延迟一点时间确保连接稳定后再订阅
|
||||||
console.log('当前选中的设备:', selectedDevice);
|
setTimeout(() => {
|
||||||
subscribeDeviceMessages(selectedDevice);
|
console.log('准备发送订阅请求,当前选中的设备:', selectedDevice);
|
||||||
} else {
|
// 根据当前选中的设备订阅消息
|
||||||
console.log('未选择具体设备,订阅所有设备在线状态');
|
if (selectedDevice !== 'all') {
|
||||||
subscribeDeviceMessages();
|
console.log('WebSocket连接稳定,订阅设备消息:', selectedDevice);
|
||||||
}
|
subscribeDeviceMessages(selectedDevice);
|
||||||
|
} else {
|
||||||
|
console.log('WebSocket连接稳定,订阅所有设备在线状态');
|
||||||
|
subscribeDeviceMessages();
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
};
|
};
|
||||||
|
|
||||||
ws.onmessage = (event) => {
|
ws.onmessage = (event) => {
|
||||||
@@ -837,29 +1000,38 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 切换设备时只发订阅,不重建ws
|
// 切换设备时只更新订阅,不重建连接
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log('选中的设备已更改:', selectedDevice);
|
console.log('选中的设备已更改:', selectedDevice);
|
||||||
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
|
||||||
if (selectedDevice !== 'all') {
|
|
||||||
console.log('WebSocket已连接,开始订阅设备消息:', selectedDevice);
|
|
||||||
subscribeDeviceMessages(selectedDevice);
|
|
||||||
} else {
|
|
||||||
console.log('WebSocket已连接,订阅所有设备在线状态');
|
|
||||||
subscribeDeviceMessages();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.log('WebSocket未连接,尝试重新连接...');
|
|
||||||
initWebSocket();
|
|
||||||
}
|
|
||||||
}, [selectedDevice]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
// 检查当前订阅状态
|
||||||
if (selectedDevice !== 'all') {
|
checkSubscriptionStatus();
|
||||||
console.log(`设备选择变更: ${selectedDevice}`);
|
|
||||||
subscribeDeviceMessages(selectedDevice);
|
// 如果切换到了不同的设备,更新订阅状态
|
||||||
|
if (currentSubscribedDevice !== selectedDevice) {
|
||||||
|
console.log('设备切换,更新订阅:', currentSubscribedDevice, '->', selectedDevice);
|
||||||
|
|
||||||
|
// 更新当前订阅的设备
|
||||||
|
setCurrentSubscribedDevice(selectedDevice);
|
||||||
|
|
||||||
|
// 延迟一点时间确保WebSocket连接稳定
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
||||||
|
console.log('WebSocket已连接,开始订阅设备消息:', selectedDevice);
|
||||||
|
if (selectedDevice !== 'all') {
|
||||||
|
subscribeDeviceMessages(selectedDevice);
|
||||||
|
} else {
|
||||||
|
subscribeDeviceMessages();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log('WebSocket未连接,尝试重新连接...');
|
||||||
|
initWebSocket();
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
return () => clearTimeout(timer);
|
||||||
}
|
}
|
||||||
}, [selectedDevice]);
|
}, [selectedDevice]); // 只监听selectedDevice的变化
|
||||||
|
|
||||||
const alertColumns = [
|
const alertColumns = [
|
||||||
{
|
{
|
||||||
@@ -936,7 +1108,10 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
key: 'action',
|
key: 'action',
|
||||||
render: (_: unknown, record: Device) => (
|
render: (_: unknown, record: Device) => (
|
||||||
<Space size="middle">
|
<Space size="middle">
|
||||||
<a onClick={() => setSelectedDevice(record.deviceSn)}>查看监控</a>
|
<a onClick={() => {
|
||||||
|
console.log('点击查看监控按钮,设备:', record.deviceSn);
|
||||||
|
setSelectedDevice(record.deviceSn);
|
||||||
|
}}>查看监控</a>
|
||||||
</Space>
|
</Space>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -946,6 +1121,8 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
const renderRealTimeData = () => {
|
const renderRealTimeData = () => {
|
||||||
const currentDevice = deviceList.find(d => d.deviceSn === selectedDevice);
|
const currentDevice = deviceList.find(d => d.deviceSn === selectedDevice);
|
||||||
console.log('渲染实时数据卡片,当前设备:', JSON.stringify(currentDevice, null, 2));
|
console.log('渲染实时数据卡片,当前设备:', JSON.stringify(currentDevice, null, 2));
|
||||||
|
console.log('当前订阅的设备:', currentSubscribedDevice);
|
||||||
|
console.log('WebSocket连接状态:', wsRef.current?.readyState);
|
||||||
|
|
||||||
if (!currentDevice) {
|
if (!currentDevice) {
|
||||||
console.log('未找到选中的设备');
|
console.log('未找到选中的设备');
|
||||||
@@ -1059,7 +1236,10 @@ const DeviceMonitor: React.FC = () => {
|
|||||||
<Select
|
<Select
|
||||||
style={{ width: 200 }}
|
style={{ width: 200 }}
|
||||||
value={selectedDevice}
|
value={selectedDevice}
|
||||||
onChange={setSelectedDevice}
|
onChange={(value) => {
|
||||||
|
console.log('Select组件onChange事件,选择设备:', value);
|
||||||
|
setSelectedDevice(value);
|
||||||
|
}}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
placeholder="请选择设备"
|
placeholder="请选择设备"
|
||||||
>
|
>
|
||||||
|
|||||||
Reference in New Issue
Block a user