Registration working

This commit is contained in:
Sven Luethi committed 2024-07-13 14:30:34 +02:00
1 parent 7f93508eb3
commit 34593f7ea4
2 files changed
+52 -45

No files matched your search

+23 -27
View File
@@ -27,38 +27,18 @@ $router->post('/api/config', function($req) use($db) {
!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]+$/') ||
!valid($msg,'temperature_offset', '/^[0-9]+\.*[0-9]*$/') ||
!valid($msg,'humidity_offset', '/^[0-9]+\.*[0-9]*$/')
!valid($msg,'humidity_offset', '/^[0-9]+\.*[0-9]*$/') ||
!valid($msg,'id','/^[0-9]+$/')
) {
echo '{"error_message": "Field verification failed."}';
http_response_code(400);
return;
}
// 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;
}
// All fields are set and no ID was given. Register new device and return new ID...
else {
$deviceData = $msg['id'] == 0 ? null : $db->getDeviceByID($msg['id']);
// If device is not registered yet, register...
if($deviceData == null) {
// All fields are set and no ID was given. Register new device and return new ID...
$config = [
'mac_address' => $msg['mac_address'],
'ip_address' => $msg['ip_address'],
@@ -69,9 +49,25 @@ $router->post('/api/config', function($req) use($db) {
'last_seen' => date('Y-m-d H:i:s')
];
$deviceID = $db->addDevice($config);
echo json_encode(['deviceID' => $deviceID]);
$config['deviceID'] = $deviceID;
echo json_encode($config);
http_response_code(200);
return;
}
// If device is registered...
// Update database entry based on post data received.
$db->updateDevice($deviceData['id'],
[
'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')
]);
// Return stored device data so device may update its settings.
echo json_encode($deviceData);
http_response_code(200);
return;
});
// Device reports temperature back on this endpoint.