<?php
//vim: ts=2 sw=2


class BacnetController {
  public function run() {
    session_start(Array('name' => 'CPTSESSID'));

    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "POST") {
      $this->doPost();
    } else if ($method == "GET") {
      $this->doGet();
    }
  }

  protected function doGet() {
    $action = $_GET['action'];
    $response = array();
    if ($action == 'discoverDevices') {
      $lowLimit = $_GET['lowLimit'];
      $highLimit = $_GET['highLimit'];
      $timeout = $_GET['timeout'];
      if (!is_numeric($lowLimit) || !is_numeric($highLimit) || !is_numeric($timeout))
        die('ERROR: invalid parameter for device discovery');

      $cmd = 'bacnet device -d all ' . escapeshellarg($lowLimit) . ' ' . escapeshellarg($highLimit) . ' ' . escapeshellarg($timeout);
      // $cmd = 'bacnet device -d mstp ' . $lowLimit . ' ' . $highLimit . ' ' . $timeout;
      $output = array();
      exec($cmd, $output)

      array_push($response, 'SUCCESS:', '');
      $response = array_merge($response, $output);
      die(implode("\n", $response));
    } else if ($action == 'discoverObjects') {
      //make max_execution_timeout bigger
      set_time_limit(300);

      $deviceId = $_GET['deviceId'];
      if (!is_numeric($deviceId))
        die('ERROR: invalid parameter for object discovery');
      $deviceId = escapeshellarg($deviceId);

      $linkType = $_GET['linkType'];
      if (strcasecmp($linkType, "MSTP") == 0)
          $cmd = 'bacnet point -d mstp ' . $deviceId;
      else if (strcasecmp($linkType, "B/IP") == 0 || strcasecmp($linkType, "IP") == 0)
          $cmd = 'bacnet point -d ip ' . $deviceId;
      else
      {
          error_log("invalid link type: " . $linkType);
          $cmd = 'bacnet point -d mstp ' . $deviceId;
      }

      $output = array();
      exec($cmd, $output)

      array_push($response, 'SUCCESS:', '');
      $response = array_merge($response, $output);
      die(implode("\n", $response));
    } else
      die('ERROR: not supported action: ' . $action);
  }

  protected function doPost() {
  }
}

$controller = new BacnetController();
$controller->run();
    
?>