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
68 lines
2.2 KiB
#include "stdlib.h"
|
|
#include "string.h"
|
|
#include "unistd.h"
|
|
#include "MQTTClient.h"
|
|
|
|
#define ADDRESS "mqtt://iot-06z00dtdbnukzsk.mqtt.iothub.aliyuncs.com:1883"
|
|
#define USERNAME "mh_2&iekhmHv4wIC"
|
|
#define PASSWORD "8491b7d3391d51f40120bb9d81a4b713c624ce7beb216b9d37076508ac6e7446"
|
|
#define CLIENTID "iekhmHv4wIC.mh_2|securemode=2,signmethod=hmacsha256,timestamp=1680575050297|"
|
|
#define QOS 0
|
|
#define TOPIC "/sys/iekhmHv4wIC/mh_2/thing/event/property/post"
|
|
#define TIMEOUT 10000L
|
|
|
|
void publish(MQTTClient client, char *topic, char *payload)
|
|
{
|
|
MQTTClient_message message = MQTTClient_message_initializer;
|
|
message.payload = payload;
|
|
message.payloadlen = strlen(payload);
|
|
message.qos = QOS;
|
|
message.retained = 0;
|
|
MQTTClient_deliveryToken token;
|
|
MQTTClient_publishMessage(client, topic, &message, &token);
|
|
MQTTClient_waitForCompletion(client, token, TIMEOUT);
|
|
printf("Send `%s` to topic `%s` \n", payload, TOPIC);
|
|
}
|
|
|
|
int on_message(void *context, char *topicName, int topicLen, MQTTClient_message *message)
|
|
{
|
|
char *payload = message->payload;
|
|
printf("Received `%s` from `%s` topic \n", payload, topicName);
|
|
MQTTClient_freeMessage(&message);
|
|
MQTTClient_free(topicName);
|
|
return 1;
|
|
}
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
int rc;
|
|
MQTTClient client;
|
|
|
|
MQTTClient_create(&client, ADDRESS, CLIENTID, 0, NULL);
|
|
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
|
|
conn_opts.username = USERNAME;
|
|
conn_opts.password = PASSWORD;
|
|
MQTTClient_setCallbacks(client, NULL, NULL, on_message, NULL);
|
|
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
|
|
{
|
|
printf("Failed to connect, return code %d\n", rc);
|
|
exit(-1);
|
|
}
|
|
else
|
|
{
|
|
printf("Connected to MQTT Broker!\n");
|
|
}
|
|
// subscribe topic
|
|
MQTTClient_subscribe(client, TOPIC, QOS);
|
|
char payload[23];
|
|
for (int i = 0; i < 100; i += 1)
|
|
{
|
|
// publish message to broker
|
|
snprintf(payload, 23, "{\"RunningState\": \"%d\"}", i);
|
|
publish(client, TOPIC, payload);
|
|
sleep(1);
|
|
}
|
|
MQTTClient_disconnect(client, TIMEOUT);
|
|
MQTTClient_destroy(&client);
|
|
return rc;
|
|
}
|