LoginSignup
1
2

More than 5 years have passed since last update.

CでMQTTを利用する。

Last updated at Posted at 2017-01-09

OS

Ubuntu

内容

IFTTTの下りをProxy越えをするのにBeebotteを経由してMQTTで行おうと思って試しましたが、MQTTのProxy越えはできませんでした。Proxyなしでは動いたのでメモを残します。

CではないですがProxy越えが出来るパターン(Webを利用)
http://qiita.com/NextWorld/items/d3b3d382fc658b244273

以降メモ
http://qiita.com/mayfair/items/e761c788a9d8787bc610
を元にBeebotteを設定。
IFTTTからBeebotteへのデータの注意
http://qiita.com/yacchin1205/items/29d31707a535eeb85a96

PahoのCをインストール

以降は
http://www.eclipse.org/paho/files/mqttdoc/Cclient/subasync.html
を書き直して見ました。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h"

#define ADDRESS     "tcp://mqtt.beebotte.com:1883"
#define CLIENTID    "test"
#define TOPIC       "ifttt/action"
#define PAYLOAD     "{\"params\":{\"content\":\"from C\"}}"
#define TOKEN       "token:*****" \\*****にtokenを書く
#define QOS         1
#define TIMEOUT     10000L

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;

    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.username = TOKEN; //ADD

    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);

    do 
    {
        ch = getchar();
    } while(ch!='Q' && ch != 'q');

    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}

コンパイルは gcc ソース -lpaho-mqtt3cで行う。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2