/ api-example.php
api-example.php
  1  <?php
  2  #
  3  # Sample Socket I/O to CGMiner API
  4  #
  5  function getsock($addr, $port)
  6  {
  7   $socket = null;
  8   $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  9   if ($socket === false || $socket === null)
 10   {
 11  	$error = socket_strerror(socket_last_error());
 12  	$msg = "socket create(TCP) failed";
 13  	echo "ERR: $msg '$error'\n";
 14  	return null;
 15   }
 16  
 17   $res = socket_connect($socket, $addr, $port);
 18   if ($res === false)
 19   {
 20  	$error = socket_strerror(socket_last_error());
 21  	$msg = "socket connect($addr,$port) failed";
 22  	echo "ERR: $msg '$error'\n";
 23  	socket_close($socket);
 24  	return null;
 25   }
 26   return $socket;
 27  }
 28  #
 29  # Slow ...
 30  function readsockline($socket)
 31  {
 32   $line = '';
 33   while (true)
 34   {
 35  	$byte = socket_read($socket, 1);
 36  	if ($byte === false || $byte === '')
 37  		break;
 38  	if ($byte === "\0")
 39  		break;
 40  	$line .= $byte;
 41   }
 42   return $line;
 43  }
 44  #
 45  function request($cmd)
 46  {
 47   $socket = getsock('127.0.0.1', 4028);
 48   if ($socket != null)
 49   {
 50  	socket_write($socket, $cmd, strlen($cmd));
 51  	$line = readsockline($socket);
 52  	socket_close($socket);
 53  
 54  	if (strlen($line) == 0)
 55  	{
 56  		echo "WARN: '$cmd' returned nothing\n";
 57  		return $line;
 58  	}
 59  
 60  	print "$cmd returned '$line'\n";
 61  
 62  	if (substr($line,0,1) == '{')
 63  		return json_decode($line, true);
 64  
 65  	$data = array();
 66  
 67  	$objs = explode('|', $line);
 68  	foreach ($objs as $obj)
 69  	{
 70  		if (strlen($obj) > 0)
 71  		{
 72  			$items = explode(',', $obj);
 73  			$item = $items[0];
 74  			$id = explode('=', $items[0], 2);
 75  			if (count($id) == 1 or !ctype_digit($id[1]))
 76  				$name = $id[0];
 77  			else
 78  				$name = $id[0].$id[1];
 79  
 80  			if (strlen($name) == 0)
 81  				$name = 'null';
 82  
 83  			if (isset($data[$name]))
 84  			{
 85  				$num = 1;
 86  				while (isset($data[$name.$num]))
 87  					$num++;
 88  				$name .= $num;
 89  			}
 90  
 91  			$counter = 0;
 92  			foreach ($items as $item)
 93  			{
 94  				$id = explode('=', $item, 2);
 95  				if (count($id) == 2)
 96  					$data[$name][$id[0]] = $id[1];
 97  				else
 98  					$data[$name][$counter] = $id[0];
 99  
100  				$counter++;
101  			}
102  		}
103  	}
104  
105  	return $data;
106   }
107  
108   return null;
109  }
110  #
111  if (isset($argv) and count($argv) > 1)
112   $r = request($argv[1]);
113  else
114   $r = request('summary');
115  #
116  echo print_r($r, true)."\n";
117  #
118  ?>