#!/usr/bin/env php
<?php
  // This script reads json pin state data from a NEMS Linux server
  // running the NEMS Tools GPIO Extender Server on port 9595.

  if (file_exists('/usr/local/bin/gpio')) {
    $hardware=1;
    $gpio_command='/usr/local/bin/gpio';
  } else if (file_exists('/usr/bin/gpio')) {
    $hardware=1;
    $gpio_command='/usr/bin/gpio';
  } else {
    $hardware=0;
  }

  if (file_exists('/usr/local/bin/nems-info')) {
    $thisIP = trim(shell_exec('/usr/local/bin/nems-info ip'));
  } else {
    $thisIP = getHostByName(getHostName());
  }

  file_put_contents('/var/log/gpioe.log',array());

  while (1 == 1) {

    # Detect local NEMS Server
    echo shell_exec('/root/nems/nems-tools/detect');

    // Can be an IP address or FQDN
    if (file_exists('/boot/nems-tools.conf')) {
      $conf = file('/boot/nems-tools.conf');
    }

    if (is_array($conf) && (count($conf) > 0)) {
      foreach ($conf as $line) {
        $tmp = explode('=',$line);
        if (is_array($tmp) && (count($tmp) == 2)) {
          $stringname = $tmp[0];
          // Eg. nemsserver=127.0.0.1 in nems-tools.conf will give $nemsserver here.
          $$stringname = trim($tmp[1]);
        }
      }

      $url = $nemsserver . ':9595'; // need to specify the port of the GPIOE Server
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_HEADER, false);
      $data = curl_exec($curl);
      curl_close($curl);
      $GPIO = json_decode($data);
      if (json_last_error() === 0) {
        $output = 'GPIO Extension to ' . $nemsserver . ' successful. ';
        if ($hardware == 0) {
          die(' However, no Raspberry Pi GPIO detected.' . PHP_EOL);
        }
        foreach ($GPIO->state as $pin=>$state) {
          if ($hardware != 0) shell_exec($gpio_command . ' -g write ' . $pin . ' ' . $state);
          $output .= 'Pin ' . $pin . ': ' . $state . ' ';
        }
        $output .= 'Omzlo Light: ' . $GPIO->omzlo . ' ';
        $output .= 'Iteration: ' . number_format($GPIO->iteration);
        shell_exec('/root/nems/nems-tools/warninglight-omzlo alerts ' . $GPIO->omzlo . ' > /dev/null 2>&1');
        file_put_contents('/var/log/gpioe.log',$output);
      } else {
        $output = 'Could not find a running NEMS Tools GPIO Extender Server at ' . $nemsserver;
        shell_exec($gpio_command . ' -g write 18 1');
        shell_exec($gpio_command . ' -g write 23 1');
        shell_exec($gpio_command . ' -g write 24 1');
        shell_exec('/root/nems/nems-tools/warninglight-omzlo alerts green1 orange1 red1 > /dev/null 2>&1');
        file_put_contents('/var/log/gpioe.log',$output);
      }
      echo $output . PHP_EOL;
      sleep(10); // Refresh every 10 seconds

    } else {
      $error = 'Attempting to find a NEMS Server...';
      file_put_contents('/var/log/gpioe.log',json_encode($error));
    }

  }


?>
