Osamu Koizumi / Mbed OS HelloMQTT

Dependencies:   MQTT

Fork of HelloMQTT by Osamu Koizumi

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MQTTNetwork.h Source File

MQTTNetwork.h

00001 #ifndef _MQTTNETWORK_H_
00002 #define _MQTTNETWORK_H_
00003 
00004 #include "NetworkInterface.h"
00005 
00006 #undef USE_TLS
00007 #if defined(MBED_CONF_APP_USE_TLS) && (MBED_CONF_APP_USE_TLS == 1)
00008   #define USE_TLS
00009 #endif
00010 
00011 #ifdef USE_TLS
00012 #include "TLSSocket.h"
00013 #endif /* USE_TLS */
00014 
00015 class MQTTNetwork {
00016 public:
00017     MQTTNetwork(NetworkInterface* aNetwork) : network(aNetwork) {
00018 #ifdef USE_TLS
00019         socket = new TLSSocket();
00020 #else
00021         socket = new TCPSocket();
00022 #endif /* USE_TLS */
00023     }
00024 
00025     ~MQTTNetwork() {
00026         delete socket;
00027     }
00028 
00029     int read(unsigned char* buffer, int len, int timeout) {
00030         return socket->recv(buffer, len);
00031     }
00032 
00033     int write(unsigned char* buffer, int len, int timeout) {
00034         return socket->send(buffer, len);
00035     }
00036 
00037     int connect(const char* hostname, int port, const char *ssl_ca_pem = NULL,
00038             const char *ssl_cli_pem = NULL, const char *ssl_pk_pem = NULL) {
00039         nsapi_error_t ret = 0;
00040         if((ret = socket->open(network)) != 0) {
00041             return ret;
00042         }
00043 #ifdef USE_TLS
00044         socket->set_root_ca_cert(ssl_ca_pem);
00045         socket->set_client_cert_key(ssl_cli_pem, ssl_pk_pem);
00046 #endif /* USE_TLS */
00047         return socket->connect(hostname, port);
00048     }
00049 
00050     int disconnect() {
00051         return socket->close();
00052     }
00053 
00054 private:
00055     NetworkInterface* network;
00056 #ifdef USE_TLS
00057     TLSSocket* socket;
00058 #else
00059     TCPSocket* socket;
00060 #endif /* USE_TLS */
00061 };
00062 
00063 #endif // _MQTTNETWORK_H_