OpenCPN Partial API docs
Loading...
Searching...
No Matches
ais_decoder.cpp
Go to the documentation of this file.
1/**************************************************************************
2 * Copyright (C) 2010 by David S. Register *
3 * *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
8 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
16 ***************************************************************************/
17
23
24// For compilers that support precompilation, includes "wx.h".
25
26#include <algorithm>
27#include <string_view>
28#include <cstdio>
29#include <fstream>
30
31#ifdef __MINGW32__
32#undef IPV6STRICT // mingw FTBS fix: missing struct ip_mreq
33#include <windows.h>
34#endif
35
36#include <wx/wxprec.h>
37#ifndef WX_PRECOMP
38#include <wx/wx.h>
39#endif
40
41#include <wx/datetime.h>
42#include <wx/event.h>
43#include <wx/log.h>
44#include <wx/string.h>
45#include <wx/textfile.h>
46#include <wx/timer.h>
47#include <wx/tokenzr.h>
48#include <wx/filename.h>
49
50// Be sure to include these before ais_decoder.h
51// to avoid a conflict with rapidjson/fwd.h
52#include "rapidjson/document.h"
53#include "rapidjson/writer.h"
54#include "rapidjson/stringbuffer.h"
55
56#include "model/ais_decoder.h"
58#include "model/meteo_points.h"
61#include "model/config_vars.h"
62#include "model/geodesic.h"
63#include "model/georef.h"
64#include "model/idents.h"
65#include "model/multiplexer.h"
66#include "model/navutil_base.h"
67#include "model/own_ship.h"
68#include "model/route_point.h"
69#include "model/select.h"
70#include "model/track.h"
71#include "N2KParser.h"
72
73#if !defined(NAN)
74static const long long lNaN = 0xfff8000000000000;
75#define NAN (*(double *)&lNaN)
76#endif
77
78wxEvtHandler *g_pais_alert_dialog_active;
79
82wxString GetShipNameFromFile(int);
84
86
87wxDEFINE_EVENT(EVT_N0183_VDO, ObservedEvt);
88wxDEFINE_EVENT(EVT_N0183_VDM, ObservedEvt);
89wxDEFINE_EVENT(EVT_N0183_FRPOS, ObservedEvt);
90wxDEFINE_EVENT(EVT_N0183_CDDSC, ObservedEvt);
91wxDEFINE_EVENT(EVT_N0183_CDDSE, ObservedEvt);
92wxDEFINE_EVENT(EVT_N0183_TLL, ObservedEvt);
93wxDEFINE_EVENT(EVT_N0183_TTM, ObservedEvt);
94wxDEFINE_EVENT(EVT_N0183_OSD, ObservedEvt);
95wxDEFINE_EVENT(EVT_N0183_WPL, ObservedEvt);
96wxDEFINE_EVENT(EVT_SIGNALK, ObservedEvt);
97wxDEFINE_EVENT(EVT_N2K_129038, ObservedEvt);
98wxDEFINE_EVENT(EVT_N2K_129039, ObservedEvt);
99wxDEFINE_EVENT(EVT_N2K_129041, ObservedEvt);
100wxDEFINE_EVENT(EVT_N2K_129794, ObservedEvt);
101wxDEFINE_EVENT(EVT_N2K_129809, ObservedEvt);
102wxDEFINE_EVENT(EVT_N2K_129810, ObservedEvt);
103wxDEFINE_EVENT(EVT_N2K_129793, ObservedEvt);
104
105BEGIN_EVENT_TABLE(AisDecoder, wxEvtHandler)
106EVT_TIMER(TIMER_AIS1, AisDecoder::OnTimerAIS)
107EVT_TIMER(TIMER_DSC, AisDecoder::OnTimerDSC)
108END_EVENT_TABLE()
109
110static constexpr double ms_to_knot_factor = 1.9438444924406;
111
112static int n_msgs;
113static int n_msg1;
114static int n_msg5;
115static int n_msg24;
116static bool b_firstrx;
117static int first_rx_ticks;
118static int rx_ticks;
119static double arpa_ref_hdg = NAN;
120
121static inline double GeodesicRadToDeg(double rads) {
122 return rads * 180.0 / M_PI;
123}
124
125static inline double MS2KNOTS(double ms) { return ms * 1.9438444924406; }
126
127static bool isBuoyMmsi(unsigned msi) {
128 // IMO standard is not yet(?) implemented for (net)buoys
129 // This adaption, based on real-world outcomes, is used instead
130 // Consider any not valid MMSI number for a class B target (message 18 or 19)
131 // to be a "net buoy"
132 int mid = msi / 1000000;
133 // MID is stated to be >200 <799. Handheld AIS starts with 8+mid thus 880
134 // "Pirate ATON buoy" seems to occur out there with MID = 799.
135 if ((mid > 200 && mid < 799) || (mid >= 800 && mid < 880) || mid >= 970) {
136 return false;
137 } else {
138 return true;
139 }
140 return false;
141}
142
143int AisMeteoNewMmsi(int, int, int, int, int);
144int origin_mmsi = 0;
145
146void AISshipNameCache(AisTargetData *pTargetData,
147 AIS_Target_Name_Hash *AISTargetNamesC,
148 AIS_Target_Name_Hash *AISTargetNamesNC, long mmsi);
149static void BuildERIShipTypeHash() {
150 make_hash_ERI(8000, _("Vessel, type unknown"));
151 make_hash_ERI(8150, _("Freightbarge"));
152 make_hash_ERI(8160, _("Tankbarge"));
153 make_hash_ERI(8163, _("Tankbarge, dry cargo as if liquid (e.g. cement)"));
154 make_hash_ERI(8450, _("Service vessel, police patrol, port service"));
155 make_hash_ERI(8430, _("Pushboat, single"));
156 make_hash_ERI(8510, _("Object, not otherwise specified"));
157 make_hash_ERI(8470, _("Object, towed, not otherwise specified"));
158 make_hash_ERI(8490, _("Bunkership"));
159 make_hash_ERI(8010, _("Motor freighter"));
160 make_hash_ERI(8020, _("Motor tanker"));
161 make_hash_ERI(8021, _("Motor tanker, liquid cargo, type N"));
162 make_hash_ERI(8022, _("Motor tanker, liquid cargo, type C"));
163 make_hash_ERI(8023, _("Motor tanker, dry cargo as if liquid (e.g. cement)"));
164 make_hash_ERI(8030, _("Container vessel"));
165 make_hash_ERI(8040, _("Gas tanker"));
166 make_hash_ERI(8050, _("Motor freighter, tug"));
167 make_hash_ERI(8060, _("Motor tanker, tug"));
168 make_hash_ERI(8070, _("Motor freighter with one or more ships alongside"));
169 make_hash_ERI(8080, _("Motor freighter with tanker"));
170 make_hash_ERI(8090, _("Motor freighter pushing one or more freighters"));
171 make_hash_ERI(8100, _("Motor freighter pushing at least one tank-ship"));
172 make_hash_ERI(8110, _("Tug, freighter"));
173 make_hash_ERI(8120, _("Tug, tanker"));
174 make_hash_ERI(8130, _("Tug freighter, coupled"));
175 make_hash_ERI(8140, _("Tug, freighter/tanker, coupled"));
176 make_hash_ERI(8161, _("Tankbarge, liquid cargo, type N"));
177 make_hash_ERI(8162, _("Tankbarge, liquid cargo, type C"));
178 make_hash_ERI(8170, _("Freightbarge with containers"));
179 make_hash_ERI(8180, _("Tankbarge, gas"));
180 make_hash_ERI(8210, _("Pushtow, one cargo barge"));
181 make_hash_ERI(8220, _("Pushtow, two cargo barges"));
182 make_hash_ERI(8230, _("Pushtow, three cargo barges"));
183 make_hash_ERI(8240, _("Pushtow, four cargo barges"));
184 make_hash_ERI(8250, _("Pushtow, five cargo barges"));
185 make_hash_ERI(8260, _("Pushtow, six cargo barges"));
186 make_hash_ERI(8270, _("Pushtow, seven cargo barges"));
187 make_hash_ERI(8280, _("Pushtow, eight cargo barges"));
188 make_hash_ERI(8290, _("Pushtow, nine or more barges"));
189 make_hash_ERI(8310, _("Pushtow, one tank/gas barge"));
190 make_hash_ERI(8320,
191 _("Pushtow, two barges at least one tanker or gas barge"));
192 make_hash_ERI(8330,
193 _("Pushtow, three barges at least one tanker or gas barge"));
194 make_hash_ERI(8340,
195 _("Pushtow, four barges at least one tanker or gas barge"));
196 make_hash_ERI(8350,
197 _("Pushtow, five barges at least one tanker or gas barge"));
198 make_hash_ERI(8360,
199 _("Pushtow, six barges at least one tanker or gas barge"));
200 make_hash_ERI(8370,
201 _("Pushtow, seven barges at least one tanker or gas barge"));
202 make_hash_ERI(8380,
203 _("Pushtow, eight barges at least one tanker or gas barge"));
204 make_hash_ERI(
205 8390, _("Pushtow, nine or more barges at least one tanker or gas barge"));
206 make_hash_ERI(8400, _("Tug, single"));
207 make_hash_ERI(8410, _("Tug, one or more tows"));
208 make_hash_ERI(8420, _("Tug, assisting a vessel or linked combination"));
209 make_hash_ERI(8430, _("Pushboat, single"));
210 make_hash_ERI(8440, _("Passenger ship, ferry, cruise ship, red cross ship"));
211 make_hash_ERI(8441, _("Ferry"));
212 make_hash_ERI(8442, _("Red cross ship"));
213 make_hash_ERI(8443, _("Cruise ship"));
214 make_hash_ERI(8444, _("Passenger ship without accommodation"));
215 make_hash_ERI(8460, _("Vessel, work maintenance craft, floating derrick, "
216 "cable-ship, buoy-ship, dredge"));
217 make_hash_ERI(8480, _("Fishing boat"));
218 make_hash_ERI(8500, _("Barge, tanker, chemical"));
219 make_hash_ERI(1500, _("General cargo Vessel maritime"));
220 make_hash_ERI(1510, _("Unit carrier maritime"));
221 make_hash_ERI(1520, _("Bulk carrier maritime"));
222 make_hash_ERI(1530, _("Tanker"));
223 make_hash_ERI(1540, _("Liquified gas tanker"));
224 make_hash_ERI(1850, _("Pleasure craft, longer than 20 metres"));
225 make_hash_ERI(1900, _("Fast ship"));
226 make_hash_ERI(1910, _("Hydrofoil"));
227}
228
229// DSE Expansion characters, decode table from ITU-R M.825 (codes 00..41).
230// Anything else (a code outside the table, a non-digit pair, an odd trailing
231// character) is not a character: it is dropped and the field is logged, since
232// a certified DSC transceiver does not produce it.
233static wxString DecodeDSEExpansionCharacters(const wxString &dseData) {
234 static constexpr std::string_view lookupTable =
235 "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ.,-/ ";
236 wxString result;
237 bool invalid = false;
238
239 for (size_t i = 0; i < dseData.length(); i += 2) {
240 wxString pair = dseData.Mid(i, 2);
241 if (pair.length() != 2 || !wxIsdigit(pair[0]) || !wxIsdigit(pair[1])) {
242 invalid = true;
243 continue;
244 }
245 size_t code = (pair[0] - '0') * 10 + (pair[1] - '0');
246 if (code >= lookupTable.size()) {
247 invalid = true;
248 continue;
249 }
250 result.append(1, lookupTable[code]);
251 }
252 if (invalid) {
253 wxLogMessage(
254 "DSE station information with invalid expansion data ignored "
255 "in part: \"%s\"",
256 dseData);
257 }
258 return result;
259}
260
261static void getMmsiProperties(std::shared_ptr<AisTargetData> &pTargetData) {
262 for (unsigned int i = 0; i < g_MMSI_Props_Array.GetCount(); i++) {
263 if (pTargetData->MMSI == g_MMSI_Props_Array[i]->MMSI) {
265 pTargetData->b_isFollower = props->m_bFollower;
266 pTargetData->b_mPropPersistTrack = props->m_bPersistentTrack;
267 if (TRACKTYPE_NEVER == props->TrackType) {
268 pTargetData->b_show_track = false;
269 } else if (TRACKTYPE_ALWAYS == props->TrackType) {
270 pTargetData->b_show_track = true;
271 }
272 break;
273 }
274 }
275}
276
277//----------------------------------------------------------------------------
278// Parse a NMEA VDM/VDO Bitstring
279//----------------------------------------------------------------------------
280static bool Parse_VDXBitstring(AisBitstring *bstr,
281 const std::shared_ptr<AisTargetData> &ptd) {
282 bool parse_result = false;
283 bool b_posn_report = false;
284
285 wxDateTime now = wxDateTime::Now();
286 now.MakeGMT();
287 int message_ID = bstr->GetInt(1, 6); // Parse on message ID
288 ptd->MID = message_ID;
289
290 // Save for Ais8_001_31 and ais8_367_33 (class AIS_METEO)
291 int met_mmsi = ptd->MMSI;
292
293 // MMSI is always in the same spot in the bitstream
294 ptd->MMSI = bstr->GetInt(9, 30);
295
296 switch (message_ID) {
297 case 1: // Position Report
298 case 2:
299 case 3: {
300 n_msg1++;
301
302 ptd->NavStatus = bstr->GetInt(39, 4);
303 ptd->SOG = 0.1 * (bstr->GetInt(51, 10));
304
305 int lon = bstr->GetInt(62, 28);
306 if (lon & 0x08000000) // negative?
307 lon |= 0xf0000000;
308 double lon_tentative = lon / 600000.;
309
310 int lat = bstr->GetInt(90, 27);
311 if (lat & 0x04000000) // negative?
312 lat |= 0xf8000000;
313 double lat_tentative = lat / 600000.;
314
315 if ((lon_tentative <= 180.) &&
316 (lat_tentative <=
317 90.)) // Ship does not report Lat or Lon "unavailable"
318 {
319 ptd->Lon = lon_tentative;
320 ptd->Lat = lat_tentative;
321 ptd->b_positionDoubtful = false;
322 ptd->b_positionOnceValid = true; // Got the position at least once
323 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
324 ptd->PositionReportTicks = now.GetTicks();
325 } else
326 ptd->b_positionDoubtful = true;
327
328 // decode balance of message....
329 ptd->COG = 0.1 * (bstr->GetInt(117, 12));
330 ptd->HDG = 1.0 * (bstr->GetInt(129, 9));
331
332 ptd->ROTAIS = bstr->GetInt(43, 8);
333 double rot_dir = 1.0;
334
335 if (ptd->ROTAIS == 128)
336 ptd->ROTAIS = -128; // not available codes as -128
337 else if ((ptd->ROTAIS & 0x80) == 0x80) {
338 ptd->ROTAIS = ptd->ROTAIS - 256; // convert to twos complement
339 rot_dir = -1.0;
340 }
341
342 ptd->ROTIND = wxRound(rot_dir * pow((((double)ptd->ROTAIS) / 4.733),
343 2)); // Convert to indicated ROT
344
345 ptd->m_utc_sec = bstr->GetInt(138, 6);
346
347 if ((1 == message_ID) ||
348 (2 == message_ID)) // decode SOTDMA per 7.6.7.2.2
349 {
350 ptd->SyncState = bstr->GetInt(151, 2);
351 ptd->SlotTO = bstr->GetInt(153, 2);
352 if ((ptd->SlotTO == 1) && (ptd->SyncState == 0)) // UTCDirect follows
353 {
354 ptd->m_utc_hour = bstr->GetInt(155, 5);
355
356 ptd->m_utc_min = bstr->GetInt(160, 7);
357
358 if ((ptd->m_utc_hour < 24) && (ptd->m_utc_min < 60) &&
359 (ptd->m_utc_sec < 60)) {
360 wxDateTime rx_time(ptd->m_utc_hour, ptd->m_utc_min, ptd->m_utc_sec);
361 rx_ticks = rx_time.GetTicks();
362 if (!b_firstrx) {
363 first_rx_ticks = rx_ticks;
364 b_firstrx = true;
365 }
366 }
367 }
368 }
369
370 // Capture Euro Inland special passing arrangement signal ("stbd-stbd")
371 ptd->blue_paddle = bstr->GetInt(144, 2);
372 ptd->b_blue_paddle = (ptd->blue_paddle == 2); // paddle is set
373
374 if (!ptd->b_isDSCtarget) ptd->Class = AIS_CLASS_A;
375
376 // Check for SART and friends by looking at first two digits of MMSI
377 int mmsi_start = ptd->MMSI / 10000000;
378
379 if (mmsi_start == 97) {
380 ptd->Class = AIS_SART;
381 ptd->StaticReportTicks =
382 now.GetTicks(); // won't get a static report, so fake it here
383
384 // On receipt of Msg 3, force any existing SART target out of
385 // acknowledge mode by adjusting its ack_time to yesterday This will
386 // cause any previously "Acknowledged" SART to re-alert.
387
388 // On reflection, re-alerting seems a little excessive in real life
389 // use. After all, the target is on-screen, and in the AIS target
390 // list. So lets just honor the programmed ACK timout value for SART
391 // targets as well
392 // ptd->m_ack_time = wxDateTime::Now() - wxTimeSpan::Day();
393 }
394
395 parse_result = true; // so far so good
396 b_posn_report = true;
397 ptd->b_VDM_secure_Pos = true;
398
399 break;
400 }
401
402 case 18: {
403 ptd->NavStatus =
404 UNDEFINED; // Class B targets have no status. Enforce this...
405
406 ptd->SOG = 0.1 * (bstr->GetInt(47, 10));
407
408 int lon = bstr->GetInt(58, 28);
409 if (lon & 0x08000000) // negative?
410 lon |= 0xf0000000;
411 double lon_tentative = lon / 600000.;
412
413 int lat = bstr->GetInt(86, 27);
414 if (lat & 0x04000000) // negative?
415 lat |= 0xf8000000;
416 double lat_tentative = lat / 600000.;
417
418 if ((lon_tentative <= 180.) &&
419 (lat_tentative <=
420 90.)) // Ship does not report Lat or Lon "unavailable"
421 {
422 ptd->Lon = lon_tentative;
423 ptd->Lat = lat_tentative;
424 ptd->b_positionDoubtful = false;
425 ptd->b_positionOnceValid = true; // Got the position at least once
426 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
427 ptd->PositionReportTicks = now.GetTicks();
428 } else
429 ptd->b_positionDoubtful = true;
430
431 ptd->COG = 0.1 * (bstr->GetInt(113, 12));
432 ptd->HDG = 1.0 * (bstr->GetInt(125, 9));
433
434 ptd->m_utc_sec = bstr->GetInt(134, 6);
435
436 if (!ptd->b_isDSCtarget) {
437 if (!isBuoyMmsi(ptd->MMSI))
438 ptd->Class = AIS_CLASS_B;
439 else
440 ptd->Class = AIS_BUOY;
441 }
442 parse_result = true; // so far so good
443 b_posn_report = true;
444 ptd->b_VDM_secure_Pos = true;
445
446 break;
447 }
448
449 case 19: { // Class B mes_ID 19 Is same as mes_ID 18 until bit 139
450 ptd->NavStatus =
451 UNDEFINED; // Class B targets have no status. Enforce this...
452 ptd->SOG = 0.1 * (bstr->GetInt(47, 10));
453 int lon = bstr->GetInt(58, 28);
454 if (lon & 0x08000000) // negative?
455 lon |= 0xf0000000;
456 double lon_tentative = lon / 600000.;
457
458 int lat = bstr->GetInt(86, 27);
459 if (lat & 0x04000000) // negative?
460 lat |= 0xf8000000;
461 double lat_tentative = lat / 600000.;
462
463 if ((lon_tentative <= 180.) &&
464 (lat_tentative <=
465 90.)) // Ship does not report Lat or Lon "unavailable"
466 {
467 ptd->Lon = lon_tentative;
468 ptd->Lat = lat_tentative;
469 ptd->b_positionDoubtful = false;
470 ptd->b_positionOnceValid = true; // Got the position at least once
471 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
472 ptd->PositionReportTicks = now.GetTicks();
473 } else
474 ptd->b_positionDoubtful = true;
475
476 ptd->COG = 0.1 * (bstr->GetInt(113, 12));
477 ptd->HDG = 1.0 * (bstr->GetInt(125, 9));
478 ptd->m_utc_sec = bstr->GetInt(134, 6);
479 // From bit 140 and forward data as of mes 5
480 bstr->GetStr(144, 120, &ptd->ShipName[0], SHIP_NAME_LEN);
481 ptd->b_nameValid = true;
482 if (!ptd->b_isDSCtarget) {
483 ptd->ShipType = (unsigned char)bstr->GetInt(264, 8);
484 }
485 ptd->DimA = bstr->GetInt(272, 9);
486 ptd->DimB = bstr->GetInt(281, 9);
487 ptd->DimC = bstr->GetInt(290, 6);
488 ptd->DimD = bstr->GetInt(296, 6);
489
490 if (!ptd->b_isDSCtarget) {
491 // Although outdated, message 19 is used by many "ATON" for net buoys
492 if (!isBuoyMmsi(ptd->MMSI))
493 ptd->Class = AIS_CLASS_B;
494 else
495 ptd->Class = AIS_BUOY;
496 }
497 parse_result = true; // so far so good
498 b_posn_report = true;
499 ptd->b_VDM_secure_Pos = true;
500
501 break;
502 }
503
504 case 27: {
505 // Long-range automatic identification system broadcast message
506 // This message is used for long-range detection of AIS Class A and Class
507 // B vessels (typically by satellite).
508
509 // Message 27 can be receiveed for a target that has already been decoded
510 // by class A message 1/2/3 or class B message 18/19. If so reject this.
511 if (ptd->b_VDM_secure_Pos) break;
512
513 // Define the constant to do the covertion from the internal encoded
514 // position in message 27. The position is less accuate : 1/10 minute
515 // position resolution.
516 int bitCorrection = 10;
517 int resolution = 10;
518
519 // Default aout of bounce values.
520 double lon_tentative = 181.;
521 double lat_tentative = 91.;
522
523#ifdef AIS_DEBUG
524 printf("AIS Message 27 - received:\r\n");
525 printf("MMSI : %i\r\n", ptd->MMSI);
526#endif
527
528 // It can be both a CLASS A and a CLASS B vessel - We have decided for
529 // CLASS A (Default if not changed by other messages.)
530 ptd->NavStatus =
531 ptd->Class == AIS_CLASS_A ? bstr->GetInt(41, 4) : UNDEFINED;
532
533 int lon = bstr->GetInt(45, 18);
534 int lat = bstr->GetInt(63, 17);
535
536 lat_tentative = lat;
537 lon_tentative = lon;
538
539 // Negative latitude?
540 if (lat >= (0x4000000 >> bitCorrection)) {
541 lat_tentative = (0x8000000 >> bitCorrection) - lat;
542 lat_tentative *= -1;
543 }
544
545 // Negative longitude?
546 if (lon >= (0x8000000 >> bitCorrection)) {
547 lon_tentative = (0x10000000 >> bitCorrection) - lon;
548 lon_tentative *= -1;
549 }
550
551 // Decode the internal position format.
552 lat_tentative = lat_tentative / resolution / 60.0;
553 lon_tentative = lon_tentative / resolution / 60.0;
554
555#ifdef AIS_DEBUG
556 printf("Latitude : %f\r\n", lat_tentative);
557 printf("Longitude : %f\r\n", lon_tentative);
558#endif
559
560 // Get the latency of the position report.
561 int positionLatency = bstr->GetInt(95, 1);
562
563 if ((lon_tentative <= 180.) &&
564 (lat_tentative <=
565 90.)) // Ship does not report Lat or Lon "unavailable"
566 {
567 ptd->Lon = lon_tentative;
568 ptd->Lat = lat_tentative;
569 ptd->b_positionDoubtful = false;
570 ptd->b_positionOnceValid = true; // Got the position at least once
571 if (positionLatency == 0) {
572// The position is less than 5 seconds old.
573#ifdef AIS_DEBUG
574 printf("Low latency position report.\r\n");
575#endif
576 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
577 ptd->PositionReportTicks = now.GetTicks();
578 }
579 } else
580 ptd->b_positionDoubtful = true;
581
582 ptd->SOG = 1.0 * (bstr->GetInt(80, 6));
583 ptd->COG = 1.0 * (bstr->GetInt(85, 9));
584
585 b_posn_report = true;
586 parse_result = true;
587 break;
588 }
589
590 case 5: {
591 if (bstr->GetBitCount() >= 424) { // Dismiss a malformed message
592 n_msg5++;
593 if (!ptd->b_isDSCtarget) ptd->Class = AIS_CLASS_A;
594
595 // Get the AIS Version indicator
596 // 0 = station compliant with Recommendation ITU-R M.1371-1
597 // 1 = station compliant with Recommendation ITU-R M.1371-3
598 // 2-3 = station compliant with future editions
599 int AIS_version_indicator = bstr->GetInt(39, 2);
600 if (AIS_version_indicator < 4) {
601 ptd->IMO = bstr->GetInt(41, 30);
602
603 bstr->GetStr(71, 42, &ptd->CallSign[0], 7);
604 bstr->GetStr(113, 120, &ptd->ShipName[0], SHIP_NAME_LEN);
605 ptd->b_nameValid = true;
606 if (!ptd->b_isDSCtarget) {
607 ptd->ShipType = (unsigned char)bstr->GetInt(233, 8);
608 }
609
610 ptd->DimA = bstr->GetInt(241, 9);
611 ptd->DimB = bstr->GetInt(250, 9);
612 ptd->DimC = bstr->GetInt(259, 6);
613 ptd->DimD = bstr->GetInt(265, 6);
614
615 ptd->ETA_Mo = bstr->GetInt(275, 4);
616 ptd->ETA_Day = bstr->GetInt(279, 5);
617 ptd->ETA_Hr = bstr->GetInt(284, 5);
618 ptd->ETA_Min = bstr->GetInt(289, 6);
619
620 ptd->Draft = (double)(bstr->GetInt(295, 8)) / 10.0;
621
622 bstr->GetStr(303, 120, &ptd->Destination[0], DESTINATION_LEN - 1);
623
624 ptd->StaticReportTicks = now.GetTicks();
625
626 parse_result = true;
627 }
628 }
629 break;
630 }
631
632 case 24: { // Static data report
633 // First, check that we have received the position and thus
634 // a main message that has given the target a relevant class
635 if (!ptd->b_positionOnceValid) break;
636
637 int part_number = bstr->GetInt(39, 2);
638 if (0 == part_number) {
639 bstr->GetStr(41, 120, &ptd->ShipName[0], SHIP_NAME_LEN);
640 ptd->b_nameValid = true;
641 parse_result = true;
642 n_msg24++;
643 } else if (1 == part_number) {
644 if (!ptd->b_isDSCtarget) {
645 ptd->ShipType = (unsigned char)bstr->GetInt(41, 8);
646 }
647 bstr->GetStr(91, 42, &ptd->CallSign[0], 7);
648
649 ptd->DimA = bstr->GetInt(133, 9);
650 ptd->DimB = bstr->GetInt(142, 9);
651 ptd->DimC = bstr->GetInt(151, 6);
652 ptd->DimD = bstr->GetInt(157, 6);
653 parse_result = true;
654 }
655 break;
656 }
657 case 4: // base station
658 {
659 ptd->Class = AIS_BASE;
660
661 ptd->m_utc_hour = bstr->GetInt(62, 5);
662 ptd->m_utc_min = bstr->GetInt(67, 6);
663 ptd->m_utc_sec = bstr->GetInt(73, 6);
664 // (79, 1);
665 int lon = bstr->GetInt(80, 28);
666 if (lon & 0x08000000) // negative?
667 lon |= 0xf0000000;
668 double lon_tentative = lon / 600000.;
669
670 int lat = bstr->GetInt(108, 27);
671 if (lat & 0x04000000) // negative?
672 lat |= 0xf8000000;
673 double lat_tentative = lat / 600000.;
674
675 if ((lon_tentative <= 180.) &&
676 (lat_tentative <=
677 90.)) // Ship does not report Lat or Lon "unavailable"
678 {
679 ptd->Lon = lon_tentative;
680 ptd->Lat = lat_tentative;
681 ptd->b_positionDoubtful = false;
682 ptd->b_positionOnceValid = true; // Got the position at least once
683 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
684 ptd->PositionReportTicks = now.GetTicks();
685 } else
686 ptd->b_positionDoubtful = true;
687
688 ptd->COG = -1.;
689 ptd->HDG = 511;
690 ptd->SOG = -1.;
691
692 parse_result = true;
693 b_posn_report = true;
694
695 break;
696 }
697 case 9: // Special Position Report (Standard SAR Aircraft Position Report)
698 {
699 ptd->SOG = bstr->GetInt(51, 10);
700
701 int lon = bstr->GetInt(62, 28);
702 if (lon & 0x08000000) // negative?
703 lon |= 0xf0000000;
704 double lon_tentative = lon / 600000.;
705
706 int lat = bstr->GetInt(90, 27);
707 if (lat & 0x04000000) // negative?
708 lat |= 0xf8000000;
709 double lat_tentative = lat / 600000.;
710
711 if ((lon_tentative <= 180.) &&
712 (lat_tentative <=
713 90.)) // Ship does not report Lat or Lon "unavailable"
714 {
715 ptd->Lon = lon_tentative;
716 ptd->Lat = lat_tentative;
717 ptd->b_positionDoubtful = false;
718 ptd->b_positionOnceValid = true; // Got the position at least once
719 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
720 ptd->PositionReportTicks = now.GetTicks();
721 } else
722 ptd->b_positionDoubtful = true;
723
724 // decode balance of message....
725 ptd->COG = 0.1 * (bstr->GetInt(117, 12));
726
727 int alt_tent = bstr->GetInt(39, 12);
728 ptd->altitude = alt_tent;
729
730 ptd->b_SarAircraftPosnReport = true;
731
732 parse_result = true;
733 b_posn_report = true;
734
735 break;
736 }
737 case 21: // Test Message (Aid to Navigation)
738 {
739 ptd->ShipType = (unsigned char)bstr->GetInt(39, 5);
740 ptd->IMO = 0;
741 ptd->SOG = 0;
742 ptd->HDG = 0;
743 ptd->COG = 0;
744 ptd->ROTAIS = -128; // i.e. not available
745 ptd->DimA = bstr->GetInt(220, 9);
746 ptd->DimB = bstr->GetInt(229, 9);
747 ptd->DimC = bstr->GetInt(238, 6);
748 ptd->DimD = bstr->GetInt(244, 6);
749 ptd->Draft = 0;
750
751 ptd->m_utc_sec = bstr->GetInt(254, 6);
752
753 int offpos = bstr->GetInt(260, 1); // off position flag
754 int virt = bstr->GetInt(270, 1); // virtual flag
755
756 if (virt)
757 ptd->NavStatus = ATON_VIRTUAL;
758 else
759 ptd->NavStatus = ATON_REAL;
760 if (ptd->m_utc_sec <= 59 /*&& !virt*/) {
761 ptd->NavStatus += 1;
762 if (offpos) ptd->NavStatus += 1;
763 }
764
765 bstr->GetStr(44, 120, &ptd->ShipName[0], SHIP_NAME_LEN);
766 // short name only, extension wont fit in Ship structure
767
768 if (bstr->GetBitCount() > 276) {
769 int nx = ((bstr->GetBitCount() - 272) / 6) * 6;
770 bstr->GetStr(273, nx, &ptd->ShipNameExtension[0], 14);
771 ptd->ShipNameExtension[14] = 0;
772 } else {
773 ptd->ShipNameExtension[0] = 0;
774 }
775
776 ptd->b_nameValid = true;
777
778 parse_result = true; // so far so good
779
780 ptd->Class = AIS_ATON;
781
782 int lon = bstr->GetInt(165, 28);
783
784 if (lon & 0x08000000) // negative?
785 lon |= 0xf0000000;
786 double lon_tentative = lon / 600000.;
787
788 int lat = bstr->GetInt(193, 27);
789
790 if (lat & 0x04000000) // negative?
791 lat |= 0xf8000000;
792 double lat_tentative = lat / 600000.;
793
794 if ((lon_tentative <= 180.) &&
795 (lat_tentative <=
796 90.)) // Ship does not report Lat or Lon "unavailable"
797 {
798 ptd->Lon = lon_tentative;
799 ptd->Lat = lat_tentative;
800 ptd->b_positionDoubtful = false;
801 ptd->b_positionOnceValid = true; // Got the position at least once
802 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
803 ptd->PositionReportTicks = now.GetTicks();
804 } else
805 ptd->b_positionDoubtful = true;
806
807 b_posn_report = true;
808 break;
809 }
810 case 8: // Binary Broadcast
811 {
812 int dac = bstr->GetInt(41, 10);
813 int fi = bstr->GetInt(51, 6);
814
815 if (dac == 200) // European inland
816 {
817 if (fi == 10) // "Inland ship static and voyage related data"
818 {
819 ptd->b_isEuroInland = true;
820
821 bstr->GetStr(57, 48, &ptd->Euro_VIN[0], 8);
822 ptd->Euro_Length = ((double)bstr->GetInt(105, 13)) / 10.0;
823 ptd->Euro_Beam = ((double)bstr->GetInt(118, 10)) / 10.0;
824 ptd->UN_shiptype = bstr->GetInt(128, 14);
825 ptd->Euro_Draft = ((double)bstr->GetInt(145, 11)) / 100.0;
826 parse_result = true;
827 }
828 }
829 if (dac == 1 || dac == 366) // IMO or US
830 {
831 if (fi == 22) // Area Notice
832 {
833 if (bstr->GetBitCount() >= 111) {
834 Ais8_001_22 an;
835 an.link_id = bstr->GetInt(57, 10);
836 an.notice_type = bstr->GetInt(67, 7);
837 an.month = bstr->GetInt(74, 4);
838 an.day = bstr->GetInt(78, 5);
839 an.hour = bstr->GetInt(83, 5);
840 an.minute = bstr->GetInt(88, 6);
841 an.duration_minutes = bstr->GetInt(94, 18);
842
843 wxDateTime now_ = wxDateTime::Now();
844 now_.MakeGMT();
845
846 an.start_time.Set(an.day, wxDateTime::Month(an.month - 1),
847 now_.GetYear(), an.hour, an.minute);
848
849 // msg is not supposed to be transmitted more than a day before it
850 // comes into effect, so a start_time less than a day or two away
851 // might indicate a month rollover
852 if (an.start_time > now_ + wxTimeSpan::Hours(48))
853 an.start_time.Set(an.day, wxDateTime::Month(an.month - 1),
854 now_.GetYear() - 1, an.hour, an.minute);
855
856 an.expiry_time =
857 an.start_time + wxTimeSpan::Minutes(an.duration_minutes);
858
859 // msg is not supposed to be transmitted beyond expiration, so
860 // taking into account a fudge factor for clock issues, assume an
861 // expiry date in the past indicates incorrect year
862 if (an.expiry_time < now_ - wxTimeSpan::Hours(24)) {
863 an.start_time.Set(an.day, wxDateTime::Month(an.month - 1),
864 now_.GetYear() + 1, an.hour, an.minute);
865 an.expiry_time =
866 an.start_time + wxTimeSpan::Minutes(an.duration_minutes);
867 }
868
869 // Default case, the IMO format
870 // https://www.e-navigation.nl/content/area-notice-0
871 int subarea_len = 87;
872 int lon_len = 25;
873 int lat_len = 24;
874 float pos_scale = 60000.0;
875 int prec_size = 3;
876 if (dac ==
877 366) { // Deprecated US format
878 // https://www.e-navigation.nl/content/area-notice-1
879 subarea_len = 90;
880 lon_len = 28;
881 lat_len = 27;
882 pos_scale = 600000.0;
883 prec_size = 0; // Not present in the in US format between
884 // coordinates and radius for some shapes
885 }
886
887 int subarea_count = (bstr->GetBitCount() - 111) / subarea_len;
888 for (int i = 0; i < subarea_count; ++i) {
889 int base = 111 + i * subarea_len;
891 sa.shape = bstr->GetInt(base + 1, 3);
892 int scale_factor = 1;
893 if (sa.shape == AIS8_001_22_SHAPE_TEXT) {
894 char t[15];
895 t[14] = 0;
896 bstr->GetStr(base + 4, subarea_len - 3, t, 14);
897 sa.text = wxString(t, wxConvUTF8);
898 } else {
899 int scale_multipliers[4] = {1, 10, 100, 1000};
900 scale_factor = scale_multipliers[bstr->GetInt(base + 4, 2)];
901 switch (sa.shape) {
902 case AIS8_001_22_SHAPE_SECTOR:
903 sa.left_bound_deg = bstr->GetInt(
904 base + 6 + lon_len + lat_len + prec_size + 12, 9);
905 sa.right_bound_deg = bstr->GetInt(
906 base + 6 + lon_len + lat_len + prec_size + 12 + 9, 9);
907 case AIS8_001_22_SHAPE_CIRCLE:
908 sa.radius_m =
909 bstr->GetInt(base + 6 + lon_len + lat_len + 3, 12) *
910 scale_factor;
911 // FALL THROUGH
912 case AIS8_001_22_SHAPE_RECT:
913 sa.longitude =
914 bstr->GetInt(base + 6, lon_len, true) / pos_scale;
915 sa.latitude =
916 bstr->GetInt(base + 6 + lon_len, lat_len, true) /
917 pos_scale;
918 sa.e_dim_m =
919 bstr->GetInt(base + 6 + lon_len + lat_len + prec_size,
920 8) *
921 scale_factor;
922 sa.n_dim_m =
923 bstr->GetInt(
924 base + 6 + lon_len + lat_len + prec_size + 8, 8) *
925 scale_factor;
926 sa.orient_deg = bstr->GetInt(
927 base + 6 + lon_len + lat_len + prec_size + 8 + 8, 9);
928 break;
929 case AIS8_001_22_SHAPE_POLYLINE:
930 case AIS8_001_22_SHAPE_POLYGON:
931 for (int j = 0; j < 4; ++j) {
932 sa.angles[j] = bstr->GetInt(base + 6 + j * 20, 10) * 0.5;
933 sa.dists_m[j] =
934 bstr->GetInt(base + 16 + j * 20, 10) * scale_factor;
935 }
936 }
937 }
938 an.sub_areas.push_back(sa);
939 }
940 ptd->area_notices[an.link_id] = an;
941 parse_result = true;
942 }
943 }
944
945 // Meteorological and Hydrographic data ref: IMO SN.1/Circ.289
946 if (fi == 31) {
947 if (bstr->GetBitCount() >= 360) {
948 // Ais8_001_31 mmsi can have been changed.
949 if (met_mmsi != 666) ptd->MMSI = met_mmsi;
950
951 // Default out of bounce values.
952 double lon_tentative = 181.;
953 double lat_tentative = 91.;
954
955 int lon = bstr->GetInt(57, 25);
956 int lat = bstr->GetInt(82, 24);
957
958 if (lon & 0x01000000) // negative?
959 lon |= 0xFE000000;
960 lon_tentative = lon / 60000.;
961
962 if (lat & 0x00800000) // negative?
963 lat |= 0xFF000000;
964 lat_tentative = lat / 60000.;
965
966 ptd->Lon = lon_tentative;
967 ptd->Lat = lat_tentative;
968
969 // Try to make unique name for each station based on position
970 wxString x = ptd->ShipName;
971 if (x.Find("METEO") == wxNOT_FOUND) {
972 double id1, id2;
973 wxString slat = wxString::Format("%0.3f", lat_tentative);
974 wxString slon = wxString::Format("%0.3f", lon_tentative);
975 slat.ToDouble(&id1);
976 slon.ToDouble(&id2);
977 wxString nameID = "METEO ";
978 nameID << wxString::Format("%0.3f", abs(id1) + abs(id2)).Right(3);
979 strncpy(ptd->ShipName, nameID, SHIP_NAME_LEN - 1);
980 }
981
982 ptd->met_data.pos_acc = bstr->GetInt(106, 1);
983 ptd->met_data.day = bstr->GetInt(107, 5);
984 ptd->met_data.hour = bstr->GetInt(112, 5);
985 ptd->met_data.minute = bstr->GetInt(117, 6);
986 ptd->met_data.wind_kn = bstr->GetInt(123, 7);
987 ptd->met_data.wind_gust_kn = bstr->GetInt(130, 7);
988 ptd->met_data.wind_dir = bstr->GetInt(137, 9);
989 ptd->met_data.wind_gust_dir = bstr->GetInt(146, 9);
990
991 int tmp = bstr->GetInt(155, 11);
992 if (tmp & 0x00000400) // negative?
993 tmp |= 0xFFFFF800;
994 ptd->met_data.air_temp = tmp / 10.;
995 ptd->met_data.rel_humid = bstr->GetInt(166, 7);
996 int dew = bstr->GetInt(173, 10);
997 if (dew & 0x00000200) // negative? (bit 9 = 1)
998 dew |= 0xFFFFFC00;
999 ptd->met_data.dew_point = dew / 10.;
1000
1001 /*Air pressure, defined as pressure reduced to sea level,
1002 in 1 hPa steps.0 = pressure 799 hPa or less
1003 1 - 401 = 800 - 1200 hPa*/
1004 ptd->met_data.airpress = bstr->GetInt(183, 9) + 799;
1005 ptd->met_data.airpress_tend = bstr->GetInt(192, 2);
1006
1007 int horVis = bstr->GetInt(194, 8);
1008 if (horVis & 0x80u) { // if MSB = 1
1009 horVis &= 0x7F; // We print >x.x
1010 ptd->met_data.hor_vis_GT = true;
1011 } else
1012 ptd->met_data.hor_vis_GT = false;
1013
1014 ptd->met_data.hor_vis = horVis / 10.0;
1015
1016 ptd->met_data.water_lev_dev = (bstr->GetInt(202, 12) / 100.) - 10.;
1017 ptd->met_data.water_lev_trend = bstr->GetInt(214, 2);
1018 ptd->met_data.current = bstr->GetInt(216, 8) / 10.;
1019 ptd->met_data.curr_dir = bstr->GetInt(224, 9);
1020 ptd->met_data.wave_height = bstr->GetInt(277, 8) / 10.;
1021 ptd->met_data.wave_period = bstr->GetInt(285, 6);
1022 ptd->met_data.wave_dir = bstr->GetInt(291, 9);
1023 ptd->met_data.swell_height = bstr->GetInt(300, 8) / 10;
1024 ptd->met_data.swell_per = bstr->GetInt(308, 6);
1025 ptd->met_data.swell_dir = bstr->GetInt(314, 9);
1026 ptd->met_data.seastate = bstr->GetInt(323, 4);
1027
1028 int wt = bstr->GetInt(327, 10);
1029 if (wt & 0x00000200) // negative? (bit 9 = 1)
1030 wt |= 0xFFFFFC00;
1031 ptd->met_data.water_temp = wt / 10.;
1032
1033 ptd->met_data.precipitation = bstr->GetInt(337, 3);
1034 ptd->met_data.salinity = bstr->GetInt(340, 9) / 10.;
1035 ptd->met_data.ice = bstr->GetInt(349, 2);
1036
1037 ptd->Class = AIS_METEO;
1038 ptd->COG = -1.;
1039 ptd->HDG = 511;
1040 ptd->SOG = -1.;
1041 ptd->b_NoTrack = true;
1042 ptd->b_show_track = false;
1043 ptd->b_positionDoubtful = false;
1044 ptd->b_positionOnceValid = true;
1045 b_posn_report = true;
1046 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
1047 ptd->PositionReportTicks = now.GetTicks();
1048 ptd->b_nameValid = true;
1049
1050 parse_result = true;
1051 }
1052 }
1053 break;
1054 }
1055
1056 if (dac == 367 && fi == 33) { // ais8_367_33
1057 // US data acording to DAC367_FI33_em_version_release_3-23mar15_0
1058 // We use only the same kind of data as of ais8_001_31 from these
1059 // reports.
1060 const int size = bstr->GetBitCount();
1061 if (size >= 168) {
1062 // Change to meteo mmsi-ID
1063 if (met_mmsi != 666) ptd->MMSI = met_mmsi;
1064 const int startbits = 56;
1065 const int slotsize = 112;
1066 const int slots_count = (size - startbits) / slotsize;
1067 int slotbit;
1068 for (int slot = 0; slot < slots_count; slot++) {
1069 slotbit = slot * slotsize;
1070 int type = bstr->GetInt(slotbit + 57, 4);
1071 ptd->met_data.hour = bstr->GetInt(slotbit + 66, 5);
1072 ptd->met_data.minute = bstr->GetInt(slotbit + 71, 6);
1073 int Site_ID = bstr->GetInt(slotbit + 77, 7);
1074
1075 // Name the station acc to site ID until message type 1
1076 if (!ptd->b_nameValid) {
1077 wxString nameID = "METEO Site: ";
1078 nameID << Site_ID;
1079 strncpy(ptd->ShipName, nameID, SHIP_NAME_LEN - 1);
1080 ptd->b_nameValid = true;
1081 }
1082
1083 if (type == 0) { // Location
1084 int lon = bstr->GetInt(slotbit + 90, 28);
1085 if (lon & 0x08000000) // negative?
1086 lon |= 0xf0000000;
1087 ptd->Lon = lon / 600000.;
1088
1089 int lat = bstr->GetInt(slotbit + 118, 27);
1090 if (lat & 0x04000000) // negative?
1091 lat |= 0xf8000000;
1092 ptd->Lat = lat / 600000.;
1093 ptd->b_positionOnceValid = true;
1094
1095 } else if (type == 1) { // Name
1096 bstr->GetStr(slotbit + 84, 84, &ptd->ShipName[0], SHIP_NAME_LEN);
1097 ptd->b_nameValid = true;
1098
1099 } else if (type == 2) { // Wind
1100 // Description 1 and 2 are real time values.
1101 int descr = bstr->GetInt(slotbit + 116, 3);
1102 if (descr == 1 || descr == 2) {
1103 ptd->met_data.wind_kn = bstr->GetInt(slotbit + 84, 7);
1104 ptd->met_data.wind_gust_kn = bstr->GetInt(slotbit + 91, 7);
1105 ptd->met_data.wind_dir = bstr->GetInt(slotbit + 98, 9);
1106 ptd->met_data.wind_gust_dir = bstr->GetInt(slotbit + 107, 9);
1107 }
1108
1109 } else if (type == 3) { // Water level
1110 // Description 1 and 2 are real time values.
1111 int descr = bstr->GetInt(slotbit + 108, 3);
1112 if (descr == 1 || descr == 2) {
1113 int wltype = bstr->GetInt(slotbit + 84, 1);
1114 int wl = bstr->GetInt(slotbit + 85, 16); // cm
1115 if (wl & 0x00004000) // negative?
1116 wl |= 0xffff0000;
1117
1118 if (wltype == 1) // 0 = deviation from datum; 1 = water depth
1119 ptd->met_data.water_level = wl / 100.; // m
1120 else
1121 ptd->met_data.water_lev_dev = wl / 100.; // m
1122 }
1123 ptd->met_data.water_lev_trend = bstr->GetInt(slotbit + 101, 2);
1124 ptd->met_data.vertical_ref = bstr->GetInt(slotbit + 103, 5);
1125
1126 } else if (type == 6) { // Horizontal Current Profil
1127 ptd->met_data.current = bstr->GetInt(slotbit + 102, 8) / 10.0;
1128 ptd->met_data.curr_dir = bstr->GetInt(slotbit + 110, 9);
1129 } else if (type == 7) { // Sea state
1130 int swell_descr =
1131 bstr->GetInt(slotbit + 111, 3); // Use 1 || 2 real data
1132 if (swell_descr == 1 || swell_descr == 2) {
1133 ptd->met_data.swell_height =
1134 bstr->GetInt(slotbit + 84, 8) / 10.0;
1135 ptd->met_data.swell_per = bstr->GetInt(slotbit + 92, 6);
1136 ptd->met_data.swell_dir = bstr->GetInt(slotbit + 98, 9);
1137 }
1138 ptd->met_data.seastate = bstr->GetInt(slotbit + 107, 4); // Bf
1139 int wt_descr = bstr->GetInt(slotbit + 131, 3);
1140 if (wt_descr == 1 || wt_descr == 2)
1141 ptd->met_data.water_temp =
1142 bstr->GetInt(slotbit + 114, 10) / 10. - 10.;
1143
1144 int wawe_descr = bstr->GetInt(slotbit + 157, 3);
1145 if (wawe_descr == 1 || wawe_descr == 2) { // Only real data
1146 ptd->met_data.wave_height =
1147 bstr->GetInt(slotbit + 134, 8) / 10.0;
1148 ptd->met_data.wave_period = bstr->GetInt(slotbit + 142, 6);
1149 ptd->met_data.wave_dir = bstr->GetInt(slotbit + 148, 9);
1150 }
1151 ptd->met_data.salinity = bstr->GetInt(slotbit + 160, 9 / 10.0);
1152
1153 } else if (type == 8) { // Salinity
1154 ptd->met_data.water_temp =
1155 bstr->GetInt(slotbit + 84, 10) / 10.0 - 10.0;
1156 ptd->met_data.salinity = bstr->GetInt(slotbit + 120, 9) / 10.0;
1157
1158 } else if (type == 9) { // Weather
1159 int tmp = bstr->GetInt(slotbit + 84, 11);
1160 if (tmp & 0x00000400) // negative?
1161 tmp |= 0xFFFFF800;
1162 ptd->met_data.air_temp = tmp / 10.;
1163 int pp, precip = bstr->GetInt(slotbit + 98, 2);
1164 switch (precip) { // Adapt to IMO precipitation
1165 case 0:
1166 pp = 1;
1167 case 1:
1168 pp = 5;
1169 case 2:
1170 pp = 4;
1171 case 3:
1172 pp = 7;
1173 }
1174 ptd->met_data.precipitation = pp;
1175 ptd->met_data.hor_vis = bstr->GetInt(slotbit + 100, 8) / 10.0;
1176 ptd->met_data.dew_point =
1177 bstr->GetInt(slotbit + 108, 10) / 10.0 - 20.0;
1178 ptd->met_data.airpress = bstr->GetInt(slotbit + 121, 9) + 799;
1179 ptd->met_data.airpress_tend = bstr->GetInt(slotbit + 130, 2);
1180 ptd->met_data.salinity = bstr->GetInt(slotbit + 135, 9) / 10.0;
1181
1182 } else if (type == 11) { // Wind V2
1183 // Description 1 and 2 are real time values.
1184 int descr = bstr->GetInt(slotbit + 113, 3);
1185 if (descr == 1 || descr == 2) {
1186 ptd->met_data.wind_kn = bstr->GetInt(slotbit + 84, 7);
1187 ptd->met_data.wind_gust_kn = bstr->GetInt(slotbit + 91, 7);
1188 ptd->met_data.wind_dir = bstr->GetInt(slotbit + 98, 9);
1189 }
1190 }
1191 }
1192
1193 if (ptd->b_positionOnceValid) {
1194 ptd->Class = AIS_METEO;
1195 ptd->COG = -1.;
1196 ptd->HDG = 511;
1197 ptd->SOG = -1.;
1198 ptd->b_NoTrack = true;
1199 ptd->b_show_track = false;
1200 ptd->b_positionDoubtful = false;
1201 b_posn_report = true;
1202 ptd->LastPositionReportTicks = ptd->PositionReportTicks;
1203 ptd->PositionReportTicks = now.GetTicks();
1204 ptd->b_nameValid = true;
1205
1206 parse_result = true;
1207 }
1208 }
1209 break;
1210 }
1211 break;
1212 }
1213 case 14: // Safety Related Broadcast
1214 {
1215 // Always capture the MSG_14 text
1216 char msg_14_text[968];
1217 if (bstr->GetBitCount() > 40) {
1218 int nx = ((bstr->GetBitCount() - 40) / 6) * 6;
1219 int nd = bstr->GetStr(41, nx, msg_14_text, 968);
1220 nd = wxMax(0, nd);
1221 nd = wxMin(nd, 967);
1222 msg_14_text[nd] = 0;
1223 ptd->MSG_14_text = wxString(msg_14_text, wxConvUTF8);
1224 }
1225 parse_result = true; // so far so good
1226
1227 break;
1228 }
1229
1230 case 6: // Addressed Binary Message
1231 [[fallthrough]];
1232 case 7: // Binary Ack
1233 [[fallthrough]];
1234 default:
1235 break;
1236 }
1237
1238 if (b_posn_report) ptd->b_lost = false;
1239
1240 if (true == parse_result) {
1241 // Revalidate the target under some conditions
1242 if (!ptd->b_active && !ptd->b_positionDoubtful && b_posn_report)
1243 ptd->b_active = true;
1244 }
1245
1246 return parse_result;
1247}
1248
1249AisDecoder::AisDecoder(const AisDecoderCallbacks &callbacks)
1250 : m_signalk_selfid(""), m_callbacks(callbacks) {
1251 // Load cached AIS target names from a file
1252 AISTargetNamesC = new AIS_Target_Name_Hash;
1253 AISTargetNamesNC = new AIS_Target_Name_Hash;
1254
1255 if (g_benableAISNameCache) {
1256 if (wxFileName::FileExists(AISTargetNameFileName)) {
1257 wxTextFile infile;
1258 if (infile.Open(AISTargetNameFileName)) {
1259 AIS_Target_Name_Hash *HashFile = AISTargetNamesNC;
1260 wxString line = infile.GetFirstLine();
1261 while (!infile.Eof()) {
1262 if (line.IsSameAs("+++==Confirmed Entry's==+++"))
1263 HashFile = AISTargetNamesC;
1264 else {
1265 if (line.IsSameAs("+++==Non Confirmed Entry's==+++"))
1266 HashFile = AISTargetNamesNC;
1267 else {
1268 wxStringTokenizer tokenizer(line, ",");
1269 int mmsi = wxAtoi(tokenizer.GetNextToken());
1270 wxString name = tokenizer.GetNextToken().Trim();
1271 (*HashFile)[mmsi] = name;
1272 }
1273 }
1274 line = infile.GetNextLine();
1275 }
1276 }
1277 infile.Close();
1278 }
1279 }
1280
1281 BuildERIShipTypeHash();
1282
1283 g_pais_alert_dialog_active = nullptr;
1284 m_bAIS_Audio_Alert_On = false;
1285
1286 m_n_targets = 0;
1287
1288 m_bAIS_AlertPlaying = false;
1289
1290 TimerAIS.SetOwner(this, TIMER_AIS1);
1291 TimerAIS.Start(TIMER_AIS_MSEC, wxTIMER_CONTINUOUS);
1292
1293 m_ptentative_dsctarget = nullptr;
1294 m_dsc_timer.SetOwner(this, TIMER_DSC);
1295
1296 // Create/connect a dynamic event handler slot for wxEVT_OCPN_DATASTREAM(s)
1297 // FIXME delete Connect(wxEVT_OCPN_DATASTREAM,
1298 // (wxObjectEventFunction)(wxEventFunction)&AisDecoder::OnEvtAIS);
1299 // Connect(EVT_OCPN_SIGNALKSTREAM,
1300 // (wxObjectEventFunction)(wxEventFunction)&AisDecoder::OnEvtSignalK);
1301 InitCommListeners();
1302}
1303
1304AisDecoder::~AisDecoder() {
1305 // for (const auto &it : GetTargetList()) {
1306 // AisTargetData *td = it.second;
1307 //
1308 // delete td;
1309 // }
1310
1311 // Write mmsi-shipsname to file in a safe way
1312 wxTempFile outfile;
1313 if (outfile.Open(AISTargetNameFileName)) {
1314 wxString content = "+++==Confirmed Entry's==+++";
1315 AIS_Target_Name_Hash::iterator it;
1316 for (it = AISTargetNamesC->begin(); it != AISTargetNamesC->end(); ++it) {
1317 content.append("\r\n");
1318 content.append(wxString::Format("%i", it->first));
1319 content.append(",").append(it->second);
1320 }
1321 content.append("\r\n");
1322 content.append("+++==Non Confirmed Entry's==+++");
1323 for (it = AISTargetNamesNC->begin(); it != AISTargetNamesNC->end(); ++it) {
1324 content.append("\r\n");
1325 content.append(wxString::Format("%i", it->first));
1326 content.append(",").append(it->second);
1327 }
1328 outfile.Write(content);
1329 outfile.Commit();
1330 }
1331
1332 AISTargetNamesC->clear();
1333 delete AISTargetNamesC;
1334 AISTargetNamesNC->clear();
1335 delete AISTargetNamesNC;
1336
1337 clear_hash_ERI();
1338
1339 m_dsc_timer.Stop();
1340 m_AIS_Audio_Alert_Timer.Stop();
1341 TimerAIS.Stop();
1342
1343#ifdef AIS_DEBUG
1344 printf(
1345 "First message[1, 2] ticks: %d Last Message [1,2]ticks %d Difference: "
1346 "%d\n",
1347 first_rx_ticks, rx_ticks, rx_ticks - first_rx_ticks);
1348#endif
1349}
1350
1351bool IsTargetOnTheIgnoreList(const int &mmsi) {
1352 // Check the MMSI-Prop list if the target shall be ignored
1353 for (unsigned int i = 0; i < g_MMSI_Props_Array.GetCount(); i++) {
1354 if (mmsi == g_MMSI_Props_Array[i]->MMSI) {
1356 if (props->m_bignore) {
1357 return true;
1358 }
1359 }
1360 }
1361 return false;
1362}
1363
1364void AisDecoder::InitCommListeners() {
1365 // Initialize the comm listeners
1366
1367 // NMEA0183
1368 // VDM
1369 Nmea0183Msg n0183_msg_VDM("VDM");
1370 listener_N0183_VDM.Listen(n0183_msg_VDM, this, EVT_N0183_VDM);
1371 Bind(EVT_N0183_VDM, [&](const ObservedEvt &ev) {
1372 auto ptr = ev.GetSharedPtr();
1373 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1374 HandleN0183_AIS(n0183_msg);
1375 });
1376
1377 // FRPOS
1378 Nmea0183Msg n0183_msg_FRPOS("FRPOS");
1379 listener_N0183_FRPOS.Listen(n0183_msg_FRPOS, this, EVT_N0183_FRPOS);
1380
1381 Bind(EVT_N0183_FRPOS, [&](const ObservedEvt &ev) {
1382 auto ptr = ev.GetSharedPtr();
1383 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1384 HandleN0183_AIS(n0183_msg);
1385 });
1386
1387 // CDDSC
1388 Nmea0183Msg n0183_msg_CDDSC("CDDSC");
1389 listener_N0183_CDDSC.Listen(n0183_msg_CDDSC, this, EVT_N0183_CDDSC);
1390 Bind(EVT_N0183_CDDSC, [&](const ObservedEvt &ev) {
1391 auto ptr = ev.GetSharedPtr();
1392 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1393 HandleN0183_AIS(n0183_msg);
1394 });
1395
1396 // CDDSE
1397 Nmea0183Msg n0183_msg_CDDSE("CDDSE");
1398 listener_N0183_CDDSE.Listen(n0183_msg_CDDSE, this, EVT_N0183_CDDSE);
1399 Bind(EVT_N0183_CDDSE, [&](const ObservedEvt &ev) {
1400 auto ptr = ev.GetSharedPtr();
1401 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1402 HandleN0183_AIS(n0183_msg);
1403 });
1404
1405 // TLL
1406 Nmea0183Msg n0183_msg_TLL("TLL");
1407 listener_N0183_TLL.Listen(n0183_msg_TLL, this, EVT_N0183_TLL);
1408
1409 Bind(EVT_N0183_TLL, [&](const ObservedEvt &ev) {
1410 auto ptr = ev.GetSharedPtr();
1411 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1412 HandleN0183_AIS(n0183_msg);
1413 });
1414
1415 // TTM
1416 Nmea0183Msg n0183_msg_ttm("TTM");
1417 listener_N0183_TTM.Listen(n0183_msg_ttm, this, EVT_N0183_TTM);
1418 Bind(EVT_N0183_TTM, [&](const ObservedEvt &ev) {
1419 auto ptr = ev.GetSharedPtr();
1420 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1421 HandleN0183_AIS(n0183_msg);
1422 });
1423
1424 // OSD
1425 Nmea0183Msg n0183_msg_OSD("OSD");
1426 listener_N0183_OSD.Listen(n0183_msg_OSD, this, EVT_N0183_OSD);
1427 Bind(EVT_N0183_OSD, [&](const ObservedEvt &ev) {
1428 auto ptr = ev.GetSharedPtr();
1429 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1430 HandleN0183_AIS(n0183_msg);
1431 });
1432
1433 // WPL
1434 Nmea0183Msg n0183_msg_WPL("WPL");
1435 listener_N0183_WPL.Listen(n0183_msg_WPL, this, EVT_N0183_WPL);
1436 Bind(EVT_N0183_WPL, [&](const ObservedEvt &ev) {
1437 auto ptr = ev.GetSharedPtr();
1438 auto n0183_msg = std::static_pointer_cast<const Nmea0183Msg>(ptr);
1439 HandleN0183_AIS(n0183_msg);
1440 });
1441
1442 // SignalK
1443 SignalkMsg sk_msg;
1444 listener_SignalK.Listen(sk_msg, this, EVT_SIGNALK);
1445 Bind(EVT_SIGNALK, [&](const ObservedEvt &ev) {
1446 HandleSignalK(obs::UnpackEvtPointer<SignalkMsg>(ev));
1447 });
1448
1449 // AIS Class A PGN 129038
1450 //-----------------------------
1451 Nmea2000Msg n2k_msg_129038(static_cast<uint64_t>(129038));
1452 listener_N2K_129038.Listen(n2k_msg_129038, this, EVT_N2K_129038);
1453 Bind(EVT_N2K_129038, [&](const ObservedEvt &ev) {
1454 HandleN2K_129038(obs::UnpackEvtPointer<Nmea2000Msg>(ev));
1455 });
1456
1457 // AIS Class B PGN 129039
1458 //-----------------------------
1459 Nmea2000Msg n2k_msg_129039(static_cast<uint64_t>(129039));
1460 listener_N2K_129039.Listen(n2k_msg_129039, this, EVT_N2K_129039);
1461 Bind(EVT_N2K_129039, [&](const ObservedEvt &ev) {
1462 HandleN2K_129039(obs::UnpackEvtPointer<Nmea2000Msg>(ev));
1463 });
1464
1465 // AIS ATON PGN 129041
1466 //-----------------------------
1467 Nmea2000Msg n2k_msg_129041(static_cast<uint64_t>(129041));
1468 listener_N2K_129041.Listen(n2k_msg_129041, this, EVT_N2K_129041);
1469 Bind(EVT_N2K_129041, [&](const ObservedEvt &ev) {
1470 HandleN2K_129041(obs::UnpackEvtPointer<Nmea2000Msg>(ev));
1471 });
1472
1473 // AIS static data class A PGN 129794
1474 //-----------------------------
1475 Nmea2000Msg n2k_msg_129794(static_cast<uint64_t>(129794));
1476 listener_N2K_129794.Listen(n2k_msg_129794, this, EVT_N2K_129794);
1477 Bind(EVT_N2K_129794, [&](const ObservedEvt &ev) {
1478 HandleN2K_129794(obs::UnpackEvtPointer<Nmea2000Msg>(ev));
1479 });
1480
1481 // AIS static data class B part A PGN 129809
1482 //-----------------------------
1483 Nmea2000Msg n2k_msg_129809(static_cast<uint64_t>(129809));
1484 listener_N2K_129809.Listen(n2k_msg_129809, this, EVT_N2K_129809);
1485 Bind(EVT_N2K_129809, [&](const ObservedEvt &ev) {
1486 HandleN2K_129809(obs::UnpackEvtPointer<Nmea2000Msg>(ev));
1487 });
1488
1489 // AIS static data class B part B PGN 129810
1490 //-----------------------------
1491 Nmea2000Msg n2k_msg_129810(static_cast<uint64_t>(129810));
1492 listener_N2K_129810.Listen(n2k_msg_129810, this, EVT_N2K_129810);
1493 Bind(EVT_N2K_129810, [&](const ObservedEvt &ev) {
1494 HandleN2K_129810(obs::UnpackEvtPointer<Nmea2000Msg>(ev));
1495 });
1496
1497 // AIS Base Station report PGN 129793
1498 //-----------------------------
1499 Nmea2000Msg n2k_msg_129793(static_cast<uint64_t>(129793));
1500 listener_N2K_129793.Listen(n2k_msg_129793, this, EVT_N2K_129793);
1501 Bind(EVT_N2K_129793, [&](const ObservedEvt &ev) {
1502 HandleN2K_129793(obs::UnpackEvtPointer<Nmea2000Msg>(ev));
1503 });
1504}
1505
1506bool AisDecoder::HandleN0183_AIS(const N0183MsgPtr &n0183_msg) {
1507 std::string str = n0183_msg->payload;
1508 wxString sentence(str.c_str());
1509 DecodeN0183(sentence);
1510 touch_state.Notify();
1511 return true;
1512}
1513
1514bool AisDecoder::HandleN2K_129038(const N2000MsgPtr &n2k_msg) {
1515 std::vector<unsigned char> v = n2k_msg->payload;
1516
1517 uint8_t MessageID;
1518 tN2kAISRepeat Repeat;
1519 uint32_t UserID;
1520 double Latitude;
1521 double Longitude;
1522 bool Accuracy;
1523 bool RAIM;
1524 uint8_t Seconds;
1525 double COG;
1526 double SOG;
1527 double Heading;
1528 double ROT;
1529 tN2kAISNavStatus NavStat = N2kaisns_Under_Way_Motoring;
1530 tN2kAISTransceiverInformation AISTransceiverInformation;
1531
1532 if (ParseN2kPGN129038(v, MessageID, Repeat, UserID, Latitude, Longitude,
1533 Accuracy, RAIM, Seconds, COG, SOG, Heading, ROT,
1534 NavStat, AISTransceiverInformation)) {
1535 unsigned mmsi = UserID;
1536 // Stop here if the target shall be ignored
1537 if (mmsi == g_OwnShipmmsi || IsTargetOnTheIgnoreList(mmsi)) return false;
1538
1539 // Is this target already in the global target list?
1540 // Search the current AISTargetList for an MMSI match
1541 std::shared_ptr<AisTargetData> pTargetData = nullptr;
1542 bool bnewtarget = false;
1543
1544 auto it = AISTargetList.find(mmsi);
1545 if (it == AISTargetList.end()) // not found
1546 {
1547 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
1548 bnewtarget = true;
1549 m_n_targets++;
1550 } else {
1551 pTargetData = it->second; // find current entry
1552 }
1553
1554 wxDateTime now = wxDateTime::Now();
1555 now.MakeUTC();
1556
1557 // Populate the target_data
1558 pTargetData->MMSI = mmsi;
1559 pTargetData->MID = MessageID;
1560 pTargetData->MMSI = mmsi;
1561 pTargetData->Class = AIS_CLASS_A;
1562 // Check for SART and friends by looking at first two digits of MMSI
1563 if (97 == pTargetData->MMSI / 10000000) {
1564 pTargetData->Class = AIS_SART;
1565 // won't get a static report, so fake it here
1566 pTargetData->StaticReportTicks = now.GetTicks();
1567 }
1568 pTargetData->NavStatus = static_cast<ais_nav_status>(NavStat);
1569 if (!N2kIsNA(SOG)) pTargetData->SOG = MS2KNOTS(SOG);
1570 if (!N2kIsNA(COG)) pTargetData->COG = GeodesicRadToDeg(COG);
1571 if (!N2kIsNA(Heading)) pTargetData->HDG = GeodesicRadToDeg(Heading);
1572 if (!N2kIsNA(Longitude)) pTargetData->Lon = Longitude;
1573 if (!N2kIsNA(Latitude)) pTargetData->Lat = Latitude;
1574
1575 pTargetData->ROTAIS = ROT;
1576
1577 // FIXME (dave)
1578 // if (ROT == 128)
1579 // pTargetData->ROTAIS = -128; // not available codes as -128
1580 // else if ((ROT & 0x80) == 0x80) {
1581 // pTargetData->ROTAIS = ROT - 256; // convert to twos complement
1582 // rot_dir = -1.0;
1583 // }
1584 //
1585 // pTargetData->ROTIND = round(rot_dir * pow((ROT / 4.733), 2));
1586
1587 pTargetData->b_OwnShip =
1588 AISTransceiverInformation ==
1589 tN2kAISTransceiverInformation::N2kaisown_information_not_broadcast;
1590 pTargetData->b_active = true;
1591 pTargetData->b_lost = false;
1592 pTargetData->b_positionOnceValid = true;
1593 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
1594 pTargetData->PositionReportTicks = now.GetTicks();
1595
1596 pSelectAIS->DeleteSelectablePoint((void *)(long)mmsi, SELTYPE_AISTARGET);
1597 CommitAISTarget(pTargetData, "", true, bnewtarget);
1598
1599 touch_state.Notify();
1600 return true;
1601 } else
1602 return false;
1603}
1604
1605// AIS position reports for Class B
1606bool AisDecoder::HandleN2K_129039(const N2000MsgPtr &n2k_msg) {
1607 std::vector<unsigned char> v = n2k_msg->payload;
1608
1609 // Input:
1610 // - N2kMsg NMEA2000 message to decode
1611 // bool ParseN2kPGN129039(std::vector<unsigned char> &v, uint8_t &MessageID,
1612 // tN2kAISRepeat &Repeat, uint32_t &UserID,
1613 // double &Latitude, double &Longitude, bool
1614 // &Accuracy, bool &RAIM, uint8_t &Seconds, double
1615 // &COG, double &SOG, tN2kAISTransceiverInformation
1616 // &AISTransceiverInformation, double &Heading,
1617 // tN2kAISUnit &Unit, bool &Display, bool &DSC, bool
1618 // &Band, bool &Msg22, tN2kAISMode &Mode, bool
1619 // &State);
1620
1621 uint8_t MessageID;
1622 tN2kAISRepeat Repeat;
1623 uint32_t UserID;
1624 double Latitude;
1625 double Longitude;
1626 bool Accuracy;
1627 bool RAIM;
1628 uint8_t Seconds;
1629 double COG;
1630 double SOG;
1631 double Heading;
1632 tN2kAISTransceiverInformation AISTransceiverInformation;
1633 tN2kAISUnit Unit;
1634 bool DSC, Band, Msg22, State, Display;
1635 tN2kAISMode Mode;
1636
1637 if (ParseN2kPGN129039(v, MessageID, Repeat, UserID, Latitude, Longitude,
1638 Accuracy, RAIM, Seconds, COG, SOG,
1639 AISTransceiverInformation, Heading, Unit, Display, DSC,
1640 Band, Msg22, Mode, State)) {
1641 uint32_t mmsi = UserID;
1642 // Stop here if the target shall be ignored
1643 if (mmsi == g_OwnShipmmsi || IsTargetOnTheIgnoreList(mmsi)) return false;
1644
1645 // Is this target already in the global target list?
1646 // Search the current AISTargetList for an MMSI match
1647 std::shared_ptr<AisTargetData> pTargetData = nullptr;
1648 bool bnewtarget = false;
1649
1650 auto it = AISTargetList.find(mmsi);
1651 if (it == AISTargetList.end()) // not found
1652 {
1653 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
1654 bnewtarget = true;
1655 m_n_targets++;
1656 } else {
1657 pTargetData = it->second; // find current entry
1658 }
1659
1660 wxDateTime now = wxDateTime::Now();
1661 now.MakeUTC();
1662
1663 // Populate the target_data
1664 pTargetData->MMSI = mmsi;
1665 pTargetData->MID = MessageID;
1666 if (!isBuoyMmsi(mmsi))
1667 pTargetData->Class = AIS_CLASS_B;
1668 else
1669 pTargetData->Class = AIS_BUOY;
1670
1671 pTargetData->NavStatus = UNDEFINED; // Class B targets have no status.
1672 if (!N2kIsNA(SOG)) pTargetData->SOG = MS2KNOTS(SOG);
1673 if (!N2kIsNA(COG)) pTargetData->COG = GeodesicRadToDeg(COG);
1674 if (!N2kIsNA(Heading)) pTargetData->HDG = GeodesicRadToDeg(Heading);
1675 if (!N2kIsNA(Longitude)) pTargetData->Lon = Longitude;
1676 if (!N2kIsNA(Latitude)) pTargetData->Lat = Latitude;
1677
1678 pTargetData->b_positionOnceValid = true;
1679 pTargetData->b_active = true;
1680 pTargetData->b_lost = false;
1681 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
1682 pTargetData->PositionReportTicks = now.GetTicks();
1683 pTargetData->b_OwnShip =
1684 AISTransceiverInformation ==
1685 tN2kAISTransceiverInformation::N2kaisown_information_not_broadcast;
1686
1687 pSelectAIS->DeleteSelectablePoint((void *)(long)mmsi, SELTYPE_AISTARGET);
1688 CommitAISTarget(pTargetData, "", true, bnewtarget);
1689
1690 touch_state.Notify();
1691 return true;
1692 } else
1693 return false;
1694
1695 return true;
1696}
1697
1698bool AisDecoder::HandleN2K_129041(const N2000MsgPtr &n2k_msg) {
1699 std::vector<unsigned char> v = n2k_msg->payload;
1700
1701 tN2kAISAtoNReportData data;
1702
1703#if 0
1704 struct tN2kAISAtoNReportData {
1705 uint8_t MessageID;
1706 tN2kAISRepeat Repeat;
1707 uint32_t UserID;
1708 double Longitude;
1709 double Latitude;
1710 bool Accuracy;
1711 bool RAIM;
1712 uint8_t Seconds;
1713 double Length;
1714 double Beam;
1715 double PositionReferenceStarboard ;
1716 double PositionReferenceTrueNorth;
1717 tN2kAISAtoNType AtoNType;
1718 bool OffPositionIndicator;
1719 bool VirtualAtoNFlag;
1720 bool AssignedModeFlag;
1721 tN2kGNSStype GNSSType;
1722 uint8_t AtoNStatus;
1723 tN2kAISTransceiverInformation AISTransceiverInformation;
1724 char AtoNName[34 + 1];
1725#endif
1726
1727 if (ParseN2kPGN129041(v, data)) {
1728 uint32_t mmsi = data.UserID;
1729 // Stop here if the target shall be ignored
1730 if (mmsi == g_OwnShipmmsi || IsTargetOnTheIgnoreList(mmsi)) return false;
1731
1732 // Is this target already in the global target list?
1733 // Search the current AISTargetList for an MMSI match
1734 std::shared_ptr<AisTargetData> pTargetData = nullptr;
1735 bool bnewtarget = false;
1736
1737 auto it = AISTargetList.find(mmsi);
1738 if (it == AISTargetList.end()) // not found
1739 {
1740 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
1741 bnewtarget = true;
1742 m_n_targets++;
1743 } else {
1744 pTargetData = it->second; // find current entry
1745 }
1746
1747 // Populate the target_data
1748 pTargetData->MMSI = mmsi;
1749
1750 wxDateTime now = wxDateTime::Now();
1751 now.MakeUTC();
1752
1753 int offpos = data.OffPositionIndicator; // off position flag
1754 int virt = data.VirtualAtoNFlag; // virtual flag
1755
1756 if (virt)
1757 pTargetData->NavStatus = ATON_VIRTUAL;
1758 else
1759 pTargetData->NavStatus = ATON_REAL;
1760
1761 pTargetData->m_utc_sec = data.Seconds;
1762
1763 if (pTargetData->m_utc_sec <= 59) {
1764 pTargetData->NavStatus += 1;
1765 if (offpos) pTargetData->NavStatus += 1;
1766 }
1767
1768 data.AtoNName[34] = 0;
1769 strncpy(pTargetData->ShipName, data.AtoNName, SHIP_NAME_LEN - 1);
1770 pTargetData->ShipName[sizeof(pTargetData->ShipName) - 1] = '\0';
1771 pTargetData->b_nameValid = true;
1772 pTargetData->MID = 124; // Indicates a name from n2k
1773
1774 pTargetData->ShipType = data.AtoNType;
1775 pTargetData->Class = AIS_ATON;
1776
1777 if (!N2kIsNA(data.Longitude)) pTargetData->Lon = data.Longitude;
1778 if (!N2kIsNA(data.Latitude)) pTargetData->Lat = data.Latitude;
1779 pTargetData->b_positionDoubtful = false;
1780 pTargetData->b_positionOnceValid = true; // Got the position at least once
1781 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
1782 pTargetData->PositionReportTicks = now.GetTicks();
1783
1784 // FIXME (dave) Populate more fiddly static data
1785
1786 pSelectAIS->DeleteSelectablePoint((void *)(long)mmsi, SELTYPE_AISTARGET);
1787 CommitAISTarget(pTargetData, "", true, bnewtarget);
1788
1789 touch_state.Notify();
1790 return true;
1791 } else
1792 return false;
1793}
1794
1795// AIS static data class A
1796bool AisDecoder::HandleN2K_129794(const N2000MsgPtr &n2k_msg) {
1797 std::vector<unsigned char> v = n2k_msg->payload;
1798
1799 uint8_t MessageID;
1800 tN2kAISRepeat Repeat;
1801 uint32_t UserID;
1802 uint32_t IMOnumber;
1803 char Callsign[21];
1804 char Name[SHIP_NAME_LEN];
1805 uint8_t VesselType;
1806 double Length;
1807 double Beam;
1808 double PosRefStbd;
1809 double PosRefBow;
1810 uint16_t ETAdate;
1811 double ETAtime;
1812 double Draught;
1813 char Destination[DESTINATION_LEN];
1814 tN2kAISVersion AISversion;
1815 tN2kGNSStype GNSStype;
1816 tN2kAISDTE DTE;
1817 tN2kAISTranceiverInfo AISinfo;
1818
1819 if (ParseN2kPGN129794(v, MessageID, Repeat, UserID, IMOnumber, Callsign, Name,
1820 VesselType, Length, Beam, PosRefStbd, PosRefBow,
1821 ETAdate, ETAtime, Draught, Destination, AISversion,
1822 GNSStype, DTE, AISinfo)) {
1823 uint32_t mmsi = UserID;
1824 // Stop here if the target shall be ignored
1825 if (mmsi == g_OwnShipmmsi || IsTargetOnTheIgnoreList(mmsi)) return false;
1826
1827 // Is this target already in the global target list?
1828 // Search the current AISTargetList for an MMSI match
1829 std::shared_ptr<AisTargetData> pTargetData = nullptr;
1830 bool bnewtarget = false;
1831
1832 auto it = AISTargetList.find(mmsi);
1833 if (it == AISTargetList.end()) // not found
1834 {
1835 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
1836 bnewtarget = true;
1837 m_n_targets++;
1838 } else {
1839 pTargetData = it->second; // find current entry
1840 }
1841
1842 // Populate the target_data
1843 pTargetData->MMSI = mmsi;
1844 strncpy(pTargetData->ShipName, Name, SHIP_NAME_LEN - 1);
1845 pTargetData->ShipName[sizeof(pTargetData->ShipName) - 1] = '\0';
1846 Name[sizeof(Name) - 1] = 0;
1847 pTargetData->b_nameValid = true;
1848 pTargetData->MID = 124; // Indicates a name from n2k
1849
1850 pTargetData->b_OwnShip =
1851 AISinfo ==
1852 tN2kAISTranceiverInfo::N2kaisti_Own_information_not_broadcast;
1853
1854 pTargetData->DimA = PosRefBow;
1855 pTargetData->DimB = Length - PosRefBow;
1856 pTargetData->DimC = Beam - PosRefStbd;
1857 pTargetData->DimD = PosRefStbd;
1858 pTargetData->Draft = Draught;
1859 pTargetData->IMO = IMOnumber;
1860 strncpy(pTargetData->CallSign, Callsign, CALL_SIGN_LEN - 1);
1861 pTargetData->CallSign[sizeof(pTargetData->CallSign) - 1] = '\0';
1862 pTargetData->ShipType = (unsigned char)VesselType;
1863 strncpy(pTargetData->Destination, Destination, DESTINATION_LEN - 1);
1864 pTargetData->Destination[sizeof(pTargetData->Destination) - 1] = '\0';
1865 Destination[sizeof(Destination) - 1] = 0;
1866
1867 if (!N2kIsNA(ETAdate) && !N2kIsNA(ETAtime)) {
1868 long secs = (ETAdate * 24 * 3600) + wxRound(ETAtime);
1869 wxDateTime t((time_t)secs);
1870 if (t.IsValid()) {
1871 wxDateTime tz = t.ToUTC();
1872 pTargetData->ETA_Mo = tz.GetMonth() + 1;
1873 pTargetData->ETA_Day = tz.GetDay();
1874 pTargetData->ETA_Hr = tz.GetHour();
1875 pTargetData->ETA_Min = tz.GetMinute();
1876 }
1877 }
1878
1879 pSelectAIS->DeleteSelectablePoint((void *)(long)mmsi, SELTYPE_AISTARGET);
1880 CommitAISTarget(pTargetData, "", true, bnewtarget);
1881
1882 touch_state.Notify();
1883 return true;
1884 } else
1885 return false;
1886}
1887// AIS static data class B part A
1888bool AisDecoder::HandleN2K_129809(const N2000MsgPtr &n2k_msg) {
1889 std::vector<unsigned char> v = n2k_msg->payload;
1890
1891 uint8_t MessageID;
1892 tN2kAISRepeat Repeat;
1893 uint32_t UserID;
1894 char Name[21];
1895
1896 if (ParseN2kPGN129809(v, MessageID, Repeat, UserID, Name)) {
1897 unsigned mmsi = UserID;
1898 // Stop here if the target shall be ignored
1899 if (mmsi == g_OwnShipmmsi || IsTargetOnTheIgnoreList(mmsi)) return false;
1900
1901 // Is this target already in the global target list?
1902 // Search the current AISTargetList for an MMSI match
1903 std::shared_ptr<AisTargetData> pTargetData = nullptr;
1904 bool bnewtarget = false;
1905
1906 auto it = AISTargetList.find(mmsi);
1907 if (it == AISTargetList.end()) // not found
1908 {
1909 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
1910 bnewtarget = true;
1911 m_n_targets++;
1912 } else {
1913 pTargetData = it->second; // find current entry
1914 }
1915
1916 // Populate the target_data
1917 pTargetData->MMSI = mmsi;
1918 Name[sizeof(Name) - 1] = 0;
1919 strncpy(pTargetData->ShipName, Name, SHIP_NAME_LEN - 1);
1920 pTargetData->b_nameValid = true;
1921 pTargetData->MID = 124; // Indicates a name from n2k
1922
1923 pSelectAIS->DeleteSelectablePoint((void *)(long)mmsi, SELTYPE_AISTARGET);
1924 CommitAISTarget(pTargetData, "", true, bnewtarget);
1925
1926 touch_state.Notify();
1927 return true;
1928
1929 } else
1930 return false;
1931}
1932
1933// AIS static data class B part B
1934bool AisDecoder::HandleN2K_129810(const N2000MsgPtr &n2k_msg) {
1935 std::vector<unsigned char> v = n2k_msg->payload;
1936
1937 uint8_t MessageID;
1938 tN2kAISRepeat Repeat;
1939 uint32_t UserID;
1940 uint8_t VesselType;
1941 char Vendor[20];
1942 char Callsign[20];
1943 double Length;
1944 double Beam;
1945 double PosRefStbd;
1946 double PosRefBow;
1947 uint32_t MothershipID;
1948
1949 if (ParseN2kPGN129810(v, MessageID, Repeat, UserID, VesselType, Vendor,
1950 Callsign, Length, Beam, PosRefStbd, PosRefBow,
1951 MothershipID)) {
1952 unsigned mmsi = UserID;
1953 // Stop here if the target shall be ignored
1954 if (mmsi == g_OwnShipmmsi || IsTargetOnTheIgnoreList(mmsi)) return false;
1955
1956 // Is this target already in the global target list?
1957 // Search the current AISTargetList for an MMSI match
1958 std::shared_ptr<AisTargetData> pTargetData = nullptr;
1959 bool bnewtarget = false;
1960
1961 auto it = AISTargetList.find(mmsi);
1962 if (it == AISTargetList.end()) // not found
1963 {
1964 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
1965 bnewtarget = true;
1966 m_n_targets++;
1967 } else {
1968 pTargetData = it->second; // find current entry
1969 }
1970
1971 // Populate the target_data
1972 pTargetData->MMSI = mmsi;
1973 pTargetData->DimA = PosRefBow;
1974 pTargetData->DimB = Length - PosRefBow;
1975 pTargetData->DimC = Beam - PosRefStbd;
1976 pTargetData->DimD = PosRefStbd;
1977 strncpy(pTargetData->CallSign, Callsign, CALL_SIGN_LEN - 1);
1978 pTargetData->CallSign[sizeof(pTargetData->CallSign) - 1] = '\0';
1979 pTargetData->ShipType = (unsigned char)VesselType;
1980
1981 pSelectAIS->DeleteSelectablePoint((void *)(long)mmsi, SELTYPE_AISTARGET);
1982 CommitAISTarget(pTargetData, "", true, bnewtarget);
1983
1984 touch_state.Notify();
1985 return true;
1986 } else
1987 return false;
1988}
1989
1990// AIS Base Station Report
1991bool AisDecoder::HandleN2K_129793(const N2000MsgPtr &n2k_msg) {
1992 std::vector<unsigned char> v = n2k_msg->payload;
1993
1994 uint8_t MessageID;
1995 tN2kAISRepeat Repeat;
1996 uint32_t UserID;
1997 double Longitude;
1998 double Latitude;
1999 unsigned int SecondsSinceMidnight;
2000 unsigned int DaysSinceEpoch;
2001
2002 if (ParseN2kPGN129793(v, MessageID, Repeat, UserID, Longitude, Latitude,
2003 SecondsSinceMidnight, DaysSinceEpoch)) {
2004 wxDateTime now = wxDateTime::Now();
2005 now.MakeUTC();
2006
2007 // Is this target already in the global target list?
2008 // Search the current AISTargetList for an MMSI match
2009 int mmsi = UserID;
2010 std::shared_ptr<AisTargetData> pTargetData = nullptr;
2011 bool bnewtarget = false;
2012
2013 auto it = AISTargetList.find(mmsi);
2014 if (it == AISTargetList.end()) // not found
2015 {
2016 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
2017 bnewtarget = true;
2018 m_n_targets++;
2019 } else {
2020 pTargetData = it->second; // find current entry
2021 }
2022
2023 // Populate the target_data
2024 pTargetData->MMSI = mmsi;
2025 pTargetData->Class = AIS_BASE;
2026
2027 if (!N2kIsNA(Longitude)) pTargetData->Lon = Longitude;
2028 if (!N2kIsNA(Latitude)) pTargetData->Lat = Latitude;
2029 pTargetData->b_positionDoubtful = false;
2030 pTargetData->b_positionOnceValid = true; // Got the position at least once
2031 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
2032 pTargetData->PositionReportTicks = now.GetTicks();
2033
2034 // FIXME (dave) Populate more fiddly static data
2035
2036 pSelectAIS->DeleteSelectablePoint((void *)(long)mmsi, SELTYPE_AISTARGET);
2037 CommitAISTarget(pTargetData, "", true, bnewtarget);
2038
2039 touch_state.Notify();
2040 return true;
2041 } else
2042 return false;
2043}
2044
2045// void AisDecoder::HandleSignalK(std::shared_ptr<const SignalkMsg> sK_msg){
2046// std::string msgTerminated = sK_msg->raw_message;;
2047// wxString sentence(msgTerminated.c_str());
2048// Decode(sentence);
2049// touch_state.notify();
2050// return true;
2051// }
2052
2053//----------------------------------------------------------------------------------
2054// Handle events from SignalK
2055//----------------------------------------------------------------------------------
2056void AisDecoder::HandleSignalK(const SignalKMsgPtr &sK_msg) {
2057 rapidjson::Document root;
2058
2059 root.Parse(sK_msg->raw_message);
2060
2061 if (root.HasParseError()) return;
2062
2063 if (root.HasMember("self")) {
2064 // m_signalk_selfid = "vessels." + (root["self"].AsString());
2065 m_signalk_selfid =
2066 (root["self"]
2067 .GetString()); // Verified for OpenPlotter node.js server 1.20
2068 }
2069 if (m_signalk_selfid.IsEmpty()) {
2070 return; // Don't handle any messages (with out self) until we know how we
2071 // are
2072 }
2073 long mmsi = 0;
2074 int meteo_SiteID = 0;
2075 if (root.HasMember("context") && root["context"].IsString()) {
2076 wxString context = root["context"].GetString();
2077 if (context == m_signalk_selfid) {
2078#if 0
2079 wxLogMessage("** Ignore context own ship..");
2080#endif
2081 return;
2082 }
2083 wxString mmsi_string;
2084 if (context.StartsWith("vessels.urn:mrn:imo:mmsi:", &mmsi_string) ||
2085 context.StartsWith("atons.urn:mrn:imo:mmsi:", &mmsi_string) ||
2086 context.StartsWith("aircraft.urn:mrn:imo:mmsi:", &mmsi_string)) {
2087 // wxLogMessage(wxString::Format("Context: %s, %s",
2088 // context.c_str(), mmsi_string));
2089 if (mmsi_string.ToLong(&mmsi)) {
2090 // wxLogMessage("Got MMSI from context.");
2091 } else {
2092 mmsi = 0;
2093 }
2094 } else if (context.StartsWith("meteo.urn:mrn:imo:mmsi:", &mmsi_string)) {
2095 // mmsi_string for a Meteo is like: 002655619:672707
2096 origin_mmsi = wxAtoi(wxString(mmsi_string).BeforeFirst(':'));
2097 meteo_SiteID = wxAtoi('1' + wxString(mmsi_string).AfterFirst(':'));
2098 // Preface "1" to distinguish e.g. "012345" from "12345"
2099 // Get a meteo mmsi_ID
2100 int meteo_mmsi = AisMeteoNewMmsi(origin_mmsi, 0, 0, 999, meteo_SiteID);
2101 if (meteo_mmsi)
2102 mmsi = meteo_mmsi;
2103 else
2104 mmsi = 0;
2105 }
2106 }
2107 if (mmsi == 0) {
2108 return; // Only handle ships with MMSI for now
2109 }
2110
2111 if (g_pMUX && g_pMUX->IsLogActive()) {
2112 wxString logmsg;
2113 logmsg.Printf("AIS :MMSI: %ld", mmsi);
2114 g_pMUX->LogInputMessage(sK_msg, false, false);
2115 }
2116
2117 // Stop here if the target shall be ignored
2118 if (IsTargetOnTheIgnoreList(mmsi)) return;
2119 // If self data is not set on the SK server, own ship mmsi
2120 // could fall through here but being set in options Own ship.
2121 if (mmsi == g_OwnShipmmsi) return;
2122
2123#if 0
2124 wxLogDebug( "AisDecoder::OnEvtSignalK: %s", root.dump().c_str(); );
2125#endif
2126 std::shared_ptr<AisTargetData> pTargetData = nullptr;
2127 std::shared_ptr<AisTargetData> pStaleTarget = nullptr;
2128 bool bnewtarget = false;
2129 int last_report_ticks;
2130 wxDateTime now;
2131 getAISTarget(mmsi, pTargetData, pStaleTarget, bnewtarget, last_report_ticks,
2132 now);
2133 if (pTargetData) {
2134 pTargetData->MMSI = mmsi;
2135 getMmsiProperties(pTargetData);
2136 if (root.HasMember("updates") && root["updates"].IsArray()) {
2137 for (rapidjson::Value::ConstValueIterator itr = root["updates"].Begin();
2138 itr != root["updates"].End(); ++itr) {
2139 handleUpdate(pTargetData, bnewtarget, *itr);
2140 }
2141 }
2142
2143 // A SART can send wo any values first transmits. Detect class already here.
2144 if (97 == mmsi / 10000000) {
2145 pTargetData->Class = AIS_SART;
2146 } else if (1994 == mmsi / 100000) {
2147 // SignalK meteo data
2148 pTargetData->Class = AIS_METEO;
2149 pTargetData->met_data.original_mmsi = origin_mmsi;
2150 pTargetData->met_data.stationID = meteo_SiteID;
2151 /* Make a unique "shipname" for each station
2152 based on position inherited from meteo_SiteID */
2153 wxString met_name = pTargetData->ShipName;
2154 if (met_name.Find("METEO") == wxNOT_FOUND) {
2155 wxString s_id;
2156 int id1, id2;
2157 s_id << meteo_SiteID;
2158 id1 = wxAtoi(s_id.Mid(1, 3));
2159 id2 = wxAtoi(s_id.Mid(4, 3));
2160 met_name = "METEO ";
2161 met_name << wxString::Format("%03d", (id1 + id2)).Right(3);
2162 strncpy(pTargetData->ShipName, met_name, SHIP_NAME_LEN - 1);
2163 }
2164 pTargetData->b_nameValid = true;
2165 pTargetData->MID = 123; // Indicates a name from SignalK
2166 pTargetData->COG = -1.;
2167 pTargetData->HDG = 511;
2168 pTargetData->SOG = -1.;
2169 pTargetData->b_NoTrack = true;
2170 pTargetData->b_show_track = false;
2171 }
2172 pTargetData->b_OwnShip = false;
2173 AISTargetList[pTargetData->MMSI] = pTargetData;
2174 }
2175}
2176
2177void AisDecoder::handleUpdate(const std::shared_ptr<AisTargetData> &pTargetData,
2178 bool bnewtarget, const rapidjson::Value &update) {
2179 wxString sfixtime = "";
2180
2181 if (update.HasMember("timestamp")) {
2182 sfixtime = update["timestamp"].GetString();
2183 }
2184 if (update.HasMember("values") && update["values"].IsArray()) {
2185 for (rapidjson::Value::ConstValueIterator itr = update["values"].Begin();
2186 itr != update["values"].End(); ++itr) {
2187 updateItem(pTargetData, bnewtarget, *itr, sfixtime);
2188 }
2189 }
2190 wxDateTime now = wxDateTime::Now();
2191 pTargetData->m_utc_hour = now.ToUTC().GetHour();
2192 pTargetData->m_utc_min = now.ToUTC().GetMinute();
2193 pTargetData->m_utc_sec = now.ToUTC().GetSecond();
2194 // pTargetData->NavStatus = 15; // undefined
2195 pTargetData->b_active = true;
2196 pTargetData->b_lost = false;
2197
2198 if (pTargetData->b_positionOnceValid) {
2199 long mmsi_long = pTargetData->MMSI;
2200 SelectItem *pSel =
2201 pSelectAIS->AddSelectablePoint(pTargetData->Lat, pTargetData->Lon,
2202 (void *)mmsi_long, SELTYPE_AISTARGET);
2203 pSel->SetUserData(pTargetData->MMSI);
2204 }
2205 UpdateOneCPA(pTargetData.get());
2206 if (pTargetData->b_show_track) UpdateOneTrack(pTargetData.get());
2207}
2208
2209void AisDecoder::updateItem(const std::shared_ptr<AisTargetData> &pTargetData,
2210 bool bnewtarget, const rapidjson::Value &item,
2211 wxString &sfixtime) const {
2212 if (item.HasMember("path") && item.HasMember("value")) {
2213 const wxString &update_path = item["path"].GetString();
2214 if (update_path == "navigation.position") {
2215 if (item["value"].HasMember("latitude") &&
2216 item["value"].HasMember("longitude")) {
2217 wxDateTime now = wxDateTime::Now();
2218 now.MakeUTC();
2219 double lat = item["value"]["latitude"].GetDouble();
2220 double lon = item["value"]["longitude"].GetDouble();
2221 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
2222 pTargetData->PositionReportTicks = now.GetTicks();
2223 pTargetData->StaticReportTicks = now.GetTicks();
2224 pTargetData->Lat = lat;
2225 pTargetData->Lon = lon;
2226 pTargetData->b_positionOnceValid = true;
2227 pTargetData->b_positionDoubtful = false;
2228 }
2229
2230 /* Not implemented in SK server (2024-01)
2231 if (item["value"].HasMember("altitude")) {
2232 pTargetData->altitude = item["value"]["altitude "].GetInt();
2233 }*/
2234 } else if (update_path == "navigation.speedOverGround" &&
2235 item["value"].IsNumber()) {
2236 pTargetData->SOG = item["value"].GetDouble() * ms_to_knot_factor;
2237 } else if (update_path == "navigation.courseOverGroundTrue" &&
2238 item["value"].IsNumber()) {
2239 pTargetData->COG = GEODESIC_RAD2DEG(item["value"].GetDouble());
2240 } else if (update_path == "navigation.headingTrue" &&
2241 item["value"].IsNumber()) {
2242 pTargetData->HDG = GEODESIC_RAD2DEG(item["value"].GetDouble());
2243 } else if (update_path == "navigation.rateOfTurn" &&
2244 item["value"].IsNumber()) {
2245 double deg_min = item["value"].GetDouble() * 180.0 / M_PI * 60.0;
2246 double rot = 4.733 * sqrt(fabs(deg_min));
2247 int rotais = wxRound(rot);
2248 if (rotais > 126) rotais = 126;
2249 pTargetData->ROTAIS = deg_min < 0 ? -rotais : rotais;
2250 pTargetData->ROTIND = wxRound(deg_min);
2251 } else if (update_path == "design.aisShipType") {
2252 if (item["value"].HasMember("id")) {
2253 if (!pTargetData->b_isDSCtarget) {
2254 pTargetData->ShipType = item["value"]["id"].GetUint();
2255 }
2256 }
2257 } else if (update_path == "atonType") {
2258 if (item["value"].HasMember("id")) {
2259 pTargetData->ShipType = item["value"]["id"].GetUint();
2260 }
2261 } else if (update_path == "virtual") {
2262 if (item["value"].GetBool()) {
2263 pTargetData->NavStatus = ATON_VIRTUAL;
2264 } else {
2265 pTargetData->NavStatus = ATON_REAL;
2266 }
2267 } else if (update_path == "offPosition") {
2268 if (item["value"].GetBool()) {
2269 if (ATON_REAL == pTargetData->NavStatus) {
2270 pTargetData->NavStatus = ATON_REAL_OFFPOSITION;
2271 } else if (ATON_VIRTUAL == pTargetData->NavStatus) {
2272 pTargetData->NavStatus = ATON_VIRTUAL_OFFPOSITION;
2273 }
2274 }
2275 } else if (update_path == "design.draft") {
2276 if (item["value"].HasMember("maximum") &&
2277 item["value"]["maximum"].IsNumber()) {
2278 pTargetData->Draft = item["value"]["maximum"].GetDouble();
2279 pTargetData->Euro_Draft = item["value"]["maximum"].GetDouble();
2280 }
2281 if (item["value"].HasMember("current") &&
2282 item["value"]["current"].IsNumber()) {
2283 double draft = item["value"]["current"].GetDouble();
2284 if (draft > 0) {
2285 pTargetData->Draft = draft;
2286 pTargetData->Euro_Draft = draft;
2287 }
2288 }
2289 } else if (update_path == "design.length") {
2290 if (pTargetData->DimB == 0) {
2291 if (item["value"].HasMember("overall")) {
2292 if (item["value"]["overall"].IsNumber()) {
2293 pTargetData->Euro_Length = item["value"]["overall"].GetDouble();
2294 pTargetData->DimA = item["value"]["overall"].GetDouble();
2295 }
2296 pTargetData->DimB = 0;
2297 }
2298 }
2299 } else if (update_path == "sensors.ais.class") {
2300 wxString aisclass = item["value"].GetString();
2301 if (aisclass == "A") {
2302 if (!pTargetData->b_isDSCtarget) pTargetData->Class = AIS_CLASS_A;
2303 } else if (aisclass == "B") {
2304 if (!pTargetData->b_isDSCtarget) {
2305 if (!isBuoyMmsi(pTargetData->MMSI))
2306 pTargetData->Class = AIS_CLASS_B;
2307 else
2308 pTargetData->Class = AIS_BUOY;
2309
2310 // Class B targets have no status. Enforce this...
2311 pTargetData->NavStatus = UNDEFINED;
2312 }
2313 } else if (aisclass == "BASE") {
2314 pTargetData->Class = AIS_BASE;
2315 } else if (aisclass == "ATON") {
2316 pTargetData->Class = AIS_ATON;
2317 }
2318 } else if (update_path == "sensors.ais.fromBow") {
2319 if (pTargetData->DimB == 0 && pTargetData->DimA != 0) {
2320 int length = pTargetData->DimA;
2321 if (item["value"].IsNumber()) {
2322 pTargetData->DimA = item["value"].GetDouble();
2323 pTargetData->DimB = length - item["value"].GetDouble();
2324 }
2325 }
2326 } else if (update_path == "design.beam") {
2327 if (pTargetData->DimD == 0) {
2328 if (item["value"].IsNumber()) {
2329 pTargetData->Euro_Beam = item["value"].GetDouble();
2330 pTargetData->DimC = item["value"].GetDouble();
2331 }
2332 pTargetData->DimD = 0;
2333 }
2334 } else if (update_path == "sensors.ais.fromCenter") {
2335 if (pTargetData->DimD == 0 && pTargetData->DimC != 0) {
2336 int beam = pTargetData->DimC;
2337 int center = beam / 2;
2338 if (item["value"].IsNumber()) {
2339 // FIXME (nohal): Dim* are int, but we have seen data streams with
2340 // doubles in them...
2341 pTargetData->DimC = center + item["value"].GetDouble();
2342 pTargetData->DimD = beam - pTargetData->DimC;
2343 }
2344 }
2345 } else if (update_path == "navigation.state") {
2346 wxString state = item["value"].GetString();
2347 if (state == "motoring") {
2348 pTargetData->NavStatus = UNDERWAY_USING_ENGINE;
2349 } else if (state == "anchored") {
2350 pTargetData->NavStatus = AT_ANCHOR;
2351 } else if (state == "not under command") {
2352 pTargetData->NavStatus = NOT_UNDER_COMMAND;
2353 } else if (state == "restricted manouverability") {
2354 pTargetData->NavStatus = RESTRICTED_MANOEUVRABILITY;
2355 } else if (state == "constrained by draft") {
2356 pTargetData->NavStatus = CONSTRAINED_BY_DRAFT;
2357 } else if (state == "moored") {
2358 pTargetData->NavStatus = MOORED;
2359 } else if (state == "aground") {
2360 pTargetData->NavStatus = AGROUND;
2361 } else if (state == "fishing") {
2362 pTargetData->NavStatus = FISHING;
2363 } else if (state == "sailing") {
2364 pTargetData->NavStatus = UNDERWAY_SAILING;
2365 } else if (state == "hazardous material high speed") {
2366 pTargetData->NavStatus = HSC;
2367 } else if (state == "hazardous material wing in ground") {
2368 pTargetData->NavStatus = WIG;
2369 } else if (state == "ais-sart") {
2370 pTargetData->NavStatus = RESERVED_14;
2371 } else {
2372 pTargetData->NavStatus = UNDEFINED;
2373 }
2374 } else if (update_path == "navigation.destination.commonName") {
2375 const wxString &destination = item["value"].GetString();
2376 pTargetData->Destination[0] = '\0';
2377 strncpy(pTargetData->Destination, destination.c_str(),
2378 DESTINATION_LEN - 1);
2379 } else if (update_path == "navigation.destination.eta") {
2380 const wxString &eta = item["value"].GetString();
2381 if (eta.Len()) {
2382 // Parse ISO 8601 date/time
2383 wxDateTime tz;
2384 ParseGPXDateTime(tz, eta);
2385 pTargetData->ETA_Mo = tz.GetMonth() + 1;
2386 pTargetData->ETA_Day = tz.GetDay();
2387 pTargetData->ETA_Hr = tz.GetHour();
2388 pTargetData->ETA_Min = tz.GetMinute();
2389 }
2390 } else if (update_path == "navigation.specialManeuver") {
2391 if (strcmp("not available", item["value"].GetString()) != 0 &&
2392 pTargetData->IMO < 1) {
2393 const wxString &bluesign = item["value"].GetString();
2394 if ("not engaged" == bluesign) {
2395 pTargetData->blue_paddle = 1;
2396 }
2397 if ("engaged" == bluesign) {
2398 pTargetData->blue_paddle = 2;
2399 }
2400 pTargetData->b_blue_paddle =
2401 pTargetData->blue_paddle == 2 ? true : false;
2402 }
2403 } else if (update_path == "sensors.ais.designatedAreaCode") {
2404 if (item["value"].GetInt() == 200) { // European inland
2405 pTargetData->b_hasInlandDac = true;
2406 }
2407 } else if (update_path == "sensors.ais.functionalId") {
2408 if (item["value"].GetInt() == 10 && pTargetData->b_hasInlandDac) {
2409 // "Inland ship static and voyage related data"
2410 pTargetData->b_isEuroInland = true;
2411 }
2412
2413 // METEO Data
2414 } else if (update_path == "environment.date") {
2415 const wxString &issued = item["value"].GetString();
2416 if (issued.Len()) {
2417 // Parse ISO 8601 date/time
2418 wxDateTime tz;
2419 ParseGPXDateTime(tz, issued);
2420 pTargetData->met_data.day = tz.GetDay();
2421 pTargetData->met_data.hour = tz.GetHour();
2422 pTargetData->met_data.minute = tz.GetMinute();
2423 }
2424 } else if (update_path == "environment.wind.averageSpeed" &&
2425 item["value"].IsNumber()) {
2426 pTargetData->met_data.wind_kn = MS2KNOTS(item["value"].GetDouble());
2427 } else if (update_path == "environment.wind.gust" &&
2428 item["value"].IsNumber()) {
2429 pTargetData->met_data.wind_gust_kn = MS2KNOTS(item["value"].GetDouble());
2430 } else if (update_path == "environment.wind.directionTrue" &&
2431 item["value"].IsNumber()) {
2432 pTargetData->met_data.wind_dir =
2433 GEODESIC_RAD2DEG(item["value"].GetDouble());
2434 } else if (update_path == "environment.wind.gustDirectionTrue" &&
2435 item["value"].IsNumber()) {
2436 pTargetData->met_data.wind_gust_dir =
2437 GEODESIC_RAD2DEG(item["value"].GetDouble());
2438 } else if (update_path == "environment.outside.temperature" &&
2439 item["value"].IsNumber()) {
2440 pTargetData->met_data.air_temp = KelvinToC(item["value"].GetDouble());
2441 } else if (update_path == "environment.outside.relativeHumidity" &&
2442 item["value"].IsNumber()) {
2443 pTargetData->met_data.rel_humid = item["value"].GetDouble();
2444 } else if (update_path == "environment.outside.dewPointTemperature" &&
2445 item["value"].IsNumber()) {
2446 pTargetData->met_data.dew_point = KelvinToC(item["value"].GetDouble());
2447 } else if (update_path == "environment.outside.pressure" &&
2448 item["value"].IsNumber()) {
2449 pTargetData->met_data.airpress =
2450 static_cast<int>(item["value"].GetDouble() / 100);
2451 } else if (update_path == "environment.water.level" &&
2452 item["value"].IsNumber()) {
2453 pTargetData->met_data.water_lev_dev = item["value"].GetDouble();
2454 } else if (update_path == "environment.water.current.drift" &&
2455 item["value"].IsNumber()) { // surfcurrspd
2456 pTargetData->met_data.current = MS2KNOTS(item["value"].GetDouble());
2457 } else if (update_path == "environment.water.current.set" &&
2458 item["value"].IsNumber()) { // surfcurrdir
2459 pTargetData->met_data.curr_dir =
2460 GEODESIC_RAD2DEG(item["value"].GetDouble());
2461 } else if (update_path == "environment.water.levelTendencyValue" &&
2462 item["value"].IsNumber()) {
2463 pTargetData->met_data.water_lev_trend =
2464 static_cast<int>(item["value"].GetDouble());
2465 } else if (update_path == "environment.water.levelTendency") {
2466 // Don't use this text we parse it ourself.
2467 } else if (update_path == "environment.water.waves.significantHeight" &&
2468 item["value"].IsNumber()) {
2469 pTargetData->met_data.wave_height = item["value"].GetDouble();
2470 } else if (update_path == "environment.water.waves.period" &&
2471 item["value"].IsNumber()) {
2472 pTargetData->met_data.wave_period =
2473 static_cast<int>(item["value"].GetDouble());
2474 } else if (update_path == "environment.water.waves.directionTrue" &&
2475 item["value"].IsNumber()) {
2476 pTargetData->met_data.wave_dir =
2477 GEODESIC_RAD2DEG(item["value"].GetDouble());
2478 } else if (update_path == "environment.water.swell.height" &&
2479 item["value"].IsNumber()) {
2480 pTargetData->met_data.swell_height = item["value"].GetDouble();
2481 } else if (update_path == "environment.water.swell.period" &&
2482 item["value"].IsNumber()) {
2483 pTargetData->met_data.swell_per =
2484 static_cast<int>(item["value"].GetDouble());
2485 } else if (update_path == "environment.water.swell.directionTrue" &&
2486 item["value"].IsNumber()) {
2487 pTargetData->met_data.swell_dir =
2488 GEODESIC_RAD2DEG(item["value"].GetDouble());
2489 } else if (update_path == "environment.water.temperature" &&
2490 item["value"].IsNumber()) {
2491 pTargetData->met_data.water_temp = KelvinToC(item["value"].GetDouble());
2492 } else if (update_path == "environment.water.salinity" &&
2493 item["value"].IsNumber()) {
2494 pTargetData->met_data.salinity = item["value"].GetDouble();
2495 } else if (update_path == "environment.water.ice") {
2496 // Don't use. We parse it ourself
2497 } else if (update_path == "environment.water.iceValue" &&
2498 item["value"].IsNumber()) {
2499 pTargetData->met_data.ice = static_cast<int>(item["value"].GetDouble());
2500 } else if (update_path == "environment.water.seaStateValue" &&
2501 item["value"].IsNumber()) {
2502 pTargetData->met_data.seastate =
2503 static_cast<int>(item["value"].GetDouble());
2504 } else if (update_path == "environment.water.seaState") {
2505 // This is the parsed (air!) Bf-scale. Don't use
2506 } else if (update_path == "environment.outside.precipitation") {
2507 // Don't use. We parse it ourself
2508 } else if (update_path == "environment.outside.precipitationValue" &&
2509 item["value"].IsNumber()) {
2510 pTargetData->met_data.precipitation =
2511 static_cast<int>(item["value"].GetDouble());
2512 } else if (update_path == "environment.outside.pressureTendencyValue" &&
2513 item["value"].IsNumber()) {
2514 pTargetData->met_data.airpress_tend =
2515 static_cast<int>(item["value"].GetDouble());
2516 } else if (update_path == "environment.outside.pressureTendency") {
2517 // Parsed value, don't use, we do it ourself
2518 } else if (update_path == "environment.outside.horizontalVisibility" &&
2519 item["value"].IsNumber()) {
2520 pTargetData->met_data.hor_vis =
2521 GEODESIC_METERS2NM(item["value"].GetDouble());
2522 } else if (update_path ==
2523 "environment.outside.horizontalVisibility.overRange") {
2524 pTargetData->met_data.hor_vis_GT = item["value"].GetBool();
2525 } else if (update_path.empty()) {
2526 if (item["value"].HasMember("name")) {
2527 const wxString &name = item["value"]["name"].GetString();
2528 strncpy(pTargetData->ShipName, name.c_str(), SHIP_NAME_LEN - 1);
2529 pTargetData->b_nameValid = true;
2530 pTargetData->MID = 123; // Indicates a name from SignalK
2531 } else if (item["value"].HasMember("registrations")) {
2532 const wxString &imo = item["value"]["registrations"]["imo"].GetString();
2533 pTargetData->IMO = wxAtoi(imo.Right(7));
2534 } else if (item["value"].HasMember("communication")) {
2535 const wxString &callsign =
2536 item["value"]["communication"]["callsignVhf"].GetString();
2537 strncpy(pTargetData->CallSign, callsign.c_str(), 7);
2538 }
2539 if (item["value"].HasMember("mmsi") &&
2540 1994 != (pTargetData->MMSI) / 100000) { // Meteo
2541 long mmsi;
2542 wxString tmp = item["value"]["mmsi"].GetString();
2543 if (tmp.ToLong(&mmsi)) {
2544 pTargetData->MMSI = mmsi;
2545
2546 if (97 == mmsi / 10000000) {
2547 pTargetData->Class = AIS_SART;
2548 }
2549 if (111 == mmsi / 1000000) {
2550 pTargetData->b_SarAircraftPosnReport = true;
2551 }
2552
2553 AISshipNameCache(pTargetData.get(), AISTargetNamesC, AISTargetNamesNC,
2554 mmsi);
2555 }
2556 }
2557 } else {
2558 wxLogMessage(wxString::Format(
2559 "** AisDecoder::updateItem: unhandled path %s", update_path));
2560#if 1
2561 rapidjson::StringBuffer buffer;
2562 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
2563 item.Accept(writer);
2564 wxString msg("update: ");
2565 msg.append(buffer.GetString());
2566 wxLogMessage(msg);
2567#endif
2568 }
2569 }
2570}
2571
2572//----------------------------------------------------------------------------------
2573// Decode a single AIVDO sentence to a Generic Position Report
2574//----------------------------------------------------------------------------------
2575AisError AisDecoder::DecodeSingleVDO(const wxString &str, GenericPosDatEx *pos,
2576 wxString *accumulator) {
2577 // Make some simple tests for validity
2578 if (str.Len() > 128) return AIS_NMEAVDX_TOO_LONG;
2579
2580 if (!NMEACheckSumOK(str)) return AIS_NMEAVDX_CHECKSUM_BAD;
2581
2582 if (!pos) return AIS_GENERIC_ERROR;
2583
2584 if (!accumulator) return AIS_GENERIC_ERROR;
2585
2586 // We only process AIVDO messages
2587 if (!str.Mid(1, 5).IsSameAs("AIVDO")) return AIS_GENERIC_ERROR;
2588
2589 // Use a tokenizer to pull out the first 4 fields
2590 wxStringTokenizer tkz(str, ",");
2591
2592 wxString token;
2593 token = tkz.GetNextToken(); // !xxVDx
2594
2595 token = tkz.GetNextToken();
2596 int nsentences = atoi(token.mb_str());
2597
2598 token = tkz.GetNextToken();
2599 int isentence = atoi(token.mb_str());
2600
2601 token = tkz.GetNextToken(); // skip 2 fields
2602 token = tkz.GetNextToken();
2603
2604 wxString string_to_parse;
2605 string_to_parse.Clear();
2606
2607 // Fill the output structure with all NANs
2608 pos->kLat = NAN;
2609 pos->kLon = NAN;
2610 pos->kCog = NAN;
2611 pos->kSog = NAN;
2612 pos->kHdt = NAN;
2613 pos->kVar = NAN;
2614 pos->kHdm = NAN;
2615
2616 // Simple case first
2617 // First and only part of a one-part sentence
2618 if ((1 == nsentences) && (1 == isentence)) {
2619 string_to_parse = tkz.GetNextToken(); // the encapsulated data
2620 }
2621
2622 else if (nsentences > 1) {
2623 if (1 == isentence) {
2624 *accumulator = tkz.GetNextToken(); // the encapsulated data
2625 }
2626
2627 else {
2628 accumulator->Append(tkz.GetNextToken());
2629 }
2630
2631 if (isentence == nsentences) { // ready to parse
2632 string_to_parse = *accumulator;
2633 }
2634 }
2635
2636 if (string_to_parse.IsEmpty() &&
2637 (nsentences > 1)) { // not ready, so return with NAN
2638 return AIS_INCOMPLETE_MULTIPART; // and non-zero return
2639 }
2640
2641 // The accumulated payload must fit AisBitstring; same guard as DecodeN0183.
2642 if (string_to_parse.Len() >= AIS_MAX_MESSAGE_LEN) {
2643 accumulator->Clear();
2644 return AIS_NMEAVDX_TOO_LONG;
2645 }
2646
2647 // Create the bit accessible string
2648 AisBitstring strbit(string_to_parse.mb_str());
2649
2650 // auto TargetData = std::make_unique<AisTargetData>(
2651 // *AisTargetDataMaker::GetInstance().GetTargetData());
2652
2653 auto TargetData = AisTargetDataMaker::GetInstance().GetTargetData();
2654
2655 bool bdecode_result = Parse_VDXBitstring(&strbit, TargetData);
2656
2657 if (bdecode_result) {
2658 switch (TargetData->MID) {
2659 case 1:
2660 case 2:
2661 case 3:
2662 case 18: {
2663 if (!TargetData->b_positionDoubtful) {
2664 pos->kLat = TargetData->Lat;
2665 pos->kLon = TargetData->Lon;
2666 } else {
2667 pos->kLat = NAN;
2668 pos->kLon = NAN;
2669 }
2670
2671 if (TargetData->COG == 360.0)
2672 pos->kCog = NAN;
2673 else
2674 pos->kCog = TargetData->COG;
2675
2676 if (TargetData->SOG > 102.2)
2677 pos->kSog = NAN;
2678 else
2679 pos->kSog = TargetData->SOG;
2680
2681 if ((int)TargetData->HDG == 511)
2682 pos->kHdt = NAN;
2683 else
2684 pos->kHdt = TargetData->HDG;
2685
2686 // VDO messages do not contain variation or magnetic heading
2687 pos->kVar = NAN;
2688 pos->kHdm = NAN;
2689 break;
2690 }
2691 default:
2692 return AIS_GENERIC_ERROR; // unrecognised sentence
2693 }
2694
2695 return AIS_NoError;
2696 } else
2697 return AIS_GENERIC_ERROR;
2698}
2699
2700//----------------------------------------------------------------------------------------
2701// Decode NMEA VDM/VDO/FRPOS/DSCDSE/TTM/TLL/OSD/RSD/TLB/WPL sentence to AIS
2702// Target(s)
2703//----------------------------------------------------------------------------------------
2704
2705AisError AisDecoder::DecodeN0183(const wxString &str) {
2706 AisError ret = AIS_GENERIC_ERROR;
2707 wxString string_to_parse;
2708
2709 double gpsg_lat, gpsg_lon, gpsg_mins, gpsg_degs;
2710 double gpsg_cog, gpsg_sog, gpsg_utc_time;
2711 int gpsg_utc_hour = 0;
2712 int gpsg_utc_min = 0;
2713 int gpsg_utc_sec = 0;
2714 char gpsg_name_str[21];
2715 wxString gpsg_date;
2716
2717 bool bdecode_result = false;
2718
2719 int gpsg_mmsi = 0;
2720 int arpa_mmsi = 0;
2721 int aprs_mmsi = 0;
2722 unsigned mmsi = 0;
2723
2724 long arpa_tgt_num = 0;
2725 double arpa_sog = 0.;
2726 double arpa_cog = 0.;
2727 double arpa_lat = 0.;
2728 double arpa_lon = 0.;
2729 double arpa_dist = 0.;
2730 double arpa_brg = 0.;
2731 wxString arpa_brgunit;
2732 wxString arpa_status;
2733 wxString arpa_distunit;
2734 wxString arpa_cogunit;
2735 double arpa_mins, arpa_degs;
2736 double arpa_utc_time;
2737 int arpa_utc_hour = 0;
2738 int arpa_utc_min = 0;
2739 int arpa_utc_sec = 0;
2740 char arpa_name_str[21];
2741 bool arpa_lost = true;
2742 bool arpa_nottracked = false;
2743
2744 double aprs_lat = 0.;
2745 double aprs_lon = 0.;
2746 char aprs_name_str[21];
2747 double aprs_mins, aprs_degs;
2748
2749 std::shared_ptr<AisTargetData> pTargetData = nullptr;
2750 std::shared_ptr<AisTargetData> pStaleTarget = nullptr;
2751 bool bnewtarget = false;
2752 int last_report_ticks;
2753
2754 // Make some simple tests for validity
2755
2756 if (str.Len() > 128) return AIS_NMEAVDX_TOO_LONG;
2757
2758 if (!NMEACheckSumOK(str)) {
2759 return AIS_NMEAVDX_CHECKSUM_BAD;
2760 }
2761 if (str.Mid(1, 2).IsSameAs("CD")) {
2762 ProcessDSx(str);
2763 return AIS_NoError;
2764 } else if (str.Mid(3, 3).IsSameAs("TTM")) {
2765 //$--TTM,xx,x.x,x.x,a,x.x,x.x,a,x.x,x.x,a,c--c,a,a*hh <CR><LF>
2766 // or
2767 //$--TTM,xx,x.x,x.x,a,x.x,x.x,a,x.x,x.x,a,c--c,a,a,hhmmss.ss,a*hh<CR><LF>
2768 wxStringTokenizer tkz(str, ",*");
2769
2770 wxString token;
2771 token = tkz.GetNextToken(); // Sentence (xxTTM)
2772 token = tkz.GetNextToken(); // 1) Target Number
2773 token.ToLong(&arpa_tgt_num);
2774 token = tkz.GetNextToken(); // 2)Target Distance
2775 token.ToDouble(&arpa_dist);
2776 token = tkz.GetNextToken(); // 3) Bearing from own ship
2777 token.ToDouble(&arpa_brg);
2778 arpa_brgunit = tkz.GetNextToken(); // 4) Bearing Units
2779 if (arpa_brgunit == "R") {
2780 if (std::isnan(arpa_ref_hdg)) {
2781 if (!std::isnan(gHdt))
2782 arpa_brg += gHdt;
2783 else
2784 arpa_brg += gCog;
2785 } else
2786 arpa_brg += arpa_ref_hdg;
2787 if (arpa_brg >= 360.) arpa_brg -= 360.;
2788 }
2789 token = tkz.GetNextToken(); // 5) Target speed
2790 token.ToDouble(&arpa_sog);
2791 token = tkz.GetNextToken(); // 6) Target Course
2792 token.ToDouble(&arpa_cog);
2793 arpa_cogunit = tkz.GetNextToken(); // 7) Course Units
2794 if (arpa_cogunit == "R") {
2795 if (std::isnan(arpa_ref_hdg)) {
2796 if (!std::isnan(gHdt))
2797 arpa_cog += gHdt;
2798 else
2799 arpa_cog += gCog;
2800 } else
2801 arpa_cog += arpa_ref_hdg;
2802 if (arpa_cog >= 360.) arpa_cog -= 360.;
2803 }
2804 token = tkz.GetNextToken(); // 8) Distance of closest-point-of-approach
2805 token = tkz.GetNextToken(); // 9) Time until closest-point-of-approach "-"
2806 // means increasing
2807 arpa_distunit = tkz.GetNextToken(); // 10)Speed/ dist unit
2808 token = tkz.GetNextToken(); // 11) Target name
2809 if (token == "") token = wxString::Format("ARPA %ld", arpa_tgt_num);
2810 int len = wxMin(token.Length(), 20);
2811 strncpy(arpa_name_str, token.mb_str(), len);
2812 arpa_name_str[len] = 0;
2813 arpa_status = tkz.GetNextToken(); // 12) Target Status
2814 if (arpa_status != "L") {
2815 arpa_lost = false;
2816 } else if (arpa_status != "")
2817 arpa_nottracked = true;
2818 wxString arpa_reftarget = tkz.GetNextToken(); // 13) Reference Target
2819 if (tkz.HasMoreTokens()) {
2820 token = tkz.GetNextToken();
2821 token.ToDouble(&arpa_utc_time);
2822 arpa_utc_hour = (int)(arpa_utc_time / 10000.0);
2823 arpa_utc_min = (int)(arpa_utc_time / 100.0) - arpa_utc_hour * 100;
2824 arpa_utc_sec =
2825 (int)arpa_utc_time - arpa_utc_hour * 10000 - arpa_utc_min * 100;
2826 } else {
2827 arpa_utc_hour = wxDateTime::Now().ToUTC().GetHour();
2828 arpa_utc_min = wxDateTime::Now().ToUTC().GetMinute();
2829 arpa_utc_sec = wxDateTime::Now().ToUTC().GetSecond();
2830 }
2831
2832 if (arpa_distunit == "K") {
2833 arpa_dist = fromUsrDistance(arpa_dist, DISTANCE_KM, g_iDistanceFormat);
2834 arpa_sog = fromUsrSpeed(arpa_sog, SPEED_KMH, g_iSpeedFormat);
2835 } else if (arpa_distunit == "S") {
2836 arpa_dist = fromUsrDistance(arpa_dist, DISTANCE_MI, g_iDistanceFormat);
2837 arpa_sog = fromUsrSpeed(arpa_sog, SPEED_MPH, g_iSpeedFormat);
2838 }
2839
2840 mmsi = arpa_mmsi = 199200000 + arpa_tgt_num;
2841 // 199 is INMARSAT-A MID, should not occur ever in AIS
2842 // stream + we make sure we are out of the hashes for
2843 // GPSGate buddies by being above 1992*
2844 } else if (str.Mid(3, 3).IsSameAs("TLL")) {
2845 //$--TLL,xx,llll.lll,a,yyyyy.yyy,a,c--c,hhmmss.ss,a,a*hh<CR><LF>
2846 //"$RATLL,01,5603.370,N,01859.976,E,ALPHA,015200.36,T,*75\r\n"
2847 wxStringTokenizer tkz(str, ",*");
2848
2849 wxString token;
2850 wxString aprs_tll_str = tkz.GetNextToken(); // Sentence (xxTLL)
2851 token = tkz.GetNextToken(); // 1) Target number 00 - 99
2852 token.ToLong(&arpa_tgt_num);
2853 token = tkz.GetNextToken(); // 2) Latitude, N/S
2854 token.ToDouble(&arpa_lat);
2855 arpa_degs = (int)(arpa_lat / 100.0);
2856 arpa_mins = arpa_lat - arpa_degs * 100.0;
2857 arpa_lat = arpa_degs + arpa_mins / 60.0;
2858 token = tkz.GetNextToken(); // hemisphere N or S
2859 if (token.Mid(0, 1).Contains("S") == true ||
2860 token.Mid(0, 1).Contains("s") == true)
2861 arpa_lat = 0. - arpa_lat;
2862 token = tkz.GetNextToken(); // 3) Longitude, E/W
2863 token.ToDouble(&arpa_lon);
2864 arpa_degs = (int)(arpa_lon / 100.0);
2865 arpa_mins = arpa_lon - arpa_degs * 100.0;
2866 arpa_lon = arpa_degs + arpa_mins / 60.0;
2867 token = tkz.GetNextToken(); // hemisphere E or W
2868 if (token.Mid(0, 1).Contains("W") == true ||
2869 token.Mid(0, 1).Contains("w") == true)
2870 arpa_lon = 0. - arpa_lon;
2871 token = tkz.GetNextToken(); // 4) Target name
2872 if (token == "") token = wxString::Format("ARPA %d", arpa_tgt_num);
2873 int len = wxMin(token.Length(), 20);
2874 strncpy(arpa_name_str, token.mb_str(), len);
2875 arpa_name_str[len] = 0;
2876 token = tkz.GetNextToken(); // 5) UTC of data
2877 token.ToDouble(&arpa_utc_time);
2878 arpa_utc_hour = (int)(arpa_utc_time / 10000.0);
2879 arpa_utc_min = (int)(arpa_utc_time / 100.0) - arpa_utc_hour * 100;
2880 arpa_utc_sec =
2881 (int)arpa_utc_time - arpa_utc_hour * 10000 - arpa_utc_min * 100;
2882 arpa_status =
2883 tkz.GetNextToken(); // 6) Target status: L = lost,tracked
2884 // target has beenlost Q = query,target in
2885 // the process of acquisition T = tracking
2886 if (arpa_status != "L")
2887 arpa_lost = false;
2888 else if (arpa_status != "")
2889 arpa_nottracked = true;
2890 wxString arpa_reftarget = tkz.GetNextToken(); // 7) Reference target=R,null
2891 mmsi = arpa_mmsi = 199200000 + arpa_tgt_num;
2892 // 199 is INMARSAT-A MID, should not occur ever in AIS
2893 // stream + we make sure we are out of the hashes for
2894 // GPSGate buddies by being above 1992*
2895 } else if (str.Mid(3, 3).IsSameAs("OSD")) {
2896 //$--OSD,x.x,A,x.x,a,x.x,a,x.x,x.x,a*hh <CR><LF>
2897 wxStringTokenizer tkz(str, ",*");
2898
2899 wxString token;
2900 token = tkz.GetNextToken(); // Sentence (xxOSD)
2901 token = tkz.GetNextToken(); // 1) Heading (true)
2902 token.ToDouble(&arpa_ref_hdg);
2903 // 2) speed
2904 // 3) Vessel Course, degrees True
2905 // 4) Course Reference, B/M/W/R/P (see note)
2906 // 5) Vessel Speed
2907 // 6) Speed Reference, B/M/W/R/P (see note)
2908 // 7) Vessel Set, degrees True - Manually entered
2909 // 8) Vessel drift (speed) - Manually entered
2910 // 9) Speed Units K = km/h; N = Knots; S = statute miles/h
2911
2912 } else if (g_bWplUsePosition && str.Mid(3, 3).IsSameAs("WPL")) {
2913 //** $--WPL,llll.ll,a,yyyyy.yy,a,c--c*hh<CR><LF>
2914 wxStringTokenizer tkz(str, ",*");
2915
2916 wxString token;
2917 token = tkz.GetNextToken(); // Sentence (xxWPL)
2918 token = tkz.GetNextToken(); // 1) Latitude, N/S
2919 token.ToDouble(&aprs_lat);
2920 aprs_degs = (int)(aprs_lat / 100.0);
2921 aprs_mins = aprs_lat - aprs_degs * 100.0;
2922 aprs_lat = aprs_degs + aprs_mins / 60.0;
2923 token = tkz.GetNextToken(); // 2) hemisphere N or S
2924 if (token.Mid(0, 1).Contains("S") == true ||
2925 token.Mid(0, 1).Contains("s") == true)
2926 aprs_lat = 0. - aprs_lat;
2927 token = tkz.GetNextToken(); // 3) Longitude, E/W
2928 token.ToDouble(&aprs_lon);
2929 aprs_degs = (int)(aprs_lon / 100.0);
2930 aprs_mins = aprs_lon - aprs_degs * 100.0;
2931 aprs_lon = aprs_degs + aprs_mins / 60.0;
2932 token = tkz.GetNextToken(); // 4) hemisphere E or W
2933 if (token.Mid(0, 1).Contains("W") == true ||
2934 token.Mid(0, 1).Contains("w") == true)
2935 aprs_lon = 0. - aprs_lon;
2936 token = tkz.GetNextToken(); // 5) Target name
2937 int len = wxMin(token.Length(), 20);
2938 strncpy(aprs_name_str, token.mb_str(), len + 1);
2939 if (0 == g_WplAction) { // APRS position reports
2940 int i, hash = 0;
2941 aprs_name_str[len] = 0;
2942 for (i = 0; i < len; i++) {
2943 hash = hash * 10;
2944 hash += (int)(aprs_name_str[i]);
2945 while (hash >= 100000) hash = hash / 100000;
2946 }
2947 mmsi = aprs_mmsi = 199300000 + hash;
2948 // 199 is INMARSAT-A MID, should not occur ever in AIS stream +
2949 // we make sure we are out of the hashes for GPSGate buddies
2950 // and ARPA by being above 1993*
2951 } else if (1 == g_WplAction) { // Create mark
2952 auto *pWP =
2953 new RoutePoint(aprs_lat, aprs_lon, "", aprs_name_str, "", false);
2954 pWP->m_bIsolatedMark = true;
2955 InsertWpt(pWP, true);
2956 }
2957 } else if (str.Mid(1, 5).IsSameAs("FRPOS")) {
2958 // parse a GpsGate Position message $FRPOS,.....
2959
2960 // Use a tokenizer to pull out the first 9 fields
2961 wxStringTokenizer tkz(str, ",*");
2962
2963 wxString token;
2964 token = tkz.GetNextToken(); // !$FRPOS
2965
2966 token = tkz.GetNextToken(); // latitude DDMM.MMMM
2967 token.ToDouble(&gpsg_lat);
2968 gpsg_degs = (int)(gpsg_lat / 100.0);
2969 gpsg_mins = gpsg_lat - gpsg_degs * 100.0;
2970 gpsg_lat = gpsg_degs + gpsg_mins / 60.0;
2971
2972 token = tkz.GetNextToken(); // hemisphere N or S
2973 if (token.Mid(0, 1).Contains("S") == true ||
2974 token.Mid(0, 1).Contains("s") == true)
2975 gpsg_lat = 0. - gpsg_lat;
2976
2977 token = tkz.GetNextToken(); // longitude DDDMM.MMMM
2978 token.ToDouble(&gpsg_lon);
2979 gpsg_degs = (int)(gpsg_lon / 100.0);
2980 gpsg_mins = gpsg_lon - gpsg_degs * 100.0;
2981 gpsg_lon = gpsg_degs + gpsg_mins / 60.0;
2982
2983 token = tkz.GetNextToken(); // hemisphere E or W
2984 if (token.Mid(0, 1).Contains("W") == true ||
2985 token.Mid(0, 1).Contains("w") == true)
2986 gpsg_lon = 0. - gpsg_lon;
2987
2988 token = tkz.GetNextToken(); // altitude AA.a
2989 // token.toDouble(&gpsg_alt);
2990
2991 token = tkz.GetNextToken(); // speed over ground SSS.SS knots
2992 token.ToDouble(&gpsg_sog);
2993
2994 token = tkz.GetNextToken(); // heading over ground HHH.hh degrees
2995 token.ToDouble(&gpsg_cog);
2996
2997 token = tkz.GetNextToken(); // date DDMMYY
2998 gpsg_date = token;
2999
3000 token = tkz.GetNextToken(); // time UTC hhmmss.dd
3001 token.ToDouble(&gpsg_utc_time);
3002 gpsg_utc_hour = (int)(gpsg_utc_time / 10000.0);
3003 gpsg_utc_min = (int)(gpsg_utc_time / 100.0) - gpsg_utc_hour * 100;
3004 gpsg_utc_sec =
3005 (int)gpsg_utc_time - gpsg_utc_hour * 10000 - gpsg_utc_min * 100;
3006
3007 // now comes the name, followed by in * and NMEA checksum
3008
3009 token = tkz.GetNextToken();
3010 int i, len, hash = 0;
3011 len = wxMin(wxStrlen(token), 20);
3012 strncpy(gpsg_name_str, token.mb_str(), len);
3013 gpsg_name_str[len] = 0;
3014 for (i = 0; i < len; i++) {
3015 hash = hash * 10;
3016 hash += (int)(token[i]);
3017 while (hash >= 100000) hash = hash / 100000;
3018 }
3019 // 199 is INMARSAT-A MID, should not occur ever in AIS stream
3020 gpsg_mmsi = 199000000 + hash;
3021 mmsi = gpsg_mmsi;
3022 } else if (!str.Mid(3, 2).IsSameAs("VD")) {
3023 return AIS_NMEAVDX_BAD;
3024 }
3025
3026 // OK, looks like the sentence is OK
3027
3028 // Use a tokenizer to pull out the first 4 fields
3029 string_to_parse.Clear();
3030
3031 if (str.Mid(3, 2).IsSameAs("VD")) {
3032 wxStringTokenizer tkz(str, ",");
3033
3034 wxString token;
3035 token = tkz.GetNextToken(); // !xxVDx
3036
3037 token = tkz.GetNextToken();
3038 nsentences = atoi(token.mb_str());
3039
3040 token = tkz.GetNextToken();
3041 isentence = atoi(token.mb_str());
3042
3043 token = tkz.GetNextToken();
3044 long lsequence_id = 0;
3045 token.ToLong(&lsequence_id);
3046
3047 token = tkz.GetNextToken();
3048 long lchannel;
3049 token.ToLong(&lchannel);
3050 // Now, some decisions
3051
3052 // Simple case first
3053 // First and only part of a one-part sentence
3054 if ((1 == nsentences) && (1 == isentence)) {
3055 string_to_parse = tkz.GetNextToken(); // the encapsulated data
3056 }
3057
3058 else if (nsentences > 1) {
3059 if (1 == isentence) {
3060 sentence_accumulator = tkz.GetNextToken(); // the encapsulated data
3061 }
3062
3063 else {
3064 sentence_accumulator += tkz.GetNextToken();
3065 }
3066
3067 if (isentence == nsentences) {
3068 string_to_parse = sentence_accumulator;
3069 }
3070 }
3071 }
3072
3073 if (mmsi || (!string_to_parse.IsEmpty() &&
3074 (string_to_parse.Len() < AIS_MAX_MESSAGE_LEN))) {
3075 // Create the bit accessible string
3076 wxCharBuffer abuf = string_to_parse.ToUTF8();
3077 if (!abuf.data()) // badly formed sentence?
3078 return AIS_GENERIC_ERROR;
3079
3080 AisBitstring strbit(abuf.data());
3081
3082 // Extract the MMSI
3083 if (!mmsi) mmsi = strbit.GetInt(9, 30);
3084 long mmsi_long = mmsi;
3085
3086 // Ais8_001_31 || ais8_367_33 (class AIS_METEO) test for a new mmsi ID
3087 int origin_mmsi = 0;
3088 int messID = strbit.GetInt(1, 6);
3089 // No need for a message without a valid mess-ID
3090 if (messID < 0 || messID > 63) return AIS_GENERIC_ERROR;
3091
3092 int dac = strbit.GetInt(41, 10);
3093 int fi = strbit.GetInt(51, 6);
3094 if (messID == 8) {
3095 int met_lon, met_lat;
3096 if (dac == 001 && fi == 31) {
3097 origin_mmsi = mmsi;
3098 met_lon = strbit.GetInt(57, 25);
3099 met_lat = strbit.GetInt(82, 24);
3100 mmsi = AisMeteoNewMmsi(mmsi, met_lat, met_lon, 25, 0);
3101 mmsi_long = mmsi;
3102
3103 } else if (dac == 367 && fi == 33) { // ais8_367_33
3104 // Check for a valid message size before further handling
3105 const int size = strbit.GetBitCount();
3106 if (size < 168) return AIS_GENERIC_ERROR;
3107 const int startb = 56;
3108 const int slot_size = 112;
3109 const int extra_bits = (size - startb) % slot_size;
3110 if (extra_bits > 0) return AIS_GENERIC_ERROR;
3111
3112 int mes_type = strbit.GetInt(57, 4);
3113 int site_ID = strbit.GetInt(77, 7);
3114 if (mes_type == 0) { // Location
3115 origin_mmsi = mmsi;
3116 met_lon = strbit.GetInt(90, 28);
3117 met_lat = strbit.GetInt(118, 27);
3118 mmsi = AisMeteoNewMmsi(mmsi, met_lat, met_lon, 28, site_ID);
3119 mmsi_long = mmsi;
3120 } else { // Other messsage types without position.
3121 // We need a previously received type 0, position message
3122 // to get use of any sensor report.
3123 int x_mmsi = AisMeteoNewMmsi(mmsi, 91, 181, 0, site_ID);
3124 if (x_mmsi) {
3125 origin_mmsi = mmsi;
3126 mmsi = x_mmsi;
3127 mmsi_long = mmsi;
3128 } else // So far no use for this report.
3129 return AIS_GENERIC_ERROR;
3130 }
3131 }
3132 }
3133
3134 // Check for own ship mmsi. It's not a valid AIS target.
3135 if (mmsi == g_OwnShipmmsi) return AIS_GENERIC_ERROR;
3136
3137 // Search the current AISTargetList for an MMSI match
3138 auto it = AISTargetList.find(mmsi);
3139 if (it == AISTargetList.end()) // not found
3140 {
3141 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
3142 bnewtarget = true;
3143 m_n_targets++;
3144
3145 if (origin_mmsi) { // New mmsi allocated for a Meteo station
3146 pTargetData->MMSI = mmsi;
3147 pTargetData->met_data.original_mmsi = origin_mmsi;
3148 }
3149 } else {
3150 pTargetData = it->second; // find current entry
3151
3152 if (!bnewtarget)
3153 pStaleTarget = pTargetData; // save a pointer to stale data
3154 if (origin_mmsi) { // Meteo point
3155 pTargetData->MMSI = mmsi;
3156 pTargetData->met_data.original_mmsi = origin_mmsi;
3157 }
3158 }
3159 for (unsigned int i = 0; i < g_MMSI_Props_Array.GetCount(); i++) {
3160 MmsiProperties *props = g_MMSI_Props_Array[i];
3161 if (mmsi == static_cast<unsigned>(props->MMSI)) {
3162 // Check if this target has a dedicated tracktype
3163 if (TRACKTYPE_NEVER == props->TrackType) {
3164 pTargetData->b_show_track = false;
3165 } else if (TRACKTYPE_ALWAYS == props->TrackType) {
3166 pTargetData->b_show_track = true;
3167 }
3168
3169 // Check to see if this MMSI has been configured to be ignored
3170 // completely...
3171 if (props->m_bignore) return AIS_NoError;
3172 // Check to see if this MMSI wants VDM translated to VDO or whether we
3173 // want to persist it's track...
3174 else if (props->m_bVDM) {
3175 // Only single line VDM messages to be translated
3176 if (str.Mid(3, 9).IsSameAs("VDM,1,1,,")) {
3177 int message_ID = strbit.GetInt(1, 6); // Parse on message ID
3178 // Only translate the dynamic positionreport messages (1, 2, 3 or
3179 // 18)
3180 if ((message_ID <= 3) || (message_ID == 18)) {
3181 // set OwnShip to prevent target from being drawn
3182 pTargetData->b_OwnShip = true;
3183 // Rename nmea sentence to AIVDO and calc a new checksum
3184 wxString aivdostr = str;
3185 aivdostr.replace(1, 5, "AIVDO");
3186 unsigned char calculated_checksum = 0;
3187 wxString::iterator j;
3188 for (j = aivdostr.begin() + 1; j != aivdostr.end() && *j != '*';
3189 ++j)
3190 calculated_checksum ^= static_cast<unsigned char>(*j);
3191 // if i is not at least 3 positons befoere end, there is no
3192 // checksum added so also no need to add one now.
3193 if (j <= aivdostr.end() - 3)
3194 aivdostr.replace(
3195 j + 1, j + 3,
3196 wxString::Format(_("%02X"), calculated_checksum));
3197
3198 gps_watchdog_timeout_ticks =
3199 60; // increase watchdog time up to 1 minute
3200 // add the changed sentence into nmea message system
3201 std::string full_sentence = aivdostr.ToStdString();
3202 auto address = std::make_shared<NavAddr0183>("virtual");
3203 // We notify based on full message, including the Talker ID
3204 // Notify message listener
3205 auto msg = std::make_shared<const Nmea0183Msg>(
3206 "AIVDO", full_sentence, address);
3207 NavMsgBus::GetInstance().Notify(std::move(msg));
3208 }
3209 }
3210 return AIS_NoError;
3211 } else
3212 break;
3213 }
3214 }
3215
3216 // Grab the stale targets's last report time
3217 wxDateTime now = wxDateTime::Now();
3218 now.MakeGMT();
3219
3220 if (pStaleTarget)
3221 last_report_ticks = pStaleTarget->PositionReportTicks;
3222 else
3223 last_report_ticks = now.GetTicks();
3224
3225 // Delete the stale AIS Target selectable point
3226 if (pStaleTarget)
3227 pSelectAIS->DeleteSelectablePoint((void *)mmsi_long, SELTYPE_AISTARGET);
3228
3229 if (pTargetData) {
3230 if (gpsg_mmsi) {
3231 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
3232 pTargetData->PositionReportTicks = now.GetTicks();
3233 pTargetData->StaticReportTicks = now.GetTicks();
3234 pTargetData->m_utc_hour = gpsg_utc_hour;
3235 pTargetData->m_utc_min = gpsg_utc_min;
3236 pTargetData->m_utc_sec = gpsg_utc_sec;
3237 pTargetData->m_date_string = gpsg_date;
3238 pTargetData->MMSI = gpsg_mmsi;
3239 pTargetData->NavStatus = 0; // underway
3240 pTargetData->Lat = gpsg_lat;
3241 pTargetData->Lon = gpsg_lon;
3242 pTargetData->b_positionOnceValid = true;
3243 pTargetData->COG = gpsg_cog;
3244 pTargetData->SOG = gpsg_sog;
3245 pTargetData->ShipType = 52; // buddy
3246 pTargetData->Class = AIS_GPSG_BUDDY;
3247 memcpy(pTargetData->ShipName, gpsg_name_str, sizeof(gpsg_name_str));
3248 pTargetData->b_nameValid = true;
3249 pTargetData->b_active = true;
3250 pTargetData->b_lost = false;
3251
3252 bdecode_result = true;
3253 } else if (arpa_mmsi) {
3254 pTargetData->m_utc_hour = arpa_utc_hour;
3255 pTargetData->m_utc_min = arpa_utc_min;
3256 pTargetData->m_utc_sec = arpa_utc_sec;
3257 pTargetData->MMSI = arpa_mmsi;
3258 pTargetData->NavStatus = 15; // undefined
3259 if (str.Mid(3, 3).IsSameAs("TLL")) {
3260 if (!bnewtarget) {
3261 int age_of_last =
3262 (now.GetTicks() - pTargetData->PositionReportTicks);
3263 if (age_of_last > 0) {
3264 ll_gc_ll_reverse(pTargetData->Lat, pTargetData->Lon, arpa_lat,
3265 arpa_lon, &pTargetData->COG, &pTargetData->SOG);
3266 pTargetData->SOG = pTargetData->SOG * 3600 / age_of_last;
3267 }
3268 }
3269 pTargetData->Lat = arpa_lat;
3270 pTargetData->Lon = arpa_lon;
3271 } else if (str.Mid(3, 3).IsSameAs("TTM")) {
3272 if (arpa_dist != 0.) // Not a new or turned off target
3273 ll_gc_ll(gLat, gLon, arpa_brg, arpa_dist, &pTargetData->Lat,
3274 &pTargetData->Lon);
3275 else
3276 arpa_lost = true;
3277 pTargetData->COG = arpa_cog;
3278 pTargetData->SOG = arpa_sog;
3279 }
3280 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
3281 pTargetData->PositionReportTicks = now.GetTicks();
3282 pTargetData->StaticReportTicks = now.GetTicks();
3283 pTargetData->b_positionOnceValid = true;
3284 pTargetData->ShipType = 55; // arpa
3285 pTargetData->Class = AIS_ARPA;
3286
3287 memcpy(pTargetData->ShipName, arpa_name_str, sizeof(arpa_name_str));
3288 if (arpa_status != "Q")
3289 pTargetData->b_nameValid = true;
3290 else
3291 pTargetData->b_nameValid = false;
3292 pTargetData->b_active = !arpa_lost;
3293 pTargetData->b_lost = arpa_nottracked;
3294
3295 bdecode_result = true;
3296 } else if (aprs_mmsi) {
3297 pTargetData->m_utc_hour = now.GetHour();
3298 pTargetData->m_utc_min = now.GetMinute();
3299 pTargetData->m_utc_sec = now.GetSecond();
3300 pTargetData->MMSI = aprs_mmsi;
3301 pTargetData->NavStatus = 15; // undefined
3302 if (!bnewtarget) {
3303 int age_of_last = (now.GetTicks() - pTargetData->PositionReportTicks);
3304 if (age_of_last > 0) {
3305 ll_gc_ll_reverse(pTargetData->Lat, pTargetData->Lon, aprs_lat,
3306 aprs_lon, &pTargetData->COG, &pTargetData->SOG);
3307 pTargetData->SOG = pTargetData->SOG * 3600 / age_of_last;
3308 }
3309 }
3310 pTargetData->LastPositionReportTicks = pTargetData->PositionReportTicks;
3311 pTargetData->PositionReportTicks = now.GetTicks();
3312 pTargetData->StaticReportTicks = now.GetTicks();
3313 pTargetData->Lat = aprs_lat;
3314 pTargetData->Lon = aprs_lon;
3315 pTargetData->b_positionOnceValid = true;
3316 pTargetData->ShipType = 56; // aprs
3317 pTargetData->Class = AIS_APRS;
3318 memcpy(pTargetData->ShipName, aprs_name_str, sizeof(aprs_name_str));
3319 pTargetData->b_nameValid = true;
3320 pTargetData->b_active = true;
3321 pTargetData->b_lost = false;
3322
3323 bdecode_result = true;
3324 } else {
3325 // The normal Plain-Old AIS target code path....
3326 bdecode_result =
3327 Parse_VDXBitstring(&strbit, pTargetData); // Parse the new data
3328 }
3329
3330 // Catch mmsi properties like track, persistent track, follower.
3331 getMmsiProperties(pTargetData);
3332
3333 // Update the most recent report period
3334 pTargetData->RecentPeriod =
3335 pTargetData->PositionReportTicks - last_report_ticks;
3336 }
3337 ret = AIS_NoError;
3338 } else {
3339 ret = AIS_Partial; // accumulating parts of a multi-sentence message
3340 pTargetData = nullptr;
3341 }
3342
3343 if (pTargetData) {
3344 // pTargetData is valid, either new or existing. Commit to GUI
3345 CommitAISTarget(pTargetData, str, bdecode_result, bnewtarget);
3346 }
3347
3348 n_msgs++;
3349#ifdef AIS_DEBUG
3350 if ((n_msgs % 10000) == 0)
3351 printf("n_msgs %10d m_n_targets: %6d n_msg1: %10d n_msg5+24: %10d \n",
3352 n_msgs, m_n_targets, n_msg1, n_msg5 + n_msg24);
3353#endif
3354
3355 return ret;
3356}
3357
3358void AisDecoder::CommitAISTarget(
3359 const std::shared_ptr<AisTargetData> &pTargetData, const wxString &str,
3360 bool message_valid, bool new_target) {
3361 m_pLatestTargetData = pTargetData;
3362
3363 if (!str.IsEmpty()) { // NMEA0183 message
3364 if (str.Mid(3, 3).IsSameAs("VDO"))
3365 pTargetData->b_OwnShip = true;
3366 else
3367 pTargetData->b_OwnShip = false;
3368 }
3369
3370 if (!pTargetData->b_OwnShip) {
3371 // set mmsi-props to default values
3372 if (0 == m_persistent_tracks.count(pTargetData->MMSI)) {
3373 // Normal target
3374 pTargetData->b_PersistTrack = false;
3375 // Or first decode for this target
3376 for (unsigned int i = 0; i < g_MMSI_Props_Array.GetCount(); i++) {
3377 if (pTargetData->MMSI == g_MMSI_Props_Array[i]->MMSI) {
3378 MmsiProperties *props = g_MMSI_Props_Array[i];
3379 pTargetData->b_mPropPersistTrack = props->m_bPersistentTrack;
3380 break;
3381 }
3382 }
3383 } else {
3384 // The track persistency enabled in the query window or mmsi-props
3385 }
3386 pTargetData->b_NoTrack = false;
3387 }
3388
3389 // If the message was decoded correctly
3390 // Update the AIS Target information
3391 if (message_valid) {
3392 // Print to name cache only if not mmsi = 0
3393 if (pTargetData->MMSI) {
3394 AISshipNameCache(pTargetData.get(), AISTargetNamesC, AISTargetNamesNC,
3395 pTargetData->MMSI);
3396 }
3397 AISTargetList[pTargetData->MMSI] =
3398 pTargetData; // update the hash table entry
3399
3400 if (!pTargetData->area_notices.empty()) {
3401 auto it = AIS_AreaNotice_Sources.find(pTargetData->MMSI);
3402 if (it == AIS_AreaNotice_Sources.end())
3403 AIS_AreaNotice_Sources[pTargetData->MMSI] = pTargetData;
3404 }
3405
3406 // If this is not an ownship message, update the AIS Target in the
3407 // Selectable list, and update the CPA info
3408 if (!pTargetData->b_OwnShip) {
3409 if (pTargetData->b_positionOnceValid) {
3410 long mmsi_long = pTargetData->MMSI;
3411 SelectItem *pSel = pSelectAIS->AddSelectablePoint(
3412 pTargetData->Lat, pTargetData->Lon, (void *)mmsi_long,
3413 SELTYPE_AISTARGET);
3414 pSel->SetUserData(pTargetData->MMSI);
3415 }
3416
3417 // Calculate CPA info for this target immediately
3418 UpdateOneCPA(pTargetData.get());
3419
3420 // Update this target's track
3421 if (pTargetData->b_show_track) UpdateOneTrack(pTargetData.get());
3422 }
3423 // TODO add ais message call
3424 plugin_msg_evt.Notify(std::make_shared<AisTargetData>(*pTargetData), "");
3425 } else {
3426 // printf("Unrecognised AIS message ID: %d\n",
3427 // pTargetData->MID);
3428 if (new_target) {
3429 // delete pTargetData; // this target is not going to be used
3430 m_n_targets--;
3431 } else {
3432 // If this is not an ownship message, update the AIS Target in the
3433 // Selectable list even if the message type was not recognized
3434 if (!pTargetData->b_OwnShip) {
3435 if (pTargetData->b_positionOnceValid) {
3436 long mmsi_long = pTargetData->MMSI;
3437 SelectItem *pSel = pSelectAIS->AddSelectablePoint(
3438 pTargetData->Lat, pTargetData->Lon, (void *)mmsi_long,
3439 SELTYPE_AISTARGET);
3440 pSel->SetUserData(pTargetData->MMSI);
3441 }
3442 }
3443 }
3444 }
3445}
3446
3447void AisDecoder::getAISTarget(long mmsi,
3448 std::shared_ptr<AisTargetData> &pTargetData,
3449 std::shared_ptr<AisTargetData> &pStaleTarget,
3450 bool &bnewtarget, int &last_report_ticks,
3451 wxDateTime &now) {
3452 now = wxDateTime::Now();
3453 auto it = AISTargetList.find(mmsi);
3454 if (it == AISTargetList.end()) // not found
3455 {
3456 pTargetData = AisTargetDataMaker::GetInstance().GetTargetData();
3457 bnewtarget = true;
3458 m_n_targets++;
3459 } else {
3460 pTargetData = it->second; // find current entry
3461 pStaleTarget = pTargetData; // save a pointer to stale data
3462 }
3463
3464 // Grab the stale targets's last report time
3465 now.MakeGMT();
3466
3467 if (pStaleTarget)
3468 last_report_ticks = pStaleTarget->PositionReportTicks;
3469 else
3470 last_report_ticks = now.GetTicks();
3471
3472 // Delete the stale AIS Target selectable point
3473 if (pStaleTarget)
3474 pSelectAIS->DeleteSelectablePoint((void *)mmsi, SELTYPE_AISTARGET);
3475}
3476
3477std::shared_ptr<AisTargetData> AisDecoder::ProcessDSx(const wxString &str,
3478 bool b_take_dsc) {
3479 double dsc_lat = 0.;
3480 double dsc_lon = 0.;
3481 double dsc_mins, dsc_degs, dsc_tmp, dsc_addr;
3482 double dse_tmp;
3483 double dse_lat = 0.;
3484 double dse_lon = 0.;
3485 long dsc_fmt, dsc_quadrant, dsc_cat, dsc_nature;
3486
3487 int dsc_mmsi = 0;
3488 int dsc_tx_mmsi = 0;
3489 int dse_mmsi = 0;
3490 double dse_cog = 0.;
3491 double dse_sog = 0.;
3492 wxString dse_shipName = "";
3493 wxString dseSymbol;
3494
3495 unsigned mmsi = 0;
3496
3497 std::shared_ptr<AisTargetData> pTargetData = nullptr;
3498
3499 // parse a DSC Position message $CDDSx,.....
3500 // Use a tokenizer to pull out the first 9 fields
3501 wxStringTokenizer tkz(str, ",*");
3502
3503 wxString token;
3504 token = tkz.GetNextToken(); // !$CDDS
3505
3506 if (str.Mid(3, 3).IsSameAs("DSC")) {
3507 m_dsc_last_string = str;
3508
3509 token = tkz.GetNextToken(); // format specifier
3510 token.ToLong(
3511 &dsc_fmt); // (02-area,12-distress,16-allships,20-individual,...)
3512
3513 token = tkz.GetNextToken(); // address i.e. mmsi*10 for received msg, or
3514 // area spec or sender mmsi for (12) and (16)
3515 if (dsc_fmt == 12 || dsc_fmt == 16) {
3516 dsc_mmsi = wxAtoi(token.Mid(0, 9));
3517 } else {
3518 token.ToDouble(&dsc_addr);
3519 dsc_mmsi = 0 - (int)(dsc_addr / 10); // as per NMEA 0183 3.01
3520 }
3521
3522 token = tkz.GetNextToken(); // category
3523 token.ToLong(&dsc_cat); // 12 - Distress (relayed)
3524
3525 token = tkz.GetNextToken(); // nature of distress or telecommand1
3526 if (!token.IsSameAs("")) { // 00-12 = nature of distress
3527 token.ToLong(&dsc_nature);
3528 } else
3529 dsc_nature = 99;
3530
3531 token = tkz.GetNextToken(); // comm type or telecommand2
3532
3533 token = tkz.GetNextToken(); // position or channel/freq
3534 token.ToDouble(&dsc_tmp);
3535
3536 token = tkz.GetNextToken(); // time or tel. no.
3537 token = tkz.GetNextToken(); // mmsi of ship in distress, relay
3538 if (dsc_fmt == 16 && dsc_cat == 12 && !token.IsSameAs("")) {
3539 // wxString dmmsi = token.Mid(0,9);
3540 dsc_tx_mmsi = dsc_mmsi; // mmsi of relay issuer
3541 dsc_mmsi = wxAtoi(token.Mid(0, 9));
3542 }
3543 token = tkz.GetNextToken(); // nature of distress, relay
3544 if (dsc_fmt == 16 && dsc_cat == 12) {
3545 if (!token.IsSameAs("")) { // 00-12 = nature of distress
3546 token.ToLong(&dsc_nature);
3547 } else
3548 dsc_nature = 99;
3549 }
3550 token = tkz.GetNextToken(); // acknowledgement
3551 token = tkz.GetNextToken(); // expansion indicator
3552
3553 dsc_quadrant = (int)(dsc_tmp / 1000000000.0);
3554
3555 if (dsc_quadrant > 3) // Position is "Unspecified", or 9999999999
3556 return nullptr;
3557
3558 dsc_lat = (int)(dsc_tmp / 100000.0);
3559 dsc_lon = dsc_tmp - dsc_lat * 100000.0;
3560 dsc_lat = dsc_lat - dsc_quadrant * 10000;
3561 dsc_degs = (int)(dsc_lat / 100.0);
3562 dsc_mins = dsc_lat - dsc_degs * 100.0;
3563 dsc_lat = dsc_degs + dsc_mins / 60.0;
3564
3565 dsc_degs = (int)(dsc_lon / 100.0);
3566 dsc_mins = dsc_lon - dsc_degs * 100.0;
3567 dsc_lon = dsc_degs + dsc_mins / 60.0;
3568 switch (dsc_quadrant) {
3569 case 0:
3570 break; // NE
3571 case 1:
3572 dsc_lon = -dsc_lon;
3573 break; // NW
3574 case 2:
3575 dsc_lat = -dsc_lat;
3576 break; // SE
3577 case 3:
3578 dsc_lon = -dsc_lon;
3579 dsc_lat = -dsc_lat;
3580 break; // SW
3581 default:
3582 break;
3583 }
3584 if (dsc_fmt != 02) mmsi = (int)dsc_mmsi;
3585
3586 } else if (str.Mid(3, 3).IsSameAs("DSE")) {
3587 token = tkz.GetNextToken(); // total number of sentences
3588 token = tkz.GetNextToken(); // sentence number
3589 token = tkz.GetNextToken(); // query/rely flag
3590 token = tkz.GetNextToken(); // vessel MMSI
3591 dse_mmsi = wxAtoi(token.Mid(
3592 0, 9)); // ITU-R M.493-10 �5.2
3593 // token.ToDouble(&dse_addr);
3594 // 0 - (int)(dse_addr / 10); // as per NMEA 0183 3.01
3595
3596#if 0
3597 token = tkz.GetNextToken(); // code field
3598 token =
3599 tkz.GetNextToken(); // data field - position - 2*4 digits latlon .mins
3600 token.ToDouble(&dse_tmp);
3601 dse_lat = (int)(dse_tmp / 10000.0);
3602 dse_lon = (int)(dse_tmp - dse_lat * 10000.0);
3603 dse_lat = dse_lat / 600000.0;
3604 dse_lon = dse_lon / 600000.0;
3605#endif
3606 // DSE Sentence may contain multiple dse expansion data items
3607 while (tkz.HasMoreTokens()) {
3608 dseSymbol = tkz.GetNextToken(); // dse expansion data symbol
3609 token = tkz.GetNextToken(); // dse expansion data
3610 if (dseSymbol.IsSameAs("00")) { // Position
3611 token.ToDouble(&dse_tmp);
3612 dse_lat = (int)(dse_tmp / 10000.0);
3613 dse_lon = (int)(dse_tmp - dse_lat * 10000.0);
3614 dse_lat = dse_lat / 600000.0;
3615 dse_lon = dse_lon / 600000.0;
3616 } else if (dseSymbol.IsSameAs("01")) { // Source & Datum
3617 } else if (dseSymbol.IsSameAs("02")) { // SOG
3618 token.ToDouble(&dse_tmp);
3619 dse_sog = dse_tmp / 10.0;
3620 } else if (dseSymbol.IsSameAs("03")) { // COG
3621 token.ToDouble(&dse_tmp);
3622 dse_cog = dse_tmp / 10.0;
3623 } else if (dseSymbol.IsSameAs("04")) { // Station Information
3624 dse_shipName = DecodeDSEExpansionCharacters(token);
3625 } else if (dseSymbol.IsSameAs("05")) { // Geographic Information
3626 } else if (dseSymbol.IsSameAs("06")) { // Persons On Board
3627 }
3628 }
3629 mmsi = abs((int)dse_mmsi);
3630 }
3631
3632 // Get the last report time for this target, if it exists
3633 wxDateTime now = wxDateTime::Now();
3634 now.MakeGMT();
3635 int last_report_ticks = now.GetTicks();
3636
3637 // Search the current AISTargetList for an MMSI match
3638 auto it = AISTargetList.find(mmsi);
3639 std::shared_ptr<AisTargetData> pStaleTarget = nullptr;
3640 if (it == AISTargetList.end()) { // not found
3641 } else {
3642 pStaleTarget = it->second; // find current entry
3643 last_report_ticks = pStaleTarget->PositionReportTicks;
3644 }
3645
3646 if (dsc_mmsi) {
3647 // Create a tentative target, but do not post it pending receipt of
3648 // extended data
3649 m_ptentative_dsctarget = AisTargetDataMaker::GetInstance().GetTargetData();
3650
3651 m_ptentative_dsctarget->PositionReportTicks = now.GetTicks();
3652 m_ptentative_dsctarget->StaticReportTicks = now.GetTicks();
3653
3654 m_ptentative_dsctarget->MMSI = mmsi;
3655 m_ptentative_dsctarget->NavStatus =
3656 99; // Undefind. "-" in the AIS target list
3657 m_ptentative_dsctarget->Lat = dsc_lat;
3658 m_ptentative_dsctarget->Lon = dsc_lon;
3659 m_ptentative_dsctarget->b_positionOnceValid = true;
3660 m_ptentative_dsctarget->COG = 0;
3661 m_ptentative_dsctarget->SOG = 0;
3662 m_ptentative_dsctarget->ShipType = dsc_fmt;
3663 m_ptentative_dsctarget->Class = AIS_DSC;
3664 m_ptentative_dsctarget->b_isDSCtarget = true;
3665 m_ptentative_dsctarget->b_nameValid = true;
3666 if (dsc_fmt == 12 || (dsc_fmt == 16 && dsc_cat == 12)) {
3667 snprintf(m_ptentative_dsctarget->ShipName, SHIP_NAME_LEN, "DISTRESS %u",
3668 mmsi);
3669 m_ptentative_dsctarget->m_dscNature = int(dsc_nature);
3670 m_ptentative_dsctarget->m_dscTXmmsi = dsc_tx_mmsi;
3671 } else {
3672 snprintf(m_ptentative_dsctarget->ShipName, SHIP_NAME_LEN, "POSITION %u",
3673 mmsi);
3674 }
3675
3676 m_ptentative_dsctarget->b_active = true;
3677 m_ptentative_dsctarget->b_lost = false;
3678 m_ptentative_dsctarget->RecentPeriod =
3679 m_ptentative_dsctarget->PositionReportTicks - last_report_ticks;
3680
3681 // Start a timer, looking for an expected DSE extension message
3682 if (!b_take_dsc) m_dsc_timer.Start(1000, wxTIMER_ONE_SHOT);
3683 }
3684
3685 // Got an extension message, or the timer expired and no extension is
3686 // expected
3687 if (dse_mmsi || b_take_dsc) {
3688 if (m_ptentative_dsctarget) {
3689 // stop the timer for sure
3690 m_dsc_timer.Stop();
3691
3692 // Update the extended information
3693 if (dse_mmsi) {
3694 m_ptentative_dsctarget->Lat =
3695 m_ptentative_dsctarget->Lat +
3696 ((m_ptentative_dsctarget->Lat) >= 0 ? dse_lat : -dse_lat);
3697 m_ptentative_dsctarget->Lon =
3698 m_ptentative_dsctarget->Lon +
3699 ((m_ptentative_dsctarget->Lon) >= 0 ? dse_lon : -dse_lon);
3700 if (!dse_shipName.empty()) {
3701 memset(m_ptentative_dsctarget->ShipName, '\0', SHIP_NAME_LEN);
3702 snprintf(m_ptentative_dsctarget->ShipName, SHIP_NAME_LEN, "%s",
3703 dse_shipName.ToAscii().data());
3704 }
3705 m_ptentative_dsctarget->COG = dse_cog;
3706 m_ptentative_dsctarget->SOG = dse_sog;
3707 }
3708
3709 // Update the most recent report period
3710 m_ptentative_dsctarget->RecentPeriod =
3711 m_ptentative_dsctarget->PositionReportTicks - last_report_ticks;
3712
3713 // And post the target
3714
3715 // Search the current AISTargetList for an MMSI match
3716 auto found = AISTargetList.find(mmsi);
3717 if (found == AISTargetList.end()) { // not found
3718 pTargetData = m_ptentative_dsctarget;
3719 } else {
3720 pTargetData = found->second; // find current entry
3721 std::vector<AISTargetTrackPoint> ptrack =
3722 std::move(pTargetData->m_ptrack);
3723 pTargetData->CloneFrom(
3724 m_ptentative_dsctarget
3725 .get()); // this will make an empty track list
3726
3727 pTargetData->m_ptrack =
3728 std::move(ptrack); // and substitute the old track list
3729
3730 // delete m_ptentative_dsctarget;
3731 }
3732
3733 // Reset for next time
3734 m_ptentative_dsctarget = nullptr;
3735
3736 m_pLatestTargetData = pTargetData;
3737
3738 AISTargetList[pTargetData->MMSI] =
3739 pTargetData; // update the hash table entry
3740
3741 long mmsi_long = pTargetData->MMSI;
3742
3743 // Delete any stale Target selectable point
3744 if (pStaleTarget)
3745 pSelectAIS->DeleteSelectablePoint((void *)mmsi_long, SELTYPE_AISTARGET);
3746 // And add the updated target
3747 SelectItem *pSel =
3748 pSelectAIS->AddSelectablePoint(pTargetData->Lat, pTargetData->Lon,
3749 (void *)mmsi_long, SELTYPE_AISTARGET);
3750 pSel->SetUserData(pTargetData->MMSI);
3751
3752 // Calculate CPA info for this target immediately
3753 UpdateOneCPA(pTargetData.get());
3754
3755 // Update this target's track
3756 if (pTargetData->b_show_track) UpdateOneTrack(pTargetData.get());
3757 }
3758 }
3759
3760 return pTargetData;
3761}
3762
3763bool AisDecoder::NMEACheckSumOK(const wxString &str_in) {
3764 unsigned char checksum_value = 0;
3765 int sentence_hex_sum;
3766
3767 wxCharBuffer buf = str_in.ToUTF8();
3768 if (!buf.data()) return false; // cannot decode string
3769
3770 char str_ascii[AIS_MAX_MESSAGE_LEN + 1];
3771 strncpy(str_ascii, buf.data(), AIS_MAX_MESSAGE_LEN);
3772 str_ascii[AIS_MAX_MESSAGE_LEN] = '\0';
3773
3774 int string_length = strlen(str_ascii);
3775
3776 int payload_length = 0;
3777 while ((payload_length < string_length) &&
3778 (str_ascii[payload_length] != '*')) // look for '*'
3779 payload_length++;
3780
3781 if (payload_length == string_length)
3782 return false; // '*' not found at all, no checksum
3783
3784 int index = 1; // Skip over the $ at the begining of the sentence
3785
3786 while (index < payload_length) {
3787 checksum_value ^= str_ascii[index];
3788 index++;
3789 }
3790
3791 if (string_length > 4) {
3792 char scanstr[3];
3793 scanstr[0] = str_ascii[payload_length + 1];
3794 scanstr[1] = str_ascii[payload_length + 2];
3795 scanstr[2] = 0;
3796 sscanf(scanstr, "%2x", &sentence_hex_sum);
3797
3798 if (sentence_hex_sum == checksum_value) return true;
3799 }
3800
3801 return false;
3802}
3803
3804void AisDecoder::UpdateAllCPA() {
3805 // Iterate thru all the targets
3806 for (const auto &it : GetTargetList()) {
3807 std::shared_ptr<AisTargetData> td = it.second;
3808
3809 if (nullptr != td) UpdateOneCPA(td.get());
3810 }
3811}
3812
3813void AisDecoder::UpdateAllTracks() {
3814 for (const auto &it : GetTargetList()) {
3815 std::shared_ptr<AisTargetData> td = it.second;
3816 if (td) UpdateOneTrack(td.get());
3817 }
3818}
3819
3820int gdup;
3821void AisDecoder::UpdateOneTrack(AisTargetData *ptarget) {
3822 if (!ptarget->b_positionOnceValid) return;
3823 // Reject for unbelievable jumps (corrupted/bad data)
3824 if (!ptarget->m_ptrack.empty()) {
3825 const AISTargetTrackPoint &LastTrackpoint = ptarget->m_ptrack.back();
3826 if (fabs(LastTrackpoint.m_lat - ptarget->Lat) > .1 ||
3827 fabs(LastTrackpoint.m_lon - ptarget->Lon) > .1) {
3828 // after an unlikely jump in pos, the last trackpoint might also be wrong
3829 // just to be sure we do delete this one as well.
3830 ptarget->m_ptrack.pop_back();
3831 ptarget->b_positionDoubtful = true;
3832 return;
3833 }
3834 }
3835
3836 // Avoid duplicate track points
3837 // Do not add track point if time since last point is < 2 seconds.
3838 if ((ptarget->PositionReportTicks - ptarget->LastPositionReportTicks) > 2) {
3839 // Create the newest point
3840 AISTargetTrackPoint ptrackpoint;
3841 ptrackpoint.m_lat = ptarget->Lat;
3842 ptrackpoint.m_lon = ptarget->Lon;
3843 ptrackpoint.m_time = wxDateTime::Now().GetTicks();
3844
3845 ptarget->m_ptrack.push_back(ptrackpoint);
3846
3847 if (ptarget->b_PersistTrack || ptarget->b_mPropPersistTrack) {
3848 Track *t;
3849 if (0 == m_persistent_tracks.count(ptarget->MMSI)) {
3850 t = new Track();
3851 t->SetName(wxString::Format(
3852 "AIS %s (%u) %s %s", ptarget->GetFullName().c_str(), ptarget->MMSI,
3853 wxDateTime::Now().FormatISODate().c_str(),
3854 wxDateTime::Now().FormatISOTime().c_str()));
3855 g_TrackList.push_back(t);
3856 new_track.Notify(t);
3857 m_persistent_tracks[ptarget->MMSI] = t;
3858 } else {
3859 t = m_persistent_tracks[ptarget->MMSI];
3860 }
3861 TrackPoint *tp = t->GetLastPoint();
3862 vector2D point(ptrackpoint.m_lon, ptrackpoint.m_lat);
3863 TrackPoint *tp1 =
3864 t->AddNewPoint(point, wxDateTime(ptrackpoint.m_time).ToUTC());
3865
3866 if (tp)
3867 pSelect->AddSelectableTrackSegment(tp->m_lat, tp->m_lon, tp1->m_lat,
3868 tp1->m_lon, tp, tp1, t);
3869
3870 // We do not want dependency on the GUI here, do we?
3871 // if( pRouteManagerDialog && pRouteManagerDialog->IsShown() )
3872 // pRouteManagerDialog->UpdateTrkListCtrl();
3873
3874 } else {
3875 // Walk the list, removing any track points that are older than the
3876 // stipulated time
3877 time_t test_time =
3878 wxDateTime::Now().GetTicks() - (time_t)(g_AISShowTracks_Mins * 60);
3879
3880 ptarget->m_ptrack.erase(
3881 std::remove_if(ptarget->m_ptrack.begin(), ptarget->m_ptrack.end(),
3882 [=](const AISTargetTrackPoint &track) {
3883 return track.m_time < test_time;
3884 }),
3885 ptarget->m_ptrack.end());
3886 }
3887 }
3888}
3889
3890void AisDecoder::DeletePersistentTrack(const Track *track) {
3891 for (auto it = m_persistent_tracks.begin(); it != m_persistent_tracks.end();
3892 it++) {
3893 if (it->second == track) {
3894 unsigned mmsi = it->first;
3895 m_persistent_tracks.erase(it);
3896 // Last tracks for this target?
3897 if (0 == m_persistent_tracks.count(mmsi)) {
3898 for (unsigned int i = 0; i < g_MMSI_Props_Array.GetCount(); i++) {
3899 if (mmsi == static_cast<unsigned>(g_MMSI_Props_Array[i]->MMSI)) {
3900 MmsiProperties *props = g_MMSI_Props_Array[i];
3901 if (props->m_bPersistentTrack) {
3902 // Ask if mmsi props should be changed.
3903 // Avoid creation of a new track while messaging
3904
3905 std::shared_ptr<AisTargetData> td =
3906 Get_Target_Data_From_MMSI(mmsi);
3907 if (td) {
3908 props->m_bPersistentTrack = false;
3909 td->b_mPropPersistTrack = false;
3910 }
3911 if (!m_callbacks.confirm_stop_track()) {
3912 props->m_bPersistentTrack = true;
3913 }
3914 }
3915 break;
3916 }
3917 }
3918 }
3919 break;
3920 }
3921 }
3922}
3923
3924void AisDecoder::UpdateAllAlarms() {
3925 m_bGeneralAlert = false; // no alerts yet
3926
3927 // Iterate thru all the targets
3928 for (const auto &it : GetTargetList()) {
3929 std::shared_ptr<AisTargetData> td = it.second;
3930
3931 if (td) {
3932 // Maintain General Alert
3933 if (!m_bGeneralAlert) {
3934 // Quick check on basic condition
3935 if ((td->CPA < g_CPAWarn_NM) && (td->TCPA > 0) &&
3936 (td->Class != AIS_ATON) && (td->Class != AIS_BASE))
3937 m_bGeneralAlert = true;
3938
3939 // Some options can suppress general alerts
3940 if (g_bAIS_CPA_Alert_Suppress_Moored && (td->SOG <= g_ShowMoored_Kts))
3941 m_bGeneralAlert = false;
3942
3943 // Skip distant targets if requested
3944 if ((g_bCPAMax) && (td->Range_NM > g_CPAMax_NM))
3945 m_bGeneralAlert = false;
3946
3947 // Skip if TCPA is too long
3948 if ((g_bTCPA_Max) && (td->TCPA > g_TCPA_Max)) m_bGeneralAlert = false;
3949
3950 // SART targets always alert if "Active"
3951 if (td->Class == AIS_SART && td->NavStatus == 14)
3952 m_bGeneralAlert = true;
3953
3954 // DSC Distress targets always alert
3955 if ((td->Class == AIS_DSC) &&
3956 ((td->ShipType == 12) || (td->ShipType == 16)))
3957 m_bGeneralAlert = true;
3958 }
3959
3960 ais_alert_type this_alarm = AIS_NO_ALERT;
3961
3962 // SART targets always alert if "Active"
3963 if (td->Class == AIS_SART && td->NavStatus == 14)
3964 this_alarm = AIS_ALERT_SET;
3965
3966 // DSC Distress targets always alert
3967 if ((td->Class == AIS_DSC) &&
3968 ((td->ShipType == 12) || (td->ShipType == 16)))
3969 this_alarm = AIS_ALERT_SET;
3970
3971 if (g_bCPAWarn && td->b_active && td->b_positionOnceValid &&
3972 (td->Class != AIS_SART) && (td->Class != AIS_DSC)) {
3973 // Skip anchored/moored(interpreted as low speed) targets if
3974 // requested
3975 if ((g_bHideMoored) && (td->SOG <= g_ShowMoored_Kts)) { // dsr
3976 td->n_alert_state = AIS_NO_ALERT;
3977 continue;
3978 }
3979
3980 // No Alert on moored(interpreted as low speed) targets if so
3981 // requested
3982 if (g_bAIS_CPA_Alert_Suppress_Moored &&
3983 (td->SOG <= g_ShowMoored_Kts)) { // dsr
3984 td->n_alert_state = AIS_NO_ALERT;
3985 continue;
3986 }
3987
3988 // Skip distant targets if requested
3989 if (g_bCPAMax) {
3990 if (td->Range_NM > g_CPAMax_NM) {
3991 td->n_alert_state = AIS_NO_ALERT;
3992 continue;
3993 }
3994 }
3995
3996 if ((td->CPA < g_CPAWarn_NM) && (td->TCPA > 0) &&
3997 (td->Class != AIS_ATON) && (td->Class != AIS_BASE) &&
3998 (td->Class != AIS_METEO)) {
3999 if (g_bTCPA_Max) {
4000 if (td->TCPA < g_TCPA_Max) {
4001 if (td->b_isFollower)
4002 this_alarm = AIS_ALERT_NO_DIALOG_SET;
4003 else
4004 this_alarm = AIS_ALERT_SET;
4005 }
4006 } else {
4007 if (td->b_isFollower)
4008 this_alarm = AIS_ALERT_NO_DIALOG_SET;
4009 else
4010 this_alarm = AIS_ALERT_SET;
4011 }
4012 }
4013 }
4014
4015 // Maintain the timer for in_ack flag
4016 // SART and DSC targets always maintain ack timeout
4017 if (td->Class == AIS_SART) {
4018 if (td->b_in_ack_timeout) {
4019 wxTimeSpan delta = wxDateTime::Now() - td->m_ack_time;
4020 // SART Alert obeys fixed 10 minute ACK-TO.
4021 if (delta.GetMinutes() >= 10) td->b_in_ack_timeout = false;
4022 }
4023 } else if (g_bAIS_ACK_Timeout ||
4024 ((td->Class == AIS_DSC) &&
4025 ((td->ShipType == 12) || (td->ShipType == 16)))) {
4026 if (td->b_in_ack_timeout) {
4027 wxTimeSpan delta = wxDateTime::Now() - td->m_ack_time;
4028 if (delta.GetMinutes() > g_AckTimeout_Mins)
4029 td->b_in_ack_timeout = false;
4030 }
4031 } else {
4032 // Not using ack timeouts.
4033 // If a target has been acknowledged, leave it ack'ed until it goes out
4034 // of AIS_ALARM_SET state
4035 if (td->b_in_ack_timeout) {
4036 if (this_alarm == AIS_NO_ALERT) td->b_in_ack_timeout = false;
4037 }
4038 }
4039
4040 td->n_alert_state = this_alarm;
4041 }
4042 }
4043}
4044
4045void AisDecoder::UpdateOneCPA(AisTargetData *ptarget) {
4046 ptarget->Range_NM = -1.; // Defaults
4047 ptarget->Brg = -1.;
4048
4049 // Ideally, project the target by the time difference between its report and
4050 // the own-ship position. The own-ship position timestamp is not available
4051 // here, so assume own-ship is current and project the target to now.
4052 ptarget->Lat_projected = ptarget->Lat;
4053 ptarget->Lon_projected = ptarget->Lon;
4054 if (ptarget->PositionReportTicks > 0 && ptarget->SOG > 0.0 &&
4055 ptarget->SOG < 102.2 && ptarget->COG >= 0.0 && ptarget->COG < 360.0) {
4056 wxDateTime now = wxDateTime::Now();
4057 now.MakeGMT();
4058 const time_t report_age = now.GetTicks() - ptarget->PositionReportTicks;
4059 if (report_age > 0) {
4060 ll_gc_ll(ptarget->Lat, ptarget->Lon, ptarget->COG,
4061 ptarget->SOG * (report_age / 3600.0), &ptarget->Lat_projected,
4062 &ptarget->Lon_projected);
4063 }
4064 }
4065
4066 // Compute the current Range/Brg to the target
4067 // This should always be possible even if GPS data is not valid
4068 // because O must always have a position for own-ship. Plugins need
4069 // AIS target range and bearing from own-ship position even if GPS is not
4070 // valid.
4071 double brg, dist;
4072 DistanceBearingMercator(ptarget->Lat_projected, ptarget->Lon_projected, gLat,
4073 gLon, &brg, &dist);
4074 ptarget->Range_NM = dist;
4075 ptarget->Brg = brg;
4076
4077 if (dist <= 1e-5) ptarget->Brg = -1.0; // Brg is undefined if Range == 0.
4078
4079 if (!ptarget->b_positionOnceValid || !bGPSValid) {
4080 ptarget->bCPA_Valid = false;
4081 return;
4082 }
4083 // Ais Meteo is not a hard target in danger for collision
4084 if (ptarget->Class == AIS_METEO) {
4085 ptarget->bCPA_Valid = false;
4086 return;
4087 }
4088
4089 // There can be no collision between ownship and itself....
4090 // This can happen if AIVDO messages are received, and there is another
4091 // source of ownship position, like NMEA GLL The two positions are always
4092 // temporally out of sync, and one will always be exactly in front of the
4093 // other one.
4094 if (ptarget->b_OwnShip) {
4095 ptarget->CPA = 100;
4096 ptarget->TCPA = -100;
4097 ptarget->bCPA_Valid = false;
4098 return;
4099 }
4100
4101 double cpa_calc_ownship_cog = gCog;
4102 double cpa_calc_target_cog = ptarget->COG;
4103
4104 // Ownship is not reporting valid SOG, so no way to calculate CPA
4105 if (std::isnan(gSog) || (gSog > 102.2)) {
4106 ptarget->bCPA_Valid = false;
4107 return;
4108 }
4109
4110 // Ownship is maybe anchored and not reporting COG
4111 if (std::isnan(gCog) || gCog == 360.0) {
4112 if (gSog < .01)
4113 cpa_calc_ownship_cog =
4114 0.; // substitute value
4115 // for the case where SOG ~= 0, and COG is unknown.
4116 else {
4117 ptarget->bCPA_Valid = false;
4118 return;
4119 }
4120 }
4121
4122 // Target is maybe anchored and not reporting COG
4123 if (ptarget->COG == 360.0) {
4124 if (ptarget->SOG > 102.2) {
4125 ptarget->bCPA_Valid = false;
4126 return;
4127 } else if (ptarget->SOG < .01) {
4128 cpa_calc_target_cog = 0.; // substitute value
4129 // for the case where SOG ~= 0, and COG is unknown.
4130 } else {
4131 ptarget->bCPA_Valid = false;
4132 return;
4133 }
4134 }
4135
4136 // Express the SOGs as meters per hour
4137 double v0 = gSog * 1852.;
4138 double v1 = ptarget->SOG * 1852.;
4139
4140 if ((v0 < 1e-6) && (v1 < 1e-6)) {
4141 ptarget->TCPA = 0.;
4142 ptarget->CPA = 0.;
4143
4144 ptarget->bCPA_Valid = false;
4145 } else {
4146 // Calculate the TCPA first
4147
4148 // Working on a Reduced Lat/Lon orthogonal plotting sheet....
4149 // Get easting/northing to target, in meters
4150
4151 double east1 = (ptarget->Lon_projected - gLon) * 60 * 1852;
4152 double north1 = (ptarget->Lat_projected - gLat) * 60 * 1852;
4153
4154 double east = east1 * (cos(gLat * PI / 180.));
4155
4156 double north = north1;
4157
4158 // Convert COGs trigonometry to standard unit circle
4159 double cosa = cos((90. - cpa_calc_ownship_cog) * PI / 180.);
4160 double sina = sin((90. - cpa_calc_ownship_cog) * PI / 180.);
4161 double cosb = cos((90. - cpa_calc_target_cog) * PI / 180.);
4162 double sinb = sin((90. - cpa_calc_target_cog) * PI / 180.);
4163
4164 // These will be useful
4165 double fc = (v0 * cosa) - (v1 * cosb);
4166 double fs = (v0 * sina) - (v1 * sinb);
4167
4168 double d = (fc * fc) + (fs * fs);
4169 double tcpa;
4170
4171 // the tracks are almost parallel
4172 if (fabs(d) < 1e-6)
4173 tcpa = 0.;
4174 else
4175 // Here is the equation for t, which will be in hours
4176 tcpa = ((fc * east) + (fs * north)) / d;
4177
4178 // Convert to minutes
4179 ptarget->TCPA = tcpa * 60.;
4180
4181 // Calculate CPA
4182 // Using TCPA, predict ownship and target positions
4183
4184 double OwnshipLatCPA, OwnshipLonCPA, TargetLatCPA, TargetLonCPA;
4185
4186 ll_gc_ll(gLat, gLon, cpa_calc_ownship_cog, gSog * tcpa, &OwnshipLatCPA,
4187 &OwnshipLonCPA);
4188 ll_gc_ll(ptarget->Lat_projected, ptarget->Lon_projected,
4189 cpa_calc_target_cog, ptarget->SOG * tcpa, &TargetLatCPA,
4190 &TargetLonCPA);
4191
4192 // And compute the distance
4193 ptarget->CPA = DistGreatCircle(OwnshipLatCPA, OwnshipLonCPA, TargetLatCPA,
4194 TargetLonCPA);
4195
4196 ptarget->bCPA_Valid = true;
4197
4198 if (ptarget->TCPA < 0) ptarget->bCPA_Valid = false;
4199 }
4200}
4201
4202void AisDecoder::OnTimerDSC(wxTimerEvent &event) {
4203 // Timer expired, no CDDSE message was received, so accept the latest CDDSC
4204 // message
4205 if (m_ptentative_dsctarget) {
4206 ProcessDSx(m_dsc_last_string, true);
4207 }
4208}
4209
4210void AisDecoder::OnTimerAIS(wxTimerEvent &event) {
4211 TimerAIS.Stop();
4212 // Scrub the target hash list
4213 // removing any targets older than stipulated age
4214
4215 wxDateTime now = wxDateTime::Now();
4216 now.MakeGMT();
4217
4218 std::unordered_map<int, std::shared_ptr<AisTargetData>> &current_targets =
4219 GetTargetList();
4220
4221 auto it = current_targets.begin();
4222 std::vector<int> remove_array; // collector for MMSI of targets to be removed
4223
4224 while (it != current_targets.end()) {
4225 if (it->second ==
4226 nullptr) // This should never happen, but I saw it once....
4227 {
4228 current_targets.erase(it);
4229 break; // leave the loop
4230 }
4231 // std::shared_ptr<AisTargetData>
4232 // xtd(std::make_shared<AisTargetData>(*it->second));
4233 std::shared_ptr<AisTargetData> xtd = it->second;
4234
4235 int target_posn_age = now.GetTicks() - xtd->PositionReportTicks;
4236 int target_static_age = now.GetTicks() - xtd->StaticReportTicks;
4237
4238 // Global variables controlling lost target handling
4239 // g_bMarkLost
4240 // g_MarkLost_Mins // Minutes until black "cross out
4241 // g_bRemoveLost
4242 // g_RemoveLost_Mins); // minutes until target is removed from screen and
4243 // internal lists
4244
4245 // g_bInlandEcdis
4246
4247 // Mark lost targets if specified
4248 double removelost_Mins = fmax(g_RemoveLost_Mins, g_MarkLost_Mins);
4249
4250 if (g_bInlandEcdis && (xtd->Class != AIS_ARPA)) {
4251 double iECD_LostTimeOut = 0.0;
4252 // special rules apply for europe inland ecdis timeout settings. overrule
4253 // option settings Won't apply for ARPA targets where the radar has all
4254 // control
4255 if (xtd->Class == AIS_CLASS_A) {
4256 if ((xtd->NavStatus == MOORED) || (xtd->NavStatus == AT_ANCHOR)) {
4257 if (xtd->SOG < 3.)
4258 iECD_LostTimeOut = 18 * 60;
4259 else
4260 iECD_LostTimeOut = 60;
4261 } else
4262 iECD_LostTimeOut = 60;
4263 } else if (xtd->Class == AIS_CLASS_B) {
4264 if (xtd->SOG < 2.)
4265 iECD_LostTimeOut = 18 * 60;
4266 else
4267 iECD_LostTimeOut = 180;
4268 } else if (xtd->Class == AIS_ATON || xtd->Class == AIS_BASE)
4269 iECD_LostTimeOut = 18 * 60; // Like a not moving Class A target
4270
4271 if ((target_posn_age > iECD_LostTimeOut) &&
4272 (xtd->Class != AIS_GPSG_BUDDY))
4273 xtd->b_active = false;
4274
4275 removelost_Mins = (2 * iECD_LostTimeOut) / 60.;
4276
4277 } else if (g_bMarkLost) {
4278 if ((target_posn_age > g_MarkLost_Mins * 60) &&
4279 (xtd->Class != AIS_GPSG_BUDDY) && (xtd->Class != AIS_SART))
4280 xtd->b_active = false;
4281 }
4282
4283 if (xtd->Class == AIS_SART || xtd->Class == AIS_METEO)
4284 removelost_Mins = 18.0;
4285
4286 // Remove lost targets if specified
4287
4288 if (g_bRemoveLost || g_bInlandEcdis) {
4289 bool b_arpalost =
4290 (xtd->Class == AIS_ARPA &&
4291 xtd->b_lost); // A lost ARPA target would be deleted at once
4292 if (((target_posn_age > removelost_Mins * 60) &&
4293 (xtd->Class != AIS_GPSG_BUDDY)) ||
4294 b_arpalost) {
4295 // So mark the target as lost, with unknown position, and make it
4296 // not selectable
4297 xtd->b_lost = true;
4298 xtd->b_positionOnceValid = false;
4299 xtd->COG = 360.0;
4300 xtd->SOG = 103.0;
4301 xtd->HDG = 511.0;
4302 xtd->ROTAIS = -128;
4303
4304 plugin_msg_evt.Notify(xtd, "");
4305
4306 long mmsi_long = xtd->MMSI;
4307 pSelectAIS->DeleteSelectablePoint((void *)mmsi_long, SELTYPE_AISTARGET);
4308
4309 // If we have not seen a static report in 3 times the removal spec,
4310 // then remove the target from all lists
4311 // or a lost ARPA target.
4312 if (target_static_age > removelost_Mins * 60 * 3 || b_arpalost) {
4313 xtd->b_removed = true;
4314 plugin_msg_evt.Notify(xtd, "");
4315 remove_array.push_back(xtd->MMSI); // Add this target to removal list
4316 }
4317 }
4318 }
4319
4320 // Remove any targets specified as to be "ignored", so that they won't
4321 // trigger phantom alerts (e.g. SARTs)
4322 for (unsigned int i = 0; i < g_MMSI_Props_Array.GetCount(); i++) {
4323 MmsiProperties *props = g_MMSI_Props_Array[i];
4324 if (xtd->MMSI == props->MMSI) {
4325 if (props->m_bignore) {
4326 remove_array.push_back(xtd->MMSI); // Add this target to removal list
4327 xtd->b_removed = true;
4328 plugin_msg_evt.Notify(xtd, "");
4329 }
4330 break;
4331 }
4332 }
4333
4334 // Check if the target has recently been set as own MMSI
4335 if (static_cast<unsigned>(xtd->MMSI) == g_OwnShipmmsi) {
4336 remove_array.push_back(xtd->MMSI); // Add this target to removal list
4337 xtd->b_removed = true;
4338 plugin_msg_evt.Notify(xtd, "");
4339 }
4340
4341 ++it;
4342 }
4343
4344 // Remove all the targets collected in remove_array in one pass
4345 for (unsigned int i = 0; i < remove_array.size(); i++) {
4346 auto itd = current_targets.find(remove_array[i]);
4347 if (itd != current_targets.end()) {
4348 std::shared_ptr<AisTargetData> td = itd->second;
4349 current_targets.erase(itd);
4350 // delete td;
4351 }
4352 }
4353
4354 UpdateAllCPA();
4355 UpdateAllAlarms();
4356
4357 // Update the general suppression flag
4358 m_bSuppressed = false;
4359 if (g_bAIS_CPA_Alert_Suppress_Moored || g_bHideMoored ||
4360 (g_bShowScaled && g_bAllowShowScaled))
4361 m_bSuppressed = true;
4362
4363 m_bAIS_Audio_Alert_On = false; // default, may be set on
4364
4365 // Process any Alarms
4366
4367 // If the AIS Alert Dialog is not currently shown....
4368
4369 // Scan all targets, looking for SART, DSC Distress, and CPA incursions
4370 // In the case of multiple targets of the same type, select the shortest
4371 // range or shortest TCPA
4372 std::shared_ptr<AisTargetData> palert_target = nullptr;
4373
4374 if (!g_pais_alert_dialog_active) {
4375 pAISMOBRoute = nullptr; // Reset the AISMOB auto route.
4376 double tcpa_min = 1e6; // really long
4377 double sart_range = 1e6;
4378 std::shared_ptr<AisTargetData> palert_target_cpa = nullptr;
4379 std::shared_ptr<AisTargetData> palert_target_sart = nullptr;
4380 std::shared_ptr<AisTargetData> palert_target_dsc = nullptr;
4381
4382 for (it = current_targets.begin(); it != current_targets.end(); ++it) {
4383 std::shared_ptr<AisTargetData> td = it->second;
4384 if (td) {
4385 if ((td->Class != AIS_SART) && (td->Class != AIS_DSC)) {
4386 if (g_bAIS_CPA_Alert && td->b_active) {
4387 if ((AIS_ALERT_SET == td->n_alert_state) && !td->b_in_ack_timeout) {
4388 if (td->TCPA < tcpa_min) {
4389 tcpa_min = td->TCPA;
4390 palert_target_cpa = td;
4391 }
4392 }
4393 }
4394 } else if ((td->Class == AIS_DSC) &&
4395 ((td->ShipType == 12) || (td->ShipType == 16))) {
4396 if (td->b_active) {
4397 if ((AIS_ALERT_SET == td->n_alert_state) && !td->b_in_ack_timeout) {
4398 palert_target_dsc = td;
4399 } else { // Reset DCS flag to open for a real AIS for the same
4400 // target
4401 td->b_isDSCtarget = false;
4402 }
4403 }
4404 }
4405
4406 else if (td->Class == AIS_SART) {
4407 if (td->b_active) {
4408 if ((AIS_ALERT_SET == td->n_alert_state) && !td->b_in_ack_timeout) {
4409 if (td->Range_NM < sart_range) {
4410 tcpa_min = sart_range;
4411 palert_target_sart = td;
4412 }
4413 }
4414 }
4415 }
4416 }
4417 }
4418
4419 // Which of multiple targets?
4420 // Give priority to SART targets, then DSC Distress, then CPA incursion
4421 palert_target = palert_target_cpa;
4422
4423 if (palert_target_sart) {
4424 palert_target = palert_target_sart;
4425 }
4426
4427 if (palert_target_dsc) {
4428 palert_target = palert_target_dsc;
4429 }
4430 } else {
4431 // Alert is currently shown, get target from from knowable GUI
4432 palert_target = Get_Target_Data_From_MMSI(m_callbacks.get_target_mmsi());
4433 }
4434 // Show or update the alert
4435 if (palert_target) info_update.Notify(palert_target, "");
4436
4437 TimerAIS.Start(TIMER_AIS_MSEC, wxTIMER_CONTINUOUS);
4438}
4439
4440std::shared_ptr<AisTargetData> AisDecoder::Get_Target_Data_From_MMSI(
4441 unsigned mmsi) {
4442 if (AISTargetList.find(mmsi) == AISTargetList.end()) return nullptr;
4443 return AISTargetList[mmsi];
4444}
4445
4446ArrayOfMmsiProperties g_MMSI_Props_Array;
4447
4448// MmsiProperties Implementation
4449
4450MmsiProperties::MmsiProperties(wxString &spec) {
4451 Init();
4452 wxStringTokenizer tkz(spec, ";");
4453 wxString s;
4454
4455 s = tkz.GetNextToken();
4456 long mmsil;
4457 s.ToLong(&mmsil);
4458 MMSI = (int)mmsil;
4459
4460 s = tkz.GetNextToken();
4461 if (s.Len()) {
4462 if (s.Upper() == "ALWAYS")
4463 TrackType = TRACKTYPE_ALWAYS;
4464 else if (s.Upper() == "NEVER")
4465 TrackType = TRACKTYPE_NEVER;
4466 }
4467
4468 s = tkz.GetNextToken();
4469 if (s.Len()) {
4470 if (s.Upper() == "IGNORE") m_bignore = true;
4471 }
4472
4473 s = tkz.GetNextToken();
4474 if (s.Len()) {
4475 if (s.Upper() == "MOB") m_bMOB = true;
4476 }
4477
4478 s = tkz.GetNextToken();
4479 if (s.Len()) {
4480 if (s.Upper() == "VDM") m_bVDM = true;
4481 }
4482
4483 s = tkz.GetNextToken();
4484 if (s.Len()) {
4485 if (s.Upper() == "FOLLOWER") m_bFollower = true;
4486 }
4487
4488 s = tkz.GetNextToken();
4489 if (s.Len()) {
4490 if (s.Upper() == "PERSIST") m_bPersistentTrack = true;
4491 }
4492
4493 s = tkz.GetNextToken();
4494 if (s.Len()) {
4495 m_ShipName = s.Upper();
4496 }
4497}
4498
4499MmsiProperties::~MmsiProperties() = default;
4500
4501void MmsiProperties::Init() {
4502 MMSI = -1;
4503 TrackType = TRACKTYPE_DEFAULT;
4504 m_bignore = false;
4505 m_bMOB = false;
4506 m_bVDM = false;
4507 m_bFollower = false;
4508 m_bPersistentTrack = false;
4509 m_ShipName = "";
4510}
4511
4512wxString MmsiProperties::Serialize() {
4513 wxString sMMSI;
4514 wxString s;
4515
4516 sMMSI.Printf("%d", MMSI);
4517 sMMSI << ";";
4518
4519 if (TrackType) {
4520 if (TRACKTYPE_ALWAYS == TrackType)
4521 sMMSI << "always";
4522 else if (TRACKTYPE_NEVER == TrackType)
4523 sMMSI << "never";
4524 }
4525 sMMSI << ";";
4526
4527 if (m_bignore) {
4528 sMMSI << "ignore";
4529 }
4530 sMMSI << ";";
4531
4532 if (m_bMOB) {
4533 sMMSI << "MOB";
4534 }
4535 sMMSI << ";";
4536
4537 if (m_bVDM) {
4538 sMMSI << "VDM";
4539 }
4540 sMMSI << ";";
4541
4542 if (m_bFollower) {
4543 sMMSI << "Follower";
4544 }
4545 sMMSI << ";";
4546
4547 if (m_bPersistentTrack) {
4548 sMMSI << "PERSIST";
4549 }
4550 sMMSI << ";";
4551
4552 if (m_ShipName == "") {
4553 m_ShipName = GetShipNameFromFile(MMSI);
4554 }
4555 sMMSI << m_ShipName;
4556 return sMMSI;
4557}
4558
4559void AISshipNameCache(AisTargetData *pTargetData,
4560 AIS_Target_Name_Hash *AISTargetNamesC,
4561 AIS_Target_Name_Hash *AISTargetNamesNC, long mmsi) {
4562 if (g_benableAISNameCache) {
4563 wxString ship_name = "";
4564
4565 // Check for valid name data
4566 if (!pTargetData->b_nameValid) {
4567 AIS_Target_Name_Hash::iterator it = AISTargetNamesC->find(mmsi);
4568 if (it != AISTargetNamesC->end()) {
4569 ship_name = (*AISTargetNamesC)[mmsi].Left(20);
4570 strncpy(pTargetData->ShipName, ship_name.mb_str(),
4571 ship_name.length() + 1);
4572 pTargetData->b_nameValid = true;
4573 pTargetData->b_nameFromCache = true;
4574 } else if (!g_bUseOnlyConfirmedAISName) {
4575 it = AISTargetNamesNC->find(mmsi);
4576 if (it != AISTargetNamesNC->end()) {
4577 ship_name = (*AISTargetNamesNC)[mmsi].Left(20);
4578 strncpy(pTargetData->ShipName, ship_name.mb_str(),
4579 ship_name.length() + 1);
4580 pTargetData->b_nameValid = true;
4581 pTargetData->b_nameFromCache = true;
4582 }
4583 }
4584 }
4585 // else there IS a valid name, lets check if it is in one of the hash lists.
4586 else if ((pTargetData->MID == 5) || (pTargetData->MID == 24) ||
4587 (pTargetData->MID == 19) ||
4588 (pTargetData->MID == 123) || // 123: Has got a name from SignalK
4589 (pTargetData->MID == 124)) { // 124: Has got a name from n2k
4590 // This message contains ship static data, so has a name field
4591 pTargetData->b_nameFromCache = false;
4592 ship_name = trimAISField(pTargetData->ShipName);
4593 AIS_Target_Name_Hash::iterator itC = AISTargetNamesC->find(mmsi);
4594 AIS_Target_Name_Hash::iterator itNC = AISTargetNamesNC->find(mmsi);
4595 if (itC !=
4596 AISTargetNamesC->end()) { // There is a confirmed entry for this mmsi
4597 if ((*AISTargetNamesC)[mmsi] ==
4598 ship_name) { // Received name is same as confirmed name
4599 if (itNC != AISTargetNamesNC->end()) { // there is also an entry in
4600 // the NC list, delete it
4601 AISTargetNamesNC->erase(itNC);
4602 }
4603 } else { // There is a confirmed name but that one is different
4604 if (itNC != AISTargetNamesNC->end()) { // there is an entry in the NC
4605 // list check if name is same
4606 if ((*AISTargetNamesNC)[mmsi] ==
4607 ship_name) { // Same name is already in NC list so promote till
4608 // confirmed list
4609 (*AISTargetNamesC)[mmsi] = ship_name;
4610 // And delete from NC list
4611 AISTargetNamesNC->erase(itNC);
4612 } else { // A different name is in the NC list, update with
4613 // received one
4614 (*AISTargetNamesNC)[mmsi] = ship_name;
4615 }
4616 if (g_bUseOnlyConfirmedAISName)
4617 strncpy(pTargetData->ShipName, (*AISTargetNamesC)[mmsi].mb_str(),
4618 (*AISTargetNamesC)[mmsi].Left(20).Length() + 1);
4619 } else { // The C list name is different but no NC entry. Add it.
4620 (*AISTargetNamesNC)[mmsi] = ship_name;
4621 }
4622 }
4623 } else { // No confirmed entry available
4624 if (itNC !=
4625 AISTargetNamesNC->end()) { // there is an entry in the NC list,
4626 if ((*AISTargetNamesNC)[mmsi] ==
4627 ship_name) { // Received name same as already in NC list, promote
4628 // to confirmen
4629 (*AISTargetNamesC)[mmsi] = ship_name;
4630 // And delete from NC list
4631 AISTargetNamesNC->erase(itNC);
4632 } else { // entry in NC list is not same as received one
4633 (*AISTargetNamesNC)[mmsi] = ship_name;
4634 }
4635 } else { // No entry in NC list so add it
4636 (*AISTargetNamesNC)[mmsi] = ship_name;
4637 }
4638 if (g_bUseOnlyConfirmedAISName) { // copy back previous name
4639 pTargetData->ShipName[SHIP_NAME_LEN - 1] = '\0';
4640 strncpy(pTargetData->ShipName, "Unknown ",
4641 SHIP_NAME_LEN - 1);
4642 }
4643 }
4644 }
4645 }
4646}
4647
4648wxString GetShipNameFromFile(int nmmsi) {
4649 wxString name = "";
4650 if (g_benableAISNameCache) {
4651 std::ifstream infile(AISTargetNameFileName.mb_str());
4652 if (infile) {
4653 std::string line;
4654 while (getline(infile, line)) {
4655 wxStringTokenizer tokenizer(wxString::FromUTF8(line.c_str()), ",");
4656 if (nmmsi == wxAtoi(tokenizer.GetNextToken())) {
4657 name = tokenizer.GetNextToken().Trim();
4658 break;
4659 } else
4660 tokenizer.GetNextToken();
4661 }
4662 }
4663 infile.close();
4664 }
4665 return name;
4666}
4667
4668void AisDecoder::UpdateMMSItoNameFile(const wxString &mmsi,
4669 const wxString &name) {
4670 // Path to the mmsitoname.csv file is already in AISTargetNameFileName
4671
4672 // Create a map to hold the current contents of the file
4673 std::map<wxString, wxString> mmsi_name_map;
4674
4675 // Read the existing file
4676 std::ifstream infile(AISTargetNameFileName.mb_str());
4677 if (infile) {
4678 std::string line;
4679 while (getline(infile, line)) {
4680 wxStringTokenizer tokenizer(wxString::FromUTF8(line.c_str()), ",");
4681 wxString file_mmsi = tokenizer.GetNextToken();
4682 wxString file_name = tokenizer.GetNextToken().Trim();
4683 mmsi_name_map[file_mmsi] = file_name;
4684 }
4685 infile.close();
4686 }
4687
4688 // Update or add the new entry.
4689 mmsi_name_map[mmsi] = name.Upper();
4690
4691 // Write the updated map back to the file
4692 std::ofstream outfile(AISTargetNameFileName.mb_str());
4693 if (outfile) {
4694 for (const auto &pair : mmsi_name_map) {
4695 std::string line = std::string(pair.first.mb_str()) + "," +
4696 std::string(pair.second.mb_str()) + "\n";
4697 outfile << line;
4698 }
4699 outfile.close();
4700 }
4701}
4702
4703wxString AisDecoder::GetMMSItoNameEntry(const wxString &mmsi) {
4704 return GetShipNameFromFile(wxAtoi(mmsi));
4705}
4706
4707// Assign a unique meteo mmsi related to position
4708int AisMeteoNewMmsi(int orig_mmsi, int m_lat, int m_lon, int lon_bits = 0,
4709 int siteID = 0) {
4710 bool found = false;
4711 int new_mmsi = 0;
4712 if ((!lon_bits || lon_bits == 999) && siteID) {
4713 // Check if a ais8_367_33 data report belongs to a present site
4714 // Or SignalK data (lon_bits == 999)
4715 auto &points = AisMeteoPoints::GetInstance().GetPoints();
4716 if (points.size()) {
4717 for (const auto &point : points) {
4718 // Does this station ID exist
4719 if (siteID == point.siteID && orig_mmsi == point.orig_mmsi) {
4720 // Created before. Continue
4721 new_mmsi = point.mmsi;
4722 found = true;
4723 break;
4724 }
4725 }
4726 }
4727 if (!found && !lon_bits) {
4728 // ais8_367_33
4729 return 0;
4730 }
4731 }
4732 double lon_tentative = 181.;
4733 double lat_tentative = 91.;
4734
4735 if (lon_bits == 25) {
4736 if (m_lon & 0x01000000) // negative?
4737 m_lon |= 0xFE000000;
4738 lon_tentative = m_lon / 60000.;
4739
4740 if (m_lat & 0x00800000) // negative?
4741 m_lat |= 0xFF000000;
4742 lat_tentative = m_lat / 60000.;
4743
4744 } else if (lon_bits == 28) {
4745 if (m_lon & 0x08000000) // negative?
4746 m_lon |= 0xf0000000;
4747 lon_tentative = m_lon / 600000.;
4748
4749 if (m_lat & 0x04000000) // negative?
4750 m_lat |= 0xf8000000;
4751 lat_tentative = m_lat / 600000.;
4752 }
4753
4754 // Since buoys can move we use position precision not better
4755 // than 50 m to be able to compare previous messages
4756 wxString slon = wxString::Format("%0.3f", lon_tentative);
4757 wxString slat = wxString::Format("%0.3f", lat_tentative);
4758
4759 // Change mmsi_ID number
4760 // Some countries use one equal mmsi for all meteo stations.
4761 // Others use the same mmsi for a meteo station and a nearby AtoN
4762 // So we create our own fake mmsi to separate them.
4763 // 199 is INMARSAT-A MID, should not occur ever in AIS stream.
4764 // 1992 to 1993 are already used so here we use 1994+
4765 static int nextMeteommsi = 199400000;
4766 auto &points = AisMeteoPoints::GetInstance().GetPoints();
4767
4768 if (lon_bits != 999 && !points.empty()) { // 999 comes from SignalK
4769 wxString t_lat, t_lon;
4770 for (const auto &point : points) {
4771 // Does this station position exist
4772 if (slat.IsSameAs(point.lat) && slon.IsSameAs(point.lon)) {
4773 // Created before. Continue
4774 new_mmsi = point.mmsi;
4775 found = true;
4776 break;
4777 }
4778 }
4779 }
4780 if (!found) {
4781 // Create a new post
4782 nextMeteommsi++;
4783 points.emplace_back(
4784 AisMeteoPoint(nextMeteommsi, slat, slon, siteID, orig_mmsi));
4785 new_mmsi = nextMeteommsi;
4786 }
4787 return new_mmsi;
4788}
Select * pSelectAIS
Global instance.
wxString AISTargetNameFileName
Global instance.
ArrayOfMmsiProperties g_MMSI_Props_Array
Global instance.
unsigned g_OwnShipmmsi
Global instance.
AisDecoder * g_pAIS
Global instance.
Class AisDecoder and helpers.
Select * pSelectAIS
Global instance.
wxString AISTargetNameFileName
Global instance.
ArrayOfMmsiProperties g_MMSI_Props_Array
Global instance.
unsigned g_OwnShipmmsi
Global instance.
Global state for AIS decoder.
AIS target definitions.
int GetInt(int sp, int len, bool signed_flag=false)
sp is starting bit, 1-based
obs::EventVar info_update
Notified when AIS user dialogs should update.
obs::EventVar plugin_msg_evt
A JSON message should be sent.
obs::EventVar touch_state
Notified when gFrame->TouchAISActive() should be invoked.
obs::EventVar new_track
Notified on new track creation.
Process incoming AIS messages.
Definition ais_decoder.h:76
void LogInputMessage(const std::shared_ptr< const NavMsg > &msg, bool is_filtered, bool is_error, const wxString &error_msg="") const
Logs an input message with context information.
void Notify(std::shared_ptr< const NavMsg > message)
Accept message received by driver, make it available for upper layers.
Custom event class for OpenCPN's notification system.
std::shared_ptr< const void > GetSharedPtr() const
Gets the event's payload data.
Raw messages layer, supports sending and recieving navmsg messages.
int g_iSpeedFormat
User-selected speed unit format for display and input.
int g_iDistanceFormat
User-selected distance (horizontal) unit format for display and input.
Global variables stored in configuration file.
OpenCPN Georef utility.
GUI constant definitions.
Meteo points are Meteorological and Hydrographic data received by NMEA0183 (AIS) VDM message 8 dac:00...
Multiplexer class and helpers.
const wxChar * ParseGPXDateTime(wxDateTime &dt, const wxChar *datetime)
This function parses a string containing a GPX time representation and returns a wxDateTime containin...
double fromUsrDistance(double usr_distance, int unit, int default_val)
Convert distance from user units to nautical miles.
Navigation Utility Functions without GUI dependencies.
bool bGPSValid
Indicate whether the Global Navigation Satellite System (GNSS) has a valid position.
Definition own_ship.cpp:34
double gHdt
True heading in degrees (0-359.99).
Definition own_ship.cpp:30
double gLat
Vessel's current latitude in decimal degrees.
Definition own_ship.cpp:26
double gCog
Course over ground in degrees (0-359.99).
Definition own_ship.cpp:28
double gSog
Speed over ground in knots.
Definition own_ship.cpp:29
double gLon
Vessel's current longitude in decimal degrees.
Definition own_ship.cpp:27
Position, course, speed, etc.
Waypoint or mark abstraction.
Route * pAISMOBRoute
Global instance.
Definition routeman.cpp:61
Select * pSelect
Global instance.
Definition select.cpp:36
Selected route, segment, waypoint, etc.
double kCog
Course over ground in degrees.
Definition ocpn_types.h:86
double kHdt
True heading in degrees.
Definition ocpn_types.h:111
double kHdm
Magnetic heading in degrees.
Definition ocpn_types.h:104
double kLat
Latitude in decimal degrees.
Definition ocpn_types.h:75
double kSog
Speed over ground in knots.
Definition ocpn_types.h:92
double kVar
Magnetic variation in degrees.
Definition ocpn_types.h:98
double kLon
Longitude in decimal degrees.
Definition ocpn_types.h:83
std::vector< Track * > g_TrackList
Global instance.
Definition track.cpp:97
Recorded track abstraction.