Jack Hansdampf / mbed-mqtt-GSOE1

Dependents:   ESP8266MQTT

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MQTTNetwork.h Source File

MQTTNetwork.h

00001 /*
00002  * Copyright (c) 2019, ARM Limited, All Rights Reserved
00003  * SPDX-License-Identifier: Apache-2.0
00004  *
00005  * Licensed under the Apache License, Version 2.0 (the "License"); you may
00006  * not use this file except in compliance with the License.
00007  * You may obtain a copy of the License at
00008  *
00009  * http://www.apache.org/licenses/LICENSE-2.0
00010  *
00011  * Unless required by applicable law or agreed to in writing, software
00012  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00013  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00014  * See the License for the specific language governing permissions and
00015  * limitations under the License.
00016  */
00017 
00018 #ifndef _MQTTNETWORK_H_
00019 #define _MQTTNETWORK_H_
00020 
00021 #include "NetworkInterface.h"
00022 #include "TCPSocket.h"
00023 
00024 class MQTTNetwork {
00025 public:
00026     MQTTNetwork(NetworkInterface *aNetwork) : network(aNetwork)
00027     {
00028         socket = new TCPSocket();
00029     }
00030 
00031     ~MQTTNetwork()
00032     {
00033         delete socket;
00034     }
00035 
00036     int read(unsigned char *buffer, int len, int timeout)
00037     {
00038         int ret = socket->recv(buffer, len);
00039         if (ret == 0) {
00040             // A receive size of 0 indicates that the socket
00041             // was successfully closed so indicate this to MQTTClient
00042             ret = -1;
00043         }
00044         return ret;
00045     }
00046 
00047     int write(unsigned char *buffer, int len, int timeout)
00048     {
00049         int ret = socket->send(buffer, len);
00050         if (ret == 0) {
00051             // The socket is closed so indicate this to MQTTClient
00052             return -1;
00053         }
00054         return ret;
00055     }
00056 
00057     int connect(const char *hostname, int port)
00058     {
00059         int ret = NSAPI_ERROR_OK;
00060         if ((ret = socket->open(network)) != NSAPI_ERROR_OK) {
00061             return ret;
00062         }
00063         SocketAddress addr;
00064         if (network->gethostbyname(hostname, &addr) != NSAPI_ERROR_OK) {
00065             return NSAPI_ERROR_DNS_FAILURE;
00066         }
00067         addr.set_port(port);
00068         return socket->connect(addr);
00069     }
00070 
00071     int disconnect()
00072     {
00073         return socket->close();
00074     }
00075 
00076 private:
00077     NetworkInterface *network;
00078     TCPSocket *socket;
00079 };
00080 
00081 #endif // _MQTTNETWORK_H_