<?php
define ("SLEEP_TIME",800000);

function open_comport($comport){
    ser_open( $comport, 9600, 8, "None", 1, "None" );    

}

function close_comport(){
    ser_close();    
}

function is_comport_open(){
	if(ser_isopen()){
		return 1;      
	}

	else{
	    return 0;
	}    
}
function get_com_port(){

	$str = ser_isopen();
	return substr($str, 0, 4);      

}

function send($bytes){
	$size= sizeof($bytes);

	$i=0;
	while($i < $size){
	    //echo "<br>";

		//echo "send byte: ";
		//echo $bytes[$i];
		ser_writebyte($bytes[$i]);
		$i++;

	}
}

function read_byte(){
    /*$byte = ser_readbyte();
	echo "<br>";
	echo "Byte read: ";
	echo  $byte;
	return $byte;*/
    return  ser_readbyte(); 

}

function no_bytes_ready(){
    return  ser_inputcount();
}

function mailbox_read($inbox,$remove){
    $command[7];
    $command[0]=0x05;  //command length

    $command[1]=0x00;
    $command[2]=0x00;

    $command[3]=0x13;
    $command[4]=10+$inbox;

    $command[5]=0x00;
    $command[6]=$remove;

	send($command);
	usleep(SLEEP_TIME);
	$size=no_bytes_ready();

	$reply[$size];
	$i=0;
	while($i < $size){

	     $reply[$i]=read_byte();
		 //echo "<br>";
		 //echo "byte recieved: ";

		 //echo $reply[$i];
		 $i++;
	}
	//echo "<br>";
	//echo "Reply: ";

	//echo $reply[7];
	return $reply;         
}

function mailbox_write($bytes,$inbox){

    $length = sizeof($bytes);
	$command[$length+7];

	$command[0]=$length+5; //command length
	$command[1]=0x00;

	$command[2]=0x80;
	$command[3]=0x09;

	$command[4]=$inbox;
	$command[5]=$length+1;

	$i=0;
	while($i < $length){
	    //echo "<br>";

		//echo "Command: ";
		//echo $bytes[$i];
		$command[$i+6]= $bytes[$i];

		$i++;
	}
	$command[$i+6]=0x00;

	send($command);
}

?>