branch with improvemnts
Fork of M2XStreamClient by
Embed:
(wiki syntax)
Show/hide line numbers
Client.cpp
00001 #include "Client.h" 00002 #include "mbed.h" 00003 00004 #include <stdint.h> 00005 00006 Client::Client() : _incnt(0), _outcnt(0), _sock() { 00007 _sock.set_blocking(false, 1500); 00008 } 00009 00010 Client::~Client() { 00011 } 00012 00013 int Client::connect(const char *host, uint16_t port) { 00014 return _sock.connect(host, port) == 0; 00015 } 00016 00017 size_t Client::write(uint8_t b) { 00018 return write(&b, 1); 00019 } 00020 00021 size_t Client::write(const uint8_t *buf, size_t size) { 00022 size_t cnt = 0; 00023 while (size) { 00024 int tmp = sizeof(_outbuf) - _outcnt; 00025 if (tmp > size) tmp = size; 00026 memcpy(_outbuf + _outcnt, buf, tmp); 00027 _outcnt += tmp; 00028 buf += tmp; 00029 size -= tmp; 00030 cnt += tmp; 00031 // if no space flush it 00032 if (_outcnt == sizeof(_outbuf)) 00033 _flushout(); 00034 } 00035 return cnt; 00036 } 00037 00038 void Client::_flushout(void) 00039 { 00040 if (_outcnt > 0) { 00041 // NOTE: we know it's dangerous to cast from (const uint8_t *) to (char *), 00042 // but we are trying to maintain a stable interface between the Arduino 00043 // one and the mbed one. What's more, while TCPSocketConnection has no 00044 // intention of modifying the data here, it requires us to send a (char *) 00045 // typed data. So we belive it's safe to do the cast here. 00046 _sock.send_all(const_cast<char*>((const char*) _outbuf), _outcnt); 00047 _outcnt = 0; 00048 } 00049 } 00050 00051 void Client::_fillin(void) 00052 { 00053 int tmp = sizeof(_inbuf) - _incnt; 00054 if (tmp) { 00055 tmp = _sock.receive_all((char*)_inbuf + _incnt, tmp); 00056 if (tmp > 0) 00057 _incnt += tmp; 00058 } 00059 } 00060 00061 void Client::flush() { 00062 _flushout(); 00063 } 00064 00065 int Client::available() { 00066 if (_incnt == 0) { 00067 _flushout(); 00068 _fillin(); 00069 } 00070 return (_incnt > 0) ? 1 : 0; 00071 } 00072 00073 int Client::read() { 00074 uint8_t ch; 00075 return (read(&ch, 1) == 1) ? ch : -1; 00076 } 00077 00078 int Client::read(uint8_t *buf, size_t size) { 00079 int cnt = 0; 00080 while (size) { 00081 // need more 00082 if (size > _incnt) { 00083 _flushout(); 00084 _fillin(); 00085 } 00086 if (_incnt > 0) { 00087 int tmp = _incnt; 00088 if (tmp > size) tmp = size; 00089 memcpy(buf, _inbuf, tmp); 00090 if (tmp != _incnt) 00091 memmove(_inbuf, _inbuf + tmp, _incnt - tmp); 00092 _incnt -= tmp; 00093 size -= tmp; 00094 buf += tmp; 00095 cnt += tmp; 00096 } else // no data 00097 break; 00098 } 00099 return cnt; 00100 } 00101 00102 void Client::stop() { 00103 _sock.close(); 00104 } 00105 00106 uint8_t Client::connected() { 00107 return _sock.is_connected() ? 1 : 0; 00108 }
Generated on Wed Jul 13 2022 05:32:06 by 1.7.2