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