-
Notifications
You must be signed in to change notification settings - Fork 515
/
Copy pathWiFiServerStream.h
123 lines (101 loc) · 2.69 KB
/
WiFiServerStream.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
WiFiServerStream.h
An Arduino Stream extension for a WiFiClient or WiFiServer to be used
with legacy Arduino WiFi shield and other boards and shields that
are compatible with the Arduino WiFi library.
Copyright (C) 2016 Jens B. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
See file LICENSE.txt for further informations on licensing terms.
Parts of this class are based on
- WiFiStream - Copyright (C) 2015-2016 Jesse Frush. All rights reserved.
published under the same license.
Last updated April 23rd, 2016
*/
#ifndef WIFI_SERVER_STREAM_H
#define WIFI_SERVER_STREAM_H
#include "WiFiStream.h"
class WiFiServerStream : public WiFiStream
{
protected:
WiFiServer _server = WiFiServer(3030);
bool _listening = false;
/**
* check if TCP client is connected
* @return true if connected
*/
virtual inline bool connect_client()
{
if ( _connected )
{
if ( _client && _client.connected() )
{
#ifdef WRITE_BUFFER_SIZE
// send buffered bytes
if (writeBufferLength) {
_client.write(writeBuffer, writeBufferLength);
writeBufferLength = 0;
}
#endif
return true;
}
stop();
}
// passive TCP connect (accept)
WiFiClient newClient = _server.available();
if ( !newClient ) return false;
_client = newClient;
_connected = true;
#ifdef WRITE_BUFFER_SIZE
writeBufferLength = 0;
#endif
if ( _currentHostConnectionCallback )
{
(*_currentHostConnectionCallback)(HOST_CONNECTION_CONNECTED);
}
return true;
}
public:
/**
* create a WiFi stream with a TCP server
*/
WiFiServerStream(uint16_t server_port) : WiFiStream(server_port) {}
/**
* maintain WiFi and TCP connection
* @return true if WiFi and TCP connection are established
*/
virtual inline bool maintain()
{
if ( connect_client() ) return true;
stop();
if ( !_listening && WiFi.status() == WL_CONNECTED )
{
// start TCP server after first WiFi connect
_server = WiFiServer(_port);
_server.begin();
_listening = true;
}
return false;
}
/**
* stop client connection
*/
virtual inline void stop()
{
if ( _client)
{
_client.stop();
if ( _currentHostConnectionCallback )
{
(*_currentHostConnectionCallback)(HOST_CONNECTION_DISCONNECTED);
}
}
_connected = false;
#ifdef WRITE_BUFFER_SIZE
writeBufferLength = 0;
#endif
}
};
#endif //WIFI_SERVER_STREAM_H