src.dualinventive.com/dinet/common/ditest-php/equipment/pi_board.php

139 lines
2.7 KiB
PHP

<?php
require_once(dirname(__FILE__) . "/../test_framework.php");
class PIBoard {
private $__componentName = "PIBoard";
private $name = "pi_board";
private $debug = false;
private $__fd = null;
private $relais_states = array(false, false, false, false);
private function debug($msg) {
if ($this->debug) {
$msg = str_replace("\r", '\r', $msg);
$msg = str_replace("\n", '\n', $msg);
DiTestMsg::dbg(trim($msg), $this->__componentName);
}
}
private function err($msg) {
DiTestMsg::err(trim($msg), $this->__componentName);
}
private function warn($msg) {
DiTestMsg::warn(trim($msg), $this->__componentName);
}
private function fail($msg) {
DiTestMsg::fail(trim($msg), $this->__componentName);
}
private function pass($msg) {
DiTestMsg::pass(trim($msg), $this->__componentName);
}
function __construct($host, $port = 2008, $debug = false) {
$this->debug = $debug;
$this->__fd = fsockopen($host, $port, $errno, $errstr, 3);
if ($this->__fd === FALSE) {
$this->fail("$errstr ($errno)");
} else {
$this->debug($host);
$this->debug($port);
$this->setInfo("host", $host);
$this->setInfo("port", $port);
// all OFF
$this->updaterelais();
}
}
function __destruct() {
if ($this->__fd) {
fclose($this->__fd);
$this->__fd = null;
}
}
function setInfo($key, $value) {
$this->__info[$key] = $value;
}
function getInfo($key) {
return $this->__info[$key];
}
private function updaterelais() {
$relais_1 = 'false';
$relais_2 = 'false';
$relais_3 = 'false';
$relais_4 = 'false';
if ($this->relais_states[0] == true)
$relais_1 = 'true';
if ($this->relais_states[1] == true)
$relais_2 = 'true';
if ($this->relais_states[2] == true)
$relais_3 = 'true';
if ($this->relais_states[3] == true)
$relais_4 = 'true';
$ar = array($relais_1, $relais_2, $relais_3, $relais_4);
$response=array();
$response["RelaisArray"]=$ar;
$json=json_encode($response);
$this->sendMessage($json);
}
private function reply() {
if ($this->__fd) {
$reply = fgets($this->__fd);
$this->debug("[reply] \"$reply\"");
return $reply;
}
return "";
}
private function request($cmd) {
if ($this->__fd) {
$cmd .= "\r\n";
$this->debug("[request] cmd: \"$cmd\"");
fputs($this->__fd, $cmd);
}
}
public function flush() {
stream_set_blocking($this->__fd, false);
stream_set_timeout($this->__fd, 1);
do {
$rep = $this->reply();
} while ($rep);
stream_set_blocking($this->__fd, true);
}
public function sendMessage($msg) {
$this->request($msg);
}
public function setrelais($id, $state) {
if ($id > 3)
return;
if ($this->__fd) {
$this->relais_states[$id] = $state;
$this->updaterelais();
}
}
}