Enhance MQTT connection handling and client ID generation. Updated the MQTT client connection method to accept username and password parameters, added validation for ASCII characters in username and password, and improved error logging for connection failures. Modified client ID generation to ensure it only contains valid ASCII characters, defaulting to a safe value if necessary.

This commit is contained in:
2025-09-08 20:02:14 +08:00
parent dec8b29c3c
commit 99ca9456c0
2 changed files with 62 additions and 2 deletions

View File

@@ -187,7 +187,7 @@ bool CustomRobot::initializeMqtt() {
mqttClient_->startMessageProcessor();
if (!mqttClient_->connect()) {
if (!mqttClient_->connect(config_.mqtt_username, config_.mqtt_password)) {
LOG_ERROR("Failed to connect to MQTT broker");
return false;
}
@@ -305,12 +305,23 @@ void CustomRobot::publishStatus() {
std::string CustomRobot::generateRandomClientId() const {
std::string baseId = config_.mqtt_client_id;
// 确保base ID只包含ASCII字符
std::string safeBaseId;
for (char c : baseId) {
if (std::isalnum(c) || c == '_' || c == '-') {
safeBaseId += c;
}
}
if (safeBaseId.empty()) {
safeBaseId = "unitree_go2_client";
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1000, 9999);
std::stringstream ss;
ss << baseId << "_" << std::time(nullptr) << "_" << dis(gen);
ss << safeBaseId << "_" << std::time(nullptr) << "_" << dis(gen);
return ss.str();
}