在 OpenWRT 上進行開發之前,我們可以先寫一隻簡單的程式,來測試 MQTT 的功能,考慮到對 OpenWRT 的支援,我們使用 mosquitto API 來進行開發。
#include <stdio.h>
#include <mosquitto.h>
void my_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
if(message->payloadlen){
printf("%s %s\n", message->topic, message->payload);
}else{
printf("%s (null)\n", message->topic);
}
fflush(stdout);
}
void my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
int i;
if(!result){
/* Subscribe to broker information topics on successful connect. */
mosquitto_subscribe(mosq, NULL, "info/#", 2);
}else{
fprintf(stderr, "Connect failed\n");
}
}
void my_subscribe_callback(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos)
{
int i;
printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
for(i=1; i<qos_count; i++){
printf(", %d", granted_qos[i]);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int i;
char *host = "localhost";
int port = 1883;
int keepalive = 60;
bool clean_session = true;
struct mosquitto *mosq = NULL;
mosquitto_lib_init();
mosq = mosquitto_new(NULL, clean_session, NULL);
if(!mosq){
fprintf(stderr, "Error: Out of memory.\n");
return 1;
}
mosquitto_connect_callback_set(mosq, my_connect_callback);
mosquitto_message_callback_set(mosq, my_message_callback);
mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
if(mosquitto_connect(mosq, host, port, keepalive)){
fprintf(stderr, "Unable to connect.\n");
return 1;
}
mosquitto_publish(mosq, NULL, "report", sizeof("hello"), "hello", 2, false);
mosquitto_loop_forever(mosq, -1, 1);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
$gcc main.c -lmosquitto -o mqtt_test
$./mqtt_test
為了要建立在 OpenWRT 上的 MQTT 開發環境,我們首先要建立一個含有 mosquitto library 的 cross compiler。相同的,我們先到menuconfig
中,將 libmosquitto-nossl 勾選,如下圖所示:
ofwrt@ofwrt-18:~/openwrt/build_dir/target-mips_24kc_musl$ ls
busybox-1.28.3 mosquitto-nossl
c-ares-1.14.0 ncurses-6.1
[...]
cp -R ~/openwrt/build_dir/target-mips_24kc_musl/mosquitto-nossl/mosquitto-1.5.1/lib/*.h ~/mqtt/include
ofwrt@ofwrt-18:~/openwrt/staging_dir/target-mips_24kc_musl/usr/lib$ cp libmosquitto* ~/mqtt/lib/
mips-openwrt-linux-gcc main_ofwrt.c -I ~/mqtt/include/ -L ~/mqtt/lib/ -lmosquitto -o mqtt_ofwrt
root@GL-AR750S:/usr/lib# ls libmosquitto*
libmosquitto.so libmosquitto.so.1