modified: app.php

modified:   database/sqlite.php
	modified:   device-api.php
This commit is contained in:
Sven Luethi committed 2024-07-13 13:47:52 +02:00
1 parent 9759ab5ee4
commit 7f93508eb3
3 files changed
+37 -21

No files matched your search

+26 -9
View File
@@ -1,5 +1,6 @@
<?php
function valid($msg, $key, $regex) {
//if(!isset($msg[$key])) {
/*
@@ -19,12 +20,12 @@ function valid($msg, $key, $regex) {
}
// Update device configuration
$router->post('/api/config', function($req) {
$router->post('/api/config', function($req) use($db) {
$msg = $req->getJSONBody();
if(!valid($msg,'mac_address', '/^[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]:[0-9a-f][0-9a-f]$/i') ||
!valid($msg,'ip_address', '/^[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$/i') ||
!valid($msg,'firmware_version', '/^[0-9]+\.[0-9]+$/') ||
!valid($msg,'firmware_version', '/^[0-9]+$/') ||
!valid($msg,'temperature_offset', '/^[0-9]+\.*[0-9]*$/') ||
!valid($msg,'humidity_offset', '/^[0-9]+\.*[0-9]*$/')
) {
@@ -35,6 +36,23 @@ $router->post('/api/config', function($req) {
// If device is already registered (it sends an ID) then figure out what values changed and send those back for the device to re-configure itself.
else if(valid($msg,'id','/^[0-9]+$/')) {
$deviceData = $db->getDeviceByID($msg['id']);
// If device is not registered yet...
if($deviceData == null) {
echo '{"error_message": "Device by that ID not found."}';
http_response_code(400);
return;
}
// Return stored device data so device may update its settings.
echo json_encode($deviceData);
// Update database entry based on post data received.
$db->updateDevice([
'mac_address' => $msg['mac_address'],
'ip_address' => $msg['ip_address'],
'ip_address_seen' => $_SERVER['REMOTE_ADDR'],
'firmware_version' => $msg['firmware_version'],
'last_seen' => date('Y-m-d H:i:s')
]);
http_response_code(200);
return;
}
@@ -42,14 +60,13 @@ $router->post('/api/config', function($req) {
// All fields are set and no ID was given. Register new device and return new ID...
else {
$config = [
'mac_address' => $msg['mac_address'],
'ip_address' => $msg['ip_address'],
'seen_ip_address' => $_SERVER['REMOTE_ADDR'],
'firmware_version' => $msg['firmware_version'],
'mac_address' => $msg['mac_address'],
'ip_address' => $msg['ip_address'],
'ip_address_seen' => $_SERVER['REMOTE_ADDR'],
'firmware_version' => $msg['firmware_version'],
'temperature_offset' => $msg['temperature_offset'],
'humidity_offset' => $msg['humidity_offset'],
'last_updated' => date('Y-m-d H:i:s'),
'last_seen' => date('Y-m-d H:i:s')
'humidity_offset' => $msg['humidity_offset'],
'last_seen' => date('Y-m-d H:i:s')
];
$deviceID = $db->addDevice($config);
echo json_encode(['deviceID' => $deviceID]);