digitemp-rrdgraph/lib/DigiTemp.php

132 lines
3.4 KiB
PHP
Raw Permalink Normal View History

2020-06-09 16:02:25 +09:00
<?php
declare(strict_types=1);
namespace Orrisroot;
class DigiTemp
{
/**
* @var string digitemp command path
*/
private string $commandPath;
/**
* @var string config file path
*/
private string $configPath;
/**
* @var array config data
*/
private array $config = [
'TTY' => '',
'READ_TIME' => 0,
'LOG_TYPE' => 0,
'LOG_FORMAT' => '',
'CNT_FORMAT' => '',
'HUM_FORMAT' => '',
'SENSORS' => 0,
'ROM' => [],
];
/**
* constructor.
*
* @param string $commandPath digitemp command path
* @param string $configPath config file path
*/
public function __construct(string $commandPath, string $configPath)
{
$this->commandPath = $commandPath;
$this->configPath = $configPath;
$this->parseConfig();
}
/**
* get number of sensors.
*/
public function getNumSensors(): int
{
return $this->config['SENSORS'];
}
/**
* get sensor id.
*
* @param int $num sensor number
*
* @return ?string
*/
public function getSensorId(int $num): ?string
{
return isset($this->config['ROM'][$num]) ? $this->config['ROM'][$num] : null;
}
/**
* read sensor.
*
* @param int $num sensor number
*
* @return ?float
*/
public function readSensor(int $num): ?float
{
$cmd = escapeshellcmd($this->commandPath.' -c '.$this->configPath.' -q -t '.$num.' -o"%.2C" 2>/dev/null');
exec($cmd, $output, $ret);
if (0 !== $ret) {
return null;
}
return (float) $output[0];
}
/**
* parse config file.
*
* @return false if failure
*/
private function parseConfig(): bool
{
foreach (file($this->configPath) as $line) {
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', trim($line), $matches);
if (empty($matches[0])) {
continue;
}
$cols = $matches[0];
$key = array_shift($cols);
$value = array_shift($cols);
switch ($key) {
2024-01-30 18:35:21 +09:00
case 'TTY':
$this->config[$key] = $value;
break;
case 'READ_TIME':
$this->config[$key] = (int) $value;
break;
case 'LOG_TYPE':
$this->config[$key] = (int) $value;
break;
case 'LOG_FORMAT':
$this->config[$key] = '"' === substr($value, 0, 1) ? stripslashes(substr($value, 1, -1)) : $value;
break;
case 'CNT_FORMAT':
$this->config[$key] = '"' === substr($value, 0, 1) ? stripslashes(substr($value, 1, -1)) : $value;
break;
case 'HUM_FORMAT':
$this->config[$key] = '"' === substr($value, 0, 1) ? stripslashes(substr($value, 1, -1)) : $value;
break;
case 'SENSORS':
$this->config[$key] = (int) $value;
break;
case 'ROM':
$this->config[$key][(int) $value] = str_replace('0x', '', implode('', array_reverse($cols)));
break;
default:
return false;
2020-06-09 16:02:25 +09:00
}
}
return true;
}
}