-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathGpsdSerial.cpp
More file actions
230 lines (194 loc) · 5.44 KB
/
Copy pathGpsdSerial.cpp
File metadata and controls
230 lines (194 loc) · 5.44 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#ifdef ARCH_PORTDUINO
#include "GpsdSerial.h"
#include "configuration.h"
#include <cerrno>
#ifdef _WIN32
#include <mutex>
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
namespace
{
// Winsock needs explicit init, closesocket(), ioctlsocket() and WSAGetLastError().
// SOCKET fits the header's `int` on Win64, and INVALID_SOCKET narrows to -1.
#ifdef _WIN32
// Done lazily to keep the dependency local to the one file that needs it.
void initSocketsOnce()
{
static std::once_flag flag;
std::call_once(flag, [] {
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
});
}
void closeSocket(int fd)
{
::closesocket(static_cast<SOCKET>(fd));
}
void setNonBlocking(int fd)
{
u_long mode = 1;
::ioctlsocket(static_cast<SOCKET>(fd), FIONBIO, &mode);
}
// Winsock has no MSG_DONTWAIT, but the socket is already non-blocking so a plain
// recv() has the same semantics.
int recvNonBlocking(int fd, void *buf, size_t len)
{
return ::recv(static_cast<SOCKET>(fd), static_cast<char *>(buf), static_cast<int>(len), 0);
}
int sendAll(int fd, const void *buf, size_t len)
{
return ::send(static_cast<SOCKET>(fd), static_cast<const char *>(buf), static_cast<int>(len), 0);
}
bool lastErrorWasWouldBlock()
{
return WSAGetLastError() == WSAEWOULDBLOCK;
}
#else
void initSocketsOnce() {}
void closeSocket(int fd)
{
::close(fd);
}
void setNonBlocking(int fd)
{
::fcntl(fd, F_SETFL, O_NONBLOCK);
}
int recvNonBlocking(int fd, void *buf, size_t len)
{
return static_cast<int>(::recv(fd, buf, len, MSG_DONTWAIT));
}
int sendAll(int fd, const void *buf, size_t len)
{
return static_cast<int>(::write(fd, buf, len));
}
bool lastErrorWasWouldBlock()
{
return errno == EAGAIN || errno == EWOULDBLOCK;
}
#endif
} // namespace
namespace arduino
{
// The single global instance used by PortduinoGlue and GPS::createGps().
GpsdSerial gpsdSerial;
void GpsdSerial::setAddress(const std::string &host, int port)
{
_host = host;
_port = port;
}
bool GpsdSerial::connectToGpsd()
{
if (_host.empty())
return false;
initSocketsOnce();
struct addrinfo hints = {}, *res = nullptr;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
std::string portStr = std::to_string(_port);
if (getaddrinfo(_host.c_str(), portStr.c_str(), &hints, &res) != 0 || !res) {
LOG_WARN("gpsdSerial: can't resolve %s", _host.c_str());
return false;
}
// Try every address returned by getaddrinfo (e.g. ::1 before 127.0.0.1).
int fd = -1;
for (struct addrinfo *rp = res; rp != nullptr; rp = rp->ai_next) {
fd = static_cast<int>(socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol));
if (fd < 0)
continue;
if (connect(fd, rp->ai_addr, static_cast<int>(rp->ai_addrlen)) == 0)
break; // connected
closeSocket(fd);
fd = -1;
}
freeaddrinfo(res);
if (fd < 0) {
LOG_WARN("gpsdSerial: connect to %s:%d failed", _host.c_str(), _port);
return false;
}
// Switch to non-blocking so available()/read() never stall the GPS thread.
setNonBlocking(fd);
// Ask gpsd to stream raw NMEA sentences.
const char watchCmd[] = "?WATCH={\"enable\":true,\"nmea\":true}\n";
sendAll(fd, watchCmd, sizeof(watchCmd) - 1);
_sockfd = fd;
_rxBuf.clear();
LOG_INFO("gpsdSerial: connected to %s:%d", _host.c_str(), _port);
return true;
}
void GpsdSerial::begin(unsigned long /*baud*/, uint16_t /*config*/)
{
if (_sockfd >= 0)
end();
_lastConnectAttemptMs = 0; // force immediate connect on begin()
connectToGpsd();
}
void GpsdSerial::end()
{
if (_sockfd >= 0) {
closeSocket(_sockfd);
_sockfd = -1;
}
_rxBuf.clear();
}
void GpsdSerial::fillBuffer()
{
if (_sockfd < 0)
return;
// Guard: if the buffer is already full, skip recv entirely so n is always
// assigned before the post-loop disconnect check below.
if (_rxBuf.size() >= RX_BUF_MAX)
return;
uint8_t tmp[256];
int n;
while (_rxBuf.size() < RX_BUF_MAX && (n = recvNonBlocking(_sockfd, tmp, sizeof(tmp))) > 0) {
size_t space = RX_BUF_MAX - _rxBuf.size();
size_t toCopy = (static_cast<size_t>(n) < space) ? static_cast<size_t>(n) : space;
for (size_t i = 0; i < toCopy; i++)
_rxBuf.push_back(tmp[i]);
}
if (n == 0 || (n < 0 && !lastErrorWasWouldBlock())) {
// gpsd closed the connection or a real error occurred.
LOG_WARN("gpsdSerial: disconnected, will retry");
closeSocket(_sockfd);
_sockfd = -1;
_rxBuf.clear();
}
}
int GpsdSerial::available()
{
if (_sockfd < 0) {
// Throttle reconnect attempts to avoid log spam and repeated DNS lookups
// when gpsd is unreachable.
uint32_t now = millis();
if (now - _lastConnectAttemptMs >= RECONNECT_INTERVAL_MS) {
_lastConnectAttemptMs = now;
connectToGpsd();
}
}
fillBuffer();
return static_cast<int>(_rxBuf.size());
}
int GpsdSerial::peek()
{
if (_rxBuf.empty())
return -1;
return static_cast<int>(_rxBuf.front());
}
int GpsdSerial::read()
{
if (_rxBuf.empty())
return -1;
uint8_t c = _rxBuf.front();
_rxBuf.pop_front();
return static_cast<int>(c);
}
} // namespace arduino
#endif // ARCH_PORTDUINO