109 lines
2.1 KiB
PHP
109 lines
2.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require __DIR__ . '/common.php';
|
|
|
|
const NON_DRIVING_INTERVAL_SEC = 10;
|
|
const LAST_ATTEMPT_FILE = '/tmp/car_poll_se.last_attempt';
|
|
|
|
$lockFp = fopen('/tmp/car_poll_se.lock', 'c');
|
|
if ($lockFp === false) {
|
|
exit(0);
|
|
}
|
|
|
|
if (!flock($lockFp, LOCK_EX | LOCK_NB)) {
|
|
exit(0);
|
|
}
|
|
|
|
register_shutdown_function(function () use ($lockFp): void {
|
|
@flock($lockFp, LOCK_UN);
|
|
@fclose($lockFp);
|
|
});
|
|
|
|
function is_fast_poll_state(): bool
|
|
{
|
|
$latest = db_latest(db());
|
|
|
|
if (!$latest) {
|
|
return true;
|
|
}
|
|
|
|
return
|
|
(int)($latest['driving'] ?? 0) === 1 ||
|
|
(int)($latest['engine'] ?? 0) === 1 ||
|
|
(int)($latest['remote_start_preparing'] ?? 0) === 1 ||
|
|
(int)($latest['remote_start_running'] ?? 0) === 1;
|
|
}
|
|
|
|
function should_skip_non_driving(): bool
|
|
{
|
|
if (!is_file(LAST_ATTEMPT_FILE)) {
|
|
return false;
|
|
}
|
|
|
|
$last = (float)trim((string)@file_get_contents(LAST_ATTEMPT_FILE));
|
|
if ($last <= 0) {
|
|
return false;
|
|
}
|
|
|
|
return (microtime(true) - $last) < NON_DRIVING_INTERVAL_SEC;
|
|
}
|
|
|
|
function mark_attempt(): void
|
|
{
|
|
@file_put_contents(LAST_ATTEMPT_FILE, (string)microtime(true), LOCK_EX);
|
|
}
|
|
|
|
function collect_once(): bool
|
|
{
|
|
$tcpMs = 0;
|
|
$connectMs = 0;
|
|
$readMs = 0;
|
|
$tcpError = '';
|
|
$trimError = '';
|
|
|
|
$sentBytes = 0;
|
|
$receivedBytes = 0;
|
|
$rawFull = tcp_request(
|
|
'se',
|
|
$tcpMs,
|
|
$connectMs,
|
|
$readMs,
|
|
$tcpError,
|
|
'collector_se',
|
|
null,
|
|
$sentBytes,
|
|
$receivedBytes
|
|
);
|
|
if ($rawFull === '') {
|
|
return false;
|
|
}
|
|
|
|
$rawTrim = make_trim($rawFull, $trimError);
|
|
if ($rawTrim === '') {
|
|
return false;
|
|
}
|
|
|
|
$data = parse_trim($rawTrim);
|
|
if (!is_valid_status_data($data)) {
|
|
return false;
|
|
}
|
|
|
|
db_insert_status(
|
|
db(),
|
|
'se',
|
|
$rawFull,
|
|
$rawTrim,
|
|
$data
|
|
);
|
|
|
|
return true;
|
|
}
|
|
|
|
if (!is_fast_poll_state() && should_skip_non_driving()) {
|
|
exit(0);
|
|
}
|
|
|
|
mark_attempt();
|
|
collect_once();
|