新增http、mqtt运行库,实现mqtt功能, 新增spdlog

This commit is contained in:
lixiaoyuan
2025-09-01 20:08:40 +08:00
parent e0b64a20c4
commit 94e467b65e
245 changed files with 54182 additions and 117 deletions

View File

@@ -0,0 +1,188 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTAsync.h"
#if !defined(_WIN32)
#include <unistd.h>
#else
#include <windows.h>
#endif
#if defined(_WRS_KERNEL)
#include <OsWrapper.h>
#endif
#define ADDRESS "tcp://test.mosquitto.org:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "MQTT Examples"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L
int finished = 0;
void connlost(void *context, char *cause)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
printf("\nConnection lost\n");
if (cause)
printf(" cause: %s\n", cause);
printf("Reconnecting\n");
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
finished = 1;
}
}
void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Disconnect failed\n");
finished = 1;
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
printf("Successful disconnection\n");
finished = 1;
}
void onSendFailure(void* context, MQTTAsync_failureData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
printf("Message send failed token %d error code %d\n", response->token, response->code);
opts.onSuccess = onDisconnect;
opts.onFailure = onDisconnectFailure;
opts.context = client;
if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start disconnect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
void onSend(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
printf("Message with token value %d delivery confirmed\n", response->token);
opts.onSuccess = onDisconnect;
opts.onFailure = onDisconnectFailure;
opts.context = client;
if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start disconnect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Connect failed, rc %d\n", response ? response->code : 0);
finished = 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
printf("Successful connection\n");
opts.onSuccess = onSend;
opts.onFailure = onSendFailure;
opts.context = client;
pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
{
/* not expecting any messages */
return 1;
}
int main(int argc, char* argv[])
{
MQTTAsync client;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
const char* uri = (argc > 1) ? argv[1] : ADDRESS;
printf("Using server at %s\n", uri);
if ((rc = MQTTAsync_create(&client, uri, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTASYNC_SUCCESS)
{
printf("Failed to create client object, return code %d\n", rc);
exit(EXIT_FAILURE);
}
if ((rc = MQTTAsync_setCallbacks(client, client, connlost, messageArrived, NULL)) != MQTTASYNC_SUCCESS)
{
printf("Failed to set callback, return code %d\n", rc);
exit(EXIT_FAILURE);
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Waiting for publication of %s\n"
"on topic %s for client with ClientID: %s\n",
PAYLOAD, TOPIC, CLIENTID);
while (!finished)
#if defined(_WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MQTTAsync_destroy(&client);
return rc;
}

View File

@@ -0,0 +1,218 @@
/*******************************************************************************
* Copyright (c) 2012, 2023 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
* Frank Pagliughi - loop to repeatedly read and sent time values.
*******************************************************************************/
// This is a somewhat contrived example to show an application that publishes
// continuously, like a data acquisition app might do. In this case, though,
// we don't have a sensor to read, so we use the system time as the number
// of milliseconds since the epoch to simulate a data input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include "MQTTAsync.h"
#if !defined(_WIN32)
#include <unistd.h>
#else
#include <windows.h>
#include <Minwinbase.h>
#endif
#if defined(_WRS_KERNEL)
#include <OsWrapper.h>
#endif
#if defined(_WIN32)
#define snprintf _snprintf
#endif
// Better not to flood a public broker. Test against localhost.
#define ADDRESS "mqtt://localhost:1883"
#define CLIENTID "ExampleClientTimePub"
#define TOPIC "data/time"
#define QOS 1
#define TIMEOUT 10000L
#define SAMPLE_PERIOD 10L // in ms
volatile int finished = 0;
volatile int connected = 0;
void connlost(void *context, char *cause)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
printf("\nConnection lost\n");
if (cause)
printf(" cause: %s\n", cause);
printf("Reconnecting\n");
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
finished = 1;
}
}
void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Disconnect failed\n");
finished = 1;
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
printf("Successful disconnection\n");
finished = 1;
}
void onSendFailure(void* context, MQTTAsync_failureData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
printf("Message send failed token %d error code %d\n", response->token, response->code);
opts.onSuccess = onDisconnect;
opts.onFailure = onDisconnectFailure;
opts.context = client;
if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start disconnect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
void onSend(void* context, MQTTAsync_successData* response)
{
// This gets called when a message is acknowledged successfully.
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Connect failed, rc %d\n", response ? response->code : 0);
finished = 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
printf("Successful connection\n");
connected = 1;
}
int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
{
/* not expecting any messages */
return 1;
}
int64_t getTime(void)
{
#if defined(_WIN32)
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
return ((((int64_t) ft.dwHighDateTime) << 8) + ft.dwLowDateTime) / 10000;
#else
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return ((int64_t) ts.tv_sec * 1000) + ((int64_t) ts.tv_nsec / 1000000);
#endif
}
int main(int argc, char* argv[])
{
MQTTAsync client;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
MQTTAsync_responseOptions pub_opts = MQTTAsync_responseOptions_initializer;
int rc;
if ((rc = MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTASYNC_SUCCESS)
{
printf("Failed to create client object, return code %d\n", rc);
exit(EXIT_FAILURE);
}
if ((rc = MQTTAsync_setCallbacks(client, client, connlost, messageArrived, NULL)) != MQTTASYNC_SUCCESS)
{
printf("Failed to set callback, return code %d\n", rc);
exit(EXIT_FAILURE);
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
while (!connected) {
#if defined(_WIN32)
Sleep(100);
#else
usleep(100000L);
#endif
}
while (!finished) {
int64_t t = getTime();
char buf[256];
int n = snprintf(buf, sizeof(buf), "%lld", (long long) t);
printf("%s\n", buf);
pub_opts.onSuccess = onSend;
pub_opts.onFailure = onSendFailure;
pub_opts.context = client;
pubmsg.payload = buf;
pubmsg.payloadlen = n;
pubmsg.qos = QOS;
pubmsg.retained = 0;
if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &pub_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
#if defined(_WIN32)
Sleep(SAMPLE_PERIOD);
#else
usleep(SAMPLE_PERIOD * 1000);
#endif
}
MQTTAsync_destroy(&client);
return rc;
}

View File

@@ -0,0 +1,206 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTAsync.h"
#if !defined(_WIN32)
#include <unistd.h>
#else
#include <windows.h>
#endif
#if defined(_WRS_KERNEL)
#include <OsWrapper.h>
#endif
#define ADDRESS "tcp://test.mosquitto.org:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "MQTT Examples"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L
int disc_finished = 0;
int subscribed = 0;
int finished = 0;
void onConnect(void* context, MQTTAsync_successData* response);
void onConnectFailure(void* context, MQTTAsync_failureData* response);
void connlost(void *context, char *cause)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
printf("\nConnection lost\n");
if (cause)
printf(" cause: %s\n", cause);
printf("Reconnecting\n");
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
finished = 1;
}
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
{
printf("Message arrived\n");
printf(" topic: %s\n", topicName);
printf(" message: %.*s\n", message->payloadlen, (char*)message->payload);
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Disconnect failed, rc %d\n", response->code);
disc_finished = 1;
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
printf("Successful disconnection\n");
disc_finished = 1;
}
void onSubscribe(void* context, MQTTAsync_successData* response)
{
printf("Subscribe succeeded\n");
subscribed = 1;
}
void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
printf("Subscribe failed, rc %d\n", response->code);
finished = 1;
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Connect failed, rc %d\n", response->code);
finished = 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
printf("Successful connection\n");
printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
"Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
opts.onSuccess = onSubscribe;
opts.onFailure = onSubscribeFailure;
opts.context = client;
if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start subscribe, return code %d\n", rc);
finished = 1;
}
}
int main(int argc, char* argv[])
{
MQTTAsync client;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
int rc;
int ch;
const char* uri = (argc > 1) ? argv[1] : ADDRESS;
printf("Using server at %s\n", uri);
if ((rc = MQTTAsync_create(&client, uri, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL))
!= MQTTASYNC_SUCCESS)
{
printf("Failed to create client, return code %d\n", rc);
rc = EXIT_FAILURE;
goto exit;
}
if ((rc = MQTTAsync_setCallbacks(client, client, connlost, msgarrvd, NULL)) != MQTTASYNC_SUCCESS)
{
printf("Failed to set callbacks, return code %d\n", rc);
rc = EXIT_FAILURE;
goto destroy_exit;
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
rc = EXIT_FAILURE;
goto destroy_exit;
}
while (!subscribed && !finished)
#if defined(_WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
if (finished)
goto exit;
do
{
ch = getchar();
} while (ch!='Q' && ch != 'q');
disc_opts.onSuccess = onDisconnect;
disc_opts.onFailure = onDisconnectFailure;
if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start disconnect, return code %d\n", rc);
rc = EXIT_FAILURE;
goto destroy_exit;
}
while (!disc_finished)
{
#if defined(_WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
}
destroy_exit:
MQTTAsync_destroy(&client);
exit:
return rc;
}

View File

@@ -0,0 +1,75 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#define ADDRESS "tcp://test.mosquitto.org:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "MQTT Examples"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
const char* uri = (argc > 1) ? argv[1] : ADDRESS;
printf("Using server at %s\n", uri);
if ((rc = MQTTClient_create(&client, uri, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to create client, return code %d\n", rc);
exit(EXIT_FAILURE);
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
if ((rc = MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to publish message, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Waiting for up to %d seconds for publication of %s\n"
"on topic %s for client with ClientID: %s\n",
(int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf("Message with delivery token %d delivered\n", token);
if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
printf("Failed to disconnect, return code %d\n", rc);
MQTTClient_destroy(&client);
return rc;
}

View File

@@ -0,0 +1,131 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#if !defined(_WIN32)
#include <unistd.h>
#else
#include <windows.h>
#endif
#define ADDRESS "tcp://test.mosquitto.org:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "MQTT Examples"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L
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)
{
printf("Message arrived\n");
printf(" topic: %s\n", topicName);
printf(" message: %.*s\n", message->payloadlen, (char*)message->payload);
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
void connlost(void *context, char *cause)
{
printf("\nConnection lost\n");
if (cause)
printf(" cause: %s\n", cause);
}
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
const char* uri = (argc > 1) ? argv[1] : ADDRESS;
printf("Using server at %s\n", uri);
if ((rc = MQTTClient_create(&client, uri, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to create client, return code %d\n", rc);
rc = EXIT_FAILURE;
goto exit;
}
if ((rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to set callbacks, return code %d\n", rc);
rc = EXIT_FAILURE;
goto destroy_exit;
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
rc = EXIT_FAILURE;
goto destroy_exit;
}
pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
deliveredtoken = 0;
if ((rc = MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to publish message, return code %d\n", rc);
rc = EXIT_FAILURE;
}
else
{
printf("Waiting for publication of %s\n"
"on topic %s for client with ClientID: %s\n",
PAYLOAD, TOPIC, CLIENTID);
while (deliveredtoken != token)
{
#if defined(_WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
}
}
if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to disconnect, return code %d\n", rc);
rc = EXIT_FAILURE;
}
destroy_exit:
MQTTClient_destroy(&client);
exit:
return rc;
}

View File

@@ -0,0 +1,118 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#define ADDRESS "tcp://test.mosquitto.org:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "MQTT Examples"
#define PAYLOAD "Hello World!"
#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)
{
printf("Message arrived\n");
printf(" topic: %s\n", topicName);
printf(" message: %.*s\n", message->payloadlen, (char*)message->payload);
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
void connlost(void *context, char *cause)
{
printf("\nConnection lost\n");
if (cause)
printf(" cause: %s\n", cause);
}
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
int rc;
const char* uri = (argc > 1) ? argv[1] : ADDRESS;
printf("Using server at %s\n", uri);
if ((rc = MQTTClient_create(&client, uri, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to create client, return code %d\n", rc);
rc = EXIT_FAILURE;
goto exit;
}
if ((rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to set callbacks, return code %d\n", rc);
rc = EXIT_FAILURE;
goto destroy_exit;
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
rc = EXIT_FAILURE;
goto destroy_exit;
}
printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
"Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
if ((rc = MQTTClient_subscribe(client, TOPIC, QOS)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to subscribe, return code %d\n", rc);
rc = EXIT_FAILURE;
}
else
{
int ch;
do
{
ch = getchar();
} while (ch!='Q' && ch != 'q');
if ((rc = MQTTClient_unsubscribe(client, TOPIC)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to unsubscribe, return code %d\n", rc);
rc = EXIT_FAILURE;
}
}
if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to disconnect, return code %d\n", rc);
rc = EXIT_FAILURE;
}
destroy_exit:
MQTTClient_destroy(&client);
exit:
return rc;
}

View File

@@ -0,0 +1,519 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
* Guilherme Maciel Ferreira - add keep alive option
* Ian Craggs - add full capability
*******************************************************************************/
#include "MQTTAsync.h"
#include "pubsub_opts.h"
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <windows.h>
#define sleep Sleep
#else
#include <unistd.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#if defined(_WRS_KERNEL)
#include <OsWrapper.h>
#endif
volatile int toStop = 0;
struct pubsub_opts opts =
{
1, 0, 0, 0, "\n", 100, /* debug/app options */
NULL, NULL, 1, 0, 0, /* message options */
MQTTVERSION_DEFAULT, NULL, "paho-c-pub", 0, 0, NULL, NULL, "localhost", "1883", NULL, 10, /* MQTT options */
NULL, NULL, 0, 0, /* will options */
0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* TLS options */
0, {NULL, NULL}, /* MQTT V5 options */
NULL, NULL, /* HTTP and HTTPS proxies */
};
MQTTAsync_responseOptions pub_opts = MQTTAsync_responseOptions_initializer;
MQTTProperty property;
MQTTProperties props = MQTTProperties_initializer;
void mysleep(int ms)
{
#if defined(_WIN32)
Sleep(ms);
#else
usleep(ms * 1000);
#endif
}
void cfinish(int sig)
{
signal(SIGINT, NULL);
toStop = 1;
}
int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
{
/* not expecting any messages */
return 1;
}
static int disconnected = 0;
void onDisconnect5(void* context, MQTTAsync_successData5* response)
{
disconnected = 1;
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
disconnected = 1;
}
static int connected = 0;
void myconnect(MQTTAsync client);
int mypublish(MQTTAsync client, int datalen, char* data);
void onConnectFailure5(void* context, MQTTAsync_failureData5* response)
{
fprintf(stderr, "Connect failed, rc %s reason code %s\n",
MQTTAsync_strerror(response->code),
MQTTReasonCode_toString(response->reasonCode));
connected = -1;
MQTTAsync client = (MQTTAsync)context;
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
fprintf(stderr, "Connect failed, rc %s\n", response ? MQTTAsync_strerror(response->code) : "none");
connected = -1;
MQTTAsync client = (MQTTAsync)context;
}
void onConnect5(void* context, MQTTAsync_successData5* response)
{
MQTTAsync client = (MQTTAsync)context;
int rc = 0;
if (opts.verbose)
printf("Connected\n");
if (opts.null_message == 1)
rc = mypublish(client, 0, "");
else if (opts.message)
rc = mypublish(client, (int)strlen(opts.message), opts.message);
else if (opts.filename)
{
int data_len = 0;
char* buffer = readfile(&data_len, &opts);
if (buffer == NULL)
toStop = 1;
else
{
rc = mypublish(client, data_len, buffer);
free(buffer);
}
}
connected = 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
int rc = 0;
if (opts.verbose)
printf("Connected\n");
if (opts.null_message == 1)
rc = mypublish(client, 0, "");
else if (opts.message)
rc = mypublish(client, (int)strlen(opts.message), opts.message);
else if (opts.filename)
{
int data_len = 0;
char* buffer = readfile(&data_len, &opts);
if (buffer == NULL)
toStop = 1;
else
{
rc = mypublish(client, data_len, buffer);
free(buffer);
}
}
connected = 1;
}
static int published = 0;
void onPublishFailure5(void* context, MQTTAsync_failureData5* response)
{
if (opts.verbose)
fprintf(stderr, "Publish failed, rc %s reason code %s\n",
MQTTAsync_strerror(response->code),
MQTTReasonCode_toString(response->reasonCode));
published = -1;
}
void onPublishFailure(void* context, MQTTAsync_failureData* response)
{
if (opts.verbose)
fprintf(stderr, "Publish failed, rc %s\n", MQTTAsync_strerror(response->code));
published = -1;
}
void onPublish5(void* context, MQTTAsync_successData5* response)
{
if (opts.verbose)
printf("Publish succeeded, reason code %s\n",
MQTTReasonCode_toString(response->reasonCode));
if (opts.null_message || opts.message || opts.filename)
toStop = 1;
published = 1;
}
void onPublish(void* context, MQTTAsync_successData* response)
{
if (opts.verbose)
printf("Publish succeeded\n");
if (opts.null_message || opts.message || opts.filename)
toStop = 1;
published = 1;
}
static int onSSLError(const char *str, size_t len, void *context)
{
MQTTAsync client = (MQTTAsync)context;
return fprintf(stderr, "SSL error: %s\n", str);
}
static unsigned int onPSKAuth(const char* hint,
char* identity,
unsigned int max_identity_len,
unsigned char* psk,
unsigned int max_psk_len,
void* context)
{
int psk_len;
int k, n;
int rc = 0;
struct pubsub_opts* opts = context;
/* printf("Trying TLS-PSK auth with hint: %s\n", hint);*/
if (opts->psk == NULL || opts->psk_identity == NULL)
{
/* printf("No PSK entered\n"); */
goto exit;
}
/* psk should be array of bytes. This is a quick and dirty way to
* convert hex to bytes without input validation */
psk_len = (int)strlen(opts->psk) / 2;
if (psk_len > max_psk_len)
{
fprintf(stderr, "PSK too long\n");
goto exit;
}
for (k=0, n=0; k < psk_len; k++, n += 2)
{
sscanf(&opts->psk[n], "%2hhx", &psk[k]);
}
/* identity should be NULL terminated string */
strncpy(identity, opts->psk_identity, max_identity_len);
if (identity[max_identity_len - 1] != '\0')
{
fprintf(stderr, "Identity too long\n");
goto exit;
}
/* Function should return length of psk on success. */
rc = psk_len;
exit:
return rc;
}
void myconnect(MQTTAsync client)
{
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
int rc = 0;
if (opts.verbose)
printf("Connecting\n");
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTAsync_connectOptions conn_opts5 = MQTTAsync_connectOptions_initializer5;
conn_opts = conn_opts5;
conn_opts.onSuccess5 = onConnect5;
conn_opts.onFailure5 = onConnectFailure5;
conn_opts.cleanstart = 1;
}
else
{
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.cleansession = 1;
}
conn_opts.keepAliveInterval = opts.keepalive;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.MQTTVersion = opts.MQTTVersion;
conn_opts.context = client;
conn_opts.automaticReconnect = 1;
conn_opts.httpProxy = opts.http_proxy;
conn_opts.httpsProxy = opts.https_proxy;
if (opts.will_topic) /* will options */
{
will_opts.message = opts.will_payload;
will_opts.topicName = opts.will_topic;
will_opts.qos = opts.will_qos;
will_opts.retained = opts.will_retain;
conn_opts.will = &will_opts;
}
if (opts.connection && (strncmp(opts.connection, "ssl://", 6) == 0 ||
strncmp(opts.connection, "tls://", 6) == 0 ||
strncmp(opts.connection, "mqtts://", 7) == 0 ||
strncmp(opts.connection, "wss://", 6) == 0))
{
if (opts.insecure)
ssl_opts.verify = 0;
else
ssl_opts.verify = 1;
ssl_opts.CApath = opts.capath;
ssl_opts.keyStore = opts.cert;
ssl_opts.trustStore = opts.cafile;
ssl_opts.privateKey = opts.key;
ssl_opts.privateKeyPassword = opts.keypass;
ssl_opts.enabledCipherSuites = opts.ciphers;
ssl_opts.ssl_error_cb = onSSLError;
ssl_opts.ssl_error_context = client;
ssl_opts.ssl_psk_cb = onPSKAuth;
ssl_opts.ssl_psk_context = &opts;
conn_opts.ssl = &ssl_opts;
}
connected = 0;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
fprintf(stderr, "Failed to start connect, return code %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
}
int mypublish(MQTTAsync client, int datalen, char* data)
{
int rc;
if (opts.verbose)
printf("Publishing data of length %d\n", datalen);
rc = MQTTAsync_send(client, opts.topic, datalen, data, opts.qos, opts.retained, &pub_opts);
if (opts.verbose && rc != MQTTASYNC_SUCCESS && !opts.quiet)
fprintf(stderr, "Error from MQTTAsync_send: %s\n", MQTTAsync_strerror(rc));
return rc;
}
void trace_callback(enum MQTTASYNC_TRACE_LEVELS level, char* message)
{
fprintf(stderr, "Trace : %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
MQTTAsync_createOptions create_opts = MQTTAsync_createOptions_initializer;
MQTTAsync client;
char* buffer = NULL;
char* url = NULL;
int url_allocated = 0;
int rc = 0;
const char* version = NULL;
const char* program_name = "paho_c_pub";
MQTTAsync_nameValue* infos = MQTTAsync_getVersionInfo();
#if !defined(_WIN32)
struct sigaction sa;
#endif
if (argc < 2)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (getopts(argc, argv, &opts) != 0)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (opts.connection)
url = opts.connection;
else
{
url = malloc(100);
url_allocated = 1;
sprintf(url, "%s:%s", opts.host, opts.port);
}
if (opts.verbose)
printf("URL is %s\n", url);
if (opts.tracelevel > 0)
{
MQTTAsync_setTraceCallback(trace_callback);
MQTTAsync_setTraceLevel(opts.tracelevel);
}
create_opts.sendWhileDisconnected = 1;
if (opts.MQTTVersion >= MQTTVERSION_5)
create_opts.MQTTVersion = MQTTVERSION_5;
rc = MQTTAsync_createWithOptions(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL, &create_opts);
if (rc != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to create client, return code: %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
#if defined(_WIN32)
signal(SIGINT, cfinish);
signal(SIGTERM, cfinish);
#else
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = cfinish;
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
#endif
rc = MQTTAsync_setCallbacks(client, client, NULL, messageArrived, NULL);
if (rc != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to set callbacks, return code: %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
if (opts.MQTTVersion >= MQTTVERSION_5)
{
pub_opts.onSuccess5 = onPublish5;
pub_opts.onFailure5 = onPublishFailure5;
if (opts.message_expiry > 0)
{
property.identifier = MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL;
property.value.integer4 = opts.message_expiry;
MQTTProperties_add(&props, &property);
}
if (opts.user_property.name)
{
property.identifier = MQTTPROPERTY_CODE_USER_PROPERTY;
property.value.data.data = opts.user_property.name;
property.value.data.len = (int)strlen(opts.user_property.name);
property.value.value.data = opts.user_property.value;
property.value.value.len = (int)strlen(opts.user_property.value);
MQTTProperties_add(&props, &property);
}
pub_opts.properties = props;
}
else
{
pub_opts.onSuccess = onPublish;
pub_opts.onFailure = onPublishFailure;
}
myconnect(client);
while (!toStop)
{
int data_len = 0;
int delim_len = 0;
if (opts.stdin_lines)
{
buffer = malloc(opts.maxdatalen);
delim_len = (int)strlen(opts.delimiter);
do
{
buffer[data_len++] = getchar();
if (data_len > delim_len)
{
if (strncmp(opts.delimiter, &buffer[data_len - delim_len], delim_len) == 0)
break;
}
} while (data_len < opts.maxdatalen);
rc = mypublish(client, data_len, buffer);
}
else
mysleep(100);
}
if (opts.message == 0 && opts.null_message == 0 && opts.filename == 0)
free(buffer);
if (opts.MQTTVersion >= MQTTVERSION_5)
disc_opts.onSuccess5 = onDisconnect5;
else
disc_opts.onSuccess = onDisconnect;
if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to start disconnect, return code: %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
while (!disconnected)
mysleep(100);
MQTTAsync_destroy(&client);
if (url_allocated)
free(url);
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,351 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
* Ian Craggs - fix for bug 413429 - connectionLost not called
* Guilherme Maciel Ferreira - add keep alive option
* Ian Craggs - add full capability
*******************************************************************************/
#include "MQTTAsync.h"
#include "MQTTClientPersistence.h"
#include "pubsub_opts.h"
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <windows.h>
#define sleep Sleep
#else
#include <sys/time.h>
#include <unistd.h>
#endif
#if defined(_WRS_KERNEL)
#include <OsWrapper.h>
#endif
volatile int finished = 0;
int subscribed = 0;
int disconnected = 0;
void mysleep(int ms)
{
#if defined(_WIN32)
Sleep(ms);
#else
usleep(ms * 1000);
#endif
}
void cfinish(int sig)
{
signal(SIGINT, NULL);
finished = 1;
}
struct pubsub_opts opts =
{
0, 0, 0, 0, "\n", 100, /* debug/app options */
NULL, NULL, 1, 0, 0, /* message options */
MQTTVERSION_DEFAULT, NULL, "paho-c-sub", 0, 0, NULL, NULL, "localhost", "1883", NULL, 10, /* MQTT options */
NULL, NULL, 0, 0, /* will options */
0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* TLS options */
0, {NULL, NULL}, /* MQTT V5 options */
NULL, NULL, /* HTTP and HTTPS proxies */
};
int messageArrived(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
{
size_t delimlen = 0;
if (opts.verbose)
printf("%d %s\t", message->payloadlen, topicName);
if (opts.delimiter)
delimlen = strlen(opts.delimiter);
if (opts.delimiter == NULL || (message->payloadlen > delimlen &&
strncmp(opts.delimiter, &((char*)message->payload)[message->payloadlen - delimlen], delimlen) == 0))
printf("%.*s", message->payloadlen, (char*)message->payload);
else
printf("%.*s%s", message->payloadlen, (char*)message->payload, opts.delimiter);
if (message->struct_version == 1 && opts.verbose)
logProperties(&message->properties);
fflush(stdout);
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
disconnected = 1;
}
void onSubscribe5(void* context, MQTTAsync_successData5* response)
{
subscribed = 1;
}
void onSubscribe(void* context, MQTTAsync_successData* response)
{
subscribed = 1;
}
void onSubscribeFailure5(void* context, MQTTAsync_failureData5* response)
{
if (!opts.quiet)
fprintf(stderr, "Subscribe failed, rc %s reason code %s\n",
MQTTAsync_strerror(response->code),
MQTTReasonCode_toString(response->reasonCode));
finished = 1;
}
void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
if (!opts.quiet)
fprintf(stderr, "Subscribe failed, rc %s\n",
MQTTAsync_strerror(response->code));
finished = 1;
}
void onConnectFailure5(void* context, MQTTAsync_failureData5* response)
{
if (!opts.quiet)
fprintf(stderr, "Connect failed, rc %s reason code %s\n",
MQTTAsync_strerror(response->code),
MQTTReasonCode_toString(response->reasonCode));
finished = 1;
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
if (!opts.quiet)
fprintf(stderr, "Connect failed, rc %s\n", response ? MQTTAsync_strerror(response->code) : "none");
finished = 1;
}
void onConnect5(void* context, MQTTAsync_successData5* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_callOptions copts = MQTTAsync_callOptions_initializer;
int rc;
if (opts.verbose)
printf("Subscribing to topic %s with client %s at QoS %d\n", opts.topic, opts.clientid, opts.qos);
copts.onSuccess5 = onSubscribe5;
copts.onFailure5 = onSubscribeFailure5;
copts.context = client;
if ((rc = MQTTAsync_subscribe(client, opts.topic, opts.qos, &copts)) != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to start subscribe, return code %s\n", MQTTAsync_strerror(rc));
finished = 1;
}
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions ropts = MQTTAsync_responseOptions_initializer;
int rc;
if (opts.verbose)
printf("Subscribing to topic %s with client %s at QoS %d\n", opts.topic, opts.clientid, opts.qos);
ropts.onSuccess = onSubscribe;
ropts.onFailure = onSubscribeFailure;
ropts.context = client;
if ((rc = MQTTAsync_subscribe(client, opts.topic, opts.qos, &ropts)) != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to start subscribe, return code %s\n", MQTTAsync_strerror(rc));
finished = 1;
}
}
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
void trace_callback(enum MQTTASYNC_TRACE_LEVELS level, char* message)
{
fprintf(stderr, "Trace : %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
MQTTAsync client;
MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
MQTTAsync_createOptions create_opts = MQTTAsync_createOptions_initializer;
MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
char* url = NULL;
const char* version = NULL;
const char* program_name = "paho_c_sub";
MQTTAsync_nameValue* infos = MQTTAsync_getVersionInfo();
#if !defined(_WIN32)
struct sigaction sa;
#endif
if (argc < 2)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (getopts(argc, argv, &opts) != 0)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (strchr(opts.topic, '#') || strchr(opts.topic, '+'))
opts.verbose = 1;
if (opts.connection)
url = opts.connection;
else
{
url = malloc(100);
sprintf(url, "%s:%s", opts.host, opts.port);
}
if (opts.verbose)
printf("URL is %s\n", url);
if (opts.tracelevel > 0)
{
MQTTAsync_setTraceCallback(trace_callback);
MQTTAsync_setTraceLevel(opts.tracelevel);
}
if (opts.MQTTVersion >= MQTTVERSION_5)
create_opts.MQTTVersion = MQTTVERSION_5;
rc = MQTTAsync_createWithOptions(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE,
NULL, &create_opts);
if (rc != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to create client, return code: %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
rc = MQTTAsync_setCallbacks(client, client, NULL, messageArrived, NULL);
if (rc != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to set callbacks, return code: %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
#if defined(_WIN32)
signal(SIGINT, cfinish);
signal(SIGTERM, cfinish);
#else
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = cfinish;
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
#endif
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTAsync_connectOptions conn_opts5 = MQTTAsync_connectOptions_initializer5;
conn_opts = conn_opts5;
conn_opts.onSuccess5 = onConnect5;
conn_opts.onFailure5 = onConnectFailure5;
conn_opts.cleanstart = 1;
}
else
{
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.cleansession = 1;
}
conn_opts.keepAliveInterval = opts.keepalive;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.MQTTVersion = opts.MQTTVersion;
conn_opts.context = client;
conn_opts.automaticReconnect = 1;
conn_opts.httpProxy = opts.http_proxy;
conn_opts.httpsProxy = opts.https_proxy;
if (opts.will_topic) /* will options */
{
will_opts.message = opts.will_payload;
will_opts.topicName = opts.will_topic;
will_opts.qos = opts.will_qos;
will_opts.retained = opts.will_retain;
conn_opts.will = &will_opts;
}
if (opts.connection && (strncmp(opts.connection, "ssl://", 6) == 0 ||
strncmp(opts.connection, "tls://", 6) == 0||
strncmp(opts.connection, "mqtts://", 7) == 0 ||
strncmp(opts.connection, "wss://", 6) == 0))
{
ssl_opts.verify = (opts.insecure) ? 0 : 1;
ssl_opts.CApath = opts.capath;
ssl_opts.keyStore = opts.cert;
ssl_opts.trustStore = opts.cafile;
ssl_opts.privateKey = opts.key;
ssl_opts.privateKeyPassword = opts.keypass;
ssl_opts.enabledCipherSuites = opts.ciphers;
conn_opts.ssl = &ssl_opts;
}
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to start connect, return code %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
while (!subscribed)
mysleep(100);
if (finished)
goto exit;
while (!finished)
mysleep(100);
disc_opts.onSuccess = onDisconnect;
if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to start disconnect, return code: %s\n", MQTTAsync_strerror(rc));
exit(EXIT_FAILURE);
}
while (!disconnected)
mysleep(100);
exit:
MQTTAsync_destroy(&client);
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,327 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
* Ian Craggs - add full capability
*******************************************************************************/
#include "MQTTClient.h"
#include "MQTTClientPersistence.h"
#include "pubsub_opts.h"
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#if defined(_WIN32)
#define sleep Sleep
#else
#include <sys/time.h>
#endif
volatile int toStop = 0;
void cfinish(int sig)
{
signal(SIGINT, NULL);
toStop = 1;
}
struct pubsub_opts opts =
{
1, 0, 0, 0, "\n", 100, /* debug/app options */
NULL, NULL, 1, 0, 0, /* message options */
MQTTVERSION_DEFAULT, NULL, "paho-cs-pub", 0, 0, NULL, NULL, "localhost", "1883", NULL, 10, /* MQTT options */
NULL, NULL, 0, 0, /* will options */
0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* TLS options */
0, {NULL, NULL}, /* MQTT V5 options */
NULL, NULL, /* HTTP and HTTPS proxies */
};
int myconnect(MQTTClient client)
{
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;
MQTTClient_willOptions will_opts = MQTTClient_willOptions_initializer;
int rc = 0;
if (opts.verbose)
printf("Connecting\n");
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTClient_connectOptions conn_opts5 = MQTTClient_connectOptions_initializer5;
conn_opts = conn_opts5;
}
conn_opts.keepAliveInterval = opts.keepalive;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.MQTTVersion = opts.MQTTVersion;
conn_opts.httpProxy = opts.http_proxy;
conn_opts.httpsProxy = opts.https_proxy;
if (opts.will_topic) /* will options */
{
will_opts.message = opts.will_payload;
will_opts.topicName = opts.will_topic;
will_opts.qos = opts.will_qos;
will_opts.retained = opts.will_retain;
conn_opts.will = &will_opts;
}
if (opts.connection && (strncmp(opts.connection, "ssl://", 6) == 0 ||
strncmp(opts.connection, "tls://", 6) == 0 ||
strncmp(opts.connection, "mqtts://", 7) == 0 ||
strncmp(opts.connection, "wss://", 6) == 0))
{
if (opts.insecure)
ssl_opts.verify = 0;
else
ssl_opts.verify = 1;
ssl_opts.CApath = opts.capath;
ssl_opts.keyStore = opts.cert;
ssl_opts.trustStore = opts.cafile;
ssl_opts.privateKey = opts.key;
ssl_opts.privateKeyPassword = opts.keypass;
ssl_opts.enabledCipherSuites = opts.ciphers;
conn_opts.ssl = &ssl_opts;
}
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTProperties props = MQTTProperties_initializer;
MQTTProperties willProps = MQTTProperties_initializer;
MQTTResponse response = MQTTResponse_initializer;
conn_opts.cleanstart = 1;
response = MQTTClient_connect5(client, &conn_opts, &props, &willProps);
rc = response.reasonCode;
MQTTResponse_free(response);
}
else
{
conn_opts.cleansession = 1;
rc = MQTTClient_connect(client, &conn_opts);
}
if (opts.verbose && rc == MQTTCLIENT_SUCCESS)
printf("Connected\n");
else if (rc != MQTTCLIENT_SUCCESS && !opts.quiet)
fprintf(stderr, "Connect failed return code: %s\n", MQTTClient_strerror(rc));
return rc;
}
int messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* m)
{
/* not expecting any messages */
return 1;
}
void connectionLost(void* context, char* reason)
{
MQTTClient client = (MQTTClient)context;
if (opts.verbose)
printf("ConnectionLost, reconnecting\n");
myconnect(client);
}
void trace_callback(enum MQTTCLIENT_TRACE_LEVELS level, char* message)
{
fprintf(stderr, "Trace : %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
MQTTClient client;
MQTTProperties pub_props = MQTTProperties_initializer;
MQTTClient_createOptions createOpts = MQTTClient_createOptions_initializer;
MQTTClient_deliveryToken last_token;
char* buffer = NULL;
int rc = 0;
char* url;
const char* version = NULL;
#if !defined(_WIN32)
struct sigaction sa;
#endif
const char* program_name = "paho_cs_pub";
MQTTClient_nameValue* infos = MQTTClient_getVersionInfo();
if (argc < 2)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (getopts(argc, argv, &opts) != 0)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (opts.connection)
url = opts.connection;
else
{
url = malloc(100);
sprintf(url, "%s:%s", opts.host, opts.port);
}
if (opts.verbose)
printf("URL is %s\n", url);
if (opts.tracelevel > 0)
{
MQTTClient_setTraceCallback(trace_callback);
MQTTClient_setTraceLevel(opts.tracelevel);
}
if (opts.MQTTVersion >= MQTTVERSION_5)
createOpts.MQTTVersion = MQTTVERSION_5;
rc = MQTTClient_createWithOptions(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE,
NULL, &createOpts);
if (rc != MQTTCLIENT_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to create client, return code: %s\n", MQTTClient_strerror(rc));
exit(EXIT_FAILURE);
}
#if defined(_WIN32)
signal(SIGINT, cfinish);
signal(SIGTERM, cfinish);
#else
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = cfinish;
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
#endif
rc = MQTTClient_setCallbacks(client, client, connectionLost, messageArrived, NULL);
if (rc != MQTTCLIENT_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to set callbacks, return code: %s\n", MQTTClient_strerror(rc));
exit(EXIT_FAILURE);
}
if (myconnect(client) != MQTTCLIENT_SUCCESS)
goto exit;
if (opts.MQTTVersion >= MQTTVERSION_5)
{
MQTTProperty property;
if (opts.message_expiry > 0)
{
property.identifier = MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL;
property.value.integer4 = opts.message_expiry;
MQTTProperties_add(&pub_props, &property);
}
if (opts.user_property.name)
{
property.identifier = MQTTPROPERTY_CODE_USER_PROPERTY;
property.value.data.data = opts.user_property.name;
property.value.data.len = (int)strlen(opts.user_property.name);
property.value.value.data = opts.user_property.value;
property.value.value.len = (int)strlen(opts.user_property.value);
MQTTProperties_add(&pub_props, &property);
}
}
while (!toStop)
{
int data_len = 0;
int delim_len = 0;
if (opts.stdin_lines)
{
buffer = malloc(opts.maxdatalen);
delim_len = (int)strlen(opts.delimiter);
do
{
int c = getchar();
if (c < 0)
goto exit;
buffer[data_len++] = c;
if (data_len > delim_len)
{
if (strncmp(opts.delimiter, &buffer[data_len - delim_len], delim_len) == 0)
break;
}
} while (data_len < opts.maxdatalen);
}
else if (opts.message)
{
buffer = opts.message;
data_len = (int)strlen(opts.message);
}
else if (opts.filename)
{
buffer = readfile(&data_len, &opts);
if (buffer == NULL)
goto exit;
}
if (opts.verbose)
fprintf(stderr, "Publishing data of length %d\n", data_len);
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTResponse response = MQTTResponse_initializer;
response = MQTTClient_publish5(client, opts.topic, data_len, buffer, opts.qos, opts.retained, &pub_props, &last_token);
rc = response.reasonCode;
}
else
rc = MQTTClient_publish(client, opts.topic, data_len, buffer, opts.qos, opts.retained, &last_token);
if (opts.stdin_lines == 0)
break;
if (rc != 0)
{
myconnect(client);
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTResponse response = MQTTResponse_initializer;
response = MQTTClient_publish5(client, opts.topic, data_len, buffer, opts.qos, opts.retained, &pub_props, &last_token);
rc = response.reasonCode;
}
else
rc = MQTTClient_publish(client, opts.topic, data_len, buffer, opts.qos, opts.retained, &last_token);
}
if (opts.qos > 0)
MQTTClient_yield();
}
rc = MQTTClient_waitForCompletion(client, last_token, 5000);
exit:
if (opts.filename || opts.stdin_lines)
free(buffer);
if (opts.MQTTVersion == MQTTVERSION_5)
rc = MQTTClient_disconnect5(client, 0, MQTTREASONCODE_SUCCESS, NULL);
else
rc = MQTTClient_disconnect(client, 0);
MQTTClient_destroy(&client);
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,257 @@
/*******************************************************************************
* Copyright (c) 2012, 2025 IBM Corp., Ian Craggs and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
* Ian Craggs - change delimiter option from char to string
* Guilherme Maciel Ferreira - add keep alive option
* Ian Craggs - add full capability
*******************************************************************************/
#include "MQTTClient.h"
#include "MQTTClientPersistence.h"
#include "pubsub_opts.h"
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#if defined(_WIN32)
#define sleep Sleep
#else
#include <sys/time.h>
#endif
volatile int toStop = 0;
struct pubsub_opts opts =
{
0, 0, 0, 0, "\n", 100, /* debug/app options */
NULL, NULL, 1, 0, 0, /* message options */
MQTTVERSION_DEFAULT, NULL, "paho-cs-sub", 0, 0, NULL, NULL, "localhost", "1883", NULL, 10, /* MQTT options */
NULL, NULL, 0, 0, /* will options */
0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* TLS options */
0, {NULL, NULL}, /* MQTT V5 options */
NULL, NULL, /* HTTP and HTTPS proxies */
};
int myconnect(MQTTClient client)
{
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;
MQTTClient_willOptions will_opts = MQTTClient_willOptions_initializer;
int rc = 0;
if (opts.verbose)
printf("Connecting\n");
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTClient_connectOptions conn_opts5 = MQTTClient_connectOptions_initializer5;
conn_opts = conn_opts5;
}
conn_opts.keepAliveInterval = opts.keepalive;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.MQTTVersion = opts.MQTTVersion;
conn_opts.httpProxy = opts.http_proxy;
conn_opts.httpsProxy = opts.https_proxy;
if (opts.will_topic) /* will options */
{
will_opts.message = opts.will_payload;
will_opts.topicName = opts.will_topic;
will_opts.qos = opts.will_qos;
will_opts.retained = opts.will_retain;
conn_opts.will = &will_opts;
}
if (opts.connection && (strncmp(opts.connection, "ssl://", 6) == 0 ||
strncmp(opts.connection, "tls://", 6) == 0 ||
strncmp(opts.connection, "mqtts://", 7) == 0 ||
strncmp(opts.connection, "wss://", 6) == 0))
{
if (opts.insecure)
ssl_opts.verify = 0;
else
ssl_opts.verify = 1;
ssl_opts.CApath = opts.capath;
ssl_opts.keyStore = opts.cert;
ssl_opts.trustStore = opts.cafile;
ssl_opts.privateKey = opts.key;
ssl_opts.privateKeyPassword = opts.keypass;
ssl_opts.enabledCipherSuites = opts.ciphers;
conn_opts.ssl = &ssl_opts;
}
if (opts.MQTTVersion == MQTTVERSION_5)
{
MQTTProperties props = MQTTProperties_initializer;
MQTTProperties willProps = MQTTProperties_initializer;
MQTTResponse response = MQTTResponse_initializer;
conn_opts.cleanstart = 1;
response = MQTTClient_connect5(client, &conn_opts, &props, &willProps);
rc = response.reasonCode;
MQTTResponse_free(response);
}
else
{
conn_opts.cleansession = 1;
rc = MQTTClient_connect(client, &conn_opts);
}
if (opts.verbose && rc == MQTTCLIENT_SUCCESS)
fprintf(stderr, "Connected\n");
else if (rc != MQTTCLIENT_SUCCESS && !opts.quiet)
fprintf(stderr, "Connect failed return code: %s\n", MQTTClient_strerror(rc));
return rc;
}
void cfinish(int sig)
{
signal(SIGINT, NULL);
toStop = 1;
}
void trace_callback(enum MQTTCLIENT_TRACE_LEVELS level, char* message)
{
fprintf(stderr, "Trace : %d, %s\n", level, message);
}
int main(int argc, char** argv)
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_createOptions createOpts = MQTTClient_createOptions_initializer;
int rc = 0;
char* url;
const char* version = NULL;
#if !defined(_WIN32)
struct sigaction sa;
#endif
const char* program_name = "paho_cs_sub";
MQTTClient_nameValue* infos = MQTTClient_getVersionInfo();
if (argc < 2)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (getopts(argc, argv, &opts) != 0)
usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
if (strchr(opts.topic, '#') || strchr(opts.topic, '+'))
opts.verbose = 1;
if (opts.connection)
url = opts.connection;
else
{
url = malloc(100);
sprintf(url, "%s:%s", opts.host, opts.port);
}
if (opts.verbose)
printf("URL is %s\n", url);
if (opts.tracelevel > 0)
{
MQTTClient_setTraceCallback(trace_callback);
MQTTClient_setTraceLevel(opts.tracelevel);
}
if (opts.MQTTVersion >= MQTTVERSION_5)
createOpts.MQTTVersion = MQTTVERSION_5;
rc = MQTTClient_createWithOptions(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE,
NULL, &createOpts);
if (rc != MQTTCLIENT_SUCCESS)
{
if (!opts.quiet)
fprintf(stderr, "Failed to create client, return code: %s\n", MQTTClient_strerror(rc));
exit(EXIT_FAILURE);
}
#if defined(_WIN32)
signal(SIGINT, cfinish);
signal(SIGTERM, cfinish);
#else
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = cfinish;
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
#endif
if (myconnect(client) != MQTTCLIENT_SUCCESS)
goto exit;
if (opts.MQTTVersion >= MQTTVERSION_5)
{
MQTTResponse response = MQTTClient_subscribe5(client, opts.topic, opts.qos, NULL, NULL);
rc = response.reasonCode;
MQTTResponse_free(response);
}
else
rc = MQTTClient_subscribe(client, opts.topic, opts.qos);
if (rc != MQTTCLIENT_SUCCESS && rc != opts.qos)
{
if (!opts.quiet)
fprintf(stderr, "Error %d subscribing to topic %s\n", rc, opts.topic);
goto exit;
}
while (!toStop)
{
char* topicName = NULL;
int topicLen;
MQTTClient_message* message = NULL;
rc = MQTTClient_receive(client, &topicName, &topicLen, &message, 1000);
if (rc == MQTTCLIENT_DISCONNECTED)
myconnect(client);
else if (message)
{
size_t delimlen = 0;
if (opts.verbose)
printf("%s\t", topicName);
if (opts.delimiter)
delimlen = strlen(opts.delimiter);
if (opts.delimiter == NULL || (message->payloadlen > delimlen &&
strncmp(opts.delimiter, &((char*)message->payload)[message->payloadlen - delimlen], delimlen) == 0))
printf("%.*s", message->payloadlen, (char*)message->payload);
else
printf("%.*s%s", message->payloadlen, (char*)message->payload, opts.delimiter);
if (message->struct_version == 1 && opts.verbose)
logProperties(&message->properties);
fflush(stdout);
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
}
}
exit:
MQTTClient_disconnect(client, 0);
MQTTClient_destroy(&client);
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,521 @@
/*******************************************************************************
* Copyright (c) 2012, 2018 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
*******************************************************************************/
#include "pubsub_opts.h"
#include <string.h>
#include <stdlib.h>
int printVersionInfo(pubsub_opts_nameValue* info)
{
int rc = 0;
printf("\nLibrary information:\n");
while (info->name)
{
printf("%s: %s\n", info->name, info->value);
info++;
rc = 1; /* at least one value printed */
}
if (rc == 1)
printf("\n");
return rc;
}
void usage(struct pubsub_opts* opts, pubsub_opts_nameValue* name_values, const char* program_name)
{
printf("Eclipse Paho MQTT C %s\n", opts->publisher ? "publisher" : "subscriber");
printVersionInfo(name_values);
printf("Usage: %s [topicname] [-t topic] [-c connection] [-h host] [-p port]\n"
" [-q qos] [-i clientid] [-u username] [-P password] [-k keepalive_timeout]\n"
, program_name);
printf(" [-V MQTT-version] [--quiet] [--trace trace-level]\n");
if (opts->publisher)
{
printf(" [-r] [-n] [-m message] [-f filename]\n");
printf(" [--maxdatalen len] [--message-expiry seconds] [--user-property name value]\n");
}
else
printf(" [-R] [--no-delimiter]\n");
printf(" [--will-topic topic] [--will-payload message] [--will-qos qos] [--will-retain]\n");
printf(" [--cafile filename] [--capath dirname] [--cert filename] [--key filename]\n"
" [--keypass string] [--ciphers string] [--insecure]");
printf(
"\n\n -t (--topic) : MQTT topic to %s to\n"
" -c (--connection) : connection string, overrides host/port e.g wss://hostname:port/ws. Use this option\n"
" rather than host/port to connect with TLS and/or web sockets. No default.\n"
" -h (--host) : host to connect to. Default is %s.\n"
" -p (--port) : network port to connect to. Default is %s.\n"
" -q (--qos) : MQTT QoS to %s with (0, 1 or 2). Default is %d.\n"
" -V (--MQTTversion) : MQTT version (31, 311, or 5). Default is 311.\n"
" --quiet : do not print error messages.\n"
" --trace : print internal trace (\"error\", \"min\", \"max\" or \"protocol\").\n",
opts->publisher ? "publish" : "subscribe", opts->host, opts->port,
opts->publisher ? "publish" : "subscribe", opts->qos);
if (opts->publisher)
{
printf(" -r (--retained) : use MQTT retain option. Default is off.\n");
printf(" -n (--null-message) : send 0-length message.\n");
printf(" -m (--message) : the payload to send.\n");
printf(" -f (--filename) : use the contents of the named file as the payload.\n");
}
printf(
" -i (--clientid) : MQTT client id. Default is %s.\n"
" -u (--username) : MQTT username. No default.\n"
" -P (--password) : MQTT password. No default.\n"
" -k (--keepalive) : MQTT keepalive timeout value. Default is %d seconds.\n"
" --delimiter : delimiter string. Default is \\n.\n",
opts->clientid, opts->keepalive);
if (opts->publisher)
{
printf(" --maxdatalen : maximum length of data to read when publishing strings (default is %d)\n",
opts->maxdatalen);
printf(" --message-expiry : MQTT 5 only. Sets the message expiry property in seconds.\n");
printf(" --user-property : MQTT 5 only. Sets a user property.\n");
}
else
{
printf(" --no-delimiter : do not use a delimiter string between messages.\n");
printf(" -R (--no-retained) : do not print retained messages.\n");
}
printf(
" --will-topic : will topic on connect. No default.\n"
" --will-payload : will message. If the will topic is set, but not payload, a null message will be set.\n"
" --will-retain : set the retained flag on the will message. The default is off.\n"
" --will-qos : the will message QoS. The default is 0.\n"
);
printf(
" --cafile : a filename for the TLS truststore.\n"
" --capath : a directory name containing TLS trusted server certificates.\n"
" --cert : a filename for the TLS keystore containing client certificates.\n"
" --key : client private key file.\n"
" --keypass : password for the client private key file.\n"
" --ciphers : the list of cipher suites that the client will present to the server during\n"
" the TLS handshake.\n"
" --insecure : don't check that the server certificate common name matches the hostname.\n"
" --psk : pre-shared-key in hexadecimal (no leading 0x) \n"
" --psk-identity : client identity string for TLS-PSK mode.\n"
);
printf(
" --http-proxy : HTTP proxy string.\n"
" --https-proxy : HTTPS proxy string.\n"
);
printf("\nSee http://eclipse.org/paho for more information about the Eclipse Paho project.\n");
exit(EXIT_FAILURE);
}
int getopts(int argc, char** argv, struct pubsub_opts* opts)
{
int count = 1;
if (argv[1][0] != '-')
{
opts->topic = argv[1];
count = 2;
}
while (count < argc)
{
if (strcmp(argv[count], "--verbose") == 0 || strcmp(argv[count], "-v") == 0)
opts->verbose = 1;
else if (strcmp(argv[count], "--quiet") == 0)
opts->quiet = 1;
else if (strcmp(argv[count], "--qos") == 0 || strcmp(argv[count], "-q") == 0)
{
if (++count < argc)
{
if (strcmp(argv[count], "0") == 0)
opts->qos = 0;
else if (strcmp(argv[count], "1") == 0)
opts->qos = 1;
else if (strcmp(argv[count], "2") == 0)
opts->qos = 2;
else
return 1;
}
else
return 1;
}
else if (strcmp(argv[count], "--connection") == 0 || strcmp(argv[count], "-c") == 0)
{
if (++count < argc)
opts->connection = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--host") == 0 || strcmp(argv[count], "-h") == 0)
{
if (++count < argc)
opts->host = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--port") == 0 || strcmp(argv[count], "-p") == 0)
{
if (++count < argc)
opts->port = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--http-proxy") == 0)
{
if (++count < argc)
opts->http_proxy = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--https-proxy") == 0)
{
if (++count < argc)
opts->https_proxy = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--clientid") == 0 || strcmp(argv[count], "-i") == 0)
{
if (++count < argc)
opts->clientid = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--username") == 0 || strcmp(argv[count], "-u") == 0)
{
if (++count < argc)
opts->username = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--password") == 0 || strcmp(argv[count], "-P") == 0)
{
if (++count < argc)
opts->password = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--maxdatalen") == 0)
{
if (++count < argc)
opts->maxdatalen = atoi(argv[count]);
else
return 1;
}
else if (strcmp(argv[count], "--delimiter") == 0)
{
if (++count < argc)
opts->delimiter = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--no-delimiter") == 0)
opts->delimiter = NULL;
else if (strcmp(argv[count], "--keepalive") == 0 || strcmp(argv[count], "-k") == 0)
{
if (++count < argc)
opts->keepalive = atoi(argv[count]);
else
return 1;
}
else if (strcmp(argv[count], "--topic") == 0 || strcmp(argv[count], "-t") == 0)
{
if (++count < argc)
opts->topic = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--will-topic") == 0)
{
if (++count < argc)
opts->will_topic = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--will-payload") == 0)
{
if (++count < argc)
opts->will_payload = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--will-qos") == 0)
{
if (++count < argc)
opts->will_qos = atoi(argv[count]);
else
return 1;
}
else if (strcmp(argv[count], "--will-retain") == 0)
{
if (++count < argc)
opts->will_retain = 1;
else
return 1;
}
else if (strcmp(argv[count], "--insecure") == 0)
opts->insecure = 1;
else if (strcmp(argv[count], "--capath") == 0)
{
if (++count < argc)
opts->capath = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--cafile") == 0)
{
if (++count < argc)
opts->cafile = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--cert") == 0)
{
if (++count < argc)
opts->cert = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--key") == 0)
{
if (++count < argc)
opts->key = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--keypass") == 0)
{
if (++count < argc)
opts->keypass = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--ciphers") == 0)
{
if (++count < argc)
opts->ciphers = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--psk") == 0)
{
if (++count < argc)
opts->psk = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "--psk-identity") == 0)
{
if (++count < argc)
opts->psk_identity = argv[count];
else
return 1;
}
else if (strcmp(argv[count], "-V") == 0)
{
if (++count < argc)
{
if (strcmp(argv[count], "mqttv31") == 0 || strcmp(argv[count], "31") == 0)
opts->MQTTVersion = MQTTVERSION_3_1;
else if (strcmp(argv[count], "mqttv311") == 0 || strcmp(argv[count], "311") == 0)
opts->MQTTVersion = MQTTVERSION_3_1_1;
else if (strcmp(argv[count], "mqttv5") == 0 || strcmp(argv[count], "5") == 0)
opts->MQTTVersion = MQTTVERSION_5;
else
return 1;
}
else
return 1;
}
else if (strcmp(argv[count], "--trace") == 0)
{
if (++count < argc)
{
if (strcmp(argv[count], "error") == 0)
opts->tracelevel = MQTTASYNC_TRACE_ERROR;
else if (strcmp(argv[count], "protocol") == 0)
opts->tracelevel = MQTTASYNC_TRACE_PROTOCOL;
else if (strcmp(argv[count], "min") == 0 || strcmp(argv[count], "on") == 0)
opts->tracelevel = MQTTASYNC_TRACE_MINIMUM;
else if (strcmp(argv[count], "max") == 0)
opts->tracelevel = MQTTASYNC_TRACE_MAXIMUM;
else
return 1;
}
else
return 1;
}
else if (opts->publisher == 0)
{
if (strcmp(argv[count], "--no-retained") == 0 || strcmp(argv[count], "-R") == 0)
opts->retained = 1;
else
{
fprintf(stderr, "Unknown option %s\n", argv[count]);
return 1;
}
}
else if (opts->publisher == 1)
{
if (strcmp(argv[count], "--retained") == 0 || strcmp(argv[count], "-r") == 0)
opts->retained = 1;
else if (strcmp(argv[count], "--user-property") == 0)
{
if (count + 2 < argc)
{
opts->user_property.name = argv[++count];
opts->user_property.value = argv[++count];
}
else
return 1;
}
else if (strcmp(argv[count], "--message-expiry") == 0)
{
if (++count < argc)
opts->message_expiry = atoi(argv[count]);
else
return 1;
}
else if (strcmp(argv[count], "-m") == 0 || strcmp(argv[count], "--message") == 0)
{
if (++count < argc)
{
opts->stdin_lines = 0;
opts->message = argv[count];
}
else
return 1;
}
else if (strcmp(argv[count], "-f") == 0 || strcmp(argv[count], "--filename") == 0)
{
if (++count < argc)
{
opts->stdin_lines = 0;
opts->filename = argv[count];
}
else
return 1;
}
else if (strcmp(argv[count], "-n") == 0 || strcmp(argv[count], "--null-message") == 0)
{
opts->stdin_lines = 0;
opts->null_message = 1;
}
else
{
fprintf(stderr, "Unknown option %s\n", argv[count]);
return 1;
}
}
else
{
fprintf(stderr, "Unknown option %s\n", argv[count]);
return 1;
}
count++;
}
if (opts->topic == NULL)
return 1;
return 0;
}
char* readfile(int* data_len, struct pubsub_opts* opts)
{
char* buffer = NULL;
long filesize = 0L;
FILE* infile = fopen(opts->filename, "rb");
if (infile == NULL)
{
fprintf(stderr, "Can't open file %s\n", opts->filename);
return NULL;
}
fseek(infile, 0, SEEK_END);
filesize = ftell(infile);
rewind(infile);
buffer = malloc(sizeof(char)*filesize);
if (buffer == NULL)
{
fprintf(stderr, "Can't allocate buffer to read file %s\n", opts->filename);
fclose(infile);
return NULL;
}
*data_len = (int)fread(buffer, 1, filesize, infile);
if (*data_len != filesize)
{
fprintf(stderr, "%d bytes read of %ld expected for file %s\n", *data_len, filesize, opts->filename);
fclose(infile);
free(buffer);
return NULL;
}
fclose(infile);
return buffer;
}
void logProperties(MQTTProperties *props)
{
int i = 0;
for (i = 0; i < props->count; ++i)
{
int id = props->array[i].identifier;
const char* name = MQTTPropertyName(id);
char* intformat = "Property name %s value %d\n";
switch (MQTTProperty_getType(id))
{
case MQTTPROPERTY_TYPE_BYTE:
printf(intformat, name, props->array[i].value.byte);
break;
case MQTTPROPERTY_TYPE_TWO_BYTE_INTEGER:
printf(intformat, name, props->array[i].value.integer2);
break;
case MQTTPROPERTY_TYPE_FOUR_BYTE_INTEGER:
printf(intformat, name, props->array[i].value.integer4);
break;
case MQTTPROPERTY_TYPE_VARIABLE_BYTE_INTEGER:
printf(intformat, name, props->array[i].value.integer4);
break;
case MQTTPROPERTY_TYPE_BINARY_DATA:
case MQTTPROPERTY_TYPE_UTF_8_ENCODED_STRING:
printf("Property name %s value len %.*s\n", name,
props->array[i].value.data.len, props->array[i].value.data.data);
break;
case MQTTPROPERTY_TYPE_UTF_8_STRING_PAIR:
printf("Property name %s key %.*s value %.*s\n", name,
props->array[i].value.data.len, props->array[i].value.data.data,
props->array[i].value.value.len, props->array[i].value.value.data);
break;
}
}
}