Skip to content

Instantly share code, notes, and snippets.

@baturin
Created January 26, 2012 16:27
Show Gist options
  • Save baturin/1683632 to your computer and use it in GitHub Desktop.
Save baturin/1683632 to your computer and use it in GitHub Desktop.
PHP script to look for a better location of 3G modem
<?php
$fcmd = fopen('/dev/ttyUSB0', 'w');
$fp = fopen('/dev/ttyUSB0', 'r');
if ($fp === false || $fcmd === false) {
throw new Exception("Failed to open modem device");
}
$levels = array();
echo "Checking";
// switch to 3g only
fwrite($fcmd, "AT^SYSCFG=14,2,3FFFFFFF,2,4\r\n");
fflush($fcmd);
sleep(5);
for ($i = 0; $i < 300; $i++) {
fwrite($fcmd, "AT+CSQ\r\n");
fflush($fcmd);
try {
$str = '';
while (!preg_match('/\+CSQ:\s*(\d+),\s*(\d+)/', $str, $matches)) {
stream_set_blocking($fp, 0);
$read = array($fp);
$write = null;
$except = null;
if (false === ($num_changed_streams = stream_select($read, $write, $except, null))) {
throw new Exception("stream_select error");
} else if ($num_changed_streams == 1) {
$a = fread($fp, 10);
$str .= $a;
} else {
throw new Exception("stream_select error - $num_changed_streams streams changed, but excepected 1");
}
}
$signal_level = $matches[1];
#echo "Signal level: $signal_level\n";
$levels[] = $signal_level;
echo get_levels_summary($levels) . "\n";
sleep(1);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
}
// switch to 'prefer 3g' mode
fwrite($fcmd, "AT^SYSCFG=2,2,3FFFFFFF,2,4\r\n");
fflush($fcmd);
fclose($fp);
function get_levels_summary($levels) {
$sum = 0;
foreach ($levels as $level) {
$sum += $level;
}
$avg = $sum / count($levels);
$result = "Cnt: " . count($levels) . '; ';
$result .= "Cur: " . $levels[count($levels) - 1] . '; ';
$result .= "Max: " . max($levels) . '; ';
$result .= "Min: " . min($levels) . '; ';
$result .= "Avg: " . $avg . ";";
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment