OpenCPN Partial API docs
Loading...
Searching...
No Matches
multiplexer.cpp
1/***************************************************************************
2 *
3 * Project: OpenCPN
4 * Purpose: NMEA Data Multiplexer Object
5 * Author: David Register
6 *
7 ***************************************************************************
8 * Copyright (C) 2010 by David S. Register *
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 * This program is distributed in the hope that it will be useful, *
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
18 * GNU General Public License for more details. *
19 * *
20 * You should have received a copy of the GNU General Public License *
21 * along with this program; if not, write to the *
22 * Free Software Foundation, Inc., *
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
24 **************************************************************************/
25
26#ifdef __MSVC__
27#include "winsock2.h"
28#include <wx/msw/winundef.h>
29#endif
30
31#include "config.h"
32
33#ifdef HAVE_LIBGEN_H
34#include <libgen.h>
35#endif
36
37#if defined(HAVE_READLINK) && !defined(HAVE_LIBGEN_H)
38#error Using readlink(3) requires libgen.h which cannot be found.
39#endif
40
41#include <wx/wx.h>
42
43#include "model/multiplexer.h"
44
45#include "model/config_vars.h"
46#include "model/conn_params.h"
50#include "model/comm_drv_n0183_android_bt.h"
52#include "model/nmea_log.h"
53
54wxDEFINE_EVENT(EVT_N0183_MUX, ObservedEvt);
55
56wxDEFINE_EVENT(EVT_N2K_129029, ObservedEvt);
57wxDEFINE_EVENT(EVT_N2K_129025, ObservedEvt);
58wxDEFINE_EVENT(EVT_N2K_129026, ObservedEvt);
59wxDEFINE_EVENT(EVT_N2K_127250, ObservedEvt);
60wxDEFINE_EVENT(EVT_N2K_129540, ObservedEvt);
61wxDEFINE_EVENT(EVT_N2K_ALL, ObservedEvt);
62
63Multiplexer *g_pMUX;
64
65bool CheckSumCheck(const std::string &sentence) {
66 size_t check_start = sentence.find('*');
67 if (check_start == wxString::npos || check_start > sentence.size() - 3)
68 return false; // * not found, or it didn't have 2 characters following it.
69
70 std::string check_str = sentence.substr(check_start + 1, 2);
71 unsigned long checksum = strtol(check_str.c_str(), 0, 16);
72 if (checksum == 0L && check_str != "00") return false;
73
74 unsigned char calculated_checksum = 0;
75 for (std::string::const_iterator i = sentence.begin() + 1;
76 i != sentence.end() && *i != '*'; ++i)
77 calculated_checksum ^= static_cast<unsigned char>(*i);
78
79 return calculated_checksum == checksum;
80}
81
82Multiplexer::Multiplexer(MuxLogCallbacks cb, bool &filter_behaviour)
83 : m_log_callbacks(cb), m_legacy_input_filter_behaviour(filter_behaviour) {
84 m_listener_N0183_all.Listen(Nmea0183Msg::MessageKey("ALL"), this,
85 EVT_N0183_MUX);
86 Bind(EVT_N0183_MUX, [&](ObservedEvt ev) {
87 auto ptr = ev.GetSharedPtr();
88 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
89 HandleN0183(n0183_msg);
90 });
91
92 InitN2KCommListeners();
93 n_N2K_repeat = 0;
94
95 if (g_GPS_Ident.IsEmpty()) g_GPS_Ident = wxT("Generic");
96}
97
98Multiplexer::~Multiplexer() {}
99
100void Multiplexer::LogOutputMessage(const std::shared_ptr<const NavMsg> &msg,
101 NavmsgStatus ns) {
102 if (m_log_callbacks.log_is_active()) {
103 ns.direction = NavmsgStatus::Direction::kOutput;
104 Logline ll(msg, ns);
105 m_log_callbacks.log_message(ll);
106 }
107}
108
109void Multiplexer::LogInputMessage(const std::shared_ptr<const NavMsg> &msg,
110 bool is_filtered, bool is_error,
111 const wxString error_msg) {
112 if (m_log_callbacks.log_is_active()) {
113 NavmsgStatus ns;
114 ns.direction = NavmsgStatus::Direction::kReceived;
115 if (is_error) {
116 ns.status = NavmsgStatus::State::kChecksumError;
117 } else {
118 if (is_filtered) {
119 if (m_legacy_input_filter_behaviour) {
120 ns.accepted = NavmsgStatus::Accepted::kFilteredNoOutput;
121 } else {
122 ns.accepted = NavmsgStatus::Accepted::kFilteredDropped;
123 }
124 } else {
125 ns.accepted = NavmsgStatus::Accepted::kOk;
126 }
127 }
128 Logline ll(msg, ns);
129 ll.error_msg = error_msg;
130 m_log_callbacks.log_message(ll);
131 }
132}
133
134void Multiplexer::HandleN0183(std::shared_ptr<const Nmea0183Msg> n0183_msg) {
135 // Find the driver that originated this message
136
137 const auto &drivers = CommDriverRegistry::GetInstance().GetDrivers();
138 auto &source_driver = FindDriver(drivers, n0183_msg->source->iface);
139
140 wxString fmsg;
141 bool bpass_input_filter = true;
142
143 // Send to the Debug Window, if open
144 // Special formatting for non-printable characters helps debugging NMEA
145 // problems
146 std::string str = n0183_msg->payload;
147
148 // Get the params for the driver sending this message
149 ConnectionParams params;
150 auto drv_serial = dynamic_cast<CommDriverN0183Serial *>(source_driver.get());
151 if (drv_serial) {
152 params = drv_serial->GetParams();
153 } else {
154 auto drv_net = dynamic_cast<CommDriverN0183Net *>(source_driver.get());
155 if (drv_net) {
156 params = drv_net->GetParams();
157 }
158#ifdef __ANDROID__
159 else {
160 auto drv_bluetooth =
161 dynamic_cast<CommDriverN0183AndroidBT *>(source_driver.get());
162
163 if (drv_bluetooth) {
164 params = drv_bluetooth->GetParams();
165 }
166 }
167#endif
168 }
169
170 // Check to see if the message passes the source's input filter
171 bpass_input_filter =
172 params.SentencePassesFilter(n0183_msg->payload.c_str(), FILTER_INPUT);
173
174 bool b_error = false;
175 wxString error_msg;
176 for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
177 if (isprint(*it))
178 fmsg += *it;
179 else {
180 wxString bin_print;
181 bin_print.Printf(_T("<0x%02X>"), *it);
182 fmsg += bin_print;
183 if ((*it != 0x0a) && (*it != 0x0d)) {
184 b_error = true;
185 error_msg = _("Non-printable character in NMEA0183 message");
186 }
187 }
188 }
189
190 // Flag checksum errors
191 bool checksumOK = CheckSumCheck(n0183_msg->payload);
192 if (!checksumOK) {
193 b_error = true;
194 error_msg = _("NMEA0183 checksum error");
195 }
196
197 wxString port(n0183_msg->source->iface);
198 LogInputMessage(n0183_msg, !bpass_input_filter, b_error, error_msg);
199
200 // Detect virtual driver, message comes from plugin API
201 // Set such source iface to "" for later test
202 std::string source_iface;
203 if (source_driver) // NULL for virtual driver
204 source_iface = source_driver->iface;
205
206 // Perform multiplexer output functions
207 for (auto &driver : drivers) {
208 if (driver->bus == NavAddr::Bus::N0183) {
209 ConnectionParams params;
210 auto drv_serial = dynamic_cast<CommDriverN0183Serial *>(driver.get());
211 if (drv_serial) {
212 params = drv_serial->GetParams();
213 } else {
214 auto drv_net = dynamic_cast<CommDriverN0183Net *>(driver.get());
215 if (drv_net) {
216 params = drv_net->GetParams();
217 }
218#ifdef __ANDROID__
219 else {
220 auto drv_bluetooth =
221 dynamic_cast<CommDriverN0183AndroidBT *>(driver.get());
222 if (drv_bluetooth) {
223 params = drv_bluetooth->GetParams();
224 }
225 }
226#endif
227 }
228
229 std::shared_ptr<const Nmea0183Msg> msg = n0183_msg;
230 if ((m_legacy_input_filter_behaviour && !bpass_input_filter) ||
231 bpass_input_filter) {
232 // Allow re-transmit on same port (if type is SERIAL),
233 // or any other NMEA0183 port supporting output
234 // But, do not echo to the source network interface. This will likely
235 // recurse...
236 if ((!params.DisableEcho && params.Type == SERIAL) ||
237 driver->iface != source_iface) {
238 if (params.IOSelect == DS_TYPE_INPUT_OUTPUT ||
239 params.IOSelect == DS_TYPE_OUTPUT) {
240 bool bout_filter = true;
241 bool bxmit_ok = true;
242 std::string id("XXXXX");
243 size_t comma_pos = n0183_msg->payload.find(",");
244 if (comma_pos != std::string::npos && comma_pos > 5)
245 id = n0183_msg->payload.substr(1, comma_pos - 1);
246 if (params.SentencePassesFilter(n0183_msg->payload.c_str(),
247 FILTER_OUTPUT)) {
248 // Reset source address. It's const, so make a modified copy
249
250 auto null_addr = std::make_shared<NavAddr>();
251 msg = std::make_shared<Nmea0183Msg>(id, n0183_msg->payload,
252 null_addr);
253 bxmit_ok = driver->SendMessage(msg, null_addr);
254 bout_filter = false;
255 }
256
257 // Send to the Debug Window, if open
258 if (m_log_callbacks.log_is_active()) {
259 NavmsgStatus ns;
260 ns.direction = NavmsgStatus::Direction::kOutput;
261 if (bout_filter) {
262 ns.accepted = NavmsgStatus::Accepted::kFilteredDropped;
263 } else {
264 if (!bxmit_ok) ns.status = NavmsgStatus::State::kTxError;
265 }
266 auto logaddr = std::make_shared<NavAddr0183>(driver->iface);
267 auto logmsg = std::make_shared<Nmea0183Msg>(
268 id, n0183_msg->payload, logaddr);
269 LogOutputMessage(logmsg, ns);
270 }
271 }
272 }
273 }
274 }
275 }
276}
277
278void Multiplexer::InitN2KCommListeners() {
279 // Create a series of N2K listeners
280 // to allow minimal N2K Debug window logging
281
282 // All N2K
283 //----------------------------------
284 Nmea2000Msg n2k_msg_All(static_cast<uint64_t>(1));
285 listener_N2K_All.Listen(n2k_msg_All, this, EVT_N2K_ALL);
286 Bind(EVT_N2K_ALL, [&](ObservedEvt ev) {
287 HandleN2K_Log(UnpackEvtPointer<Nmea2000Msg>(ev));
288 });
289}
290
291bool Multiplexer::HandleN2K_Log(std::shared_ptr<const Nmea2000Msg> n2k_msg) {
292 if (!m_log_callbacks.log_is_active()) return false;
293
294 auto payload = n2k_msg.get()->payload;
295 // extract PGN
296 unsigned int pgn = 0;
297 pgn += n2k_msg.get()->payload.at(3);
298 pgn += n2k_msg.get()->payload.at(4) << 8;
299 pgn += n2k_msg.get()->payload.at(5) << 16;
300
301#if 0
302 printf(" %d: payload\n", pgn);
303 for(size_t i=0; i< payload.size(); i++){
304 printf("%02X ", payload.at(i));
305 }
306 printf("\n");
307 std::string pretty = n2k_msg->to_string();
308 printf("%s\n\n", pretty.c_str());
309#endif
310
311 // Input, or output?
312 if (payload.at(0) == 0x94) { // output
313 NavmsgStatus ns;
314 ns.direction = NavmsgStatus::Direction::kOutput;
315 LogOutputMessage(n2k_msg, ns);
316 } else { // input
317 // extract data source
318 std::string source = n2k_msg.get()->source->to_string();
319
320 // extract source ID
321 unsigned char source_id = n2k_msg.get()->payload.at(7);
322 char ss[4];
323 sprintf(ss, "%d", source_id);
324 std::string ident = std::string(ss);
325
326 if (pgn == last_pgn_logged) {
327 n_N2K_repeat++;
328 return false;
329 } else {
330 if (n_N2K_repeat) {
331 wxString repeat_log_msg;
332 repeat_log_msg.Printf("...Repeated %d times\n", n_N2K_repeat);
333 // LogInputMessage(repeat_log_msg, "N2000", false, false); FIXME(leamas)
334 n_N2K_repeat = 0;
335 }
336 }
337
338 wxString log_msg;
339 log_msg.Printf("PGN: %d Source: %s ID: %s Desc: %s\n", pgn, source, ident,
340 N2K_LogMessage_Detail(pgn).c_str());
341
342 LogInputMessage(n2k_msg, false, false);
343
344 last_pgn_logged = pgn;
345 }
346 return true;
347}
348
349std::string Multiplexer::N2K_LogMessage_Detail(unsigned int pgn) {
350 std::string notused = "Not used by OCPN, maybe by Plugins";
351
352 switch (pgn) {
353 case 129029:
354 return "GNSS Position & DBoard: SAT System";
355 case 129025:
356 return "Position rapid";
357 case 129026:
358 return "COG/SOG rapid";
359 case 129038:
360 return "AIS Class A position report";
361 case 129039:
362 return "AIS Class B position report";
363 case 129041:
364 return "AIS Aids to Navigation (AtoN) Report";
365 case 129793:
366 return "AIS Base Station report";
367 case 129794:
368 return "AIS static data class A";
369 ;
370 case 129809:
371 return "AIS static data class B part A";
372 case 129810:
373 return "AIS static data class B part B";
374 case 127250:
375 return "Heading rapid";
376 case 129540:
377 return "GNSS Sats & DBoard: SAT Status";
378 //>> Dashboard
379 case 127245:
380 return "DBoard: Rudder data";
381 case 127257:
382 return "DBoard: Roll Pitch";
383 case 128259:
384 return "DBoard: Speed through water";
385 ;
386 case 128267:
387 return "DBoard: Depth Data";
388 case 128275:
389 return "DBoard: Distance log";
390 case 130306:
391 return "DBoard: Wind data";
392 case 130310:
393 return "DBoard: Envorinment data";
394 // Not used PGNs
395 case 126992:
396 return "System time. " + notused;
397 case 127233:
398 return "Man Overboard Notification. " + notused;
399 case 127237:
400 return "Heading/Track control. " + notused;
401 case 127251:
402 return "Rate of turn. " + notused;
403 case 127258:
404 return "Magnetic variation. " + notused;
405 case 127488:
406 return "Engine rapid param. " + notused;
407 case 127489:
408 return "Engine parameters dynamic. " + notused;
409 case 127493:
410 return "Transmission parameters dynamic. " + notused;
411 case 127497:
412 return "Trip Parameters, Engine. " + notused;
413 case 127501:
414 return "Binary status report. " + notused;
415 case 127505:
416 return "Fluid level. " + notused;
417 case 127506:
418 return "DC Detailed Status. " + notused;
419 case 127507:
420 return "Charger Status. " + notused;
421 case 127508:
422 return "Battery Status. " + notused;
423 case 127513:
424 return "Battery Configuration Status. " + notused;
425 case 128000:
426 return "Leeway. " + notused;
427 case 128776:
428 return "Windlass Control Status. " + notused;
429 case 128777:
430 return "Windlass Operating Status. " + notused;
431 case 128778:
432 return "Windlass Monitoring Status. " + notused;
433 case 129033:
434 return "Date,Time & Local offset. " + notused;
435 case 129539:
436 return "GNSS DOP data. " + notused;
437 case 129283:
438 return "Cross Track Error. " + notused;
439 case 129284:
440 return "Navigation info. " + notused;
441 case 129285:
442 return "Waypoint list. " + notused;
443 case 129802:
444 return "AIS Safety Related Broadcast Message. " + notused;
445 case 130074:
446 return "Waypoint list. " + notused;
447 case 130311:
448 return "Environmental parameters. " + notused;
449 case 130312:
450 return "Temperature. " + notused;
451 case 130313:
452 return "Humidity. " + notused;
453 case 130314:
454 return "Actual Pressure. " + notused;
455 case 130315:
456 return "Set Pressure. " + notused;
457 case 130316:
458 return "Temperature extended range. " + notused;
459 case 130323:
460 return "Meteorological Station Data. " + notused;
461 case 130576:
462 return "Trim Tab Position. " + notused;
463 case 130577:
464 return "Direction Data. " + notused;
465 default:
466 return "No description. Not used by OCPN, maybe passed to plugins";
467 }
468}
const std::vector< DriverPtr > & GetDrivers() const
void LogInputMessage(const std::shared_ptr< const NavMsg > &msg, bool is_filtered, bool is_error, const wxString error_msg="")
Logs an input message with context information.
Representation of message status as determined by the multiplexer.
static std::string MessageKey(const char *type="ALL")
Return key which should be used to listen to given message type.
See: https://github.com/OpenCPN/OpenCPN/issues/2729#issuecomment-1179506343.
void Listen(const std::string &key, wxEvtHandler *listener, wxEventType evt)
Set object to send wxEventType ev to listener on changes in key.
Custom event class for OpenCPN's notification system.
std::shared_ptr< const void > GetSharedPtr() const
Gets the event's payload data.
NMEA0183 over IP driver.
NMEA0183 serial driver.
DriverPtr & FindDriver(const std::vector< DriverPtr > &drivers, const std::string &iface, const NavAddr::Bus _bus)
Search list of drivers for a driver with given interface string.
Driver registration container, a singleton.
Raw messages layer, supports sending and recieving navmsg messages.
Item in the log window.
Definition nmea_log.h:10