/*
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;
}
|