Files
dc-sensor/software/database/sqlite.php
T
2024-07-13 14:30:34 +02:00

195 lines
6.4 KiB
PHP

<?php
interface DBIface
{
public function __construct();
public function addDevice($deviceData);
public function getDevices();
public function getDeviceById($id);
public function updateDevice($id, $deviceData);
public function deleteDevice($id);
public function createOrUpdateReading($deviceID, $temperature, $humidity);
}
class DB implements DBIface {
private $pdo;
public function __construct() {
try {
if (!file_exists(__DIR__ . '/db.sqlite')) {
$this->pdo = new PDO('sqlite:'.__DIR__.'/db.sqlite');
$this->createTables();
syslog(LOG_INFO,"New SQLite Database was created.");
}
else {
$this->pdo = new PDO('sqlite:'.__DIR__.'/db.sqlite');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec("PRAGMA foreign_keys = ON");
}
} catch (PDOException $e) {
syslog(LOG_EMERG,"Could not connect to the database: " . $e->getMessage());
die("Could not connect to the database: " . $e->getMessage());
}
}
public function createTables() {
$sql = "
CREATE TABLE IF NOT EXISTS devices (
id INTEGER PRIMARY KEY,
mac_address TEXT NOT NULL,
ip_address TEXT NOT NULL,
ip_address_seen TEXT NOT NULL,
firmware_version INTEGER NOT NULL,
temperature_offset INTEGER DEFAULT 0,
humidity_offset 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);
echo "Table 'devices' and 'readings' created successfully.";
} catch (PDOException $e) {
die("Error creating table: " . $e->getMessage());
}
}
public function addDevice($deviceData) {
$sql = "
INSERT INTO devices (mac_address, ip_address, ip_address_seen, firmware_version, temperature_offset, humidity_offset, last_seen)
VALUES (:mac_address, :ip_address, :ip_address_seen, :firmware_version, :temperature_offset, :humidity_offset, :last_seen)
";
try {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($deviceData);
return $this->pdo->lastInsertId();
} catch (PDOException $e) {
die("Error inserting device: " . $e->getMessage());
}
}
public function getDevices() {
$sql = "SELECT * FROM devices";
try {
$stmt = $this->pdo->query($sql);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error fetching devices: " . $e->getMessage());
}
}
public function getDeviceById($id) {
$sql = "SELECT * FROM devices WHERE id = :id";
try {
$stmt = $this->pdo->prepare($sql);
$stmt->execute(['id' => $id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error fetching device: " . $e->getMessage());
}
}
public function updateDevice($id, $deviceData) {
// Start building the SQL query
$sql = "UPDATE devices SET ";
// Add the columns to be updated
$columns = [];
foreach ($deviceData as $column => $value) {
$columns[] = "$column = :$column";
}
$sql .= implode(", ", $columns);
// Add the WHERE clause based on id
$sql .= " WHERE id = :id";
try {
// Prepare the statement
$stmt = $this->pdo->prepare($sql);
// Bind the parameters for the columns to be updated
foreach ($deviceData as $column => $value) {
$stmt->bindValue(":$column", $value);
}
// Bind the parameter for the id
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
// Execute the statement
return $stmt->execute();
} catch (PDOException $e) {
die("Error updating device: " . $e->getMessage());
}
}
public function deleteDevice($id) {
$sql = "DELETE FROM devices WHERE id = :id";
try {
$stmt = $this->pdo->prepare($sql);
$stmt->execute(['id' => $id]);
return $stmt->rowCount();
} catch (PDOException $e) {
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());
}
}
}
/*
$newDevice = [
'id' => 'device123',
'mac_address' => '00:1B:44:11:3A:B7',
'ip_address' => '192.168.1.2',
'ip_address_seen' => '212.71.123.123',
'firmware_version' => '1.0.1',
'temperature_offset' => 0,
'humidity_offset' => 0,
'last_updated' => date('Y-m-d H:i:s'),
'last_seen' => date('Y-m-d H:i:s')
];
$deviceDb->addDevice($newDevice);
$devices = $deviceDb->getDevices();
print_r($devices);
*/
?>