Subversion Repositories HomeAutomation

Rev

Rev 633 | Rev 681 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | SVN | RSS feed

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