source: core/trunk/client/flarmclient.pl @ 289

Last change on this file since 289 was 289, checked in by dominic, 11 years ago

Added Flarm Configuration at client startup

  • Property svn:mime-type set to text/plain
File size: 9.2 KB
Line 
1#!/usr/bin/perl
2#-------------------------------------------------------------------------------
3# This file is part of the FLARM¨-Radar Project.
4#   
5#   Copyright 2013 Netzschmiede GmbH (http://www.netzschmiede.ch)
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11#   http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19#   Project Website: www.flarmradar.ch
20#   Email: info@flarmradar.ch
21#-------------------------------------------------------------------------------
22
23use strict;
24use warnings;
25use Getopt::Std;
26use File::Basename;
27use Time::HiRes qw(gettimeofday);
28use POSIX qw(strftime);
29use POSIX qw(setsid);
30use LWP::UserAgent;
31use Device::SerialPort;
32use constant {
33        OPS => 0b001,
34        DEBUG => 0b010,
35        TRACE => 0b100
36};
37my %config;
38my %options;
39my $log;
40my $log_initialized = 0;
41my $flarm;
42
43# default values
44my $log_ops = 1;
45my $log_debug = 0;
46my $log_trace = 0;
47my $interval = 3;
48my $skip = 1;
49
50# signal handlers
51# toggle $log_trace with 'kill -USR1 <pid>'
52$SIG{USR1} = sub {
53        if ($log_trace) {
54                $log_trace = 0;
55        } else {
56                $log_trace = 1;
57        }
58};
59$SIG{INT} = sub {
60        die("terminate program");
61};
62
63# display a help page
64sub usage {
65  print <<EOF;
66NAME
67  $0 -- stream flarm records to server
68
69SYNOPSIS
70  $0 [-c config_file] [-d] [-f data_file] [-i n] [-j m] [-r] [-t] [-h]
71
72DESCRIPTION
73  The following options are available:
74 
75  -c    Use the specified configuration file. Use the default configuration
76                file as a starting point for customization.
77               
78  -d    Write out debug information
79                WARNING: If your configuration is to write the out put to a file (see
80                option 'log') then this might fill up the file system.                 
81               
82  -f    Read the data from the specified data file instead of the serial
83                device. This is mainly used for testing and development.
84
85  -i    Bundle records, send a request to the server every i-th GPGGA record.
86                Used for bandwidth optimization. Defaults to 3.
87               
88  -j    Send every j-th record to the server. Used for bandwidth
89                optimization. Defaults to 1.
90               
91  -t    Trace client operations, write out all data read from the flarm device
92                WARNING: If your configuration is to write the out put to a file (see
93                option 'log') then this might fill up the file system.
94               
95  -h    Print this help.
96
97EOF
98  exit 0;
99}
100
101# a very basic logger
102sub logit {
103        my ($aspect, $msg) = @_;
104       
105        if (!$log_initialized) {
106                if (exists($config{'log'})) {
107                        open($log, ">> $config{'log'}") || die("Failed to open log file $config{'log'}: $!");
108                } else {
109                        $log = *STDOUT;
110                }
111                $log_initialized = 1;
112        }
113        print $log "$msg\n" if (($aspect & OPS) && $log_ops);
114        print $log "$msg\n" if (($aspect & TRACE) && $log_trace);
115        print $log "$msg\n" if (($aspect & DEBUG) && $log_debug);
116}
117
118# read config file
119sub readconfig {
120        my ($config_file) = @_;
121        open(CONF, "< $config_file") || die("failed to open config file for reading: $!");
122        while(my $line = <CONF>) {
123                chomp($line);
124                next if $line =~ /^\s*#/;
125                next if $line =~ /^\s*$/;
126                if ($line =~ /^\s*(\S*)\s*=\s*(\S*)\s*$/) {
127                        $config{$1} = $2;
128                }
129        }
130        close(CONF);
131}
132
133# abstraction for reading data (from flarm device or from file)
134sub readdata {
135        unless (defined($flarm)) {
136                # initialize our flarm object
137                if (defined($options{'f'})) {
138                        logit(OPS, "read flarm data from file " . $options{'f'});
139                        open($flarm, "< $options{'f'}") || die("failed to open flarm data file for reading: $!");
140                } else {
141                        # check that we have the required configuration options
142                        die("missing option 'serial_device' in configuration file") unless (defined($config{'serial_device'}));
143                        die("device does not exist: " . $config{'serial_device'}) unless (-c $config{'serial_device'});
144                        die("missing option 'baud' in configuration file") unless (defined($config{'baud'}));
145                       
146                        # create serial device object
147                        logit(OPS, "read flarm data from " . $config{'serial_device'} . " with baud=" . $config{'baud'});
148                        $flarm = new Device::SerialPort ($config{'serial_device'}) || die "Can't open $config{'serial_device'}!\n";
149                        $flarm->baudrate($config{'baud'});
150                        $flarm->parity("none");
151                        $flarm->databits(8);
152                        $flarm->stopbits(1);
153                        $flarm->are_match("\r\n");
154                       
155                        # === BEGIN Flarm Config ===
156                        my $cmd = undef;
157                        # ACFT = Type of aircraft: unknown
158                        # NMEAOUT = Send all data incl. Flarm propriatery data: 1
159                        # UI = Disable buzzer, enable led warnings: 3
160                        # PRIV = Disable stealth mode: 0
161                        # THRE = Threshold for aircraft on ground is 2 m/s: 2
162                        # Range = Set detection range of aircraft to maximum: 25500
163                        my @item = ("\$PFLAC,S,ACFT,0\r\n","\$PFLAC,S,NMEAOUT,1\r\n","\$PFLAC,S,UI,3\r\n",
164                                    "\$PFLAC,S,PRIV,0\r\n","\$PFLAC,S,THRE,2\r\n","\$PFLAC,S,RANGE,25500\r\n");
165                       
166                        foreach $cmd (@item) {
167                                local $/ = "\r\n";
168                                # Read data back from Flarm
169                                my $continue = 1;
170                                my $record = undef;
171                                               
172                                while ($continue) {
173                                        $record = $flarm->lookfor();
174                                        if (length($record)) {
175                                                my ($fanswer,$checksum) = split('\*',$record);
176                                                undef $checksum;
177                                                my $cmd2 = $cmd;
178                                                $cmd2 =~ s/,S,/,A,/g;
179                                                chomp($cmd2);
180                                                # print $cmd2 . "\n";
181                                                if ($fanswer ~~ $cmd2) {
182                                                        # print "Setting accepted by Flarm: " . $cmd2 . "\n";
183                                                        logit(OPS, "Setting accepted by Flarm: " . $cmd2);
184                                                        $continue = 0;
185                                                } else {
186                                                        my $cmd3 = $cmd;
187                                                        chomp($cmd3);
188                                                        logit(OPS, "Send Flarm config command " . $cmd3);
189                                                        my $count_out = $flarm->write($cmd);
190                                                        warn "write failed\n" unless ($count_out);
191                                                        warn "write incomplete\n" if ( $count_out != length($cmd) );
192                                                } #else
193                                        } #endif
194                                } #while
195                        } #foreach
196                        undef $cmd;
197                        undef @item;
198                        # === END Flarm Config ===
199                }
200        }
201       
202        my $record = undef;
203        if (defined($options{'f'})) {
204                $record = <$flarm>;
205        } else {
206                until($record = $flarm->lookfor()) {
207                        sleep(1);
208                }
209        }
210        chomp($record);
211        return $record;
212}
213
214# as the name says
215sub exact_time {
216        return strftime("%H:%M:%S", localtime()) . "." . (gettimeofday())[1];
217}
218
219# send the records to the server. We don't make a request for each record for
220# performance reasons.
221sub flush {
222        my ($records, $url, $ua) = @_;
223        logit(DEBUG, exact_time() . " start flushing data to server");
224       
225        my $date = `date -u +%Y/%m/%d`;
226        chomp($date);
227        my $resturl = $url . "/" . $date;
228        logit(DEBUG, exact_time() . " request resource: " . $resturl);
229       
230        # compose the request
231        my $request = HTTP::Request->new('PUT');
232        $request->url($resturl);
233        $request->header('stationKey'=>$config{'key'});
234        my $content = compress($records);
235        logit(DEBUG, exact_time() . " put on wire: " . $content);
236        $request->content($content);
237       
238        # run the request
239        logit(DEBUG, exact_time() . " start server push");
240        my $response = $ua->request($request);
241        logit(DEBUG, exact_time() . " end server push");
242       
243        # analyze the response
244        my $code = $response->code;
245        $response->code == 200 || logit(DEBUG, "error processing records (" . $response->code . ") records=[" . $records . "]");
246        logit(DEBUG, exact_time() . " end flushing data");
247}
248
249# remove all unused records, debug information, etc.
250sub compress {
251        my ($records) = @_;
252        my $on_wire;
253        foreach my $record (split(';', $records)) {
254                if ($record =~ /^\$GPGGA,/ || $record =~ /^\$PFLAA,/) {
255                        $on_wire = (defined($on_wire)) ? $on_wire . ";" . $record : $record;
256                }               
257        }
258        return $on_wire;
259}
260
261#
262# here starts our main program
263#
264
265# parse options
266getopts('c:di:j:f:th', \%options);
267
268my $cfile;
269if (defined($options{'c'})) {
270        $cfile = $options{'c'};
271} elsif (-f "/etc/flarmclient.conf") {
272        $cfile = "/etc/flarmclient.conf";
273} else {
274        # last resort, search for a config file in the local directory
275        $cfile = "./flarmclient.conf";
276}
277
278# read config file
279die ("no config file found") unless (-f "$cfile");
280readconfig($cfile);
281
282if (defined($options{'d'})) {
283        $log_debug = 1;
284}
285if (defined($options{'i'})) {
286        $interval = $options{'i'};
287}
288if (defined($options{'j'})) {
289        $skip = $options{'j'}
290}
291if (defined($options{'h'})) {
292        usage();
293}
294if (defined($options{'t'})) {
295        $log_trace = 1;
296}
297
298# validation: key must be present in config file
299die("no key found in config file " . $cfile . " (option: key)") unless defined($config{'key'});
300
301# force a flush right away and after every write or print
302local $| = 1;
303
304# ok, everything is setup
305logit(OPS, "start client, connect to " . $config{'url'});
306
307# create UserAgent object
308my $ua = new LWP::UserAgent;
309
310my $buf;
311my $i = 0;
312
313# Configure Flarm device
314# flarmconfig();
315
316while(my $record = readdata()) {
317       
318        # send only n-th sequence to the server (option -s). A sequence is terminated with a GPGGA-record
319        if ($i % $skip == 0) {
320                       
321                logit(TRACE, $record);
322                $buf = (defined($buf)) ? "$buf;$record" : $record;
323        }
324               
325        # a GPGGA record terminates the sequence
326        if ($record =~ /^\$GPGGA,/) {
327                if ($i % ($interval * $skip) == 0) {
328                        flush($buf, $config{'url'}, $ua) ;
329                        $buf = undef;
330                        sleep($interval * $skip) if (defined($options{'f'}));
331                }
332               
333                $i++;
334        }
335}
336exit 0;
337
338END {
339        logit(OPS, "client is shutting down");
340        if (exists($config{"log"})) {
341                close($log);
342        }
343        undef $ua;
344        undef $flarm;
345}
346
Note: See TracBrowser for help on using the repository browser.