MQTTClient_publish.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*******************************************************************************
  2. * Copyright (c) 2012, 2022 IBM Corp., Ian Craggs
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v2.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * https://www.eclipse.org/legal/epl-2.0/
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs - initial contribution
  15. *******************************************************************************/
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include "MQTTClient.h"
  20. #define ADDRESS "tcp://mqtt.eclipseprojects.io:1883"
  21. #define CLIENTID "ExampleClientPub"
  22. #define TOPIC "MQTT Examples"
  23. #define PAYLOAD "Hello World!"
  24. #define QOS 1
  25. #define TIMEOUT 10000L
  26. int main(int argc, char* argv[])
  27. {
  28. MQTTClient client;
  29. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  30. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  31. MQTTClient_deliveryToken token;
  32. int rc;
  33. const char* uri = (argc > 1) ? argv[1] : ADDRESS;
  34. printf("Using server at %s\n", uri);
  35. if ((rc = MQTTClient_create(&client, uri, CLIENTID,
  36. MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
  37. {
  38. printf("Failed to create client, return code %d\n", rc);
  39. exit(EXIT_FAILURE);
  40. }
  41. conn_opts.keepAliveInterval = 20;
  42. conn_opts.cleansession = 1;
  43. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  44. {
  45. printf("Failed to connect, return code %d\n", rc);
  46. exit(EXIT_FAILURE);
  47. }
  48. pubmsg.payload = PAYLOAD;
  49. pubmsg.payloadlen = (int)strlen(PAYLOAD);
  50. pubmsg.qos = QOS;
  51. pubmsg.retained = 0;
  52. if ((rc = MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token)) != MQTTCLIENT_SUCCESS)
  53. {
  54. printf("Failed to publish message, return code %d\n", rc);
  55. exit(EXIT_FAILURE);
  56. }
  57. printf("Waiting for up to %d seconds for publication of %s\n"
  58. "on topic %s for client with ClientID: %s\n",
  59. (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
  60. rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  61. printf("Message with delivery token %d delivered\n", token);
  62. if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
  63. printf("Failed to disconnect, return code %d\n", rc);
  64. MQTTClient_destroy(&client);
  65. return rc;
  66. }