从回调中访问配置(mqtt)

时间:2018-06-16 16:12:32

标签: c mqtt

原谅我的英语。

代码: https://www.eclipse.org/paho/files/mqttdoc/MQTTAsync/html/subscribe.html

我正在修改这个例子,我的问题是它的onConnect回调我想提供TOPIC(以前从配置文件加载)或者在这个例子中:

https://www.eclipse.org/paho/files/mqttdoc/MQTTAsync/html/publish.html

在显示的示例中,他们使用#define

...
#define TOPIC       "MQTT Examples"
...
void onConnect(void* context, MQTTAsync_successData* response)
{
...
        if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
...
}

int main(int argc, char* argv[])
{
...
        MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL);
...
        conn_opts.onSuccess = onConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = client;
        if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start connect, return code %d\n", rc);
                exit(EXIT_FAILURE);
        }
...

我的问题是,这是最正确的方法吗?使用全局变量?

由于

2 个答案:

答案 0 :(得分:1)

是的,您可以使用全局变量或在on_connect函数中加载配置文件。使用全局变量更有效,因为您只需加载配置文件一次。

答案 1 :(得分:0)

我解决了我的问题,我认为这是最好的方式(如果没有反馈欢迎)

typedef struct mqtt_context{
    MQTTAsync client;
    char *MQTT_Broker_Addr;
    char *Username;
    char *Password;
    char *ClientID;
    char *Payload;
    int Qos;
} mqtt_context;

void onConnect(void* context, MQTTAsync_successData* response)
{

    mqtt_context *ctx = (mqtt_context *)context;
    MQTTAsync_responseOptions ropts = MQTTAsync_responseOptions_initializer;
    ropts.context = ctx;

    MQTTAsync_subscribe(ctx->client, ctx->Topic, ctx->Qos, &ropts);

}

int main(int argc, char* argv[])
{
    mqtt_context *ctx = g_malloc0(sizeof(struct mqtt_context));

    ctx->MQTT_Broker_Addr = g_strdup ("xxx");

    ctx->ClientID = "ExampleClientSub";
    ctx->Username = "xxxxxx";
    ctx->Password = "xxxx";
...

 MQTTAsync_setCallbacks(ctx->client, ctx, connlost, msgarrvd, NULL)
...
 MQTTAsync_connect(ctx->client, &conn_opts)
...
}