HelloMQTT over TLS.
Fork of HelloMQTT by
HelloMQTT over TLS
This program is a fork of HelloMQTT. Added TLS capability by using TLSSocket library. Tested on K64F.
This sample program connects to iot.eclipse.org:8883
by default. Verifies server identification. Subscribes a certain topic. Then publishes three messages with different QoSs, i.e. QoS0
, QoS1
, and QoS2
.
Warning
Some brokers do not accept QoS2 and/or QoS1 message. For example, AWS IoT Message Broker doesn't accept QoS2. In such broker, this program doesn't work as is. Change QoS level.
Output from console
HelloMQTT: version is 0.70 Opening network interface... Network interface opened successfully. Connecting to host iot.eclipse.org:8883 ... Connection established. MQTT client is trying to connect the server ... Client connected. Client is trying to subscribe a topic "mbed-test". Client has subscribed a topic "mbed-test". Client publishes messages ... Publishing message QoS 0. QoS 0 message published. ! Message arrived: qos 0, retained 0, dup 0, packetid 6257 ! Payload Hello World! QoS 0 message from app version 0.700000 Publishing message QoS 1. QoS 1 message published. ! Message arrived: qos 1, retained 0, dup 0, packetid 1 ! Payload Hello World! QoS 1 message from app version 0.700000 Publishing message QoS 2. QoS 2 message published. ! Message arrived: qos 2, retained 0, dup 0, packetid 2 ! Payload Hello World! QoS 2 message from app version 0.700000 Version 0.70: finish 3 msgs
Known Issues
On K64F, when serial baud rate is changed from 9600 to 115200, program fails.
Diff: MQTTNetwork.h
- Revision:
- 24:e7cf8b02e012
- Parent:
- 21:a68bd76740f9
- Child:
- 34:8f7a465c2192
diff -r e38aaf532823 -r e7cf8b02e012 MQTTNetwork.h --- a/MQTTNetwork.h Tue Jan 16 13:41:29 2018 +0000 +++ b/MQTTNetwork.h Mon Apr 16 18:55:41 2018 +0900 @@ -3,10 +3,23 @@ #include "NetworkInterface.h" +#undef USE_TLS +#if defined(MBED_CONF_APP_USE_TLS) && (MBED_CONF_APP_USE_TLS == 1) + #define USE_TLS +#endif + +#ifdef USE_TLS +#include "TLSSocket.h" +#endif /* USE_TLS */ + class MQTTNetwork { public: MQTTNetwork(NetworkInterface* aNetwork) : network(aNetwork) { +#ifdef USE_TLS + socket = new TLSSocket(); +#else socket = new TCPSocket(); +#endif /* USE_TLS */ } ~MQTTNetwork() { @@ -21,8 +34,14 @@ return socket->send(buffer, len); } - int connect(const char* hostname, int port) { - socket->open(network); + int connect(const char* hostname, int port, const char *ssl_ca_pem = NULL) { + nsapi_error_t ret = 0; + if((ret = socket->open(network)) != 0) { + return ret; + } +#ifdef USE_TLS + socket->set_root_ca_pem(ssl_ca_pem); +#endif /* USE_TLS */ return socket->connect(hostname, port); } @@ -32,7 +51,11 @@ private: NetworkInterface* network; +#ifdef USE_TLS + TLSSocket* socket; +#else TCPSocket* socket; +#endif /* USE_TLS */ }; #endif // _MQTTNETWORK_H_