Subversion Repositories HomeAutomation

Rev

Rev 681 | Details | Compare with Previous | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
626 arune 1
#!/usr/bin/perl
2
 
681 arune 3
# 
4
# for use with serial ports, install module with apt-get install libdevice-serialport-perl
5
# 
6
# 
7
# 
626 arune 8
 
681 arune 9
 
626 arune 10
$hubport = 1200;
11
#$udpip = "193.11.254.22";
12
#$udpport = 1100;
13
 
14
 
15
require 5.002;
16
use IO::Socket;
17
use IO::Select;
18
use threads;
19
use Getopt::Long;
20
 
21
$binaryname = "canDaemon.pl";
22
if ( @ARGV > 0 ) {
23
    GetOptions( "baudrate=i"    => \$baudarg,   #
24
            "server=s"  => \$serverarg,         #
25
            "port=i"    => \$portarg,           #
26
            "tcpport=i" => \$tcpportarg,        #
27
            "device=s"  => \$devicearg,         #
28
            "help"      => \$help,              #
29
                        );
681 arune 30
} else {
31
    $help = 1;
626 arune 32
}
681 arune 33
 
626 arune 34
if ($help) {
35
    print "Usage ./$binaryname [options]\n";
36
    print "Options:\n";
37
    print "  -d <device> (udp or /dev/ttyXYZ)       Choose hardware for communication\n";
38
    print "  -b <baudrate>              Baudrate, for serial devices\n";
39
    print "  -s <server>                    Server, for udp devices\n";
40
    print "  -p <port>                  Port, for udp devices\n";
41
    print "  -t <tcpport>                   Port, for tcp server (default 1200)\n";
42
    print "  -h <help>                  Shows this usage\n";
43
    print "\n";
44
    print "example: ./$binaryname -d /dev/ttyUSB0 -b 38400\n";
45
    print "example: ./$binaryname -d udp -s 192.168.0.10 -p 1100\n";
46
 
47
    exit 0;
48
}
49
if ($serverarg) {
50
    $udpip = $serverarg;
51
}
52
#print $udpip;
53
if ($portarg) {
54
    $udpport = $portarg;
55
}
56
if ($tcpportarg) {
57
    $hubport = $tcpportarg;
58
}
59
 
60
$C2SSTARTSTR = 253;
61
$C2SENDSTR = 250;
62
 
63
### create a tcp server ###
64
$linelength=1000;
65
&tcpServerInit;
66
$thr = threads->new(\&tcpServerThread);
67
$thr->detach;
68
 
69
### create a connection to hardware ###
70
if ($devicearg) {
71
    if ($devicearg =~ m/^udp$/) {
72
        ### if the hardware is an udp node ###
73
        &udpServerInit;
74
        $thr = threads->new(\&udpServerThread);
75
        $thr->detach;
76
    }
77
    ### else, the hardware is serial, check for device, this might not work in windows ###
78
#   elsif (-e $devicearg) {
650 arune 79
    else {
626 arune 80
        if (!$baudarg) {
81
            print "For a serial device you need to specifiy baudrate, now using default 19200\n";
82
            $baudarg = 19200;
83
        }
633 arune 84
 
85
        eval 'use Device::SerialPort';      ### install module with aptitude install libdevice-serialport-perl
86
        if ($@) {
87
            eval 'use Win32::SerialPort';
88
            if ($@) {
89
                print "Could not find Device::SerialPort or Win32::SerialPort, I quit.\n";
90
                exit 0;
91
            } else {
92
                $usingWin32Serial = 1;
93
            }
94
        } else {
95
            $usingDeviceSerial = 1;
96
        }
97
 
626 arune 98
        &serialConnInit;
99
        $thr = threads->new(\&serialConnThread);
100
        $thr->detach;      
650 arune 101
    }
626 arune 102
#   } else {
103
#       print "Argument $devicearg is not correct\n";
104
#       exit 0;
105
#   }
106
}
107
 
108
### loop here until user aborts with ctrl+c ###
109
while (1) { sleep 1; }
110
 
111
 
112
##################### Hardware connection to TCP HUB ############################
113
sub hardwareConnThread {
114
    ### Check for data from HUB ###
115
    while ( $newmsg = <$hwCremote> ) {
116
        ### Convert to can2serial format ### 
117
        &stringToc2s($newmsg, $retstring);
118
        if ($retstring) {
119
            #print length($retstring)."\n";
120
            #&c2sToString($retstring, $newretstring);
121
            #print "TO SEND: ".$newretstring."\n";
122
            #print $udpCsocket $retstring;
123
 
124
            ### Send data ###
125
            if (length($hardwareSendFunction) > 0) {
126
                &{$hardwareSendFunction}($retstring);
127
            }
128
 
129
        }
130
    }  
131
}
132
 
133
sub hardwareConnInit {
134
    print "Connecting hardware to tcpServer\n";
135
    $hwCremote = IO::Socket::INET->new(Proto    => "tcp", PeerAddr => "localhost", PeerPort => $hubport,)
136
                  or die "cannot connect to $hubport port at localhost";
137
}
138
 
139
##################### Serial Connection ############################
140
sub serialConnThread {
141
    $serialBuffer = "";
142
    while(1) {
143
        my ($count,$saw)=$serialPort->read(1); # will read _up to_ 1 chars
144
        if ($count > 0) {
145
            $serialBuffer.=$saw;
146
            serialConnProcessBuffer($serialBuffer);
147
        }
148
    }
149
}
150
 
151
sub serialConnProcessBuffer {
152
    my $input = $_[0];
153
    my $output = $input;
154
    my $newmsg;
155
    my $retstring;
156
 
157
    ### Cut all leading chars that is not a start-char ###
158
    for ($i = 0; $i < length($input); $i++) {
159
        if (ord(substr($input, $i, 1)) == $C2SSTARTSTR) {
160
            $input = substr($input, $i);
161
            break;
162
        }
163
    }
164
    ### Check for possible complete packets ###
165
    for ($i = 0; $i < length($input)-16; $i++) {
166
        my $newmsg = substr($input, $i, 17);
167
        $retstring = "";
168
        &c2sToString($newmsg, $retstring);
169
        if (length($retstring)>0) {
170
            if ($hwCremote) {
171
                ### Send to tcp hub ###
172
                print $hwCremote $retstring . "\n";
173
            }
174
            #print $retstring."\n";
175
            $output = substr($input, $i+17);
176
            $i+=16;
177
        }
178
    }
179
 
180
    ### Store modified buffer ###
181
    $_[0] = $output;
182
}
183
 
184
sub serialConnInit {
185
    print "Connecting to hardware over serial port\n";
186
    $quiet=0;
633 arune 187
    if ($usingDeviceSerial == 1) {
188
        $serialPort = new Device::SerialPort($devicearg, $quiet) || die "failed to open serial port, $devicearg is not valid?";
189
    } elsif ($usingWin32Serial == 1) {
190
        $serialPort = new Win32::SerialPort($devicearg, $quiet) || die "failed to open serial port, $devicearg is not valid?";
191
    }
626 arune 192
    $serialPort->databits(8)            || die "failed setting databits";
193
    $serialPort->baudrate($baudarg)     || die "failed setting baudrate";
194
    $serialPort->parity("none")         || die "failed setting parity";
195
    $serialPort->stopbits(1)            || die "failed setting stopbits";
196
    $serialPort->handshake("none")      || die "failed setting handshake";
197
    $serialPort->write_settings         || die "no settings";
198
 
199
    $serialPort->read_char_time(0);     # don't wait for each character
200
    $serialPort->read_const_time(1000); # 1 second per unfulfilled "read" call
201
 
202
    ### create a connection between the hardware and the tcp-server ###
203
    &hardwareConnInit;
204
    $hardwareSendFunction = "serialConnSend";       ### set up callback for a 'send data' function
205
    $thr = threads->new(\&hardwareConnThread);
206
    $thr->detach;
207
}
208
 
209
sub serialConnSend {
210
    $cnt = $serialPort->write($_[0]);
211
}
212
 
213
##################### UDP Connection ############################
214
sub udpServerThread {
215
    $MAXLEN = 1024;
216
    my $newmsg;
217
    my $retstring;
218
    while ($udpSsocket->recv($newmsg, $MAXLEN)) {
219
        my($udpport, $ipaddr) = sockaddr_in($udpSsocket->peername);
220
        $peer_addr = inet_ntoa($ipaddr);
221
 
222
        ### check ipaddr to ip in commandlinearg ###
223
        if ($udpip == $peer_addr) {
224
            #check len of incomming data
225
            if (length($newmsg) > 16 && length($newmsg) < 20) {
226
                $retstring = "";
227
                &c2sToString($newmsg, $retstring);
228
                if (length($retstring) > 0 && $hwCremote) {
229
                    print $hwCremote $retstring . "\n";
230
                }
231
            }
232
        }
233
    }
234
 
235
}
236
 
237
sub udpServerInit {
238
    print "Starting udpServer\n";
239
    $udpSsocket = IO::Socket::INET->new(LocalPort => $udpport, Proto => 'udp')
240
        or die "socket: $@";
241
 
242
    $udpCsocket = IO::Socket::INET->new(PeerPort => $udpport, Proto => 'udp', PeerAddr => $udpip)
243
        or die "socket: $@";
244
 
245
    #här ska keep-alive/start-paket skickas till ipt enligt commandline-arg
246
 
247
    ### create a connection between the hardware and the tcp-server ###
248
    &hardwareConnInit;
249
    $hardwareSendFunction = "udpServerSend";        ### set up callback for a 'send data' function
250
    $thr = threads->new(\&hardwareConnThread);
251
    $thr->detach;
252
 
253
}
254
 
255
sub udpServerSend {
256
    print $udpCsocket $_[0];
257
}
258
 
259
##################### TCP HUB ############################
260
sub tcpServerThread {
261
    while(@ready = $tcpSselect->can_read) {
262
        for $tcpSsocket (@ready) {
263
            if($tcpSsocket == $tcpSlisten) {
264
                &tcpServerConn;
265
            } else {
266
                $tcpSsocket->recv($line,$linelength);
267
                if ($line eq "") {
268
                    &tcpServerClientDis;
269
                } else {
270
                    $line =~ s/\n.*//gm;    #remove newline and everything after it
271
                    $line =~ s/\r.*//gm;    #remove linefeed and everything after it
272
                    print "Got packet '".$line."' from client ".$tcpSsocket->fileno."\n";
273
 
274
                    $rxerror = 0;
275
                    testPacket($line, 0, $rxerror);
276
 
277
                    if ($rxerror == 0) {
278
                        #Add newline to each packet
279
                        $line .= "\n";
280
 
281
                        &tcpServerBroadcastExcept($line, $tcpSsocket);
282
                    }
283
                }
284
            }
285
        }
286
    }
287
}
288
 
289
#initiate the tcp server
290
sub tcpServerInit {
291
    $tcpSlisten = IO::Socket::INET->new(Proto => "tcp", LocalPort => $hubport, Listen => 1, Reuse => 1)
292
                or die $!;
293
 
294
    $tcpSselect = IO::Select->new($tcpSlisten);
295
    print "Starting tcpServer\n";
296
}
297
 
298
#a client connected
299
sub tcpServerConn {
300
    $new = $tcpSlisten->accept;
301
    $tcpSselect->add($new);
302
    print $new->fileno . ": connected\n";
303
}
304
 
305
#a client disconnected
306
sub tcpServerClientDis {
307
    print $tcpSsocket->fileno . ": disconnected\n";
308
    $tcpSselect->remove($tcpSsocket);
309
    $tcpSsocket->close;
310
}
311
 
312
#subroutine sends data to all connected clients except for one specified 
313
sub tcpServerBroadcastExcept {
314
    my $first = 0;
315
    my $data = $_[0];
316
    my $exception = $_[1];
317
    for $eachsocket ($tcpSselect->handles) {
318
        if ($eachsocket==$tcpSlisten) {     #dont send to self
319
            next;
320
        } elsif ($eachsocket==$exception) {     #dont send to the specified exception
321
            next;
322
        } else {
323
            if ($first==0) {
324
                $first = 1;
325
                print "Sending to client ".$eachsocket->fileno;
326
            } else {
327
                print ", ".$eachsocket->fileno;
328
            }
329
            $eachsocket->send($data) or do {
330
                &tcpServerClientDis;
331
            }
332
        }
333
    }
334
    if ($first==1) {
335
        print "\n";
336
    }
337
}
338
 
339
##################### General functions ############################
340
 
341
#this function should do a number of tests on $_[0] and print messages if packet is malformed and return 1 in $_[2]
342
#messages can be suppressed by having $_[1] as 1
343
sub testPacket {
344
    my $input = $_[0];
345
    my $messages = $_[1];
346
 
347
    #line should be parsed somewhat here, check PKT, AUT and so on
348
    $testErr = 0;
349
    if (length($input) < 16) {
350
        $testErr = 1;
351
        if ($messages!=1) {print "Packet was malformed, not long enough\n";}
352
    }
353
    if ($testErr == 0 && substr($input, 0, 4) != "PKT ") {
354
        $testErr = 1;
355
        if ($messages!=1) {print "Packet was malformed, should start with PKT\n";}
356
    }
357
    #if (substr($line, 12, 1) != " " || substr($line, 14, 1) != " ") {
358
    #   $testErr = 1;
359
    #   print "Packet was malformed, spaces not in the correct place\n";
360
    #}
361
    @splitinput = split(/ +/, $input);
362
    $inputarrlen = @splitinput;
363
    if ($testErr == 0 && ($inputarrlen < 4 || $inputarrlen > 12)) {
364
        $testErr = 1;
365
        if ($messages!=1) {print "Packet was malformed, to many or to few parts\n";}
366
    }
367
    if ($testErr == 0 && length($splitinput[1]) != 8) {
368
        $testErr = 1;
369
        if ($messages!=1) {print "Packet was malformed, id part must be 8 digits (padded with zeros)\n";}
370
    }
371
    if ($testErr == 0 && length($splitinput[2]) != 1) {
372
        $testErr = 1;
373
        if ($messages!=1) {print "Packet was malformed, ext part must be 1 digit\n";}
374
    }
375
    if ($testErr == 0 && length($splitinput[3]) != 1) {
376
        $testErr = 1;
377
        if ($messages!=1) {print "Packet was malformed, rtr part must be 1 digit\n";}
378
    }
379
    for ($i = 4; $i < $inputarrlen; $i++) {
380
        if ($testErr == 0 && length($splitinput[$i]) != 2) {
381
            $testErr = 1;
382
            if ($messages!=1) {print "Packet was malformed, data parts must be 2 digits (padded with zero)\n";}
383
        }
384
    }
385
    $checkstrlen = length($input)-4;
386
    $checkstr = substr($input, 4, $checkstrlen);
387
    if ($testErr == 0 && $checkstr !~ m/^[0-9a-fA-F ]*$/) {
388
        $testErr = 1;
389
        if ($messages!=1) {print "Packet was malformed, not hex\n";}
390
    }
391
 
392
    $_[2] = $testErr;
393
}
394
 
395
#this function should parse $_[0] (can2serial-data) and save in $_[1] as string
396
sub c2sToString {
397
    my $input = $_[0];
398
    my $output = "";
399
    #if not correct input data, then dont save anything in $_[1]
400
    if (ord(substr($input, 0, 1))==$C2SSTARTSTR && ord(substr($input, 16, 1))==$C2SENDSTR) {
401
        #$output = "boundaries=ok ";
402
        $id = ord(substr($input, 1, 1)) + ord(substr($input, 2, 1))*256 + ord(substr($input, 3, 1))*256*256 + ord(substr($input, 4, 1))*256*256*256;
403
        $ext = ord(substr($input, 5, 1));
404
        $rtr = ord(substr($input, 6, 1));
405
        $dl = ord(substr($input, 7, 1));
406
        if ($ext < 2 && $rtr < 2 && $dl < 9) {
407
            $output .= sprintf "%08x ", $id;
408
            $output .= $ext . " " . $rtr;
409
            for ($i = 0; $i < $dl; $i++) {
410
                $data = ord(substr($input, 8+$i, 1));
411
                $output .= sprintf " %02x", $data;
412
            }
413
            $_[1] = "PKT ".$output;
414
        }
415
    }
416
}
417
 
418
#this function should parse $_[0] (string) and save in $_[1] as can2serial-data
419
sub stringToc2s {
420
    my $input = $_[0];
421
    my $output = "";
422
    #if not correct input data, then dont save anything in $_[1]
423
    if (length($input) > 15) {
424
        #minor checks, the data from the tcp-server should be valid
425
        @splitinput = split(/ +/, $input);
426
        $inputarrlen = @splitinput;
427
        if (substr($input, 0, 4) == "PKT " && substr($input, 12, 1) == " " && substr($input, 14, 1) == " " && $inputarrlen > 3 && $inputarrlen < 13) {
428
            $id = hex($splitinput[1]);
429
            $ext = hex($splitinput[2]);
430
            $rtr = hex($splitinput[3]);
431
            @data = @splitinput[4..($inputarrlen-1)];
432
            $dl = @data;
433
 
434
            $output .= chr($C2SSTARTSTR);
435
            $output .= chr($id & 0xff);
436
            $output .= chr(($id>>8) & 0xff);
437
            $output .= chr(($id>>16) & 0xff);
438
            $output .= chr(($id>>24) & 0xff);
439
            $output .= chr($ext);
440
            $output .= chr($rtr);
441
            $output .= chr($dl);
442
            for ($i = 0; $i < 8; $i++) {
443
                if ($i < $dl) {
444
                    $output .= chr(hex($data[$i]));
445
                } else {
446
                    $output .= chr(" ");
447
                }
448
            }
449
            $output .= chr($C2SENDSTR);
450
            $_[1] = $output;
451
        }
452
    }
453
}