<?php  			// Programming Xport or Wiport general io  Dez. 2007  A.Schnell

$Host = "192.168.1.234";

$Response = sendcommand($Host,0x11,0,0); // get directions (1 Output 0 Input)
printf("\nDirections    :%016b",$Response); 

$Response = sendcommand($Host,0x12,0,0); // get active level (high or low active)
printf("\nActive Levels :%016b",$Response);
$Response = sendcommand($Host,0x13,0,0); // get active io state
printf("\nIO States     :%016b",$Response);

$Response = setportbit(0,1);  // io Bit 3 auf 1 setzen
printf("\nNew States    :%016b",$Response);

$n = 3; $iobit = getportbit($n);   // get state of IOBit n
echo "\nIObit(",$n,") :",$iobit;

exit;
   
function setportbit($iobit,$value)  // iobit 0..10, $value 0 oder 1
{	global $Host;	
	$b = pow(2,$iobit);				// bitmask
	if($value) $v = $b; else $v = 0;
    $par1 = $b; $par2 = $v;  // $par1 mask, $par2 Bitvalue
    return sendcommand($Host,0x1B,$par1,$par2);
}

function getportbit($iobit) // iobit 0..10
{	global $Host;
	$Result = sendcommand($Host,0x13,0,0);
	$bitvalue = $Result & pow(2,$iobit);    // Bit ausmaskieren
	if($bitvalue) $bitvalue = 1;  			// only 0 or 1 as bitvalue
	return $bitvalue;		
}

function sendcommand($Host,$command,$par1,$par2)
{ 	$noerr = true; $Port = 0x77f0; // local  wiport socket for gpio
	$wiport = @fsockopen($Host, $Port, $ErrNo, $ErrStr, 5) or $noerr = false;
	if($noerr) {
		$carray = pack("CLL",$command,$par1,$par2); // C:8Bit, L:32Bit, L:32Bit
		fwrite($wiport,$carray,9);     // total 9 Bytes
		$Response = fread($wiport,5);  // get 5 Byte response from wiport 
		fclose($wiport);
		$carray = unpack("C/L",$Response); // C:8Bit command, L:32Bit result -> carray[1]
		return ($carray[1]);
   	} else return false;
}

?>
