refactor(config): 重构配置系统和MQTT相关功能

移除状态发布功能,简化配置系统
更新MQTT配置和主题设置
调整README文档以反映最新变更
This commit is contained in:
2025-09-20 19:54:04 +08:00
parent f7acf6ff51
commit f30590033b
6 changed files with 113 additions and 107 deletions

153
README.md
View File

@@ -11,7 +11,6 @@ A high-performance C++ implementation for controlling Unitree GO2 robot with rea
- **📝 Comprehensive Logging**: Multi-level logging with file and console output - **📝 Comprehensive Logging**: Multi-level logging with file and console output
- **⚙️ Configuration Management**: JSON-based configuration with runtime presets - **⚙️ Configuration Management**: JSON-based configuration with runtime presets
- **🧭 Navigation Support**: SLAM and navigation capabilities - **🧭 Navigation Support**: SLAM and navigation capabilities
- **📊 State Publishing**: Real-time robot state broadcasting
- **🎭 Special Actions**: Support for dances, tricks, and custom motions - **🎭 Special Actions**: Support for dances, tricks, and custom motions
- **🚀 High Performance**: Optimized for real-time control with configurable frequencies - **🚀 High Performance**: Optimized for real-time control with configurable frequencies
- **🔧 Development Tools**: Built-in scripts and utilities for easy deployment - **🔧 Development Tools**: Built-in scripts and utilities for easy deployment
@@ -79,31 +78,7 @@ The system supports flexible configuration through compile-time defaults. Config
The default configuration is defined in `include/config.hpp`: The default configuration is defined in `include/config.hpp`:
```cpp
// Network settings
constexpr std::string_view NETWORK_INTERFACE = "eth0";
// MQTT settings
constexpr std::string_view MQTT_BROKER = "192.168.2.236";
constexpr int MQTT_PORT = 1883;
constexpr std::string_view MQTT_CLIENT_ID = "unitree_go2_client";
constexpr std::string_view MQTT_USERNAME = "lzwc";
constexpr std::string_view MQTT_PASSWORD = "Lzwc@4187.";
// Topic settings
constexpr std::string_view TOPIC_PREFIX = "unitree/go2";
constexpr std::string_view TOPIC_CMD = "cmd";
constexpr std::string_view TOPIC_STATE = "state";
// Robot control settings
constexpr double CONTROL_FREQUENCY = 200.0; // Hz
constexpr double STATE_PUBLISH_FREQUENCY = 50.0; // Hz
// Safety settings
constexpr double MAX_LINEAR_VELOCITY = 1.5; // m/s
constexpr double MAX_ANGULAR_VELOCITY = 2.0; // rad/s
constexpr double EMERGENCY_STOP_TIMEOUT = 5.0; // seconds
```
To customize these settings, modify the values in `include/config.hpp` and rebuild the project. To customize these settings, modify the values in `include/config.hpp` and rebuild the project.
@@ -123,13 +98,9 @@ To customize these settings, modify the values in `include/config.hpp` and rebui
The robot runs with sensible defaults out of the box: The robot runs with sensible defaults out of the box:
- **Network Interface**: `eth0`
- **MQTT Broker**: `192.168.2.236:1883`
- **MQTT Credentials**: Username `lzwc`, Password `Lzwc@4187.`
- **Control Frequency**: 200Hz
- **Safety Limits**: Conservative settings for safe operation
- **Logging**: INFO level to console
Configuration is done at compile time by modifying values in `include/config.hpp`.
No configuration files or command-line arguments needed! No configuration files or command-line arguments needed!
## MQTT API ## MQTT API
@@ -138,24 +109,23 @@ The robot communicates via MQTT using the following topic structure:
### Command Topics ### Command Topics
- `unitree/go2/cmd/oac`: Obstacle avoidance commands - `unitree/go2/cmd`: All commands (sport, navigation, robot state, obstacle avoidance)
- `unitree/go2/cmd/sport`: Sport mode commands
- `unitree/go2/cmd/rsc`: Robot state commands Commands are sent to the command topic with a JSON payload specifying the command type and parameters.
- `unitree/go2/cmd/nav`: Navigation commands
### State Topics
- `unitree/go2/state/robot`: Robot state (position, IMU, motors, etc.)
- `unitree/go2/state/heartbeat`: System status and statistics
- `unitree/go2/state/response`: Command execution responses
- `unitree/go2/state/error`: Error messages
### Sport Commands ### Sport Commands
Sport commands are sent with a JSON payload containing the command type and optional parameters:
```json ```json
{ {
"request_id": "unique_id", "type": "sport",
"cmd": "StandUp" "cmd": "StandUp",
"param": {
// Optional parameters depending on the command
}
} }
``` ```
@@ -170,36 +140,65 @@ Supported sport commands:
- `Dance1`: Dance routine 1 - `Dance1`: Dance routine 1
- `Dance2`: Dance routine 2 - `Dance2`: Dance routine 2
- `Hello`: Greeting gesture - `Hello`: Greeting gesture
- `Move`: Move with specified velocities (vx, vy, vyaw)
- `Euler`: Set body orientation (roll, pitch, yaw)
- And many more...
### Navigation Commands ### Navigation Commands
Navigation commands are sent with a JSON payload containing the command type and parameters:
```json ```json
{ {
"request_id": "unique_id", "type": "nav",
"cmd": "startMapping" "cmd": "startMapping"
} }
``` ```
Supported navigation commands: Supported navigation commands:
- `startMapping`: Start SLAM mapping - `start_mapping`: Start SLAM mapping
- `endMapping`: End SLAM mapping - `end_mapping`: End SLAM mapping with map address parameter
- `pauseNavigation`: Pause navigation - `initialize_pose`: Set initial pose with position and orientation
- `resumeNavigation`: Resume navigation - `pose_navigation`: Navigate to a specific pose
- `closeSlam`: Close SLAM service - `pause_navigation`: Pause navigation
- `resume_navigation`: Resume navigation
- `close_slam`: Close SLAM service
### System Commands ### Obstacle Avoidance Commands
Obstacle avoidance commands are sent with a JSON payload containing the command type and parameters:
```json ```json
{ {
"request_id": "unique_id", "type": "oac",
"cmd": "SwitchSet",
"param": {
"enable": true
}
}
```
Supported obstacle avoidance commands:
- `SwitchSet`: Enable/disable obstacle avoidance
- `SwitchGet`: Get obstacle avoidance status
- `UseRemoteCommandFromApi`: Configure remote command source
- `MoveToAbsolutePosition`: Move to absolute position
- `MoveToIncrementPosition`: Move to increment position
### System Commands
System commands are sent with a JSON payload containing the command type and parameters:
```json
{
"type": "rsc",
"cmd": "GetServiceList" "cmd": "GetServiceList"
} }
``` ```
Supported system commands: Supported system commands:
- `GetServiceList`: Get list of available services - `list`: Get list of available services
- `SwitchService`: Enable/disable a service - `switch`: Enable/disable a service
- `SetReportFreq`: Set state reporting frequency
## Supported Actions ## Supported Actions
@@ -218,11 +217,11 @@ Supported system commands:
- `Hello`: Greeting gesture - `Hello`: Greeting gesture
### Navigation Actions ### Navigation Actions
- `startMapping`: Start SLAM mapping - `start_mapping`: Start SLAM mapping
- `endMapping`: End SLAM mapping and save map - `end_mapping`: End SLAM mapping and save map
- `pauseNavigation`: Pause navigation - `pause_navigation`: Pause navigation
- `resumeNavigation`: Resume navigation - `resume_navigation`: Resume navigation
- `closeSlam`: Close SLAM service - `close_slam`: Close SLAM service
## Safety Features ## Safety Features
@@ -247,22 +246,22 @@ Supported system commands:
### Custom Configurations ### Custom Configurations
To customize the configuration, modify the values in `include/config.hpp`: The robot's configuration is defined at compile time in `include/config.hpp`. To customize the configuration:
```cpp 1. Edit the constants in `include/config.hpp` to change default values
// Example: Change MQTT broker address 2. Rebuild the project:
constexpr std::string_view MQTT_BROKER = "192.168.1.100";
// Example: Change control frequency
constexpr double CONTROL_FREQUENCY = 400.0; // Hz
```
After making changes, rebuild the project:
```bash ```bash
cd build cd build
make -j$(nproc) make -j$(nproc)
``` ```
Common configuration options include:
- Network interface
- MQTT broker settings
- Topic prefixes
- Control frequencies
- Safety limits
## Quick Start Scripts ## Quick Start Scripts
The project includes utility scripts for easy deployment: The project includes utility scripts for easy deployment:
@@ -282,6 +281,7 @@ unitree-go2/
├── CMakeLists.txt # Build configuration ├── CMakeLists.txt # Build configuration
├── README.md # This file ├── README.md # This file
├── LICENSE # License information ├── LICENSE # License information
├── .gitignore # Git ignore file
├── config/ # Configuration files (optional) ├── config/ # Configuration files (optional)
├── include/ # Header files ├── include/ # Header files
│ ├── config.hpp # Configuration management │ ├── config.hpp # Configuration management
@@ -292,13 +292,13 @@ unitree-go2/
│ ├── navigation.hpp # Navigation and SLAM │ ├── navigation.hpp # Navigation and SLAM
│ └── nlohmann/ # JSON library │ └── nlohmann/ # JSON library
├── src/ # Source files ├── src/ # Source files
│ ├── config.cpp │ ├── config.cpp # Configuration implementation
│ ├── controller.cpp │ ├── controller.cpp # Robot controller implementation
│ ├── custom_robot.cpp │ ├── custom_robot.cpp # Main orchestrator implementation
│ ├── logger.cpp │ ├── logger.cpp # Logging system implementation
│ ├── main.cpp │ ├── main.cpp # Entry point
│ ├── mqtt.cpp │ ├── mqtt.cpp # MQTT client implementation
│ └── navigation.cpp │ └── navigation.cpp # Navigation and SLAM implementation
├── scripts/ # Utility scripts ├── scripts/ # Utility scripts
│ ├── install_deps.sh # Install dependencies │ ├── install_deps.sh # Install dependencies
│ └── run_robot.sh # Run with optimal settings │ └── run_robot.sh # Run with optimal settings
@@ -348,9 +348,8 @@ This project is licensed under the MIT License - see the LICENSE file for detail
## Performance Notes ## Performance Notes
- **Control Frequency**: Default 200Hz, configurable up to 400Hz for high-performance applications - **Control Frequency**: Default 200Hz, configurable up to 400Hz for high-performance applications
- **State Publishing**: Default 50Hz, can be adjusted based on network bandwidth
- **Memory Usage**: Optimized for minimal heap allocations during runtime - **Memory Usage**: Optimized for minimal heap allocations during runtime
- **CPU Usage**: Multi-threaded design with separate threads for control, MQTT, and state publishing - **CPU Usage**: Multi-threaded design with separate threads for control and MQTT
## Contributing ## Contributing

View File

@@ -25,14 +25,13 @@ constexpr std::string_view MQTT_CLIENT_ID = "unitree_go2_client";
constexpr std::string_view MQTT_USERNAME = "lzwc"; constexpr std::string_view MQTT_USERNAME = "lzwc";
constexpr std::string_view MQTT_PASSWORD = "Lzwc@4187."; constexpr std::string_view MQTT_PASSWORD = "Lzwc@4187.";
// Topic settings // MQTT Topics
constexpr std::string_view TOPIC_PREFIX = "unitree/go2"; constexpr const char* TOPIC_PREFIX = "unitree/go2";
constexpr std::string_view TOPIC_CMD = "cmd"; constexpr const char* TOPIC_CMD = "cmd";
constexpr std::string_view TOPIC_STATE = "state"; constexpr const char* TOPIC_STATE = "state";
constexpr const char* TOPIC_HEARTBEAT = "heartbeat";
// Robot control settings constexpr const char* TOPIC_RESPONSE = "response";
constexpr double CONTROL_FREQUENCY = 200.0; // Hz constexpr const char* TOPIC_ERROR = "error";
constexpr double STATE_PUBLISH_FREQUENCY = 50.0; // Hz
// Safety settings // Safety settings
constexpr double MAX_LINEAR_VELOCITY = 1.5; // m/s constexpr double MAX_LINEAR_VELOCITY = 1.5; // m/s
@@ -58,7 +57,6 @@ public:
std::string topic_state; std::string topic_state;
double control_frequency; double control_frequency;
double state_publish_frequency;
double max_linear_velocity; double max_linear_velocity;
double max_angular_velocity; double max_angular_velocity;
double emergency_stop_timeout; double emergency_stop_timeout;

View File

@@ -33,7 +33,6 @@ public:
bool initializeMqtt(); bool initializeMqtt();
void onMqttMessage(const std::string& topic, const std::string& payload); void onMqttMessage(const std::string& topic, const std::string& payload);
void onMqttConnection(bool connected); void onMqttConnection(bool connected);
void publishStatus();
void processCmd(const nlohmann::json& message); void processCmd(const nlohmann::json& message);
bool processOacCmd(const std::string& cmd, const nlohmann::json& message); bool processOacCmd(const std::string& cmd, const nlohmann::json& message);

View File

@@ -105,8 +105,10 @@ if [ ! -f "$CONFIG_FILE" ]; then
"interface": "eth0" "interface": "eth0"
}, },
"mqtt": { "mqtt": {
"broker": "localhost", "broker": "192.168.2.236",
"port": 1883, "port": 1883,
"username": "lzwc",
"password": "Lzwc@4187.",
"client_id": "unitree_go2_client" "client_id": "unitree_go2_client"
}, },
"topics": { "topics": {
@@ -115,8 +117,7 @@ if [ ! -f "$CONFIG_FILE" ]; then
"state": "state" "state": "state"
}, },
"robot": { "robot": {
"control_frequency": 200.0, "control_frequency": 200.0
"state_publish_frequency": 50.0
}, },
"safety": { "safety": {
"max_linear_velocity": 1.5, "max_linear_velocity": 1.5,

View File

@@ -3,25 +3,29 @@
namespace custom { namespace custom {
void CustomConfig::loadDefaults() { void CustomConfig::loadDefaults() {
network_interface = std::string(NETWORK_INTERFACE); // Network settings
mqtt_broker = std::string(MQTT_BROKER); network_interface = NETWORK_INTERFACE;
mqtt_broker = MQTT_BROKER;
mqtt_port = MQTT_PORT; mqtt_port = MQTT_PORT;
mqtt_username = std::string(MQTT_USERNAME); mqtt_username = MQTT_USERNAME;
mqtt_password = std::string(MQTT_PASSWORD); mqtt_password = MQTT_PASSWORD;
mqtt_client_id = std::string(MQTT_CLIENT_ID);
topic_prefix = std::string(TOPIC_PREFIX); // Topic settings
topic_cmd = std::string(TOPIC_CMD); topic_prefix = TOPIC_PREFIX;
topic_state = std::string(TOPIC_STATE); topic_cmd = TOPIC_CMD;
topic_state = TOPIC_STATE;
topic_heartbeat = TOPIC_HEARTBEAT;
topic_response = TOPIC_RESPONSE;
topic_error = TOPIC_ERROR;
// Robot control settings
control_frequency = CONTROL_FREQUENCY; control_frequency = CONTROL_FREQUENCY;
state_publish_frequency = STATE_PUBLISH_FREQUENCY;
// Safety settings
command_timeout = COMMAND_TIMEOUT;
max_linear_velocity = MAX_LINEAR_VELOCITY; max_linear_velocity = MAX_LINEAR_VELOCITY;
max_angular_velocity = MAX_ANGULAR_VELOCITY; max_angular_velocity = MAX_ANGULAR_VELOCITY;
emergency_stop_timeout = EMERGENCY_STOP_TIMEOUT; emergency_stop_timeout = EMERGENCY_STOP_TIMEOUT;
stand_height = STAND_HEIGHT;
default_gait = static_cast<int>(DEFAULT_GAIT);
} }
} // namespace custom } // namespace custom

View File

@@ -12,7 +12,13 @@
namespace custom { namespace custom {
CustomRobot::CustomRobot() CustomRobot::CustomRobot()
: initialized_(false), running_(false), controller_(nullptr), navigation_(nullptr), rsc_(nullptr), mqttClient_(nullptr) { : controller_(nullptr)
, navigation_(nullptr)
, rsc_(nullptr)
, mqttClient_(nullptr)
, running_(false)
, initialized_(false) {
}
config_.loadDefaults(); config_.loadDefaults();
try { try {
@@ -224,7 +230,6 @@ void CustomRobot::onMqttMessage(const std::string& topic, const std::string& pay
void CustomRobot::onMqttConnection(bool connected) { void CustomRobot::onMqttConnection(bool connected) {
if (connected) { if (connected) {
LOG_INFO("MQTT client connected to broker"); LOG_INFO("MQTT client connected to broker");
} else { } else {
LOG_WARN("MQTT client disconnected from broker"); LOG_WARN("MQTT client disconnected from broker");
} }