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

Last change on this file since 288 was 288, checked in by smoser, 11 years ago

#156

  • Property svn:mime-type set to text/plain
File size: 7.6 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'});
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        }
156       
157        my $record = undef;
158        if (defined($options{'f'})) {
159                $record = <$flarm>;
160        } else {
161                until($record = $flarm->lookfor()) {
162                        sleep(1);
163                }
164        }
165        chomp($record);
166        return $record;
167}
168
169# as the name says
170sub exact_time {
171        return strftime("%H:%M:%S", localtime()) . "." . (gettimeofday())[1];
172}
173
174# send the records to the server. We don't make a request for each record for
175# performance reasons.
176sub flush {
177        my ($records, $url, $ua) = @_;
178        logit(DEBUG, exact_time() . " start flushing data to server");
179       
180        my $date = `date -u +%Y/%m/%d`;
181        chomp($date);
182        my $resturl = $url . "/" . $date;
183        logit(DEBUG, exact_time() . " request resource: " . $resturl);
184       
185        # compose the request
186        my $request = HTTP::Request->new('PUT');
187        $request->url($resturl);
188        $request->header('stationKey'=>$config{'key'});
189        my $content = compress($records);
190        logit(DEBUG, exact_time() . " put on wire: " . $content);
191        $request->content($content);
192       
193        # run the request
194        logit(DEBUG, exact_time() . " start server push");
195        my $response = $ua->request($request);
196        logit(DEBUG, exact_time() . " end server push");
197       
198        # analyze the response
199        my $code = $response->code;
200        $response->code == 200 || logit(DEBUG, "error processing records (" . $response->code . ") records=[" . $records . "]");
201        logit(DEBUG, exact_time() . " end flushing data");
202}
203
204# remove all unused records, debug information, etc.
205sub compress {
206        my ($records) = @_;
207        my $on_wire;
208        foreach my $record (split(';', $records)) {
209                if ($record =~ /^\$GPGGA,/ || $record =~ /^\$PFLAA,/) {
210                        $on_wire = (defined($on_wire)) ? $on_wire . ";" . $record : $record;
211                }               
212        }
213        return $on_wire;
214}
215
216
217
218#
219# here starts our main program
220#
221
222# parse options
223getopts('c:di:j:f:th', \%options);
224
225my $cfile;
226if (defined($options{'c'})) {
227        $cfile = $options{'c'};
228} elsif (-f "/etc/flarmclient.conf") {
229        $cfile = "/etc/flarmclient.conf";
230} else {
231        # last resort, search for a config file in the local directory
232        $cfile = "./flarmclient.conf";
233}
234
235# read config file
236die ("no config file found") unless (-f "$cfile");
237readconfig($cfile);
238
239if (defined($options{'d'})) {
240        $log_debug = 1;
241}
242if (defined($options{'i'})) {
243        $interval = $options{'i'};
244}
245if (defined($options{'j'})) {
246        $skip = $options{'j'}
247}
248if (defined($options{'h'})) {
249        usage();
250}
251if (defined($options{'t'})) {
252        $log_trace = 1;
253}
254
255# validation: key must be present in config file
256die("no key found in config file " . $cfile . " (option: key)") unless defined($config{'key'});
257
258# force a flush right away and after every write or print
259local $| = 1;
260
261# ok, everything is setup
262logit(OPS, "start client, connect to " . $config{'url'});
263
264# create UserAgent object
265my $ua = new LWP::UserAgent;
266
267my $buf;
268my $i = 0;
269while(my $record = readdata()) {
270       
271        # send only n-th sequence to the server (option -s). A sequence is terminated with a GPGGA-record
272        if ($i % $skip == 0) {
273                       
274                logit(TRACE, $record);
275                $buf = (defined($buf)) ? "$buf;$record" : $record;
276        }
277               
278        # a GPGGA record terminates the sequence
279        if ($record =~ /^\$GPGGA,/) {
280                if ($i % ($interval * $skip) == 0) {
281                        flush($buf, $config{'url'}, $ua) ;
282                        $buf = undef;
283                        sleep($interval * $skip) if (defined($options{'f'}));
284                }
285               
286                $i++;
287        }
288}
289exit 0;
290
291END {
292        logit(OPS, "client is shutting down");
293        if (exists($config{"log"})) {
294                close($log);
295        }
296        undef $ua;
297        undef $flarm;
298}
299
Note: See TracBrowser for help on using the repository browser.