source: rtos_arduino/trunk/arduino_lib/libraries/Firmata/utility/EthernetClientStream.cpp@ 224

Last change on this file since 224 was 224, checked in by ertl-honda, 8 years ago

1.7.10のファイルに更新

File size: 2.5 KB
Line 
1/*
2 EthernetClientStream.cpp
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.
7
8 Copyright (C) 2013 Norbert Truchsess. All rights reserved.
9
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.
14
15 See file LICENSE.txt for further informations on licensing terms.
16
17 formatted using the GNU C formatting and indenting
18 */
19
20#include "EthernetClientStream.h"
21#include <Arduino.h>
22
23//#define SERIAL_DEBUG
24#include "firmataDebug.h"
25
26#define MILLIS_RECONNECT 5000
27
28EthernetClientStream::EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port)
29: client(client),
30 localip(localip),
31 ip(ip),
32 host(host),
33 port(port),
34 connected(false)
35{
36}
37
38int
39EthernetClientStream::available()
40{
41 return maintain() ? client.available() : 0;
42}
43
44int
45EthernetClientStream::read()
46{
47 return maintain() ? client.read() : -1;
48}
49
50int
51EthernetClientStream::peek()
52{
53 return maintain() ? client.peek() : -1;
54}
55
56void EthernetClientStream::flush()
57{
58 if (maintain())
59 client.flush();
60}
61
62size_t
63EthernetClientStream::write(uint8_t c)
64{
65 return maintain() ? client.write(c) : 0;
66}
67
68void
69EthernetClientStream::maintain(IPAddress localip)
70{
71// temporary hack to Firmata to compile for Intel Galileo
72// the issue is documented here: https://github.com/firmata/arduino/issues/218
73#if !defined(ARDUINO_LINUX)
74 // ensure the local IP is updated in the case that it is changed by the DHCP server
75 if (this->localip != localip)
76 {
77 this->localip = localip;
78 if (connected)
79 stop();
80 }
81#endif
82}
83
84void
85EthernetClientStream::stop()
86{
87 client.stop();
88 connected = false;
89 time_connect = millis();
90}
91
92bool
93EthernetClientStream::maintain()
94{
95 if (client && client.connected())
96 return true;
97
98 if (connected)
99 {
100 stop();
101 }
102 // if the client is disconnected, attempt to reconnect every 5 seconds
103 else if (millis()-time_connect >= MILLIS_RECONNECT)
104 {
105 connected = host ? client.connect(host, port) : client.connect(ip, port);
106 if (!connected) {
107 time_connect = millis();
108 DEBUG_PRINTLN("connection failed. attempting to reconnect...");
109 } else {
110 DEBUG_PRINTLN("connected");
111 }
112 }
113 return connected;
114}
Note: See TracBrowser for help on using the repository browser.