代码拉取完成,页面将自动刷新
/*
needs libmosquitto-dev
$ gcc -o libmosq libmosq.c -lmosquitto
*/
#include <stdio.h>
#include <mosquitto.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct mosquitto *mosq = NULL;
char const *topic = NULL;
void mosq_log_callback(struct mosquitto *mosq, void *userdata, int level, const char *str)
{
/* Pring all log messages regardless of level. */
switch(level){
//case MOSQ_LOG_DEBUG:
//case MOSQ_LOG_INFO:
//case MOSQ_LOG_NOTICE:
case MOSQ_LOG_WARNING:
case MOSQ_LOG_ERR: {
printf("%i:%s\n", level, str);
}
}
}
void (*g_mosq_msg_handler)(char const *topic, char const *payload, int payload_len);
void mosq_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) {
g_mosq_msg_handler(msg->topic, (char const *)msg->payload, msg->payloadlen);
}
void mosq_disconn_callback(struct mosquitto *mosq, void *userdata, int reason) {
mosquitto_reconnect(mosq);
}
void mosq_conn_callback(struct mosquitto *mosq, void *userdata, int reason) {
mosquitto_subscribe(mosq, NULL, topic, 0);
}
void mqtt_setup(char const *ip, int pport, char const *subtopicpattern, void (*hdr)(char const *, char const *, int)){
char const *host = ip;//"localhost";
int port = pport;//1883;
int keepalive = 60;
bool clean_session = true;
topic = subtopicpattern;//"/testtopic";
mosquitto_lib_init();
mosq = mosquitto_new(NULL, clean_session, NULL);
if(!mosq){
fprintf(stderr, "Error: Out of memory.\n");
exit(1);
}
mosquitto_log_callback_set(mosq, mosq_log_callback);
mosquitto_disconnect_callback_set(mosq, mosq_disconn_callback);
mosquitto_connect_callback_set(mosq, mosq_conn_callback);
g_mosq_msg_handler = hdr;
mosquitto_message_callback_set(mosq, mosq_message_callback);
if(mosquitto_connect(mosq, host, port, keepalive)){
fprintf(stderr, "<Unable to connect.>\n");
// exit(1);
}
int loop = mosquitto_loop_start(mosq);
if(loop != MOSQ_ERR_SUCCESS){
fprintf(stderr, "Unable to start loop: %i\n", loop);
exit(1);
}
}
int mqtt_send(char const *ptopic, char *msg, int len){
return mosquitto_publish(mosq, NULL, ptopic, len, msg, 0, 0);
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。