-
Notifications
You must be signed in to change notification settings - Fork 4
/
FAP.pm
3554 lines (3152 loc) · 99 KB
/
FAP.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Ham::APRS::FAP;
# File modified by Juan Carlos Perez De Castro (Wodie) KM4NNO/XE1F.
=head1 NAME
Ham::APRS::FAP - Finnish APRS Parser (Fabulous APRS Parser)
=head1 SYNOPSIS
use Ham::APRS::FAP qw(parseaprs);
my $aprspacket = 'OH2RDP>BEACON,OH2RDG*,WIDE:!6028.51N/02505.68E#PHG7220/RELAY,WIDE, OH2AP Jarvenpaa';
my %packetdata;
my $retval = parseaprs($aprspacket, \%packetdata);
if ($retval == 1) {
# decoding ok, do something with the data
while (my ($key, $value) = each(%packetdata)) {
print "$key: $value\n";
}
} else {
warn "Parsing failed: $packetdata{resultmsg} ($packetdata{resultcode})\n";
}
=head1 ABSTRACT
This module is a fairly complete APRS parser. It parses normal,
mic-e and compressed location packets, NMEA location packets,
objects, items, messages, telemetry and most weather packets. It is
stable and fast enough to parse the APRS-IS stream in real time.
The package also contains the Ham::APRS::IS module which, in turn,
is an APRS-IS client library.
=head1 DESCRIPTION
Unless a debugging mode is enabled, all errors and warnings are reported
through the API (as opposed to printing on STDERR or STDOUT), so that
they can be reported nicely on the user interface of an application.
This parser is not known to crash on invalid packets. It is used to power
the L<http://aprs.fi/> web site.
APRS features specifically NOT handled by this module:
=over
=item * special objects (area, signpost, etc)
=item * network tunneling/third party packets
=item * direction finding
=item * station capability queries
=item * status reports (partially)
=item * user defined data formats
=back
This module is based (on those parts that are implemented)
on APRS specification 1.0.1.
This module requires a reasonably recent L<Date::Calc> module.
=head1 EXPORT
None by default.
=head1 FUNCTION REFERENCE
=cut
use strict;
use warnings;
use Date::Calc qw(check_date Today Date_to_Time Add_Delta_YM Mktime);
use Math::Trig;
require Exporter;
our @ISA = qw(Exporter);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use Ham::APRS::FAP ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
##our %EXPORT_TAGS = (
## 'all' => [ qw(
##
## ) ],
##);
our @EXPORT_OK = (
## @{ $EXPORT_TAGS{'all'} },
'&parseaprs',
'&kiss_to_tnc2',
'&tnc2_to_kiss',
'&aprs_duplicate_parts',
'&count_digihops',
'&check_ax25_call',
'&distance',
'&direction',
'&make_object',
'&make_item',
'&make_nws',
'&make_timestamp',
'&make_position',
'&mice_mbits_to_message',
);
##our @EXPORT = qw(
##
##);
our $VERSION = '1.22';
# Preloaded methods go here.
# no debugging by default
my $debug = 0;
my %result_messages = (
'unknown' => 'Unsupported packet format',
'packet_no' => 'No packet given to parse',
'packet_short' => 'Too short packet',
'packet_nobody' => 'No body in packet',
'srccall_noax25' => 'Source callsign is not a valid AX.25 call',
'srccall_badchars' => 'Source callsign contains bad characters',
'dstpath_toomany' => 'Too many destination path components to be AX.25',
'dstcall_none' => 'No destination field in packet',
'dstcall_noax25' => 'Destination callsign is not a valid AX.25 call',
'digicall_noax25' => 'Digipeater callsign is not a valid AX.25 call',
'digicall_badchars' => 'Digipeater callsign contains bad characters',
'timestamp_inv_loc' => 'Invalid timestamp in location',
'timestamp_inv_obj' => 'Invalid timestamp in object',
'timestamp_inv_sta' => 'Invalid timestamp in status',
'timestamp_inv_gpgga' => 'Invalid timestamp in GPGGA sentence',
'timestamp_inv_gpgll' => 'Invalid timestamp in GPGLL sentence',
'packet_invalid' => 'Invalid packet',
'nmea_inv_cval' => 'Invalid coordinate value in NMEA sentence',
'nmea_large_ew' => 'Too large value in NMEA sentence (east/west)',
'nmea_large_ns' => 'Too large value in NMEA sentence (north/south)',
'nmea_inv_sign' => 'Invalid lat/long sign in NMEA sentence',
'nmea_inv_cksum' => 'Invalid checksum in NMEA sentence',
'gprmc_fewfields' => 'Less than ten fields in GPRMC sentence ',
'gprmc_nofix' => 'No GPS fix in GPRMC sentence',
'gprmc_inv_time' => 'Invalid timestamp in GPRMC sentence',
'gprmc_inv_date' => 'Invalid date in GPRMC sentence',
'gprmc_date_out' => 'GPRMC date does not fit in an Unix timestamp',
'gpgga_fewfields' => 'Less than 11 fields in GPGGA sentence',
'gpgga_nofix' => 'No GPS fix in GPGGA sentence',
'gpgll_fewfields' => 'Less than 5 fields in GPGLL sentence',
'gpgll_nofix' => 'No GPS fix in GPGLL sentence',
'nmea_unsupp' => 'Unsupported NMEA sentence type',
'obj_short' => 'Too short object',
'obj_inv' => 'Invalid object',
'obj_dec_err' => 'Error in object location decoding',
'item_short' => 'Too short item',
'item_inv' => 'Invalid item',
'item_dec_err' => 'Error in item location decoding',
'loc_short' => 'Too short uncompressed location',
'loc_inv' => 'Invalid uncompressed location',
'loc_large' => 'Degree value too large',
'loc_amb_inv' => 'Invalid position ambiguity',
'mice_short' => 'Too short mic-e packet',
'mice_inv' => 'Invalid characters in mic-e packet',
'mice_inv_info' => 'Invalid characters in mic-e information field',
'mice_amb_large' => 'Too much position ambiguity in mic-e packet',
'mice_amb_inv' => 'Invalid position ambiguity in mic-e packet',
'mice_amb_odd' => 'Odd position ambiguity in mic-e packet',
'comp_inv' => 'Invalid compressed packet',
'msg_inv' => 'Invalid message packet',
'wx_unsupp' => 'Unsupported weather format',
'user_unsupp' => 'Unsupported user format',
'dx_inv_src' => 'Invalid DX spot source callsign',
'dx_inf_freq' => 'Invalid DX spot frequency',
'dx_no_dx' => 'No DX spot callsign found',
'tlm_inv' => 'Invalid telemetry packet',
'tlm_large' => 'Too large telemetry value',
'tlm_unsupp' => 'Unsupported telemetry',
'exp_unsupp' => 'Unsupported experimental',
'sym_inv_table' => 'Invalid symbol table or overlay',
);
=over
=item result_messages( )
Returns a reference to a hash containing all possible
return codes as the keys and their plain english descriptions
as the values of the hash.
=back
=cut
sub result_messages() {
return \%result_messages;
}
# these functions are used to report warnings and parser errors
# from the module
sub _a_err($$;$) {
my ($rethash, $errcode, $val) = @_;
$rethash->{'resultcode'} = $errcode;
$rethash->{'resultmsg'}
= defined $result_messages{$errcode}
? $result_messages{$errcode} : $errcode;
$rethash->{'resultmsg'} .= ': ' . $val if (defined $val);
if ($debug > 0) {
warn "Ham::APRS::FAP ERROR $errcode: " . $rethash->{'resultmsg'} . "\n";
}
}
sub _a_warn($$;$) {
my ($rethash, $errcode, $val) = @_;
push @{ $rethash->{'warncodes'} }, $errcode;
if ($debug > 0) {
warn "Ham::APRS::FAP WARNING $errcode: "
. (defined $result_messages{$errcode}
? $result_messages{$errcode} : $errcode)
. (defined $val ? ": $val" : '')
. "\n";
}
}
# message bit types for mic-e
# from left to right, bits a, b and c
# standard one bit is 1, custom one bit is 2
my %mice_messagetypes = (
'111' => 'off duty',
'222' => 'custom 0',
'110' => 'en route',
'220' => 'custom 1',
'101' => 'in service',
'202' => 'custom 2',
'100' => 'returning',
'200' => 'custom 3',
'011' => 'committed',
'022' => 'custom 4',
'010' => 'special',
'020' => 'custom 5',
'001' => 'priority',
'002' => 'custom 6',
'000' => 'emergency',
);
=over
=item mice_mbits_to_message($packetdata{'mbits'})
Convert mic-e message bits (three numbers 0-2) to a textual message.
Returns the message on success, undef on failure.
=back
=cut
sub mice_mbits_to_message($) {
my $bits = shift @_;
if ($bits =~ /^\s*([0-2]{3})\s*$/o) {
$bits = $1;
if (defined($mice_messagetypes{$bits})) {
return $mice_messagetypes{$bits};
}
}
return undef;
}
# A list of mappings from GPSxyz (or SPCxyz)
# to APRS symbols. Overlay characters (z) are
# not handled here
my %dstsymbol = (
'BB' => q(/!), 'BC' => q(/"), 'BD' => q(/#), 'BE' => q(/$),
'BF' => q(/%), 'BG' => q(/&), 'BH' => q(/'), 'BI' => q!/(!,
'BJ' => q!/)!, 'BK' => q(/*), 'BL' => q(/+), 'BM' => q(/,),
'BN' => q(/-), 'BO' => q(/.), 'BP' => q(//),
'P0' => q(/0), 'P1' => q(/1), 'P2' => q(/2), 'P3' => q(/3),
'P4' => q(/4), 'P5' => q(/5), 'P6' => q(/6), 'P7' => q(/7),
'P8' => q(/8), 'P9' => q(/9),
'MR' => q(/:), 'MS' => q(/;), 'MT' => q(/<), 'MU' => q(/=),
'MV' => q(/>), 'MW' => q(/?), 'MX' => q(/@),
'PA' => q(/A), 'PB' => q(/B), 'PC' => q(/C), 'PD' => q(/D),
'PE' => q(/E), 'PF' => q(/F), 'PG' => q(/G), 'PH' => q(/H),
'PI' => q(/I), 'PJ' => q(/J), 'PK' => q(/K), 'PL' => q(/L),
'PM' => q(/M), 'PN' => q(/N), 'PO' => q(/O), 'PP' => q(/P),
'PQ' => q(/Q), 'PR' => q(/R), 'PS' => q(/S), 'PT' => q(/T),
'PU' => q(/U), 'PV' => q(/V), 'PW' => q(/W), 'PX' => q(/X),
'PY' => q(/Y), 'PZ' => q(/Z),
'HS' => q(/[), 'HT' => q(/\\), 'HU' => q(/]), 'HV' => q(/^),
'HW' => q(/_), 'HX' => q(/`),
'LA' => q(/a), 'LB' => q(/b), 'LC' => q(/c), 'LD' => q(/d),
'LE' => q(/e), 'LF' => q(/f), 'LG' => q(/g), 'LH' => q(/h),
'LI' => q(/i), 'LJ' => q(/j), 'LK' => q(/k), 'LL' => q(/l),
'LM' => q(/m), 'LN' => q(/n), 'LO' => q(/o), 'LP' => q(/p),
'LQ' => q(/q), 'LR' => q(/r), 'LS' => q(/s), 'LT' => q(/t),
'LU' => q(/u), 'LV' => q(/v), 'LW' => q(/w), 'LX' => q(/x),
'LY' => q(/y), 'LZ' => q(/z),
'J1' => q(/{), 'J2' => q(/|), 'J3' => q(/}), 'J4' => q(/~),
'OB' => q(\\!), 'OC' => q(\\"), 'OD' => q(\\#), 'OE' => q(\\$),
'OF' => q(\\%), 'OG' => q(\\&), 'OH' => q(\\'), 'OI' => q!\\(!,
'OJ' => q!\\)!, 'OK' => q(\\*), 'OL' => q(\\+), 'OM' => q(\\,),
'ON' => q(\\-), 'OO' => q(\\.), 'OP' => q(\\/),
'A0' => q(\\0), 'A1' => q(\\1), 'A2' => q(\\2), 'A3' => q(\\3),
'A4' => q(\\4), 'A5' => q(\\5), 'A6' => q(\\6), 'A7' => q(\\7),
'A8' => q(\\8), 'A9' => q(\\9),
'NR' => q(\\:), 'NS' => q(\\;), 'NT' => q(\\<), 'NU' => q(\\=),
'NV' => q(\\>), 'NW' => q(\\?), 'NX' => q(\\@),
'AA' => q(\\A), 'AB' => q(\\B), 'AC' => q(\\C), 'AD' => q(\\D),
'AE' => q(\\E), 'AF' => q(\\F), 'AG' => q(\\G), 'AH' => q(\\H),
'AI' => q(\\I), 'AJ' => q(\\J), 'AK' => q(\\K), 'AL' => q(\\L),
'AM' => q(\\M), 'AN' => q(\\N), 'AO' => q(\\O), 'AP' => q(\\P),
'AQ' => q(\\Q), 'AR' => q(\\R), 'AS' => q(\\S), 'AT' => q(\\T),
'AU' => q(\\U), 'AV' => q(\\V), 'AW' => q(\\W), 'AX' => q(\\X),
'AY' => q(\\Y), 'AZ' => q(\\Z),
'DS' => q(\\[), 'DT' => q(\\\\), 'DU' => q(\\]), 'DV' => q(\\^),
'DW' => q(\\_), 'DX' => q(\\`),
'SA' => q(\\a), 'SB' => q(\\b), 'SC' => q(\\c), 'SD' => q(\\d),
'SE' => q(\\e), 'SF' => q(\\f), 'SG' => q(\\g), 'SH' => q(\\h),
'SI' => q(\\i), 'SJ' => q(\\j), 'SK' => q(\\k), 'SL' => q(\\l),
'SM' => q(\\m), 'SN' => q(\\n), 'SO' => q(\\o), 'SP' => q(\\p),
'SQ' => q(\\q), 'SR' => q(\\r), 'SS' => q(\\s), 'ST' => q(\\t),
'SU' => q(\\u), 'SV' => q(\\v), 'SW' => q(\\w), 'SX' => q(\\x),
'SY' => q(\\y), 'SZ' => q(\\z),
'Q1' => q(\\{), 'Q2' => q(\\|), 'Q3' => q(\\}), 'Q4' => q(\\~),
);
# conversion constants
our $knot_to_kmh = 1.852; # nautical miles per hour to kilometers per hour
our $mph_to_kmh = 1.609344; # miles per hour to kilometers per hour
our $kmh_to_ms = 10 / 36; # kilometers per hour to meters per second
our $mph_to_ms = $mph_to_kmh * $kmh_to_ms; # miles per hour to meters per second
our $hinch_to_mm = 0.254; # hundredths of an inch to millimeters
our $feet_to_meters = 0.3048;
=over
=item debug($enable)
Enables (debug(1)) or disables (debug(0)) debugging.
When debugging is enabled, warnings and errors are emitted using the warn() function,
which will normally result in them being printed on STDERR. Succesfully
printed packets will be also printed on STDOUT in a human-readable
format.
When debugging is disabled, nothing will be printed on STDOUT or STDERR -
all errors and parsing results need to be collected from the returned
hash reference.
=back
=cut
sub debug($) {
my $dval = shift @_;
if ($dval) {
$debug = 1;
} else {
$debug = 0;
}
}
# Return a human readable timestamp in UTC.
# If no parameter is given, use current time,
# else use the unix timestamp given in the parameter.
sub _gettime {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday);
if (scalar(@_) >= 1) {
my $tstamp = shift @_;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = gmtime($tstamp);
} else {
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = gmtime();
}
my $timestring = sprintf('%d-%02d-%02d %02d:%02d:%02d UTC',
$year + 1900,
$mon + 1,
$mday,
$hour,
$min,
$sec);
return $timestring;
}
=over
=item distance($lon0, $lat0, $lon1, $lat1)
Returns the distance in kilometers between two locations
given in decimal degrees. Arguments are given in order as
lon0, lat0, lon1, lat1, east and north positive.
The calculation uses the great circle distance, it
is not too exact, but good enough for us.
=back
=cut
sub distance($$$$) {
my $lon0 = shift @_;
my $lat0 = shift @_;
my $lon1 = shift @_;
my $lat1 = shift @_;
# decimal to radian
$lon0 = deg2rad($lon0);
$lon1 = deg2rad($lon1);
$lat0 = deg2rad($lat0);
$lat1 = deg2rad($lat1);
# Use the haversine formula for distance calculation
# http://mathforum.org/library/drmath/view/51879.html
my $dlon = $lon1 - $lon0;
my $dlat = $lat1 - $lat0;
my $a = (sin($dlat/2)) ** 2 + cos($lat0) * cos($lat1) * (sin($dlon/2)) ** 2;
my $c = 2 * atan2(sqrt($a), sqrt(1-$a));
my $distance = $c * 6366.71; # in kilometers
return $distance;
}
=over
=item direction($lon0, $lat0, $lon1, $lat1)
Returns the initial great circle direction in degrees
from lat0/lon0 to lat1/lon1. Locations are input
in decimal degrees, north and east positive.
=back
=cut
sub direction($$$$) {
my $lon0 = shift @_;
my $lat0 = shift @_;
my $lon1 = shift @_;
my $lat1 = shift @_;
$lon0 = deg2rad($lon0);
$lon1 = deg2rad($lon1);
$lat0 = deg2rad($lat0);
$lat1 = deg2rad($lat1);
# direction from Aviation Formulary V1.42 by Ed Williams
# by way of http://mathforum.org/library/drmath/view/55417.html
my $direction = atan2(sin($lon1-$lon0)*cos($lat1),
cos($lat0)*sin($lat1)-sin($lat0)*cos($lat1)*cos($lon1-$lon0));
if ($direction < 0) {
# make direction positive
$direction += 2 * pi;
}
return rad2deg($direction);
}
=over
=item count_digihops($header)
Count the number of digipeated hops in a (KISS) packet and
return it. Returns -1 in case of error.
The header parameter can contain the full packet or just the header
in TNC2 format. All callsigns in the header must be AX.25 compatible
and remember that the number returned is just an educated guess, not
absolute truth.
=back
=cut
sub count_digihops($) {
my $header = shift @_;
# Do a rough check on the header syntax
$header =~ tr/\r\n//d;
$header = uc($header);
if ($header =~ /^([^:]+):/o) {
# remove data part of packet, if present
$header = $1;
}
my $hops = undef;
if ($header =~ /^([A-Z0-9-]+)\>([A-Z0-9-]+)$/o) {
# check the callsigns for validity
my $retval = check_ax25_call($1);
if (not(defined($retval))) {
if ($debug > 0) {
warn "count_digihops: invalid source callsign ($1)\n";
}
return -1;
}
$retval = check_ax25_call($2);
if (not(defined($retval))) {
if ($debug > 0) {
warn "count_digihops: invalid destination callsign ($2)\n";
}
return -1;
}
# no path at all, so zero hops
return 0;
} elsif ($header =~ /^([A-Z0-9-]+)\>([A-Z0-9-]+),([A-Z0-9,*-]+)$/o) {
my $retval = check_ax25_call($1);
if (not(defined($retval))) {
if ($debug > 0) {
warn "count_digihops: invalid source callsign ($1)\n";
}
return -1;
}
$retval = check_ax25_call($2);
if (not(defined($retval))) {
if ($debug > 0) {
warn "count_digihops: invalid destination callsign ($2)\n";
}
return -1;
}
# some hops
$hops = $3;
} else {
# invalid
if ($debug > 0) {
warn "count_digihops: invalid packet header\n";
}
return -1;
}
my $hopcount = 0;
# split the path into parts
my @parts = split(/,/, $hops);
# now examine the parts one by one
foreach my $piece (@parts) {
# remove the possible "digistar" from the end of callsign
# and take note of its existence
my $wasdigied = 0;
if ($piece =~ /^[A-Z0-9-]+\*$/o) {
$wasdigied = 1;
$piece =~ s/\*$//;
}
# check the callsign for validity and expand it
my $call = check_ax25_call($piece);
if (not(defined($call))) {
if ($debug > 0) {
warn "count_digihops: invalid callsign in path ($piece)\n";
}
return -1;
}
# check special cases, wideN-N and traceN-N for now
if ($call =~ /^WIDE([1-7])-([0-7])$/o) {
my $difference = $1 - $2;
if ($difference < 0) {
# ignore reversed N-N
if ($debug > 0) {
warn "count_digihops: reversed N-N in path ($call)\n";
}
next;
}
$hopcount += $difference;
} elsif ($call =~ /^TRACE([1-7])-([0-7])$/o) {
# skip traceN-N because the hops are already individually shown
# before this
next;
} else {
# just a normal packet. if "digistar" is there,
# increment the digicounter by one
if ($wasdigied == 1) {
$hopcount++;
}
}
}
return $hopcount;
}
# Return a unix timestamp based on an
# APRS six (+ one char for type) character timestamp.
# If an invalid timestamp is given, return 0.
sub _parse_timestamp($$) {
my($options, $stamp) = @_;
# Check initial format
return 0 if ($stamp !~ /^(\d{2})(\d{2})(\d{2})(z|h|\/)$/o);
return "$1$2$3" if ($options->{'raw_timestamp'});
my $stamptype = $4;
if ($stamptype eq 'h') {
# HMS format
my $hour = $1;
my $minute = $2;
my $second = $3;
# Check for invalid time
if ($hour > 23 || $minute > 59 || $second > 59) {
return 0;
}
# All calculations here are in UTC, but
# if this is run under old MacOS (pre-OSX), then
# Date_to_Time could be in local time..
my $currenttime = time();
my ($cyear, $cmonth, $cday) = Today(1);
my $tstamp = Date_to_Time($cyear, $cmonth, $cday, $hour, $minute, $second);
# If the time is more than about one hour
# into the future, roll the timestamp
# one day backwards.
if ($currenttime + 3900 < $tstamp) {
$tstamp -= 86400;
# If the time is more than about 23 hours
# into the past, roll the timestamp one
# day forwards.
} elsif ($currenttime - 82500 > $tstamp) {
$tstamp += 86400;
}
return $tstamp;
} elsif ($stamptype eq 'z' ||
$stamptype eq '/') {
# Timestamp is DHM, UTC (z) or local (/).
# Always intepret local to mean local
# to this computer.
my $day = $1;
my $hour = $2;
my $minute = $3;
if ($day < 1 || $day > 31 || $hour > 23 || $minute > 59) {
return 0;
}
# If time is under about 12 hours into
# the future, go there.
# Otherwise get the first matching
# time in the past.
my $currenttime = time();
my ($cyear, $cmonth, $cday);
if ($stamptype eq 'z') {
($cyear, $cmonth, $cday) = Today(1);
} else {
($cyear, $cmonth, $cday) = Today(0);
}
# Form the possible timestamps in
# this, the next and the previous month
my ($fwdyear, $fwdmonth) = (Add_Delta_YM($cyear, $cmonth, $cday, 0, 1))[0,1];
my ($backyear, $backmonth) = (Add_Delta_YM($cyear, $cmonth, $cday, 0, -1))[0,1];
my $fwdtstamp = undef;
my $currtstamp = undef;
my $backtstamp = undef;
if (check_date($cyear, $cmonth, $day)) {
if ($stamptype eq 'z') {
$currtstamp = Date_to_Time($cyear, $cmonth, $day, $hour, $minute, 0);
} else {
$currtstamp = Mktime($cyear, $cmonth, $day, $hour, $minute, 0);
}
}
if (check_date($fwdyear, $fwdmonth, $day)) {
if ($stamptype eq 'z') {
$fwdtstamp = Date_to_Time($fwdyear, $fwdmonth, $day, $hour, $minute, 0);
} else {
$fwdtstamp = Mktime($cyear, $cmonth, $day, $hour, $minute, 0);
}
}
if (check_date($backyear, $backmonth, $day)) {
if ($stamptype eq 'z') {
$backtstamp = Date_to_Time($backyear, $backmonth, $day, $hour, $minute, 0);
} else {
$backtstamp = Mktime($cyear, $cmonth, $day, $hour, $minute, 0);
}
}
# Select the timestamp to use. Pick the timestamp
# that is largest, but under about 12 hours from
# current time.
if (defined($fwdtstamp) && ($fwdtstamp - $currenttime) < 43400) {
return $fwdtstamp;
} elsif (defined($currtstamp) && ($currtstamp - $currenttime) < 43400) {
return $currtstamp;
} elsif (defined($backtstamp)) {
return $backtstamp;
}
}
# return failure if we haven't returned with
# a success earlier
return 0;
}
# clean up a comment string - remove control codes
# but stay UTF-8 clean
sub _cleanup_comment($) {
$_[0] =~ tr/[\x20-\x7e\x80-\xfe]//cd;
$_[0] =~ s/^\s+//;
$_[0] =~ s/\s+$//;
return $_[0];
}
# Return position resolution in meters based on the number
# of minute decimal digits. Also accepts negative numbers,
# i.e. -1 for 10 minute resolution and -2 for 1 degree resolution.
# Calculation is based on latitude so it is worst case
# (resolution in longitude gets better as you get closer to the poles).
sub _get_posresolution($) {
return $knot_to_kmh * ($_[0] <= -2 ? 600 : 1000) * 10 ** (-1 * $_[0]);
}
# return an NMEA latitude or longitude.
# 1st parameter is the (dd)dmm.m(mmm..) string and
# 2nd is the north/south or east/west indicator
# returns undef on error. The returned value
# is decimal degrees, north and east positive.
sub _nmea_getlatlon($$$) {
my ($value, $sign, $rh) = @_;
# upcase the sign for compatibility
$sign = uc($sign);
# Be leninent on what to accept, anything
# goes as long as degrees has 1-3 digits,
# minutes has 2 digits and there is at least
# one decimal minute.
if ($value =~ /^\s*(\d{1,3})([0-5][0-9])\.(\d+)\s*$/o) {
my $minutes = $2 . '.' . $3;
$value = $1 + ($minutes / 60);
# capture position resolution in meters based
# on the amount of minute decimals present
$rh->{'posresolution'} = _get_posresolution(length($3));
} else {
_a_err($rh, 'nmea_inv_cval', $value);
return undef;
}
if ($sign =~ /^\s*[EW]\s*$/o) {
# make sure the value is ok
if ($value > 179.999999) {
_a_err($rh, 'nmea_large_ew', $value);
return undef;
}
# west negative
if ($sign =~ /^\s*W\s*$/o) {
$value *= -1;
}
} elsif ($sign =~ /^\s*[NS]\s*$/o) {
# make sure the value is ok
if ($value > 89.999999) {
_a_err($rh, 'nmea_large_ns', $value);
return undef;
}
# south negative
if ($sign =~ /^\s*S\s*$/o) {
$value *= -1;
}
} else {
# incorrect sign
_a_err($rh, 'nmea_inv_sign', $sign);
return undef;
}
# all ok
return $value;
}
# return a two element array, first containing
# the symbol table id (or overlay) and second
# containing symbol id. return undef in error
sub _get_symbol_fromdst($) {
my $dstcallsign = shift @_;
my $table = undef;
my $code = undef;
if ($dstcallsign =~ /^(GPS|SPC)([A-Z0-9]{2,3})/o) {
my $leftoverstring = $2;
my $type = substr($leftoverstring, 0, 1);
my $sublength = length($leftoverstring);
if ($sublength == 3) {
if ($type eq 'C' || $type eq 'E') {
my $numberid = substr($leftoverstring, 1, 2);
if ($numberid =~ /^(\d{2})$/o &&
$numberid > 0 &&
$numberid < 95) {
$code = chr($1 + 32);
if ($type eq 'C') {
$table = '/';
} else {
$table = "\\";
}
return ($table, $code);
} else {
return undef;
}
} else {
# secondary symbol table, with overlay
# Check first that we really are in the
# secondary symbol table
my $dsttype = substr($leftoverstring, 0, 2);
my $overlay = substr($leftoverstring, 2, 1);
if (($type eq 'O' ||
$type eq 'A' ||
$type eq 'N' ||
$type eq 'D' ||
$type eq 'S' ||
$type eq 'Q') && $overlay =~ /^[A-Z0-9]$/o) {
if (defined($dstsymbol{$dsttype})) {
$code = substr($dstsymbol{$dsttype}, 1, 1);
return ($overlay, $code);
} else {
return undef;
}
} else {
return undef;
}
}
} else {
# primary or secondary symbol table, no overlay
if (defined($dstsymbol{$leftoverstring})) {
$table = substr($dstsymbol{$leftoverstring}, 0, 1);
$code = substr($dstsymbol{$leftoverstring}, 1, 1);
return ($table, $code);
} else {
return undef;
}
}
} else {
return undef;
}
# failsafe catch-all
return undef;
}
# Parse an NMEA location
sub _nmea_to_decimal($$$$$) {
#(substr($body, 1), $srccallsign, $dstcallsign, \%poshash)
my($options, $body, $srccallsign, $dstcallsign, $rethash) = @_;
if ($debug > 1) {
# print packet, after stripping control chars
my $printbody = $body;
$printbody =~ tr/[\x00-\x1f]//d;
warn "NMEA: from $srccallsign to $dstcallsign: $printbody\n";
}
# verify checksum first, if it is provided
$body =~ s/\s+$//; # remove possible white space from the end
if ($body =~ /^([\x20-\x7e]+)\*([0-9A-F]{2})$/io) {
my $checksumarea = $1;
my $checksumgiven = hex($2);
my $checksumcalculated = 0;
for (my $i = 0; $i < length($checksumarea); $i++) {
$checksumcalculated ^= ord(substr($checksumarea, $i, 1));
}
if ($checksumgiven != $checksumcalculated) {
# invalid checksum
_a_err($rethash, 'nmea_inv_cksum');
return 0;
}
# make a note of the existance of a checksum
$rethash->{'checksumok'} = 1;
}
# checksum ok or not provided
$rethash->{'format'} = 'nmea';
# use a dot as a default symbol if one is not defined in
# the destination callsign
my ($symtable, $symcode) = _get_symbol_fromdst($dstcallsign);
if (not(defined($symtable)) || not(defined($symcode))) {
$rethash->{'symboltable'} = '/';
$rethash->{'symbolcode'} = '/';
} else {
$rethash->{'symboltable'} = $symtable;
$rethash->{'symbolcode'} = $symcode;
}
# Split to NMEA fields
$body =~ s/\*[0-9A-F]{2}$//; # remove checksum from body first
my @nmeafields = split(/,/, $body);
# Now check the sentence type and get as much info
# as we can (want).
if ($nmeafields[0] eq 'GPRMC') {
# we want at least 10 fields
if (@nmeafields < 10) {
_a_err($rethash, 'gprmc_fewfields', scalar(@nmeafields));
return 0;
}
if ($nmeafields[2] ne 'A') {
# invalid position
_a_err($rethash, 'gprmc_nofix');
return 0;
}
# check and save the timestamp
my ($hour, $minute, $second);
if ($nmeafields[1] =~ /^\s*(\d{2})(\d{2})(\d{2})(|\.\d+)\s*$/o) {
# if seconds has a decimal part, ignore it
# leap seconds are not taken into account...
if ($1 > 23 || $2 > 59 || $3 > 59) {
_a_err($rethash, 'gprmc_inv_time', $nmeafields[1]);
return 0;
}
$hour = $1 + 0; # force numeric
$minute = $2 + 0;
$second = $3 + 0;
} else {
_a_err($rethash, 'gprmc_inv_time');
return 0;
}
my ($year, $month, $day);
if ($nmeafields[9] =~ /^\s*(\d{2})(\d{2})(\d{2})\s*$/o) {
# check the date for validity. Assume
# years 0-69 are 21st century and years
# 70-99 are 20th century
$year = 2000 + $3;
if ($3 >= 70) {
$year = 1900 + $3;
}
# check for invalid date
if (not(check_date($year, $2, $1))) {
_a_err($rethash, 'gprmc_inv_date', "$year $2 $1");
return 0;
}
$month = $2 + 0; # force numeric
$day = $1 + 0;
} else {
_a_err($rethash, 'gprmc_inv_date');
return 0;
}
# Date_to_Time() can only handle 32-bit unix timestamps,
# so make sure it is not used for those years that
# are outside that range.
if ($year >= 2038 || $year < 1970) {
$rethash->{'timestamp'} = 0;
_a_err($rethash, 'gprmc_date_out', $year);
return 0;
} else {
$rethash->{'timestamp'} = Date_to_Time($year, $month, $day, $hour, $minute, $second);
}
# speed (knots) and course, make these optional
# in the parsing sense (don't fail if speed/course
# can't be decoded).
if ($nmeafields[7] =~ /^\s*(\d+(|\.\d+))\s*$/o) {
# convert to km/h
$rethash->{'speed'} = $1 * $knot_to_kmh;
}
if ($nmeafields[8] =~ /^\s*(\d+(|\.\d+))\s*$/o) {
# round to nearest integer
my $course = int($1 + 0.5);
# if zero, set to 360 because in APRS
# zero means invalid course...
if ($course == 0) {
$course = 360;
} elsif ($course > 360) {
$course = 0; # invalid
}
$rethash->{'course'} = $course;
} else {
$rethash->{'course'} = 0; # unknown
}
# latitude and longitude
my $latitude = _nmea_getlatlon($nmeafields[3], $nmeafields[4], $rethash);
if (not(defined($latitude))) {
return 0;
}
$rethash->{'latitude'} = $latitude;
my $longitude = _nmea_getlatlon($nmeafields[5], $nmeafields[6], $rethash);
if (not(defined($longitude))) {
return 0;
}
$rethash->{'longitude'} = $longitude;
# we have everything we want, return
return 1;
} elsif ($nmeafields[0] eq 'GPGGA') {
# we want at least 11 fields
if (@nmeafields < 11) {
_a_err($rethash, 'gpgga_fewfields', scalar(@nmeafields));
return 0;
}
# check for position validity
if ($nmeafields[6] =~ /^\s*(\d+)\s*$/o) {
if ($1 < 1) {
_a_err($rethash, 'gpgga_nofix', $1);
return 0;
}
} else {
_a_err($rethash, 'gpgga_nofix');
return 0;
}
# Use the APRS time parsing routines to check