#!/usr/bin/php
<?php
	$tries = 0;
	$done = false;
	do {
		$output = shell_exec('timeout 2s stdbuf -oL hcitool lescan 2>&1');

		if (strpos($output, 'Input/output error') === false) {
			$done = true;
			break;
		} else {
			//echo 'reset' . "\n";
			system('hciconfig hci0 reset');
		}

		$tries++;
	} while ($tries < 3);

	if (!$done) {
		die('failed');
	}

	$lines = explode("\n", $output);
	$deviceList = array();
	foreach ($lines as $k => $v) {
		$line = trim($v);
		//echo 'line: ' . $line . "\n\n";

		$parts = explode(' ', $line);
		if (sizeof($parts) < 2) continue;

		$mac = $parts[0];
		$name = $parts[1];

		if ($name == 'Scan') continue;

		/// Do not overwrite if 'unknown'
		if ($name == '(unknown)') {
			if (!isset($deviceList[$mac])) $deviceList[$mac] = '';
		} else {
			$deviceList[$mac] = $name;
		}
	}

	//print_r($deviceList);

	$result = '';

	foreach ($deviceList as $k => $v) {
		$result .= $k . ',' . $v . ';';
	}

	echo $result;	
?>
