3 An Arduino-Stream that wraps an instance of Client reconnecting to
4 the remote-ip in a transparent way. A disconnected client may be
5 recognized by the returnvalues -1 from calls to peek or read and
6 a 0 from calls to write.
8 Copyright (C) 2013 Norbert Truchsess. All rights reserved.
10 This library is free software; you can redistribute it and/or
11 modify it under the terms of the GNU Lesser General Public
12 License as published by the Free Software Foundation; either
13 version 2.1 of the License, or (at your option) any later version.
15 See file LICENSE.txt for further informations on licensing terms.
17 Last updated June 18th, 2016
20 #ifndef ETHERNETCLIENTSTREAM_H
21 #define ETHERNETCLIENTSTREAM_H
26 //#define SERIAL_DEBUG
27 #include "firmataDebug.h"
29 #define MILLIS_RECONNECT 5000
31 class EthernetClientStream : public Stream
34 EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port);
39 size_t write(uint8_t);
40 void maintain(IPAddress localip);
49 uint32_t time_connect;
56 * EthernetClientStream.cpp
57 * Copied here as a hack to linker issues with 3rd party board packages that don't properly
58 * implement the Arduino network APIs.
60 EthernetClientStream::EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port)
71 EthernetClientStream::available()
73 return maintain() ? client.available() : 0;
77 EthernetClientStream::read()
79 return maintain() ? client.read() : -1;
83 EthernetClientStream::peek()
85 return maintain() ? client.peek() : -1;
88 void EthernetClientStream::flush()
95 EthernetClientStream::write(uint8_t c)
97 return maintain() ? client.write(c) : 0;
101 EthernetClientStream::maintain(IPAddress localip)
103 // ensure the local IP is updated in the case that it is changed by the DHCP server
104 if (this->localip != localip) {
105 this->localip = localip;
112 EthernetClientStream::stop()
116 time_connect = millis();
120 EthernetClientStream::maintain()
122 if (client && client.connected())
128 // if the client is disconnected, attempt to reconnect every 5 seconds
129 else if (millis() - time_connect >= MILLIS_RECONNECT) {
130 connected = host ? client.connect(host, port) : client.connect(ip, port);
132 time_connect = millis();
133 DEBUG_PRINTLN("Connection failed. Attempting to reconnect...");
135 DEBUG_PRINTLN("Connected");
141 #endif /* ETHERNETCLIENTSTREAM_H */