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 if ((sentence[0] == '$' || sentence[0] == '!') && sentence.size() > 5) {
155 m_driver_stats.rx_count += sentence.size();
156 std::string identifier;
157 // We notify based on full message, including the Talker ID
158 identifier = sentence.substr(1, 5);
159
160 // notify message listener and also "ALL" N0183 messages, to support plugin
161 // API using original talker id
162 auto msg =
163 std::make_shared<const Nmea0183Msg>(identifier, sentence, GetAddress());
164 auto msg_all = std::make_shared<const Nmea0183Msg>(*msg, "ALL");
165
166 if (m_params.SentencePassesFilter(sentence, FILTER_INPUT))
167 m_listener.Notify(std::move(msg));
168 m_listener.Notify(std::move(msg_all));
169 }
170}
171
172void CommDriverN0183Net::Open() {
173#ifdef __UNIX__
174 in_addr_t addr =
175 ((struct sockaddr_in*)m_addr.GetAddressData())->sin_addr.s_addr;
176#else
177 unsigned int addr = inet_addr(m_addr.IPAddress().mb_str());
178#endif
179 // Create the socket
180 switch (m_params.NetProtocol) {
181 case GPSD: {
182 OpenNetworkGpsd();
183 break;
184 }
185 case TCP: {
186 OpenNetworkTcp(addr);
187 break;
188 }
189 case UDP: {
190 OpenNetworkUdp(addr);
191 break;
192 }
193 default:
194 break;
195 }
196 m_ok = true;
197}
198
199void CommDriverN0183Net::OpenNetworkUdp(unsigned int addr) {
200 if (m_params.IOSelect != DS_TYPE_OUTPUT) {
201 // We need a local (bindable) address to create the Datagram receive socket
202 // Set up the reception socket
203 wxIPV4address conn_addr;
204 conn_addr.Service(std::to_string(m_params.NetworkPort));
205 conn_addr.AnyAddress();
206 conn_addr.AnyAddress();
207 m_sock =
208 new wxDatagramSocket(conn_addr, wxSOCKET_NOWAIT | wxSOCKET_REUSEADDR);
209
210 // Test if address is IPv4 multicast
211 if ((ntohl(addr) & 0xf0000000) == 0xe0000000) {
212 m_is_multicast = true;
213 m_mrq_container->SetMrqAddr(addr);
214 m_sock->SetOption(IPPROTO_IP, IP_ADD_MEMBERSHIP, &m_mrq_container->m_mrq,
215 sizeof(m_mrq_container->m_mrq));
216 }
217
218 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
219
220 m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG | wxSOCKET_INPUT_FLAG |
221 wxSOCKET_LOST_FLAG);
222 m_sock->Notify(TRUE);
223 m_sock->SetTimeout(1); // Short timeout
224 m_driver_stats.available = true;
225 }
226
227 // Set up another socket for transmit
228 if (m_params.IOSelect != DS_TYPE_INPUT) {
229 wxIPV4address tconn_addr;
230 tconn_addr.Service(0); // use ephemeral out port
231 tconn_addr.AnyAddress();
232 m_tsock =
233 new wxDatagramSocket(tconn_addr, wxSOCKET_NOWAIT | wxSOCKET_REUSEADDR);
234 // Here would be the place to disable multicast loopback
235 // but for consistency with broadcast behaviour, we will
236 // instead rely on setting priority levels to ignore
237 // sentences read back that have just been transmitted
238 if (!m_is_multicast && IsBroadcastAddr(addr, g_netmask_bits)) {
239 int broadcastEnable = 1;
240 m_tsock->SetOption(SOL_SOCKET, SO_BROADCAST, &broadcastEnable,
241 sizeof(broadcastEnable));
242 }
243 }
244
245 // In case the connection is lost before acquired....
246 m_connect_time = std::chrono::steady_clock::now();
247}
248
249void CommDriverN0183Net::OpenNetworkTcp(unsigned int addr) {
250 if (addr == INADDR_ANY) {
251 MESSAGE_LOG << "Listening for TCP connections on " << INADDR_ANY;
252 m_socket_server = new wxSocketServer(m_addr, wxSOCKET_REUSEADDR);
253 m_socket_server->SetEventHandler(*this, DS_SERVERSOCKET_ID);
254 m_socket_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
255 m_socket_server->Notify(TRUE);
256 m_socket_server->SetTimeout(1); // Short timeout
257 } else {
258 MESSAGE_LOG << "Opening TCP connection to " << m_params.NetworkAddress
259 << ":" << m_params.NetworkPort;
260 m_sock = new wxSocketClient();
261 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
262 int notify_flags = (wxSOCKET_CONNECTION_FLAG | wxSOCKET_LOST_FLAG);
263 if (m_params.IOSelect != DS_TYPE_INPUT)
264 notify_flags |= wxSOCKET_OUTPUT_FLAG;
265 if (m_params.IOSelect != DS_TYPE_OUTPUT)
266 notify_flags |= wxSOCKET_INPUT_FLAG;
267 m_sock->SetNotify(notify_flags);
268 m_sock->Notify(true);
269 m_sock->SetTimeout(1); // Short timeout
270
271 m_rx_connect_event = false;
272 m_socket_timer.Start(100, wxTIMER_ONE_SHOT); // schedule a connection
273 }
274
275 // In case the connection is lost before acquired....
276 m_connect_time = std::chrono::steady_clock::now();
277}
278
279void CommDriverN0183Net::OpenNetworkGpsd() {
280 m_sock = new wxSocketClient();
281 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
282 m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG | wxSOCKET_INPUT_FLAG |
283 wxSOCKET_LOST_FLAG);
284 m_sock->Notify(TRUE);
285 m_sock->SetTimeout(1); // Short timeout
286
287 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
288 tcp_socket->Connect(m_addr, false);
289 m_rx_connect_event = false;
290}
291
292void CommDriverN0183Net::OnSocketReadWatchdogTimer() {
293 m_dog_value--;
294
295 if (m_dog_value <= 0) { // No receive in n seconds
296 if (GetParams().NoDataReconnect) {
297 // Reconnect on NO DATA is true, so try to reconnect now.
298 if (m_params.NetProtocol == TCP) {
299 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
300 if (tcp_socket) tcp_socket->Close();
301
302 int n_reconnect_delay = wxMax(N_DOG_TIMEOUT - 2, 2);
303 wxLogMessage("Reconnection scheduled in %d seconds.",
304 n_reconnect_delay);
305 m_socket_timer.Start(n_reconnect_delay * 1000, wxTIMER_ONE_SHOT);
306
307 // Stop DATA watchdog, will be restarted on successful connection.
308 m_socketread_watchdog_timer.Stop();
309 }
310 }
311 }
312}
313
314void CommDriverN0183Net::OnTimerSocket() {
315 // Attempt a connection
316 using namespace std::chrono;
317 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
318 if (tcp_socket) {
319 if (tcp_socket->IsDisconnected()) {
320 m_driver_stats.available = false;
321 wxLogDebug("Attempting reconnection...");
322 m_rx_connect_event = false;
323 // Stop DATA watchdog, may be restarted on successful connection.
324 m_socketread_watchdog_timer.Stop();
325 tcp_socket->Connect(m_addr, false);
326
327 // schedule another connection attempt, in case this one fails
328 int n_reconnect_delay = N_DOG_TIMEOUT;
329 m_socket_timer.Start(n_reconnect_delay * 1000, wxTIMER_ONE_SHOT);
330
331 // Possibly report connect error to GUI.
332 if (m_connect_time == time_point<steady_clock>()) return;
333 auto since_connect = steady_clock::now() - m_connect_time;
334 if (since_connect > 10s && !m_is_conn_err_reported) {
335 std::stringstream ss;
336 ss << "Cannot connect to remote server " << m_params.NetworkAddress
337 << ":" << m_params.NetworkPort;
338 CommDriverRegistry::GetInstance().evt_driver_msg.Notify(ss.str());
339 m_is_conn_err_reported = true;
340 m_driver_stats.error_count++;
341 }
342 }
343 }
344}
345
346void CommDriverN0183Net::HandleResume() {
347 // Attempt a stop and restart of connection
348 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
349 if (tcp_socket) {
350 m_socketread_watchdog_timer.Stop();
351
352 tcp_socket->Close();
353
354 // schedule reconnect attempt
355 int n_reconnect_delay = wxMax(N_DOG_TIMEOUT - 2, 2);
356 wxLogMessage("Reconnection scheduled in %d seconds.", n_reconnect_delay);
357
358 m_socket_timer.Start(n_reconnect_delay * 1000, wxTIMER_ONE_SHOT);
359 }
360}
361
362bool CommDriverN0183Net::SendMessage(std::shared_ptr<const NavMsg> msg,
363 std::shared_ptr<const NavAddr> addr) {
364 auto msg_0183 = std::dynamic_pointer_cast<const Nmea0183Msg>(msg);
365 std::string payload(msg_0183->payload);
366 if (!ocpn::endswith(payload, "\r\n")) payload += "\r\n";
367 m_driver_stats.tx_count += payload.size();
368 return SendSentenceNetwork(payload.c_str());
369}
370
371void CommDriverN0183Net::OnSocketEvent(wxSocketEvent& event) {
372#define RD_BUF_SIZE 4096
373 // Allows handling of high volume data streams, such as a National AIS
374 // stream with 100s of msgs a second.
375
376 switch (event.GetSocketEvent()) {
377 case wxSOCKET_INPUT: // from gpsd Daemon
378 {
379 // TODO determine if the following SetFlags needs to be done at every
380 // socket event or only once when socket is created, it it needs to be
381 // done at all!
382 // m_sock->SetFlags(wxSOCKET_WAITALL | wxSOCKET_BLOCK); // was
383 // (wxSOCKET_NOWAIT);
384
385 // We use wxSOCKET_BLOCK to avoid Yield() reentrancy problems
386 // if a long ProgressDialog is active, as in S57 SENC creation.
387
388 // Disable input event notifications to preclude re-entrancy on
389 // non-blocking socket
390 // m_sock->SetNotify(wxSOCKET_LOST_FLAG);
391 uint8_t buff[RD_BUF_SIZE + 1];
392 event.GetSocket()->Read(buff, RD_BUF_SIZE);
393 if (!event.GetSocket()->Error()) {
394 unsigned count = event.GetSocket()->LastCount();
395 for (unsigned i = 0; i < count; i += 1) n0183_buffer.Put(buff[i]);
396 while (n0183_buffer.HasSentence()) {
397 HandleN0183Msg(n0183_buffer.GetSentence() + "\r\n");
398 }
399 }
400 m_dog_value = N_DOG_TIMEOUT; // feed the dog
401 break;
402 }
403
404 case wxSOCKET_LOST: {
405 m_driver_stats.available = false;
406 using namespace std::chrono;
407 if (m_params.NetProtocol == TCP || m_params.NetProtocol == GPSD) {
408 if (m_rx_connect_event) {
409 MESSAGE_LOG << "NetworkDataStream connection lost: "
410 << m_params.GetDSPort();
411 }
412 if (m_socket_server) {
413 m_sock->Destroy();
414 m_sock = nullptr;
415 break;
416 }
417 auto since_connect = 10s;
418 // ten secs assumed, if connect time is uninitialized
419 auto now = steady_clock::now();
420 if (m_connect_time != time_point<steady_clock>())
421 since_connect = duration_cast<seconds>(now - m_connect_time);
422
423 auto retry_time = 5s; // default
424 // If the socket has never connected, and it is a short interval since
425 // the connect request then stretch the time a bit. This happens on
426 // Windows if there is no default IP on any interface
427 if (!m_rx_connect_event && (since_connect < 5s)) retry_time = 10s;
428
429 m_socketread_watchdog_timer.Stop();
430
431 // Schedule a re-connect attempt
432 m_socket_timer.Start(duration_cast<milliseconds>(retry_time).count(),
433 wxTIMER_ONE_SHOT);
434 }
435 break;
436 }
437
438 case wxSOCKET_CONNECTION: {
439 if (m_params.NetProtocol == GPSD) {
440 // Sign up for watcher mode, Cooked NMEA
441 // Note that SIRF devices will be converted by gpsd into
442 // pseudo-NMEA
443
444 char cmd[] = R"--(?WATCH={"class":"WATCH", "nmea":true})--";
445 m_sock->Write(cmd, strlen(cmd));
446 } else if (m_params.NetProtocol == TCP) {
447 MESSAGE_LOG << "TCP NetworkDataStream connection established: "
448 << m_params.GetDSPort();
449
450 m_dog_value = N_DOG_TIMEOUT; // feed the dog
451 if (m_params.IOSelect != DS_TYPE_OUTPUT) {
452 // start the DATA watchdog only if NODATA Reconnect is desired
453 if (GetParams().NoDataReconnect)
454 m_socketread_watchdog_timer.Start(1000);
455 }
456
457 if (m_params.IOSelect != DS_TYPE_INPUT && GetSock()->IsOk())
458 (void)SetOutputSocketOptions(m_sock);
459 m_socket_timer.Stop();
460 m_rx_connect_event = true;
461 }
462
463 m_driver_stats.available = true;
464 m_connect_time = std::chrono::steady_clock::now();
465 break;
466 }
467
468 default:
469 break;
470 }
471}
472
473void CommDriverN0183Net::OnServerSocketEvent(wxSocketEvent& event) {
474 switch (event.GetSocketEvent()) {
475 case wxSOCKET_CONNECTION: {
476 m_sock = m_socket_server->Accept(false);
477
478 if (GetSock()) {
479 m_sock->SetTimeout(2);
480 // GetSock()->SetFlags(wxSOCKET_BLOCK);
481 m_sock->SetEventHandler(*this, DS_SOCKET_ID);
482 int notify_flags = (wxSOCKET_CONNECTION_FLAG | wxSOCKET_LOST_FLAG);
483 if (m_params.IOSelect != DS_TYPE_INPUT) {
484 notify_flags |= wxSOCKET_OUTPUT_FLAG;
485 (void)SetOutputSocketOptions(m_sock);
486 }
487 if (m_params.IOSelect != DS_TYPE_OUTPUT)
488 notify_flags |= wxSOCKET_INPUT_FLAG;
489 m_sock->SetNotify(notify_flags);
490 m_sock->Notify(true);
491 }
492 break;
493 }
494 default:
495 break;
496 }
497}
498
499bool CommDriverN0183Net::SendSentenceNetwork(const wxString& payload) {
500 if (m_txenter)
501 return false; // do not allow recursion, could happen with non-blocking
502 // sockets
503 m_txenter++;
504
505 bool ret = true;
506 wxDatagramSocket* udp_socket;
507 switch (m_params.NetProtocol) {
508 case TCP:
509 if (GetSock() && GetSock()->IsOk()) {
510 m_sock->Write(payload.mb_str(), strlen(payload.mb_str()));
511 if (GetSock()->Error()) {
512 if (m_socket_server) {
513 m_sock->Destroy();
514 m_sock = nullptr;
515 } else {
516 auto* tcp_socket = dynamic_cast<wxSocketClient*>(m_sock);
517 if (tcp_socket) tcp_socket->Close();
518 if (!m_socket_timer.IsRunning())
519 m_socket_timer.Start(5000, wxTIMER_ONE_SHOT);
520 // schedule a reconnect
521 m_socketread_watchdog_timer.Stop();
522 }
523 ret = false;
524 }
525
526 } else
527 ret = false;
528 break;
529 case UDP:
530 udp_socket = dynamic_cast<wxDatagramSocket*>(m_tsock);
531 if (udp_socket && udp_socket->IsOk()) {
532 udp_socket->SendTo(m_addr, payload.mb_str(), payload.size());
533 if (udp_socket->Error()) ret = false;
534 } else {
535 ret = false;
536 }
537 m_driver_stats.available = ret;
538 break;
539
540 case GPSD:
541 default:
542 ret = false;
543 break;
544 }
545 m_txenter--;
546 return ret;
547}
548
549void CommDriverN0183Net::Close() {
550 MESSAGE_LOG << "Closing NMEA NetworkDataStream " << m_params.NetworkPort;
551 // Kill off the TCP Socket if alive
552 if (m_sock) {
553 if (m_is_multicast)
554 m_sock->SetOption(IPPROTO_IP, IP_DROP_MEMBERSHIP, &m_mrq_container->m_mrq,
555 sizeof(m_mrq_container->m_mrq));
556 m_sock->Notify(FALSE);
557 m_sock->Destroy();
558 }
559
560 if (m_tsock) {
561 m_tsock->Notify(FALSE);
562 m_tsock->Destroy();
563 }
564
565 if (m_socket_server) {
566 m_socket_server->Notify(FALSE);
567 m_socket_server->Destroy();
568 }
569
570 m_socket_timer.Stop();
571 m_socketread_watchdog_timer.Stop();
572 m_driver_stats.available = false;
573}
NMEA0183 drivers common part.
EventVar evt_driver_msg
Notified for messages from drivers.
Interface implemented by transport layer and possible other parties like test code which should handl...
Definition comm_driver.h:48
virtual void Notify(std::shared_ptr< const NavMsg > message)=0
Handle a received message.
const void Notify()
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.
Adds a std::shared<void> element to wxCommandEvent.
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.
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.