#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mosquitto.h"
#define HOST "your_broker_address"
#define PORT 1883
#define KEEP_ALIVE 60
#define MSG_MAX_SIZE 50
#define TRUE 1
#define FALSE 0
#define QOS 2
#define TIMEOUT 10000L
#define PUB_TOPIC "your_pub_topic"
#define SUB_TOPIC "your_sub_topic"
int loop_flag = TRUE;
int msg_delivered = FALSE;
int msg_arrived = FALSE;
void publish_callback(struct mosquitto *mosq, void *userdata, int mid)
{
printf("Message with mid %d was published.\n", mid);
msg_delivered = TRUE;
}
void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
if(message->payloadlen)
{
printf("Received message: %s\n", message->payload);
msg_arrived = TRUE;
}
}
int main()
{
struct mosquitto *mosq = NULL;
char buf[MSG_MAX_SIZE];
int rc;
mosquitto_lib_init();
mosq = mosquitto_new(NULL, TRUE, NULL);
if(!mosq)
{
fprintf(stderr, "Can't create mosquitto object.\n");
mosquitto_lib_cleanup();
return 1;
}
mosquitto_connect_callback_set(mosq, publish_callback);
mosquitto_message_callback_set(mosq, message_callback);
rc = mosquitto_connect(mosq, HOST, PORT, KEEP_ALIVE);
if(rc)
{
fprintf(stderr, "Can't connect to mosquitto server.\n");
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 1;
}
rc = mosquitto_subscribe(mosq, NULL, SUB_TOPIC, QOS);
if(rc)
{
fprintf(stderr, "Subscribe failed.\n");
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 1;
}
// 假设get_temperature_str是一个获取当前温度并转换为字符串的函数
strcpy(buf, get_temperature_str());
rc = mosquitto_publish(mosq, NULL, PUB_TOPIC, strlen(buf), buf, QOS, TRUE);
if(rc)
{
fprintf(stderr, "Publish failed.\n");
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 1;
}
while(loop_flag)
{
mosquitto_loop(mosq, TIMEOUT, TRUE);
if(msg_delivered && msg_arrived) break;
}
mosquitto_unsubscribe(mosq, SUB_TOPIC, NULL);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
在这个代码实例中,我们使用了一个假设的函数get_temperature_str()
来获取温度并将其转换为字符串。这个函数需要在实际应用中根据你的硬件和环境进行实现。另外,请确保替换your_broker_address
、your_pub_topic
和\`your\_sub\_to