@@ -16,27 +16,47 @@ MqttConfig MqttSubscriber::loadMqttConfig(const std::string& filename) {
1616 file >> config_json;
1717 }
1818
19- spdlog::info (" MQTT 配置文件: Host={}, Port={}, Client ID={}" , config_json[" mqtt" ][" host" ].dump (), config_json[" mqtt" ][" port" ].dump (), config_json[" mqtt" ][" client_id" ].dump ());
19+ // 默认配置,如果配置文件不存在则使用默认值
20+ std::string host = " 127.0.0.1" ;
21+ uint16_t port = 1883 ;
22+ std::string client_id;
23+
24+ // 文件存在则更新上面的默认值
25+ if (config_json.contains (" mqtt" ) && config_json[" mqtt" ].is_object ()) {
26+ auto & mqtt = config_json[" mqtt" ];
27+ if (mqtt.contains (" host" ) && mqtt[" host" ].is_string ()) {
28+ host = mqtt[" host" ].get <std::string>();
29+ }
30+ if (mqtt.contains (" port" ) && mqtt[" port" ].is_number ()) {
31+ port = mqtt[" port" ].get <uint16_t >();
32+ }
33+ if (mqtt.contains (" client_id" ) && mqtt[" client_id" ].is_string ()) {
34+ client_id = mqtt[" client_id" ].get <std::string>();
35+ }
36+ }
37+
38+ spdlog::info (" MQTT 配置文件: Host={}, Port={}, Client ID={}" , host, port, client_id);
2039
2140 MqttConfig config;
22- config.host = config_json[ " mqtt " ][ " host" ] ;
23- config.port = config_json[ " mqtt " ][ " port" ] ;
41+ config.host = host;
42+ config.port = port;
2443
2544 // 如果 client_id 不存在或为空,则生成并保存
26- if (!config_json.contains (" mqtt" ) ||
27- !config_json[" mqtt" ].contains (" client_id" ) ||
28- config_json[" mqtt" ][" client_id" ].get <std::string>().empty ()) {
29-
45+ if (client_id.empty ()) {
3046 config.client_id = generate_client_id ();
3147 spdlog::info (" client_id 不存在,生成ID: {}" , config.client_id );
48+
3249 // 更新配置
50+ config_json[" mqtt" ][" host" ] = host;
51+ config_json[" mqtt" ][" port" ] = port;
3352 config_json[" mqtt" ][" client_id" ] = config.client_id ;
53+
3454 std::ofstream out_file (filename);
3555 if (out_file.is_open ()) {
3656 out_file << config_json.dump (4 );
3757 }
3858 } else {
39- config.client_id = config_json[ " mqtt " ][ " client_id" ] ;
59+ config.client_id = client_id;
4060 }
4161
4262 return config;
0 commit comments