Paho MQTT c++连接用户和密码

Paho MQTT C++ connection user and password

本文关键字:密码 用户 连接 MQTT c++ Paho      更新时间:2023-10-16

我正在实现一个通过MQTT发送数据的客户端,并且我正在使用Paho MQTT c++库。现在我需要添加对用户和密码身份验证的支持,当我尝试这样设置它们时:

std::string user = "user";
std::string password = "password";
mqtt::connect_options connOpts;
connOpts.set_user_name(user);
connOpts.set_password(password);

得到

对mqtt::connect_options::set_user_name(std:string)的未定义引用const&)

但是在头文件connection_options.h

/**
 * Sets the user name to use for the connection.
 * @param userName 
 */
void set_user_name(const std::string& userName);
set_password(password);

我遇到的另一个问题是,我无法保持我的连接存活,因为我不能在类中拥有mqtt::async_client对象全局,我只能在发布函数中创建它。

我遇到了这个问题,并通过在connect_options.h中的set_user_nameset_password函数中添加我自己的代码来修复它(它们不会在c++包装器中的任何其他文件中初始化)。

void set_user_name(const std::string& userName){
    const char * usr = userName.c_str();
    opts_.username = usr;
}

void set_password(const std::string& password){
    const char * pw = password.c_str();
    opts_.password = pw;
}

请试试:

auto connOpts = mqtt::connect_options_builder()     
    .clean_session()
    .user_name("User name here")                  // put username here
    .password(binary_ref_passwd)
    .will(mqtt::message(TOPIC, LWT_PAYLOAD, QOS))
    .finalize();
相关文章: