Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
MQTTSocket.h
00001 #if !defined(MQTTSOCKET_H) 00002 #define MQTTSOCKET_H 00003 00004 #include "MQTTmbed.h" 00005 #include <Timer.h> 00006 00007 class MQTTSocket 00008 { 00009 public: 00010 MQTTSocket(NetworkInterface *anet) : net(anet) 00011 { 00012 open = false; 00013 } 00014 00015 int connect(char* hostname, int port, int timeout=1000) 00016 { 00017 if (open) 00018 disconnect(); 00019 nsapi_error_t rc = mysock.open(net); 00020 open = true; 00021 mysock.set_blocking(true); 00022 mysock.set_timeout((unsigned int)timeout); 00023 rc = mysock.connect(hostname, port); 00024 mysock.set_blocking(false); // blocking timeouts seem not to work 00025 return rc; 00026 } 00027 00028 // common read/write routine, avoiding blocking timeouts 00029 int common(unsigned char* buffer, int len, int timeout, bool read) 00030 { 00031 timer.start(); 00032 mysock.set_blocking(false); // blocking timeouts seem not to work 00033 int bytes = 0; 00034 bool first = true; 00035 do 00036 { 00037 if (first) 00038 first = false; 00039 else 00040 wait_ms(timeout < 100 ? timeout : 100); 00041 int rc; 00042 if (read) 00043 rc = mysock.recv((char*)buffer, len); 00044 else 00045 rc = mysock.send((char*)buffer, len); 00046 if (rc < 0) 00047 { 00048 if (rc != NSAPI_ERROR_WOULD_BLOCK) 00049 { 00050 bytes = -1; 00051 break; 00052 } 00053 } 00054 else 00055 bytes += rc; 00056 } 00057 while (bytes < len && timer.read_ms() < timeout); 00058 timer.stop(); 00059 return bytes; 00060 } 00061 00062 /* returns the number of bytes read, which could be 0. 00063 -1 if there was an error on the socket 00064 */ 00065 int read(unsigned char* buffer, int len, int timeout) 00066 { 00067 return common(buffer, len, timeout, true); 00068 } 00069 00070 int write(unsigned char* buffer, int len, int timeout) 00071 { 00072 return common(buffer, len, timeout, false); 00073 } 00074 00075 int disconnect() 00076 { 00077 open = false; 00078 return mysock.close(); 00079 } 00080 00081 /*bool is_connected() 00082 { 00083 return mysock.is_connected(); 00084 }*/ 00085 00086 private: 00087 00088 bool open; 00089 TCPSocket mysock; 00090 NetworkInterface *net; 00091 Timer timer; 00092 00093 }; 00094 00095 #endif
Generated on Mon Jul 18 2022 07:40:17 by
1.7.2