#------------------------------------------------------------------------------- # This file is part of the FLARM®-Radar Project. # # Copyright 2012-2014 Simon Moser # Copyright 2013-2014 Dominic Spreitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Project Website: www.flarmradar.ch # Email: info@flarmradar.ch #------------------------------------------------------------------------------- #!/usr/bin/perl #------------------------------------------------------------------------------- # This file is part of the FLARM�-Radar Project. # # Copyright 2013 Netzschmiede GmbH (http://www.netzschmiede.ch) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Project Website: www.flarmradar.ch # Email: info@flarmradar.ch #------------------------------------------------------------------------------- use strict; use warnings; use Getopt::Std; use File::Basename; use Time::HiRes qw(gettimeofday); use POSIX qw(strftime); use POSIX qw(setsid); use LWP::UserAgent; use Device::SerialPort; # constants use constant { OPS => 0b001, DEBUG => 0b010, TRACE => 0b100 }; # FIXME: increas that value my $MAX_READ_OP = 10000; # variables my %config; my %options; my $log; my $log_initialized = 0; #device initialization disabled temporarily my $flarm_initialized = 1; my $read_cnt = 0; my $flarm; # defaults my $log_ops = 1; my $log_debug = 0; my $log_trace = 0; my $interval = 3; my $skip = 1; # signal handlers # toggle $log_trace with 'kill -USR1 ' $SIG{USR1} = sub { if ($log_trace) { $log_trace = 0; } else { $log_trace = 1; } }; $SIG{INT} = sub { die("terminate program"); }; # display a help page sub usage { print <> $config{'log'}") || die("Failed to open log file $config{'log'}: $!"); select($log); $| = 1; } else { $log = *STDOUT; } $log_initialized = 1; } print $log "$msg\n" if (($aspect & OPS) && $log_ops); print $log "$msg\n" if (($aspect & TRACE) && $log_trace); print $log "$msg\n" if (($aspect & DEBUG) && $log_debug); } # read config file sub readconfig { my ($config_file) = @_; open(CONF, "< $config_file") || die("failed to open config file for reading: $!"); while(my $line = ) { chomp($line); next if $line =~ /^\s*#/; next if $line =~ /^\s*$/; if ($line =~ /^\s*(\S*)\s*=\s*(\S*)\s*$/) { $config{$1} = $2; } } close(CONF); } # send a command to the flarm, optionally wait for the expected answer sub send_flarm_cmd { my ($cmd, $expected_answer) = @_; } # initialize a flarm device, this routine is called during # bootstrap only sub initialize_device { # === BEGIN Flarm Config === my $cmd = undef; # ACFT = Type of aircraft: unknown # NMEAOUT = Send all data incl. Flarm propriatery data: 1 # UI = Disable buzzer, enable led warnings: 3 # PRIV = Disable stealth mode: 0 # THRE = Threshold for aircraft on ground is 2 m/s: 2 # RANGE = Set detection range of aircraft to maximum: 25500 # DEBUG = Removes height restrictions my @item = ("\$PFLAC,S,ACFT,0\r\n","\$PFLAC,S,NMEAOUT,1\r\n","\$PFLAC,S,UI,3\r\n", "\$PFLAC,S,PRIV,0\r\n","\$PFLAC,S,THRE,2\r\n","\$PFLAC,S,RANGE,25500\r\n", "\$PFLAC,S,DEBUG,9\r\n"); foreach $cmd (@item) { local $/ = "\r\n"; # Read data back from Flarm my $continue = 1; my $record = undef; while ($continue) { $record = $flarm->lookfor(); if (length($record)) { my ($fanswer,$checksum) = split('\*',$record); undef $checksum; my $cmd2 = uc($cmd); $cmd2 =~ s/,S,/,A,/g; chomp($cmd2); # print $cmd2 . "\n"; if ($fanswer ~~ $cmd2) { # print "Setting accepted by Flarm: " . $cmd2 . "\n"; logit(OPS, "Setting accepted by Flarm: " . $cmd2); $continue = 0; } else { my $cmd3 = $cmd; chomp($cmd3); logit(OPS, "Send Flarm config command " . $cmd3); my $count_out = $flarm->write($cmd); warn "write failed\n" unless ($count_out); warn "write incomplete\n" if ( $count_out != length($cmd) ); } #else } #endif } #while } #foreach undef $cmd; undef @item; # === END Flarm Config === $flarm_initialized = 1; } # abstraction for reading data (from flarm device or from file) sub readdata { unless (defined($flarm)) { # initialize our flarm object if (defined($options{'f'})) { logit(OPS, "read flarm data from file " . $options{'f'}); open($flarm, "< $options{'f'}") || die("failed to open flarm data file for reading: $!"); } else { # check that we have the required configuration options die("missing option 'serial_device' in configuration file") unless (defined($config{'serial_device'})); die("device does not exist: " . $config{'serial_device'}) unless (-c $config{'serial_device'}); die("missing option 'baud' in configuration file") unless (defined($config{'baud'})); # create serial device object logit(OPS, "initialize serial port reader on device=" . $config{'serial_device'} . " with baud=" . $config{'baud'}); $flarm = new Device::SerialPort ($config{'serial_device'}) || die "Can't open $config{'serial_device'}!\n"; $flarm->baudrate($config{'baud'}); $flarm->parity("none"); $flarm->databits(8); $flarm->stopbits(1); $flarm->are_match("\r\n"); initialize_device() unless ($flarm_initialized); } } # read data my $record = undef; if (defined($options{'f'})) { $record = <$flarm>; } else { my $read_start = exact_time("%s"); until($record = $flarm->lookfor()) { logit(DEBUG, exact_time() . " wait for data from flarm device"); sleep(1); $read_start = exact_time("%s"); } my $read_duration = exact_time("%s") - $read_start; logit(DEBUG, "read duration=" . $read_duration); $flarm = undef if ($read_duration > 0.5); # pro-active workaround to prevent failures during continuous operation $read_cnt++; if ($read_cnt >= $MAX_READ_OP) { logit(DEBUG, exact_time() . " reset serial port reader"); $flarm = undef; $read_cnt = 0; } } chomp($record); return $record; } # as the name says sub exact_time { my ($format) = @_; $format = "%H:%M:%S" unless defined($format); return strftime($format, localtime()) . "." . (gettimeofday())[1]; } # send the records to the server. We don't make a request for each record for # performance reasons. sub flush { my ($records, $url, $ua) = @_; logit(DEBUG, exact_time() . " start flushing data to server"); my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); my $date= sprintf("%04d", ($year + 1900))."/".sprintf("%02d", ($mon + 1))."/".sprintf("%02d", $mday); my $resturl = $url . "/" . $date; logit(DEBUG, exact_time() . " request resource: " . $resturl); # compose the request my $request = HTTP::Request->new('PUT'); $request->url($resturl); $request->header('stationKey'=>$config{'key'}); my $content = compress($records); logit(DEBUG, exact_time() . " put on wire: " . $content); $request->content($content); # run the request logit(DEBUG, exact_time() . " start server push"); my $response = $ua->request($request); logit(DEBUG, exact_time() . " end server push"); # analyze the response my $code = $response->code; $response->code == 200 || logit(DEBUG, "error processing records (" . $response->code . ") records=[" . $records . "]"); logit(DEBUG, exact_time() . " end flushing data"); } # remove all unused records, debug information, etc. sub compress { my ($records) = @_; my $on_wire; foreach my $record (split(';', $records)) { if ($record =~ /^\$GPGGA,/ || $record =~ /^\$PFLAA,/) { $on_wire = (defined($on_wire)) ? $on_wire . ";" . $record : $record; } } return $on_wire; } # # here starts our main program # # parse options getopts('c:di:j:f:th', \%options); my $cfile; if (defined($options{'c'})) { $cfile = $options{'c'}; } elsif (-f "/etc/flarmclient.conf") { $cfile = "/etc/flarmclient.conf"; } else { # last resort, search for a config file in the local directory $cfile = "./flarmclient.conf"; } # read config file die ("no config file found") unless (-f "$cfile"); readconfig($cfile); if (defined($options{'d'})) { $log_debug = 1; } if (defined($options{'i'})) { $interval = $options{'i'}; } if (defined($options{'j'})) { $skip = $options{'j'} } if (defined($options{'h'})) { usage(); } if (defined($options{'t'})) { $log_trace = 1; } # validation: key must be present in config file die("no key found in config file " . $cfile . " (option: key)") unless defined($config{'key'}); # force a flush right away and after every write or print local $| = 1; # ok, everything is setup logit(OPS, "start client, connect to " . $config{'url'}); # create UserAgent object my $ua = new LWP::UserAgent; my $buf; my $i = 0; while(my $record = readdata()) { # send only n-th sequence to the server (option -s). A sequence is terminated with a GPGGA-record if ($i % $skip == 0) { logit(TRACE, $record); $buf = (defined($buf)) ? "$buf;$record" : $record; } # a GPGGA record terminates the sequence if ($record =~ /^\$GPGGA,/) { if ($i % ($interval * $skip) == 0) { flush($buf, $config{'url'}, $ua) ; $buf = undef; if (defined($options{'f'})) { sleep($interval * $skip) } elsif ($i > $MAX_READ_OP) { # force a re-initialization $i = 0; $flarm = undef; } } else { $i++; } } } exit 0; END { logit(OPS, "client is shutting down"); if (exists($config{"log"})) { close($log); } undef $ua; undef $flarm; }