You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.2 KiB

2 years ago
  1. #include "stdlib.h"
  2. #include "string.h"
  3. #include "unistd.h"
  4. #include "MQTTClient.h"
  5. #define ADDRESS "mqtt://iot-06z00dtdbnukzsk.mqtt.iothub.aliyuncs.com:1883"
  6. #define USERNAME "mh_2&iekhmHv4wIC"
  7. #define PASSWORD "8491b7d3391d51f40120bb9d81a4b713c624ce7beb216b9d37076508ac6e7446"
  8. #define CLIENTID "iekhmHv4wIC.mh_2|securemode=2,signmethod=hmacsha256,timestamp=1680575050297|"
  9. #define QOS 0
  10. #define TOPIC "/sys/iekhmHv4wIC/mh_2/thing/event/property/post"
  11. #define TIMEOUT 10000L
  12. void publish(MQTTClient client, char *topic, char *payload)
  13. {
  14. MQTTClient_message message = MQTTClient_message_initializer;
  15. message.payload = payload;
  16. message.payloadlen = strlen(payload);
  17. message.qos = QOS;
  18. message.retained = 0;
  19. MQTTClient_deliveryToken token;
  20. MQTTClient_publishMessage(client, topic, &message, &token);
  21. MQTTClient_waitForCompletion(client, token, TIMEOUT);
  22. printf("Send `%s` to topic `%s` \n", payload, TOPIC);
  23. }
  24. int on_message(void *context, char *topicName, int topicLen, MQTTClient_message *message)
  25. {
  26. char *payload = message->payload;
  27. printf("Received `%s` from `%s` topic \n", payload, topicName);
  28. MQTTClient_freeMessage(&message);
  29. MQTTClient_free(topicName);
  30. return 1;
  31. }
  32. int main(int argc, char *argv[])
  33. {
  34. int rc;
  35. MQTTClient client;
  36. MQTTClient_create(&client, ADDRESS, CLIENTID, 0, NULL);
  37. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  38. conn_opts.username = USERNAME;
  39. conn_opts.password = PASSWORD;
  40. MQTTClient_setCallbacks(client, NULL, NULL, on_message, NULL);
  41. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  42. {
  43. printf("Failed to connect, return code %d\n", rc);
  44. exit(-1);
  45. }
  46. else
  47. {
  48. printf("Connected to MQTT Broker!\n");
  49. }
  50. // subscribe topic
  51. MQTTClient_subscribe(client, TOPIC, QOS);
  52. char payload[23];
  53. for (int i = 0; i < 100; i += 1)
  54. {
  55. // publish message to broker
  56. snprintf(payload, 23, "{\"RunningState\": \"%d\"}", i);
  57. publish(client, TOPIC, payload);
  58. sleep(1);
  59. }
  60. MQTTClient_disconnect(client, TIMEOUT);
  61. MQTTClient_destroy(&client);
  62. return rc;
  63. }