door: don't require default row in database

This commit is contained in:
2026-01-13 11:35:34 +09:00
parent b9992c7c57
commit 32ba9c11f7
6 changed files with 36 additions and 17 deletions

View File

@@ -39,11 +39,6 @@ CREATE TABLE motd (
);
CREATE TABLE door (
`time` DATETIME PRIMARY KEY,
`time` INTEGER PRIMARY KEY,
`open` BOOLEAN NOT NULL
);
INSERT INTO
`door`(`time`, `open`)
VALUES
(0, FALSE);

View File

@@ -38,9 +38,7 @@ CREATE TABLE "motd" (
"content" TEXT NOT NULL
);
CREATE TABLE "door" ("time" INTEGER PRIMARY KEY, "open" BOOLEAN);
INSERT INTO
"door"("time", "open")
VALUES
(0, FALSE);
CREATE TABLE "door" (
"time" INTEGER PRIMARY KEY,
"open" BOOLEAN NOT NULL
);

View File

@@ -70,9 +70,9 @@ class Door {
}
/**
* @return array{time: DateTimeImmutable, open: bool}
* @return ?array{time: DateTimeImmutable, open: bool}
*/
public function getCurrent(): array {
public function getCurrent(): ?array {
$query = '
SELECT
time,
@@ -85,6 +85,10 @@ class Door {
$statement->execute();
$row = $statement->fetch();
if (!$row) {
return null;
}
return [
'time' => (new DateTimeImmutable)->setTimestamp((int) $row['time']),
'open' => (bool) $row['open'],

View File

@@ -60,7 +60,12 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
]);
} else {
// Only last entry
$line = (object) $door->getCurrent();
$line = $door->getCurrent();
if (is_null($line)) {
echo '{"status": "error", "message": "No door data"}';
exit;
}
$line = (object) $line;
echo json_encode([
'status' => 'OK',
'time' => $line->time->getTimestamp(),

View File

@@ -9,7 +9,16 @@ $motdfetcher = new pvv\side\MOTD($pdo);
$motd = $motdfetcher->getMOTD();
$door = new pvv\side\Door($pdo);
$doorEntry = (object) $door->getCurrent();
$doorEntry = $door->getCurrent();
if (!is_null($doorEntry)) {
$doorEntry = (object) $doorEntry;
} else {
$doorEntry = (object) [
'time' => new DateTimeImmutable('@0'),
'open' => false,
];
}
if ($doorEntry->time->getTimestamp() < (time() - 60 * 30)) {
$doorStateText = 'Ingen data fra dørsensor';
} else {

View File

@@ -9,7 +9,15 @@ $pdo = new PDO($DB_DSN, $DB_USER, $DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$door = new pvv\side\Door($pdo);
$doorEntry = (object) $door->getCurrent();
$doorEntry = $door->getCurrent();
if (!is_null($doorEntry)) {
$doorEntry = (object) $doorEntry;
} else {
$doorEntry = (object) [
'time' => new DateTimeImmutable('@0'),
'open' => false,
];
}
?>
{