设备上下线订阅

This commit is contained in:
PC 2026-03-09 10:11:58 +08:00
parent 5ef02659e1
commit eb904c65aa
2 changed files with 34 additions and 2 deletions

View File

@ -94,7 +94,7 @@ public class MqttHandler extends ChannelInboundHandlerAdapter {
processReceivedMessage(topic, content);
} catch (Exception e) {
log.error("处理MQTT消息异常主题: {}", topic, e);
}finally {
} finally {
payload.release();
}
}
@ -134,6 +134,19 @@ public class MqttHandler extends ChannelInboundHandlerAdapter {
} else if (topic.startsWith("control/")) {
handleControlCommand(topic, content);
}
if (topic.startsWith("$SYS/brokers/")) {
boolean isOnline = isConnectedEvent(topic);
String clientId = objectMapper.readValue(content, ObjectNode.class).get("clientid").asText();
if (isOnline) {
log.info("设备上线: {}", clientId);
} else {
log.info("设备下线: {}", clientId);
}
ObjectNode jsonNode = objectMapper.createObjectNode();
jsonNode.put("deviceId", clientId);
jsonNode.put("isOnline", isOnline);
kafkaProducer.send("device_online", objectMapper.writeValueAsString(jsonNode));
}
} catch (Exception e) {
log.error("处理MQTT消息业务逻辑异常", e);
}
@ -196,4 +209,23 @@ public class MqttHandler extends ChannelInboundHandlerAdapter {
throw new RuntimeException("Failed to process JSON", e);
}
}
/**
* 判断MQTT主题是否为上线事件
*
* @param topic 主题字符串
* @return true: 上线事件, false: 下线事件若主题无法识别则返回false
*/
private boolean isConnectedEvent(String topic) {
if (topic == null) return false;
if (topic.endsWith("/connected")) {
return true;
} else if (topic.endsWith("/disconnected")) {
return false;
} else {
// 既不是connected也不是disconnected可根据需要处理例如抛异常或记录警告
log.warn("未知的上下线主题格式: {}", topic);
return false; // 默认返回false下线或根据业务决定
}
}
}

View File

@ -29,7 +29,7 @@ mqtt:
port: 1883
username: admin
password: admin970529
auto-subscribe-topics: ecu/rpt/#,ecu/rsp/#
auto-subscribe-topics: ecu/rpt/#,ecu/rsp/#,$SYS/brokers/+/clients/+/connected,$SYS/brokers/+/clients/+/disconnected
timeout: 10 # 减少超时时间以便更快失败
clean-session: true
keep-alive: 60