Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b7ca8bc

Browse files
committed
EthernetServerStream write buffer
- reduce network overhead by buffering writes
1 parent 417fa0c commit b7ca8bc

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

utility/EthernetServerStream.h

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
1111
See file LICENSE.txt for further informations on licensing terms.
1212
13-
Last updated July 10th, 2017
13+
Last updated March 21st 2020
1414
*/
1515

1616
#ifndef ETHERNETSERVERSTREAM_H
@@ -23,6 +23,17 @@
2323
//#define SERIAL_DEBUG
2424
#include "firmataDebug.h"
2525

26+
// If defined and set to a value higher than 1 all single bytes writes
27+
// will be buffered until one of the following conditions is met:
28+
// 1) write buffer full
29+
// 2) any call to read(), available(), maintain(), peek() or flush()
30+
// By combining the buffered bytes into a single TCP frame this feature will significantly
31+
// reduce the network and receiver load by the factor 1/(1/20 + 1/bufferedSize).
32+
// Buffer sizes up to 80 have been tested successfully. Note that higher buffer values
33+
// may cause slight delays between an event and the network transmission.
34+
#define WRITE_BUFFER_SIZE 40
35+
36+
2637
class EthernetServerStream : public Stream
2738
{
2839
public:
@@ -39,6 +50,10 @@ class EthernetServerStream : public Stream
3950
IPAddress localip;
4051
uint16_t port;
4152
bool connected;
53+
#ifdef WRITE_BUFFER_SIZE
54+
uint8_t writeBuffer[WRITE_BUFFER_SIZE];
55+
uint8_t writeBufferLength;
56+
#endif
4257
bool maintain();
4358
void stop();
4459

@@ -58,21 +73,37 @@ EthernetServerStream::EthernetServerStream(IPAddress localip, uint16_t port)
5873
: localip(localip),
5974
port(port),
6075
connected(false)
76+
#ifdef WRITE_BUFFER_SIZE
77+
, writeBufferLength(0)
78+
#endif
6179
{
6280
}
6381

6482
bool EthernetServerStream::connect_client()
6583
{
6684
if ( connected )
6785
{
68-
if ( client && client.connected() ) return true;
86+
if ( client && client.connected() )
87+
{
88+
#ifdef WRITE_BUFFER_SIZE
89+
// send buffered bytes
90+
if (writeBufferLength) {
91+
client.write(writeBuffer, writeBufferLength);
92+
writeBufferLength = 0;
93+
}
94+
#endif
95+
return true;
96+
}
6997
stop();
7098
}
7199

72100
EthernetClient newClient = server.available();
73101
if ( !newClient ) return false;
74102
client = newClient;
75103
connected = true;
104+
#ifdef WRITE_BUFFER_SIZE
105+
writeBufferLength = 0;
106+
#endif
76107
DEBUG_PRINTLN("Connected");
77108
return true;
78109
}
@@ -126,6 +157,9 @@ EthernetServerStream::stop()
126157
client.stop();
127158
}
128159
connected = false;
160+
#ifdef WRITE_BUFFER_SIZE
161+
writeBufferLength = 0;
162+
#endif
129163
}
130164

131165
bool

0 commit comments

Comments
 (0)