modified: software/database/sqlite.php
modified: software/device-api.php Temperature registration added
This commit is contained in:
1 parent
34593f7ea4
commit
13e6cf1032
2 files changed
+30
-44
No files matched your search
@@ -8,7 +8,6 @@ interface DBIface
|
||||
public function getDeviceById($id);
|
||||
public function updateDevice($id, $deviceData);
|
||||
public function deleteDevice($id);
|
||||
public function createOrUpdateReading($deviceID, $temperature, $humidity);
|
||||
}
|
||||
|
||||
|
||||
@@ -43,16 +42,11 @@ class DB implements DBIface {
|
||||
firmware_version INTEGER NOT NULL,
|
||||
temperature_offset INTEGER DEFAULT 0,
|
||||
humidity_offset INTEGER DEFAULT 0,
|
||||
temperature INTEGER DEFAULT 0,
|
||||
humidity INTEGER DEFAULT 0,
|
||||
read_at INTEGER DEFAULT 0,
|
||||
last_seen TEXT DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS readings (
|
||||
dev_id INTEGER PRIMARY KEY,
|
||||
temperature INTEGER NOT NULL,
|
||||
humidity INTEGER NOT NULL,
|
||||
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||
FOREIGN KEY(dev_id) REFERENCES devices(id) ON UPDATE CASCADE ON DELETE CASCADE
|
||||
);
|
||||
|
||||
";
|
||||
try {
|
||||
$this->pdo->exec($sql);
|
||||
@@ -98,6 +92,10 @@ class DB implements DBIface {
|
||||
}
|
||||
|
||||
public function updateDevice($id, $deviceData) {
|
||||
// Add last_seen parameter
|
||||
$deviceData['last_seen'] = date('Y-m-d H:i:s');
|
||||
|
||||
|
||||
// Start building the SQL query
|
||||
$sql = "UPDATE devices SET ";
|
||||
|
||||
@@ -141,37 +139,6 @@ public function updateDevice($id, $deviceData) {
|
||||
die("Error deleting device: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function createOrUpdateReading($deviceID, $temperature, $humidity) {
|
||||
$readingData = [
|
||||
"dev_id" => $deviceID,
|
||||
"temperature" => $temperature,
|
||||
"humidity" => $humidity
|
||||
];
|
||||
|
||||
$sql = "SELECT COUNT(*) FROM readings WHERE dev_id = :dev_id";
|
||||
try {
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
//$stmt->execute(['dev_id' => $deviceID]);
|
||||
$stmt->execute($readingData);
|
||||
$exists = $stmt->fetchColumn() > 0;
|
||||
|
||||
if ($exists) {
|
||||
$sql = "UPDATE readings SET temperature = :temperature, humidity = :humidity WHERE dev_id = :dev_id";
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($readingData);
|
||||
return $stmt->rowCount();
|
||||
}
|
||||
else {
|
||||
$sql = "INSERT INTO readings (dev_id, temperature, humidity) VALUES (:dev_id, :temperature, :humidity)";
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($readingData);
|
||||
return $this->pdo->lastInsertId();
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
die("Error creating or updating reading: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
Reference in new issue
Block a user