MQTTClient_publish.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*******************************************************************************
  2. * Copyright (c) 2012, 2017 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  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://localhost: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. MQTTClient_create(&client, ADDRESS, CLIENTID,
  34. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  35. conn_opts.keepAliveInterval = 20;
  36. conn_opts.cleansession = 1;
  37. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  38. {
  39. printf("Failed to connect, return code %d\n", rc);
  40. exit(EXIT_FAILURE);
  41. }
  42. pubmsg.payload = PAYLOAD;
  43. pubmsg.payloadlen = (int)strlen(PAYLOAD);
  44. pubmsg.qos = QOS;
  45. pubmsg.retained = 0;
  46. MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
  47. printf("Waiting for up to %d seconds for publication of %s\n"
  48. "on topic %s for client with ClientID: %s\n",
  49. (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
  50. rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  51. printf("Message with delivery token %d delivered\n", token);
  52. MQTTClient_disconnect(client, 10000);
  53. MQTTClient_destroy(&client);
  54. return rc;
  55. }