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.

64 lines
2.2 KiB

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