Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<?php
if($argc != 2) {
echo 'Usage: '.$argv[0].' Port'."\n";
echo 'example: '.$argv[0].' /dev/ttyUSB0'."\n";
exit(2);
}
$port = @fopen($argv[1], 'r+');
if(!$port) {
echo 'Could not open port '.$argv[1]."\n";
exit(3);
}
$out=fopen('data.raw', 'a');
$b=0;
$buffer = array();
while(!feof($port)) {
$curByte = ord(fread($port, 1));
$buffer[] = $curByte;
while(count($buffer) > 0 && $buffer[0] != 0xAA) {
array_shift($buffer);
}
if(count($buffer) < 10) continue;
if($buffer[9] != 0xAB) {
//Well, this sucks… Remove possible SOT and retry
array_shift($buffer);
continue;
}
switch($buffer[1]) {
case 0xC0:
sds011_getData($buffer);
break;
//case 0xC5:
//Todo - Command response
//break;
default:
echo '['.strftime("%Y-%m-%d %H:%M:%S").'] -';
foreach ($buffer as $byte) {
echo ' 0x'.str_pad(dechex($byte), 2, '0', STR_PAD_LEFT);
}
$data_chksum=0;
for($i = 2; $i < 8; $i++) $data_chksum+=$buffer[$i];
$data_chksum %= 256;
if($data_chksum == $buffer[8]) {
echo ' - CRC OK';
}else{
echo ' - CRC ERR';
}
echo "\n";
}
for($i=0; $i<=9; $i++) array_shift($buffer); //Remove Packet
}
function sds011_getData($buffer) {
global $cmd_expect_dat;
$data_pm10 = $buffer[4] + ($buffer[5] << 8);
$data_pm25 = $buffer[2] + ($buffer[3] << 8);
$data_devid = $buffer[6] + ($buffer[7] << 8);
$data_chksum = 0;
for($i = 2; $i < 8; $i++) $data_chksum+=$buffer[$i];
$data_chksum %= 256;
if($data_chksum != $buffer[8]) {
echo 'Checksum error: Got 0x'.str_pad(dechex($buffer[9]), 2, '0', STR_PAD_LEFT).' - expected: 0x'.str_pad(dechex($data_chksum), 2, '0', STR_PAD_LEFT)."\n";
//exit(5);
}
echo '['.strftime("%Y-%m-%d %H:%M:%S").'] - ';
echo 'SDS device ID: 0x'.str_pad(dechex($data_devid), 2, '0', STR_PAD_LEFT)." - ";
echo 'Particle 2.5µm: '.$data_pm25." - ";
echo 'Particle 10.0µm: '.$data_pm10."\n";
return array(
'devId' => $data_devid,
'pm10' => $data_pm10,
'pm25' => $data_pm25
);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment