Subversion Repositories HomeAutomation

Rev

Rev 1080 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | SVN | RSS feed

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