test.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. function readSensor() {
  3. $res;
  4. $output;
  5. exec("./mkr680-reader", $output, $res);
  6. $arr = array(
  7. "temperature" => -1,
  8. "pressure" => -1,
  9. "humidity" => -1,
  10. "gas resistance" => -1,
  11. "iaq (accuracy)" => -1
  12. );
  13. // prepare the output by converting to lowercase and splitting
  14. foreach($output as $k=>$v) {
  15. $t = strtok(strtolower($v), ':');
  16. $output[$k] = array($t, strtok(''));
  17. }
  18. // perform the search
  19. foreach($arr as $k=>$v) {
  20. foreach($output as $j=>$w) {
  21. if(0 === strpos($w[0], $k)) {
  22. $arr[$k] = $w[1];
  23. unset($output[$j]);
  24. }
  25. }
  26. }
  27. // cleanup by removing excess information
  28. $iaq = trim($arr["iaq (accuracy)"]);
  29. foreach($arr as $k=>$v) {
  30. // get first "word", and split on every character
  31. $v = str_split(strtok(trim($v), ' '), 1);
  32. $s = "";
  33. foreach($v as $t) {
  34. if('.' === $t) { $s .= '.'; continue; }
  35. //var_dump($t, 0x32, ord($t), chr($t));
  36. if((0x29 < ord($t)) && (0x40 > ord($t))) $s .= $t;
  37. else break;
  38. }
  39. $arr[$k] = $s;
  40. }
  41. // final formatting, unit conversions, precision, etc
  42. $arr["temperature"] = $arr["temperature"] . " C";
  43. $arr["pressure"] = $arr["pressure"] . " hPa";
  44. $arr["humidity"] = $arr["humidity"] . " %";
  45. $arr["gas resistance"] = $arr["gas resistance"] . " Ohm";
  46. $arr["iaq (accuracy)"] = $iaq;
  47. return $arr;
  48. }
  49. $last="";
  50. // monitor the sensor, running mkr680-reader takes about a quarter second,
  51. while(true) {
  52. $now = readSensor();
  53. if($last === $now) { echo "same" . PHP_EOL; continue; }
  54. $last = $now;
  55. var_dump($last);
  56. // the sensor takes at least a second before new samples are available
  57. //usleep(1000 /*uS*/ * 1750 /* and ~250ms for mkr680-reader gives 2 seconds */);
  58. // thinking about it differently, reading every 15 minutes gives about 100 readings per day
  59. sleep(15 /*minutes*/ * 60 /*seconds*/);
  60. }