• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #if !defined(MQTTSOCKET_H)
2 #define MQTTSOCKET_H
3 
4 #include "MQTTmbed.h"
5 #include <EthernetInterface.h>
6 #include <Timer.h>
7 
8 class MQTTSocket
9 {
10 public:
MQTTSocket(EthernetInterface * anet)11     MQTTSocket(EthernetInterface *anet)
12     {
13         net = anet;
14         open = false;
15     }
16 
17     int connect(char* hostname, int port, int timeout=1000)
18     {
19         if (open)
20             disconnect();
21         nsapi_error_t rc = mysock.open(net);
22         open = true;
23         mysock.set_blocking(true);
24         mysock.set_timeout((unsigned int)timeout);
25         rc = mysock.connect(hostname, port);
26         mysock.set_blocking(false);  // blocking timeouts seem not to work
27         return rc;
28     }
29 
30     // common read/write routine, avoiding blocking timeouts
common(unsigned char * buffer,int len,int timeout,bool read)31     int common(unsigned char* buffer, int len, int timeout, bool read)
32     {
33         timer.start();
34         mysock.set_blocking(false); // blocking timeouts seem not to work
35         int bytes = 0;
36         bool first = true;
37         do
38         {
39             if (first)
40                 first = false;
41             else
42                 wait_ms(timeout < 100 ? timeout : 100);
43             int rc;
44             if (read)
45                 rc = mysock.recv((char*)buffer, len);
46             else
47                 rc = mysock.send((char*)buffer, len);
48             if (rc < 0)
49             {
50                 if (rc != NSAPI_ERROR_WOULD_BLOCK)
51                 {
52                     bytes = -1;
53                     break;
54                 }
55             }
56             else
57                 bytes += rc;
58         }
59         while (bytes < len && timer.read_ms() < timeout);
60         timer.stop();
61         return bytes;
62     }
63 
64     /* returns the number of bytes read, which could be 0.
65        -1 if there was an error on the socket
66     */
read(unsigned char * buffer,int len,int timeout)67     int read(unsigned char* buffer, int len, int timeout)
68     {
69         return common(buffer, len, timeout, true);
70     }
71 
write(unsigned char * buffer,int len,int timeout)72     int write(unsigned char* buffer, int len, int timeout)
73     {
74         return common(buffer, len, timeout, false);
75     }
76 
disconnect()77     int disconnect()
78     {
79         open = false;
80         return mysock.close();
81     }
82 
83     /*bool is_connected()
84     {
85         return mysock.is_connected();
86     }*/
87 
88 private:
89 
90     bool open;
91     TCPSocket mysock;
92     EthernetInterface *net;
93     Timer timer;
94 
95 };
96 
97 #endif
98