1 #define MQTTCLIENT_QOS2 1
2
3 #include <memory.h>
4
5 #include "MQTTClient.h"
6
7 #define DEFAULT_STACK_SIZE -1
8
9 #include "linux.cpp"
10
11 int arrivedcount = 0;
12
messageArrived(MQTT::MessageData & md)13 void messageArrived(MQTT::MessageData& md)
14 {
15 MQTT::Message &message = md.message;
16
17 printf("Message %d arrived: qos %d, retained %d, dup %d, packetid %d\n",
18 ++arrivedcount, message.qos, message.retained, message.dup, message.id);
19 printf("Payload %.*s\n", (int)message.payloadlen, (char*)message.payload);
20 }
21
22
main(int argc,char * argv[])23 int main(int argc, char* argv[])
24 {
25 IPStack ipstack = IPStack();
26 float version = 0.3;
27 const char* topic = "mbed-sample";
28
29 printf("Version is %f\n", version);
30
31 MQTT::Client<IPStack, Countdown> client = MQTT::Client<IPStack, Countdown>(ipstack);
32
33 const char* hostname = "iot.eclipse.org";
34 int port = 1883;
35 printf("Connecting to %s:%d\n", hostname, port);
36 int rc = ipstack.connect(hostname, port);
37 if (rc != 0)
38 printf("rc from TCP connect is %d\n", rc);
39
40 printf("MQTT connecting\n");
41 MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
42 data.MQTTVersion = 3;
43 data.clientID.cstring = (char*)"mbed-icraggs";
44 rc = client.connect(data);
45 if (rc != 0)
46 printf("rc from MQTT connect is %d\n", rc);
47 printf("MQTT connected\n");
48
49 rc = client.subscribe(topic, MQTT::QOS2, messageArrived);
50 if (rc != 0)
51 printf("rc from MQTT subscribe is %d\n", rc);
52
53 MQTT::Message message;
54
55 // QoS 0
56 char buf[100];
57 sprintf(buf, "Hello World! QoS 0 message from app version %f", version);
58 message.qos = MQTT::QOS0;
59 message.retained = false;
60 message.dup = false;
61 message.payload = (void*)buf;
62 message.payloadlen = strlen(buf)+1;
63 rc = client.publish(topic, message);
64 if (rc != 0)
65 printf("Error %d from sending QoS 0 message\n", rc);
66 else while (arrivedcount == 0)
67 client.yield(100);
68
69 // QoS 1
70 printf("Now QoS 1\n");
71 sprintf(buf, "Hello World! QoS 1 message from app version %f", version);
72 message.qos = MQTT::QOS1;
73 message.payloadlen = strlen(buf)+1;
74 rc = client.publish(topic, message);
75 if (rc != 0)
76 printf("Error %d from sending QoS 1 message\n", rc);
77 else while (arrivedcount == 1)
78 client.yield(100);
79
80 // QoS 2
81 sprintf(buf, "Hello World! QoS 2 message from app version %f", version);
82 message.qos = MQTT::QOS2;
83 message.payloadlen = strlen(buf)+1;
84 rc = client.publish(topic, message);
85 if (rc != 0)
86 printf("Error %d from sending QoS 2 message\n", rc);
87 while (arrivedcount == 2)
88 client.yield(100);
89
90 rc = client.unsubscribe(topic);
91 if (rc != 0)
92 printf("rc from unsubscribe was %d\n", rc);
93
94 rc = client.disconnect();
95 if (rc != 0)
96 printf("rc from disconnect was %d\n", rc);
97
98 ipstack.disconnect();
99
100 printf("Finishing with %d messages received\n", arrivedcount);
101
102 return 0;
103 }
104
105