2 # various utilities which are exported globally
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
16 use Time::HiRes qw(gettimeofday tv_interval);
21 use vars qw(@month %patmap $pi $d2r $r2d @ISA @EXPORT);
25 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf
26 parray parraypairs phex phash shellregex readfilestr writefilestr
28 print_all_fields cltounix unpad is_callsign is_latlong
29 is_qra is_freq is_digits is_pctext is_pcflag insertitem deleteitem
30 is_prefix dd is_ipaddr $pi $d2r $r2d localdata localdata_mv
31 diffms _diffms _diffus difft parraydifft is_ztime basecall
35 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
48 # a full time for logging and other purposes
52 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
54 my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
58 # get a zulu time in cluster format (2300Z)
62 $t = defined $t ? $t : time;
64 my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
65 my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
69 # get a cluster format date (23-Jun-1998)
73 $t = defined $t ? $t : time;
75 my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
77 my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
81 # return a cluster style date time
86 my $date = cldate($t, $dst);
87 my $time = ztime($t, $dst);
91 # return a unix date from a cluster date and time
96 my ($thisyear) = (gmtime)[5] + 1900;
98 return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
99 return 0 if $3 > 2036;
100 return 0 unless abs($thisyear-$3) <= 1;
102 return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
103 $time = "$1:$2 +0000";
104 my $r = str2time("$date $time");
106 return $r == -1 ? undef : $r;
109 # turn a latitude in degrees into a string
113 my ($deg, $min, $let);
114 $let = $n >= 0 ? 'N' : 'S';
117 $min = int ((($n - $deg) * 60) + 0.5);
118 return "$deg $min $let";
121 # turn a longitude in degrees into a string
125 my ($deg, $min, $let);
126 $let = $n >= 0 ? 'E' : 'W';
129 $min = int ((($n - $deg) * 60) + 0.5);
130 return "$deg $min $let";
133 # turn a true into 'yes' and false into 'no'
137 return $n ? $main::yes : $main::no;
140 # provide a data dumpered version of the object passed
144 my $dd = new Data::Dumper([$value]);
147 $dd->Quotekeys($] < 5.005 ? 1 : 0);
148 $value = $dd->Dumpxs;
149 $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
150 $value =~ s/^\s*\[//;
151 $value =~ s/\]\s*$//;
156 # format a prompt with its current value and return it with its privilege
159 my ($line, $value, $promptl) = @_;
160 my ($priv, $prompt, $action) = split ',', $line;
162 # if there is an action treat it as a subroutine and replace $value
164 my $q = qq{\$value = $action(\$value)};
166 } elsif (ref $value) {
170 $prompt = sprintf "%${promptl}s: %s", $prompt, $value;
171 return ($priv, $prompt);
174 # turn a hex field into printed hex
178 return sprintf '%X', $val;
181 # take an arg as a hash of call=>time pairs and print it
186 for (sort keys %$ref) {
187 $out .= "$_=" . atime($ref->{$_}) . ", ";
194 # take an arg as an array list and print it
198 return ref $ref ? join(', ', sort @{$ref}) : $ref;
201 # take the arg as an array reference and print as a list of pairs
208 for ($i = 0; $i < @$ref; $i += 2) {
210 my $r2 = @$ref[$i+1];
213 chop $out; # remove last space
214 chop $out; # remove last comma
218 # take the arg as a hash reference and print it out as such
224 while (my $k = sort keys %$ref) {
225 $out .= "${k}=>$ref->{$k}, ";
227 $out =~ s/, $// if $out;
234 my @a = split /,/, $ref->field_prompt(shift);
235 my @b = split /,/, $ref->field_prompt(shift);
236 return lc $a[1] cmp lc $b[1];
239 # print all the fields for a record according to privilege
241 # The prompt record is of the format '<priv>,<prompt>[,<action>'
242 # and is expanded by promptf above
246 my $self = shift; # is a dxchan
247 my $ref = shift; # is a thingy with field_prompt and fields methods defined
249 my @fields = $ref->fields;
251 my $width = $self->width - 1;
255 # find the maximum length of the prompt
256 foreach $field (@fields) {
257 if (defined $ref->{$field}) {
258 my (undef, $prompt, undef) = split ',', $ref->field_prompt($field);
259 $promptl = length $prompt if length $prompt > $promptl;
264 foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
265 if (defined $ref->{$field}) {
266 my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field}, $promptl);
268 if (length $ans > $width) {
269 $Text::Wrap::columns = $width-2;
270 my ($p, $a) = split /: /, $ans, 2;
271 @tmp = split/\n/, Text::Wrap::wrap("$p: ", (' ' x $promptl) . ': ', $a);
275 push @out, @tmp if ($self->priv >= $priv);
281 # generate a regex from a shell type expression
282 # see 'perl cookbook' 6.9
286 $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
288 return '^' . $in . "\$";
291 # read in a file into a string and return it.
292 # the filename can be split into a dir and file and the
293 # file can be in upper or lower case.
294 # there can also be a suffix
297 my ($dir, $file, $suffix) = @_;
302 $fn = "$dir/$f.$suffix";
305 $fn = "$dir/$file.$suffix";
318 my $fh = new IO::File $fn;
328 # write out a file in the format required for reading
329 # in via readfilestr, it expects the same arguments
330 # and a reference to an object
340 confess('no object to write in writefilestr') unless $obj;
341 confess('object not a reference in writefilestr') unless ref $obj;
345 $fn = "$dir/$f.$suffix";
348 $fn = "$dir/$file.$suffix";
361 my $fh = new IO::File ">$fn";
363 my $dd = new Data::Dumper([ $obj ]);
367 # $fh->print(@_) if @_ > 0; # any header comments, lines etc
368 $fh->print($dd->Dumpxs);
375 copy(@_) or return $!;
378 # remove leading and trailing spaces from an input string
387 # check that a field only has callsign characters in it
391 (?:\d?[A-Z]{1,2}\d{0,2}/)? # out of area prefix /
392 (?:\d?[A-Z]{1,2}\d{1,5}) # main prefix one (required) - lengthened for special calls
393 [A-Z]{1,8} # callsign letters (required)
394 (?:-(?:\d{1,2}))? # - nn possibly (eg G8BPQ-8)
395 (?:/[0-9A-Z]{1,7})? # / another prefix, callsign or special label (including /MM, /P as well as /EURO or /LGT) possibly
396 (?:/(?:AM?|MM?|P))? # finally /A /AM /M /MM /P
399 # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX/MM
404 return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x # basic prefix
408 # check that a PC protocol field is valid text
411 return undef unless length $_[0];
412 return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
416 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
419 return $_[0] =~ /^[01\*\-]+$/;
422 # check that a thing is a frequency
425 return $_[0] =~ /^\d+(?:\.\d+)?$/;
428 # check that a thing is just digits
431 return $_[0] =~ /^[\d]+$/;
434 # does it look like a qra locator?
437 return unless length $_[0] == 4 || length $_[0] == 6;
438 return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d(?:[A-Xa-x][A-Xa-x])?$/;
441 # does it look like a valid lat/long
444 return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
447 # is it an ip address?
450 return $_[0] =~ /^\d+\.\d+\.\d+\.\d+$/ || $_[0] =~ /^[0-9a-f:,]+$/;
453 # is it a zulu time hhmmZ
456 return $_[0] =~ /^(?:(?:2[0-3])|(?:[01][0-9]))[0-5][0-9]Z$/;
459 # insert an item into a list if it isn't already there returns 1 if there 0 if not
465 return 1 if grep {$_ eq $item } @$list;
470 # delete an item from a list if it is there returns no deleted
477 @$list = grep {$_ ne $item } @$list;
481 # find the correct local_data directory
482 # basically, if there is a local_data directory with this filename and it is younger than the
483 # equivalent one in the (system) data directory then return that name rather than the system one
487 my $lfn = "$main::local_data/$ifn";
488 my $dfn = "$main::data/$ifn";
490 if (-e "$main::local_data") {
491 if ((-e $dfn) && (-e $lfn)) {
492 $lfn = $dfn if -M $dfn < -M $lfn;
494 $lfn = $dfn if -e $dfn;
503 # move a file or a directory from data -> local_data if isn't there already
507 if (-e "$main::data/$ifn" ) {
508 unless (-e "$main::local_data/$ifn") {
509 move("$main::data/$ifn", "$main::local_data/$ifn") or die "localdata_mv: cannot move $ifn from '$main::data' -> '$main::local_data' $!\n";
514 # measure the time taken for something to happen; use Time::HiRes qw(gettimeofday tv_interval);
518 my $tb = shift || [gettimeofday];
519 my $a = int($ta->[0] * 1000) + int($ta->[1] / 1000);
520 my $b = int($tb->[0] * 1000) + int($tb->[1] / 1000);
524 # and in microseconds
528 my $tb = shift || [gettimeofday];
529 my $a = int($ta->[0] * 1000000) + int($ta->[1]);
530 my $b = int($tb->[0] * 1000000) + int($tb->[1]);
541 my $msecs = _diffms($ta, $tb);
544 my $s = "subprocess stats cmd: '$line' $call ${msecs}mS";
545 $s .= " $no lines" if $no;
549 # expects either an array reference or two times (in the correct order [start, end])
556 if (ref $b eq 'ARRAY') {
557 $t = $b->[1] - $b->[0];
559 if ($adds && $adds =~ /^\d+$/ && $adds >= $b) {
563 $t = $main::systime - $b;
566 return '-(ve)' if $t < 0;
570 $out .= sprintf ("%s${d}d", $adds?' ':'') if $d;
573 $out .= sprintf ("%s${h}h", $adds?' ':'') if $h;
576 $out .= sprintf ("%s${m}m", $adds?' ':'') if $m;
577 if ($d == 0 && $adds || $adds == 2) {
579 $out .= sprintf ("%s${s}s", $adds?' ':'') if $s;
580 $out ||= sprintf ("%s0s", $adds?' ':'');
582 $out = '0s' unless length $out;
586 # print an array ref of difft refs
592 my $s = $_->[2] ? "($_->[2])" : '';
593 $out .= sprintf "%s=%s$s, ", atime($_->[0]), difft($_->[0], $_->[1]);
601 my ($r) = $_[0] =~ m|^(?:[\w\d]+/)?([\w\d]+).*$|;