4 require 
'BayEOSGatewayClient.php';
 
    9 $config=parse_ini_file(
'/etc/bayeos-xbee-router.ini');
 
   14     for($i=0;$i<count(
$config[
'device']);$i++){
 
   15         $names[$i]=
'XBeeRouter.'.$i; 
 
   23     private $read_error_count;
 
   28         $this->xbee= 
new XBee();
 
   30         $this->xbee_panid=$this->xbee->getPANID();
 
   36     private function openDevice(){
 
   38         if($this->device==
'auto'){
 
   39             $this->device=$this->findDevice();
 
   42             die(
"No device available");
 
   43         $this->xbee->confDefaults($this->device);
 
   44         $this->xbee->confBaudRate($this->
getOption(
'baud',38400));
 
   45         if($this->xbee->open()===FALSE)
 
   46             die(
"Could not open baySerial device");
 
   47         $fp=fopen(str_replace(
'/dev/',
'/var/lock/',$this->device),
'w');
 
   48         fwrite(
$fp,
''.getmypid());
 
   50         echo date(
'Y-m-d H:i:s').
': '.$this->name.
': '.$this->device.
' opened'.
"\n";
 
   54     private function findDevice(){
 
   55         $devices=glob($this->
getOption(
'device_search',
'/dev/ttyUSB*'));
 
   56         for(
$i=0;
$i<count($devices);
$i++){
 
   57             $lockfile=str_replace(
'/dev/',
'/var/lock/',$devices[
$i]);
 
   58             if(! file_exists($lockfile)) 
return $devices[
$i];
 
   60             $fp=fopen($lockfile,
'r');
 
   64             exec(
'ps '.(
int)$pid, $lines_out);
 
   65             if(count($lines_out) < 2) {
 
   67                 fwrite(STDERR,date(
'Y-m-d H:i:s').
': '.$this->name.
': Old lockfile '.$lockfile.
' detected. Deleting '.
"\n");
 
   77     private function closeDevice(){
 
   79         unlink(str_replace(
'/dev/',
'/var/lock/',$this->device));
 
   84         if(
$data=$this->xbee->getFrame($this->getOption(
'read_timeout',120))){
 
   85             $this->read_error_count=0;
 
   86             return $this->_parseRX16(
$data[
'frame']);
 
   88         $this->read_error_count++;
 
   89         if($this->read_error_count>$this->
getOption(
'maxerror_before_reopen',2)){
 
   91             fwrite(STDERR,date(
'Y-m-d H:i:s').
': '.$this->name.
': Reopening device'.
"\n");
 
   93             $this->read_error_count=0;
 
  100         $this->writer->saveRoutedFrameRSSI(
$data[
'myid'],$this->xbee_panid,
$data[
'rssi'],
$data[
'payload']);
 
  103     private function _parseRX16(
$frame){
 
  106         if($api!=pack(
"C",0x81)) 
return FALSE;
 
  107         return array(
'myid' => array_pop(unpack(
'n',substr(
$frame,3,2))),
 
  108                 'rssi' => array_pop(unpack(
'C',substr(
$frame,5,1))),
 
  109                 'payload' => substr(
$frame,7,-1));
 
getOption($key, $default='')
 
if(!isset($config['names'])) else $names