src.dualinventive.com/dinet/libdi-php/bin/di-candump-log

103 lines
2.3 KiB
PHP
Executable File

#!/usr/bin/php -q
<?php
function to_str($prefix, $value) {
$constants = get_defined_constants(true);
foreach($constants['di'] as $k => $v) {
if (strrpos($k, $prefix) !== false) {
if ($value == $v)
return $k;
}
}
return "";
}
if (!isset($argv[1])) {
echo "argument expected" . PHP_EOL;
echo "usage: di-candump <iface, e.g \"can0\", \"vcan0\">" . PHP_EOL;
exit(1);
}
$fd = di_can_open($argv[1]);
if ($fd === null) {
echo "error opening: '".$argv[1]."'" . PHP_EOL;
echo "usage: di-candump <iface, e.g \"can0\", \"vcan0\">" . PHP_EOL;
exit(1);
}
declare(ticks=1);
function sig_handler($signo)
{
echo "Got signal $signo...\n";
di_can_close($GLOBALS['fd']);
unset($GLOBALS['fd']);
switch ($signo) {
case SIGINT:
exit;
break;
case SIGTERM:
exit;
break;
case SIGHUP:
break;
default:
}
}
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
pcntl_signal(SIGINT, "sig_handler");
while (1) {
$x = di_can_recv($fd);
if ($x === null)
continue;
if ($x['msgtype'] != DI_CAN_MSGTYPE_LOG)
continue;
// Unpack MessagePack
if (isset($x['msg']) && $x['msg'] !== null) {
if ($x['ptype'] == DI_CAN_PTYPE_MSGPACK)
$x['msg'] = msgpack_unpack($x['msg']);
if ($x['msgtype'] == DI_CAN_MSGTYPE_LOG) {
$x['msg']['loglevel'] = to_str("DI_LOG_LEVEL_", $x['msg']['loglevel']);
$x['msg']['component'] = to_str("DI_LOG_COMPONENT_", $x['msg']['component']);
}
}
$x['dtype'] = to_str("DI_LOG_LEVEL_", $x['dtype']);
$dtype = str_replace("DI_LOG_LEVEL_", "", $x['dtype']);
// Unset size/msg and ptype when there is no payload
if ($x['size'] == 0) {
unset($x['size']);
unset($x['msg']);
unset($x['ptype']);
} else {
if ($x['ptype'] == DI_CAN_PTYPE_MSGPACK) {
//$msg = json_encode($x['msg']);
$msg = $x['msg']['msg'];
}
}
// Convert src and dst node id to hex
$src_id = dechex($x['src_id']);
$src_id = '0x' . str_pad($src_id, 8, "0", STR_PAD_LEFT);
$dst_id = dechex($x['dst_id']);
$dst_id = '0x' . str_pad($dst_id, 8, "0", STR_PAD_LEFT);
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
$timestr = $d->format("Y-m-d H:i:s.u");
echo "[" . $timestr . "] $src_id $dtype $msg". PHP_EOL;
unset($x);
}
?>