WeMosを使ってみる

RaspberryとのMQTT通信(WeMos→Raspberry)

Paho MQTT C Client編


前回、「paho-mqtt pythonライブラリ」を使って、WeMosとのMQTT通信を紹介しました。
そこで、今回はRaspberryのSubscriberをC言語で作ってみます。
最初にRaspberry側に「Paho MQTT C Client」をインストールします。
「Paho MQTT C Client」のLinuxへのインストールはこちらで紹介されていますが、実際に試し たところ
以下の手順でRaspberryにインストールすることができました。
$ sudo apt-get install libssl-dev
$ git clone https://github.com/eclipse/paho.mqtt.c.git
$ cd paho.mqtt.c/
$ make
$ sudo make install

コンパイルは「cc -o test1 test1.c -l paho-mqtt3c」です。
定期的にMQTTClient_yield()を実行しないと、サーバーから切断されてしまいます。
そこで、こ ちらのページを参考にgetchar()をnonblocking動作にしています。
/*
 cc -o test1 test1.c -l paho-mqtt3c
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include "MQTTClient.h"

#define ADDRESS     "tcp://broker.hivemq.com:1883"
#define TOPIC       "nopnop2002"
#define QOS         1

volatile MQTTClient_deliveryToken deliveredtoken;

void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("Message with token value %d delivery confirmed\n", dt);
    deliveredtoken = dt;
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int i;
    char* payloadptr;

    printf("Message arrived\n");
    printf("     topic: %s\n", topicName);
    printf("   message: ");

    payloadptr = message->payload;
    for(i=0; i<message->payloadlen; i++)
    {
        putchar(*payloadptr++);
    }
    putchar('\n');
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

void connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf("     cause: %s\n", cause);
}

int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    int ch;
    char clientId[40];

    pid_t c_pid = getpid();
    sprintf(clientId, "CLIENT-%d", c_pid);
    printf("clientId=%s\n", clientId);
    MQTTClient_create(&client, ADDRESS, clientId, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);
    }
    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
           "Press Q<Enter> to quit\n\n", TOPIC, clientId, QOS);
    MQTTClient_subscribe(client, TOPIC, QOS);

    struct termios save_settings;
    struct termios settings;

    tcgetattr( fileno( stdin ), &save_settings );
    settings = save_settings;

    settings.c_lflag       &= ~( ECHO | ICANON ); /* echobackしない & LFを待たない */
    /* settings.c_lflag       &= ~( ECHO ); /\* echobackしない *\/ */
    /* settings.c_lflag       &= ~( ICANON ); /\* LFを待たない *\/ */
    tcsetattr( fileno( stdin ), TCSANOW, &settings );
    fcntl( fileno( stdin ), F_SETFL, O_NONBLOCK ); /* non blocking */

    time_t last_time = time(NULL);;
    do
    {
        ch = getchar();
        time_t current_time = time(NULL);
        time_t diff_time = current_time - last_time;
        if (diff_time >= 30) {
            printf("MQTTClient_yield\n");
            MQTTClient_yield();
            last_time = time(NULL);;
        }
    } while(ch!='Q' && ch != 'q');

    tcsetattr( fileno( stdin ), TCSANOW, &save_settings );
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}

このプログラムを実行すると、RaspberryのSubscriberには以下のように表示されます。


今までに
mosquitto-clientsを使ったSubscriber
paho-mqtt pythonライブラリを使ったSubscriber
・Paho MQTT C Clientを使ったSubscriber
の3つを紹介しましたが、全て同時に並行して動かすことができます。


今までは
WeMos(Publisher)--->Broker--->Raspberry(Subscriber)
を紹介しましたが、次回は
Raspberry(Publisher)--->Broker--->WeMos(Subscriber)
を紹介します。

続く....