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