DIY-IOT: control.php source code

This post is a support-article to the DIY-IOT series, and contain the source code for the project.

control.php

The serverside code, implementing the API


/*
 * -----------------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <steen@ieee.org> wrote this file.  As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.   Steen Garbers Enevoldsen
 * -----------------------------------------------------------------------------------
 */

<?php $realm = 'gds-iot'; $users = array('TypeUsernameHere' => 'TypePasswordHere');

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
  header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
     '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

  die('UNAUTHORIZED');
  }

// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']]))
      die('WRONG_CREDENTIALS');

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
  die('WRONG_CREDENTIALS');

// ok, valid username and password

// function to parse the http auth header
function http_digest_parse($txt)
{
  // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
      $data = array();
        $keys = implode('|', array_keys($needed_parts));
	  preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

  foreach ($matches as $m) {
    $data[$m[1]] = $m[3] ? $m[3] : $m[4];
    unset($needed_parts[$m[1]]);
  }

  return $needed_parts ? false : $data;
}

// User validated, now do the real stuff

$action = $_GET['action'];
$port = $_GET['device'];

// We use GPIO#17 and GPIO#27 for controlling the relays
// Configure the ports as output.
$setmode17 = shell_exec("/usr/local/bin/gpio -g mode 17 out");
$setmode27 = shell_exec("/usr/local/bin/gpio -g mode 27 out");

switch ($port)
{
case 1:
    $portreal="27"; // Device#1 maps to GPIO#27
    break;
case 2:
    $portreal="17"; // Device#2 maps to GPIO#17
    break;
default:
    die('INVALID_DEVICE');
    break;
}

switch($action) // What are we asked to do?
  {
  case 'ON':
    $gpio_on = shell_exec("/usr/local/bin/gpio -g write " . $portreal . " 1"); // Turn on the desired GPIO
    $gpio_stat = shell_exec("/usr/local/bin/gpio -g read " . $portreal); // Read status of port
    if ($gpio_stat <> 1)
      {
      echo "SYSTEM_ERROR"; // We turned on the port, but it reads as off, return System Error
      }
    else
      {
      echo "DEVICE_" . $port . "_ON"; // All is good, return OK
      }
    break;
  case 'OFF':
    $gpio_off = shell_exec("/usr/local/bin/gpio -g write " . $portreal . " 0"); // Turn off the desired GPIO
    $gpio_stat = shell_exec("/usr/local/bin/gpio -g read " . $portreal); // Read port status
    if ($gpio_stat <> 0)
      {
      echo "SYSTEM_ERROR"; // We asked to turn off, but port is still on, return system error.
      }
    else
      {
      echo "DEVICE_" . $port . "_OFF"; // All good, return confirm
      }
    break;
  case 'STATUS': // We're asked to return status of port
    $gpio_stat = shell_exec("/usr/local/bin/gpio -g read " . $portreal); // Read status of port
    switch ($gpio_stat)
      {
      case 0:
      echo "DEVICE_" . $port . "_OFF";
      //   echo "OFF";
      break;
      case 1:
      echo "DEVICE_" . $port . "_ON";
      //   echo "ON";
      break;
      default:
      echo "SYSTEM_ERROR";
      }

    break;
  default:
    echo "API_ERROR";
    break;
  }

?>