spaceapi/generator/generator.php

87 lines
2.6 KiB
PHP
Raw Normal View History

2021-01-03 23:04:07 +01:00
#!/usr/bin/env php
<?php
chdir(__DIR__);
$search = [];
$replace = [];
foreach (getenv() as $k => $v) {
$search[] = "\$$k";
$replace[] = '"' . addslashes($v) . '"';
}
2023-01-09 23:54:42 +01:00
$conf = yaml_parse(
str_replace($search, $replace, file_get_contents(__DIR__ . "/config.yaml"))
);
2021-01-03 23:04:07 +01:00
$c = new \Mosquitto\Client();
2023-01-09 23:54:42 +01:00
if (isset($conf["mqtt"]["user"])) {
$c->setCredentials($conf["mqtt"]["user"], $conf["mqtt"]["password"]);
}
2021-01-03 23:04:07 +01:00
$c->onMessage(function (\Mosquitto\Message $message) use (&$data, $conf) {
2023-01-09 23:54:42 +01:00
if (!isset($data[$message->topic])) {
return;
}
2021-01-03 23:04:07 +01:00
2023-01-09 23:54:42 +01:00
switch ($data[$message->topic]["cast"]) {
case "int":
$data[$message->topic]["value"] = (int) $message->payload;
2021-01-03 23:04:07 +01:00
break;
2023-01-09 23:54:42 +01:00
case "float":
$data[$message->topic]["value"] = (float) $message->payload;
2021-01-03 23:04:07 +01:00
break;
2023-01-09 23:54:42 +01:00
case "bool":
$data[$message->topic]["value"] = (bool) $message->payload;
2021-01-03 23:04:07 +01:00
break;
default:
2023-01-09 23:54:42 +01:00
echo "error, cast type " .
$data[$message->topic]["cast"] .
" unknown\n";
2021-01-03 23:04:07 +01:00
die(1);
}
2023-01-19 15:01:30 +01:00
var_dump($data);
2023-01-09 23:54:42 +01:00
$data[$message->topic]["changed"] = time();
$out = file_get_contents(__DIR__ . "/template.json");
$out = preg_replace_callback(
2023-01-19 15:01:30 +01:00
"/\"{{(?<name>[^#}]+?)(#(?<modifier>[^}]+))?}}\"/",
2023-01-09 23:54:42 +01:00
function ($m) use ($data, $conf) {
$value = $data[$conf["variables"][$m["name"]]["topic"]]["value"];
$modifier = isset($m["modifier"]) ? $m["modifier"] : "noop";
switch ($modifier) {
case "timestamp":
$value =
$data[$conf["variables"][$m["name"]]["topic"]][
"changed"
];
break;
case "noop":
break;
default:
echo "error, modifier " . $m["modifier"] . " unknown\n";
die(1);
}
return json_encode($value);
},
$out
);
2021-01-03 23:04:07 +01:00
2023-01-09 23:54:42 +01:00
$out = json_encode(
json_decode($out),
JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
);
if (!is_dir("public")) {
mkdir("public");
}
file_put_contents("public/spaceapi.json", $out);
2021-01-03 23:04:07 +01:00
});
2023-01-09 23:54:42 +01:00
$c->connect($conf["mqtt"]["host"]);
2021-01-03 23:04:07 +01:00
$data = [];
2023-01-09 23:54:42 +01:00
foreach ($conf["variables"] as $name => $variable) {
$data[$variable["topic"]] = [
"value" => null,
"cast" => $variable["cast"],
"name" => $name,
"changed" => 0,
2021-01-03 23:04:07 +01:00
];
2023-01-09 23:54:42 +01:00
$c->subscribe($variable["topic"], 2);
2021-01-03 23:04:07 +01:00
}
2023-01-09 23:54:42 +01:00
$c->loopForever();