OpenCPN Partial API docs
Loading...
Searching...
No Matches
comm_drv_n0183_net.cpp
Go to the documentation of this file.
1/**************************************************************************
2 * Copyright (C) 2022 David Register *
3 * Copyright (C) 2022 Alec Leamas *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 **************************************************************************/
20
26#ifdef __MSVC__
27#include "winsock2.h"
28#include <wx/msw/winundef.h>
29#include <ws2tcpip.h>
30#endif
31
32#include <wx/wxprec.h>
33
34#ifndef WX_PRECOMP
35#include <wx/wx.h>
36#endif
37
38#include <ctime>
39#include <deque>
40
41#ifndef __WXMSW__
42#include <arpa/inet.h>
43#include <netinet/tcp.h>
44#endif
45
46#include <wx/datetime.h>
47#include <wx/socket.h>
48#include <wx/log.h>
49#include <wx/memory.h>
50#include <wx/chartype.h>
51#include <wx/sckaddr.h>
52
56#include "model/config_vars.h"
57#include "model/garmin_protocol_mgr.h"
58#include "model/idents.h"
59#include "model/logger.h"
60#include "model/sys_events.h"
61
62#include "observable.h"
63
64using namespace std::literals::chrono_literals;
65
66#define N_DOG_TIMEOUT 8
67
69static bool IsBroadcastAddr(unsigned addr, unsigned netmask_bits) {
70 assert(netmask_bits <= 32);
71 uint32_t netmask = 0xffffffff << (32 - netmask_bits);
72 uint32_t host_mask = ~netmask;
73 return (addr & host_mask) == host_mask;
74}
75
77public:
78 struct ip_mreq m_mrq;
79 void SetMrqAddr(unsigned int addr) {
80 m_mrq.imr_multiaddr.s_addr = addr;
81 m_mrq.imr_interface.s_addr = INADDR_ANY;
82 }
83};
84
85static bool SetOutputSocketOptions(wxSocketBase* tsock) {
86 int ret;
87
88 // Disable nagle algorithm on outgoing connection
89 // Doing this here rather than after the accept() is
90 // pointless on platforms where TCP_NODELAY is
91 // not inherited. However, none of OpenCPN's currently
92 // supported platforms fall into that category.
93
94 int nagleDisable = 1;
95 ret = tsock->SetOption(IPPROTO_TCP, TCP_NODELAY, &nagleDisable,
96 sizeof(nagleDisable));
97
98 // Drastically reduce the size of the socket output buffer
99 // so that when client goes away without properly closing, the stream will
100 // quickly fill the output buffer, and thus fail the write() call
101 // within a few seconds.
102 unsigned long outbuf_size = 1024; // Smallest allowable value on Linux
103 return (tsock->SetOption(SOL_SOCKET, SO_SNDBUF, &outbuf_size,
104 sizeof(outbuf_size)) &&
105 ret);
106}
107
108//========================================================================
109/*
110 * CommDriverN0183Net implementation
111 */
112CommDriverN0183Net::CommDriverN0183Net(const ConnectionParams* params,
113 DriverListener& listener)
114 : CommDriverN0183(NavAddr::Bus::N0183, params->GetStrippedDSPort()),
115 m_params(*params),
116 m_listener(listener),
117 m_sock(nullptr),
118 m_tsock(nullptr),
119 m_socket_server(nullptr),
120 m_is_multicast(false),
121 m_stats_timer(*this, 2s),
122 m_txenter(0),
123 m_dog_value(0),
124 m_rx_connect_event(false),
125 m_socket_timer(*this),
126 m_socketread_watchdog_timer(*this),
127 m_ok(false),
128 m_is_conn_err_reported(false) {
129 m_addr.Hostname(params->NetworkAddress);
130 m_addr.Service(params->NetworkPort);
131 this->attributes["netAddress"] = params->NetworkAddress.ToStdString();
132 this->attributes["netPort"] = std::to_string(params->NetworkPort);
133 this->attributes["userComment"] = params->UserComment.ToStdString();
134 this->attributes["ioDirection"] = DsPortTypeToString(params->IOSelect);
135 m_driver_stats.driver_bus = NavAddr::Bus::N0183;
136 m_driver_stats.driver_iface = params->GetStrippedDSPort();
137
138 m_mrq_container = std::make_unique<MrqContainer>();
139
140 // Establish event listeners
141 resume_listener.Init(SystemEvents::GetInstance().evt_resume,
142 [&](ObservedEvt&) { HandleResume(); });
143 Bind(wxEVT_SOCKET, &CommDriverN0183Net::OnSocketEvent, this, DS_SOCKET_ID);
144 Bind(wxEVT_SOCKET, &CommDriverN0183Net::OnServerSocketEvent, this,
145 DS_SERVERSOCKET_ID);
146
147 Open();
148}
149
150CommDriverN0183Net::~CommDriverN0183Net() { Close(); }
151
152void CommDriverN0183Net::HandleN0183Msg(const std::string& sentence) {
153 // Sanity check
154 m_driver_stats.rx_count += sentence.size();
155 SendToListener(sentence, m_listener, m_params);
156}
157
158void CommDriverN0183Net::Open() {
159#ifdef __UNIX__
160 in_addr_t addr =
161 ((struct sockaddr_in*)m_addr.GetAddressData())->sin_addr.s_addr;
162#else
163 unsigned int addr = inet_addr(m_addr.IPAddress().mb_str());
164#endif
165 // Create the socket
166 switch (m_params.NetProtocol) {
167 case GPSD: {
168 OpenNetworkGpsd();
169 break;
170 }
171 case TCP: {
172 OpenNetworkTcp(addr);
173 break;
174 }
175 case UDP: {
176 OpenNetworkUdp(addr);
177 break;
178 }
179 default:
180 break;
181 }
182 m_ok = true;
183}
184
185void CommDriverN0183Net::OpenNetworkUdp(unsigned int addr) {
186 if (m_params.IOSelect != DS_TYPE_OUTPUT) {
187 // We need a local (bindable) address to create the Datagram receive socket
188 // Set up the reception socket
189 wxIPV4address conn_addr;
190 conn_addr.Service(std::to_string(m_params.NetworkPort));
191 conn_addr.AnyAddress();
192 conn_addr.AnyAddress();
193 m_sock =
194 new wxDatagramSocket(conn_addr, wxSOCKET_NOWAIT | wxSOCKET_REUSEADDR);
195
196 // Test if address is IPv4 multicast
197 if ((ntohl(addr) & 0xf0000000) == 0xe0000000) {
198 m_is_multicast = true;
199 m_mrq_container->SetMrqAddr(addr);
200 m_sock->SetOption(IPPROTO_IP, IP_ADD_MEMBERSHIP, &m_mrq_container->m_mrq,
201 sizeof(m_mrq_container->m_mrq));
202 }
203
204 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
205
206 m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG | wxSOCKET_INPUT_FLAG |
207 wxSOCKET_LOST_FLAG);
208 m_sock->Notify(TRUE);
209 m_sock->SetTimeout(1); // Short timeout
210 m_driver_stats.available = true;
211 }
212
213 // Set up another socket for transmit
214 if (m_params.IOSelect != DS_TYPE_INPUT) {
215 wxIPV4address tconn_addr;
216 tconn_addr.Service(0); // use ephemeral out port
217 tconn_addr.AnyAddress();
218 m_tsock =
219 new wxDatagramSocket(tconn_addr, wxSOCKET_NOWAIT | wxSOCKET_REUSEADDR);
220 // Here would be the place to disable multicast loopback
221 // but for consistency with broadcast behaviour, we will
222 // instead rely on setting priority levels to ignore
223 // sentences read back that have just been transmitted
224 if (!m_is_multicast && IsBroadcastAddr(addr, g_netmask_bits)) {
225 int broadcastEnable = 1;
226 m_tsock->SetOption(SOL_SOCKET, SO_BROADCAST, &broadcastEnable,
227 sizeof(broadcastEnable));
228 m_driver_stats.available = true;
229 }
230 }
231
232 // In case the connection is lost before acquired....
233 m_connect_time = std::chrono::steady_clock::now();
234}
235
236void CommDriverN0183Net::OpenNetworkTcp(unsigned int addr) {
237 if (addr == INADDR_ANY) {
238 MESSAGE_LOG << "Listening for TCP connections on " << INADDR_ANY;
239 m_socket_server = new wxSocketServer(m_addr, wxSOCKET_REUSEADDR);
240 m_socket_server->SetEventHandler(*this, DS_SERVERSOCKET_ID);
241 m_socket_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
242 m_socket_server->Notify(TRUE);
243 m_socket_server->SetTimeout(1); // Short timeout
244 } else {
245 MESSAGE_LOG << "Opening TCP connection to " << m_params.NetworkAddress
246 << ":" << m_params.NetworkPort;
247 m_sock = new wxSocketClient();
248 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
249 int notify_flags = (wxSOCKET_CONNECTION_FLAG | wxSOCKET_LOST_FLAG);
250 if (m_params.IOSelect != DS_TYPE_INPUT)
251 notify_flags |= wxSOCKET_OUTPUT_FLAG;
252 if (m_params.IOSelect != DS_TYPE_OUTPUT)
253 notify_flags |= wxSOCKET_INPUT_FLAG;
254 m_sock->SetNotify(notify_flags);
255 m_sock->Notify(true);
256 m_sock->SetTimeout(1); // Short timeout
257
258 m_rx_connect_event = false;
259 m_socket_timer.Start(100, wxTIMER_ONE_SHOT); // schedule a connection
260 }
261
262 // In case the connection is lost before acquired....
263 m_connect_time = std::chrono::steady_clock::now();
264}
265
266void CommDriverN0183Net::OpenNetworkGpsd() {
267 m_sock = new wxSocketClient();
268 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
269 m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG | wxSOCKET_INPUT_FLAG |
270 wxSOCKET_LOST_FLAG);
271 m_sock->Notify(TRUE);
272 m_sock->SetTimeout(1); // Short timeout
273
274 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
275 tcp_socket->Connect(m_addr, false);
276 m_rx_connect_event = false;
277}
278
279void CommDriverN0183Net::OnSocketReadWatchdogTimer() {
280 m_dog_value--;
281
282 if (m_dog_value <= 0) { // No receive in n seconds
283 if (GetParams().NoDataReconnect) {
284 // Reconnect on NO DATA is true, so try to reconnect now.
285 if (m_params.NetProtocol == TCP) {
286 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
287 if (tcp_socket) tcp_socket->Close();
288
289 int n_reconnect_delay = wxMax(N_DOG_TIMEOUT - 2, 2);
290 wxLogMessage("Reconnection scheduled in %d seconds.",
291 n_reconnect_delay);
292 m_socket_timer.Start(n_reconnect_delay * 1000, wxTIMER_ONE_SHOT);
293
294 // Stop DATA watchdog, will be restarted on successful connection.
295 m_socketread_watchdog_timer.Stop();
296 }
297 }
298 }
299}
300
301void CommDriverN0183Net::OnTimerSocket() {
302 // Attempt a connection
303 using namespace std::chrono;
304 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
305 if (tcp_socket) {
306 if (tcp_socket->IsDisconnected()) {
307 m_driver_stats.available = false;
308 wxLogDebug("Attempting reconnection...");
309 m_rx_connect_event = false;
310 // Stop DATA watchdog, may be restarted on successful connection.
311 m_socketread_watchdog_timer.Stop();
312 tcp_socket->Connect(m_addr, false);
313
314 // schedule another connection attempt, in case this one fails
315 int n_reconnect_delay = N_DOG_TIMEOUT;
316 m_socket_timer.Start(n_reconnect_delay * 1000, wxTIMER_ONE_SHOT);
317
318 // Possibly report connect error to GUI.
319 if (m_connect_time == time_point<steady_clock>()) return;
320 auto since_connect = steady_clock::now() - m_connect_time;
321 if (since_connect > 10s && !m_is_conn_err_reported) {
322 std::stringstream ss;
323 ss << _("Cannot connect to remote server ") << m_params.NetworkAddress
324 << ":" << m_params.NetworkPort;
325 CommDriverRegistry::GetInstance().evt_driver_msg.Notify(ss.str());
326 m_is_conn_err_reported = true;
327 m_driver_stats.error_count++;
328 }
329 }
330 }
331}
332
333void CommDriverN0183Net::HandleResume() {
334 // Attempt a stop and restart of connection
335 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
336 if (tcp_socket) {
337 m_socketread_watchdog_timer.Stop();
338
339 tcp_socket->Close();
340
341 // schedule reconnect attempt
342 int n_reconnect_delay = wxMax(N_DOG_TIMEOUT - 2, 2);
343 wxLogMessage("Reconnection scheduled in %d seconds.", n_reconnect_delay);
344
345 m_socket_timer.Start(n_reconnect_delay * 1000, wxTIMER_ONE_SHOT);
346 }
347}
348
349bool CommDriverN0183Net::SendMessage(std::shared_ptr<const NavMsg> msg,
350 std::shared_ptr<const NavAddr> addr) {
351 auto msg_0183 = std::dynamic_pointer_cast<const Nmea0183Msg>(msg);
352 std::string payload(msg_0183->payload);
353 if (!ocpn::endswith(payload, "\r\n")) payload += "\r\n";
354 m_driver_stats.tx_count += payload.size();
355 return SendSentenceNetwork(payload.c_str());
356}
357
358void CommDriverN0183Net::OnSocketEvent(wxSocketEvent& event) {
359#define RD_BUF_SIZE 4096
360 // Allows handling of high volume data streams, such as a National AIS
361 // stream with 100s of msgs a second.
362
363 switch (event.GetSocketEvent()) {
364 case wxSOCKET_INPUT: // from gpsd Daemon
365 {
366 // TODO determine if the following SetFlags needs to be done at every
367 // socket event or only once when socket is created, it it needs to be
368 // done at all!
369 // m_sock->SetFlags(wxSOCKET_WAITALL | wxSOCKET_BLOCK); // was
370 // (wxSOCKET_NOWAIT);
371
372 // We use wxSOCKET_BLOCK to avoid Yield() reentrancy problems
373 // if a long ProgressDialog is active, as in S57 SENC creation.
374
375 // Disable input event notifications to preclude re-entrancy on
376 // non-blocking socket
377 // m_sock->SetNotify(wxSOCKET_LOST_FLAG);
378 uint8_t buff[RD_BUF_SIZE + 1];
379 event.GetSocket()->Read(buff, RD_BUF_SIZE);
380 if (!event.GetSocket()->Error()) {
381 unsigned count = event.GetSocket()->LastCount();
382 for (unsigned i = 0; i < count; i += 1) n0183_buffer.Put(buff[i]);
383 while (n0183_buffer.HasSentence()) {
384 HandleN0183Msg(n0183_buffer.GetSentence() + "\r\n");
385 }
386 }
387 m_dog_value = N_DOG_TIMEOUT; // feed the dog
388 break;
389 }
390
391 case wxSOCKET_LOST: {
392 m_driver_stats.available = false;
393 using namespace std::chrono;
394 if (m_params.NetProtocol == TCP || m_params.NetProtocol == GPSD) {
395 if (m_rx_connect_event) {
396 MESSAGE_LOG << "NetworkDataStream connection lost: "
397 << m_params.GetDSPort();
398 }
399 if (m_socket_server) {
400 m_sock->Destroy();
401 m_sock = nullptr;
402 break;
403 }
404 auto since_connect = 10s;
405 // ten secs assumed, if connect time is uninitialized
406 auto now = steady_clock::now();
407 if (m_connect_time != time_point<steady_clock>())
408 since_connect = duration_cast<seconds>(now - m_connect_time);
409
410 auto retry_time = 5s; // default
411 // If the socket has never connected, and it is a short interval since
412 // the connect request then stretch the time a bit. This happens on
413 // Windows if there is no default IP on any interface
414 if (!m_rx_connect_event && (since_connect < 5s)) retry_time = 10s;
415
416 m_socketread_watchdog_timer.Stop();
417
418 // Schedule a re-connect attempt
419 m_socket_timer.Start(duration_cast<milliseconds>(retry_time).count(),
420 wxTIMER_ONE_SHOT);
421 }
422 break;
423 }
424
425 case wxSOCKET_CONNECTION: {
426 if (m_params.NetProtocol == GPSD) {
427 // Sign up for watcher mode, Cooked NMEA
428 // Note that SIRF devices will be converted by gpsd into
429 // pseudo-NMEA
430
431 char cmd[] = R"--(?WATCH={"class":"WATCH", "nmea":true})--";
432 m_sock->Write(cmd, strlen(cmd));
433 } else if (m_params.NetProtocol == TCP) {
434 MESSAGE_LOG << "TCP NetworkDataStream connection established: "
435 << m_params.GetDSPort();
436
437 m_dog_value = N_DOG_TIMEOUT; // feed the dog
438 if (m_params.IOSelect != DS_TYPE_OUTPUT) {
439 // start the DATA watchdog only if NODATA Reconnect is desired
440 if (GetParams().NoDataReconnect)
441 m_socketread_watchdog_timer.Start(1000);
442 }
443
444 if (m_params.IOSelect != DS_TYPE_INPUT && GetSock()->IsOk())
445 (void)SetOutputSocketOptions(m_sock);
446 m_socket_timer.Stop();
447 m_rx_connect_event = true;
448 }
449
450 m_driver_stats.available = true;
451 m_connect_time = std::chrono::steady_clock::now();
452 break;
453 }
454
455 default:
456 break;
457 }
458}
459
460void CommDriverN0183Net::OnServerSocketEvent(wxSocketEvent& event) {
461 switch (event.GetSocketEvent()) {
462 case wxSOCKET_CONNECTION: {
463 m_sock = m_socket_server->Accept(false);
464
465 if (GetSock()) {
466 m_sock->SetTimeout(2);
467 // GetSock()->SetFlags(wxSOCKET_BLOCK);
468 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
469 int notify_flags = (wxSOCKET_CONNECTION_FLAG | wxSOCKET_LOST_FLAG);
470 if (m_params.IOSelect != DS_TYPE_INPUT) {
471 notify_flags |= wxSOCKET_OUTPUT_FLAG;
472 (void)SetOutputSocketOptions(m_sock);
473 }
474 if (m_params.IOSelect != DS_TYPE_OUTPUT)
475 notify_flags |= wxSOCKET_INPUT_FLAG;
476 m_sock->SetNotify(notify_flags);
477 m_sock->Notify(true);
478 }
479 break;
480 }
481 default:
482 break;
483 }
484}
485
486bool CommDriverN0183Net::SendSentenceNetwork(const wxString& payload) {
487 if (m_txenter)
488 return false; // do not allow recursion, could happen with non-blocking
489 // sockets
490 m_txenter++;
491
492 bool ret = true;
493 wxDatagramSocket* udp_socket;
494 switch (m_params.NetProtocol) {
495 case TCP:
496 if (GetSock() && GetSock()->IsOk()) {
497 m_sock->Write(payload.mb_str(), strlen(payload.mb_str()));
498 m_dog_value = N_DOG_TIMEOUT; // feed the dog
499 if (GetSock()->Error()) {
500 if (m_socket_server) {
501 m_sock->Destroy();
502 m_sock = nullptr;
503 } else {
504 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
505 if (tcp_socket) tcp_socket->Close();
506 if (!m_socket_timer.IsRunning())
507 m_socket_timer.Start(5000, wxTIMER_ONE_SHOT);
508 // schedule a reconnect
509 m_socketread_watchdog_timer.Stop();
510 }
511 ret = false;
512 }
513
514 } else
515 ret = false;
516 m_driver_stats.available = ret;
517
518 break;
519 case UDP:
520 udp_socket = dynamic_cast<wxDatagramSocket*>(m_tsock);
521 if (udp_socket && udp_socket->IsOk()) {
522 udp_socket->SendTo(m_addr, payload.mb_str(), payload.size());
523 m_dog_value = N_DOG_TIMEOUT; // feed the dog
524 if (udp_socket->Error()) ret = false;
525 } else {
526 ret = false;
527 }
528 m_driver_stats.available = ret;
529 break;
530
531 case GPSD:
532 default:
533 ret = false;
534 break;
535 }
536 m_txenter--;
537 return ret;
538}
539
540void CommDriverN0183Net::Close() {
541 MESSAGE_LOG << "Closing NMEA NetworkDataStream " << m_params.NetworkPort;
542 m_stats_timer.Stop();
543 // Kill off the TCP Socket if alive
544 if (m_sock) {
545 if (m_is_multicast)
546 m_sock->SetOption(IPPROTO_IP, IP_DROP_MEMBERSHIP, &m_mrq_container->m_mrq,
547 sizeof(m_mrq_container->m_mrq));
548 m_sock->Notify(FALSE);
549 m_sock->Destroy();
550 }
551
552 if (m_tsock) {
553 m_tsock->Notify(FALSE);
554 m_tsock->Destroy();
555 }
556
557 if (m_socket_server) {
558 m_socket_server->Notify(FALSE);
559 m_socket_server->Destroy();
560 }
561
562 m_socket_timer.Stop();
563 m_socketread_watchdog_timer.Stop();
564 m_driver_stats.available = false;
565}
NMEA0183 basic parsing common parts:
void SendToListener(const std::string &payload, DriverListener &listener, const ConnectionParams &params)
Wrap argument string in NavMsg pointer, forward to listener.
EventVar evt_driver_msg
Notified for messages from drivers.
Interface for handling incoming messages.
Definition comm_driver.h:52
void Notify() override
Notify all listeners, no data supplied.
bool HasSentence() const
Return true if a sentence is available to be returned by GetSentence()
std::string GetSentence()
Retrieve a sentence from buffer.
void Put(uint8_t ch)
Add a single character, possibly making a sentence available.
Where messages are sent to or received from.
Custom event class for OpenCPN's notification system.
NMEA0183 over IP driver.
Driver registration container, a singleton.
Raw messages layer, supports sending and recieving navmsg messages.
Enhanced logging interface on top of wx/log.h.
bool endswith(const std::string &str, const std::string &suffix)
Return true if s ends with given suffix.
General observable implementation with several specializations.
unsigned tx_count
Number of bytes sent since program start.
unsigned rx_count
Number of bytes received since program start.
unsigned error_count
Number of detected errors since program start.
Suspend/resume and new devices events exchange point.