sender.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. function readSensor() {
  3. $res;
  4. $output;
  5. exec("./mkr680-reader", $output, $res);
  6. $arr = array(
  7. "temperature" => NULL,
  8. "pressure" => NULL,
  9. "humidity" => NULL,
  10. "gas resistance" => NULL,
  11. "iaq (accuracy)" => NULL
  12. );
  13. // do a quick sanity check on data usually 224 bytes, 200 is probably good enough
  14. if(200 > strlen(implode("\n", $output))) { return false; }
  15. // prepare the output by converting to lowercase and splitting
  16. foreach($output as $k=>$v) {
  17. $t = strtok(strtolower($v), ':');
  18. $output[$k] = array($t, strtok(''));
  19. }
  20. // perform the search
  21. foreach($arr as $k=>$v) {
  22. foreach($output as $j=>$w) {
  23. if(0 === strpos($w[0], $k)) {
  24. $arr[$k] = $w[1];
  25. unset($output[$j]);
  26. }
  27. }
  28. }
  29. // cleanup by removing excess information
  30. $iaq = trim($arr["iaq (accuracy)"]);
  31. foreach($arr as $k=>$v) {
  32. // get first "word", and split on every character
  33. $v = str_split(strtok(trim($v), ' '), 1);
  34. $s = "";
  35. foreach($v as $t) {
  36. if('.' === $t) { $s .= '.'; continue; }
  37. //var_dump($t, 0x32, ord($t), chr($t));
  38. if((0x29 < ord($t)) && (0x40 > ord($t))) $s .= $t;
  39. else break;
  40. }
  41. $arr[$k] = $s;
  42. }
  43. // final formatting, unit conversions, precision, etc
  44. $arr["temperature"] = $arr["temperature"] . " C";
  45. $arr["pressure"] = $arr["pressure"] . " Pa";
  46. $arr["humidity"] = $arr["humidity"] . " %";
  47. $arr["gas resistance"] = $arr["gas resistance"] . " Ohm";
  48. $arr["iaq (accuracy)"] = $iaq;
  49. // one last sanity check, everything should be set
  50. foreach($arr as $v) if(NULL === $v) return false;
  51. return $arr;
  52. }
  53. $last="";
  54. // monitor the sensor, running mkr680-reader takes about a quarter second,
  55. while(true) {
  56. // read data, retry in ten seconds on failure
  57. if(false === ($now = readSensor())) { sleep(10 /*seconds*/); continue; }
  58. // only send data if there is a change
  59. if($last === $now) continue;
  60. $last = $now;
  61. // send data to mmcgo
  62. $now["sensor"] = 'H';
  63. file_get_contents("http://mmcgo.com/radon/environmental.php", false, stream_context_create(array("http"=>array(
  64. "method" => "POST",
  65. "header" => "Content-Type: application/x-www-form-urlencoded",
  66. "content" => http_build_query($now)
  67. ))));
  68. //var_dump($last);
  69. // the sensor takes at least a second before new samples are available
  70. //usleep(1000 /*uS*/ * 1750 /* and ~250ms for mkr680-reader gives 2 seconds */);
  71. // thinking about it differently, reading every 15 minutes gives about 100 readings per day
  72. sleep(15 /*minutes*/ * 60 /*seconds*/);
  73. }