From 44c4c84292697ab6e208605d7b213d2ec0953525 Mon Sep 17 00:00:00 2001 From: JonatanRek Date: Wed, 11 Mar 2020 12:22:44 +0100 Subject: [PATCH] Firmware Updater (Backend + GUI) --- .gitignore | 1 + api.php | 96 ++++++++++++++++------------- app/class/DeviceManager.php | 9 +++ app/templates/part/deviceEdit.phtml | 11 ++++ app/views/Home.php | 1 + update.php | 86 +++++++++++--------------- 6 files changed, 110 insertions(+), 94 deletions(-) diff --git a/.gitignore b/.gitignore index 527fcff..23e8a8b 100644 --- a/.gitignore +++ b/.gitignore @@ -6,5 +6,6 @@ _nemazat/css/main.css.map _nemazat/css/main.css _nemazat/css/font-awesome.min.css app/logs/*.log +.vscode/ .vscode/sftp.json app/updater/*.bin diff --git a/api.php b/api.php index 19d00dc..296e929 100644 --- a/api.php +++ b/api.php @@ -38,8 +38,9 @@ Db::connect (DBHOST, DBUSER, DBPASS, DBNAME); //Read API data $json = file_get_contents('php://input'); $obj = json_decode($json, true); + if (defined(DEBUGMOD) && DEBUGMOD == 1) { - $logManager->write("[API] Rest API request body -> decodet to json \n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO); + $logManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO); } //zabespecit proti Ddosu @@ -52,7 +53,7 @@ if (isset($obj['user']) && $obj['user'] != ''){ UserManager::atHome($userId, $atHome); $logManager->write("[Record] user " . $userId . " changet his home state to " . $atHome . " " . RECORDTIMOUT , LogRecordType::INFO); echo 'Saved: ' . $atHome; - header("HTTP/1.1 200 OK"); + header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); die(); } } @@ -64,7 +65,7 @@ if (DEBUGMOD != 1) { 'state' => 'unsuccess', 'errorMSG' => "Using API from your IP insnt alowed!", )); - header("HTTP/1.1 401 Unauthorized"); + header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); $logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING); exit(); } @@ -90,18 +91,23 @@ try { //Variables $token = $obj['token']; $values = null; +$settings = null; if (isset($obj['values'])) { $values = $obj['values']; } +if (isset($obj['settings'])) { + $settings = $obj['settings']; +} + //Checks if ($token == null || $token == "") { echo json_encode(array( 'state' => 'unsuccess', 'errorMSG' => "Missing Value Token in JSON payload", )); - header("HTTP/1.1 401 Unauthorized"); + header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); die(); } @@ -119,24 +125,24 @@ if (!DeviceManager::registeret($token)) { if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) { SubDeviceManager::create($deviceId, $key, UNITS[$key]); } - + if ($notificationData != []) { $subscribers = $notificationMng::getSubscription(); foreach ($subscribers as $key => $subscriber) { - $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " "); + $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO); $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); } } } - + //Notification for newly added Device $subscribers = $notificationMng::getSubscription(); foreach ($subscribers as $key => $subscriber) { - $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " "); + $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO); $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); } - - header("HTTP/1.1 401 Unauthorized"); + + header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); echo json_encode(array( 'state' => 'unsuccess', 'errorMSG' => "Device not registeret", @@ -146,7 +152,7 @@ if (!DeviceManager::registeret($token)) { } if (!DeviceManager::approved($token)) { - header("HTTP/1.1 401 Unauthorized"); + header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); echo json_encode(array( 'state' => 'unsuccess', 'errorMSG' => "Unaproved Device", @@ -154,9 +160,14 @@ if (!DeviceManager::approved($token)) { exit(); } +// Diagnostic Data Write to DB +if (isset($settings)){ + DeviceManager::editByToken($token, ['mac' => $settings["network"]["mac"], 'ip_address' => $settings["network"]["ip"]]); +} + // Subdevices first data! if ($values != null || $values != "") { - + //ZAPIS $device = DeviceManager::getDeviceByToken($token); $deviceId = $device['device_id']; @@ -166,40 +177,40 @@ if ($values != null || $values != "") { } RecordManager::create($deviceId, $key, round($value['value'],3)); $logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::INFO); - + //notification if ($key == 'door' || $key == 'water') { $notificationMng = new NotificationManager; $notificationData = []; - + switch ($key) { case 'door': - $notificationData = [ - 'title' => 'Info', - 'body' => 'Someone just open up '.$device['name'], - 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', - ]; - + $notificationData = [ + 'title' => 'Info', + 'body' => 'Someone just open up '.$device['name'], + 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', + ]; + break; case 'water': - $notificationData = [ - 'title' => 'Alert', - 'body' => 'Wather leak detected by '.$device['name'], - 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', - ]; + $notificationData = [ + 'title' => 'Alert', + 'body' => 'Wather leak detected by '.$device['name'], + 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', + ]; break; } if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value']; if ($notificationData != []) { $subscribers = $notificationMng::getSubscription(); foreach ($subscribers as $key => $subscriber) { - $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " "); + $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO); $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); } } } } - + $hostname = strtolower($device['name']); $hostname = str_replace(' ', '_', $hostname); $jsonAnswer = [ @@ -211,46 +222,45 @@ if ($values != null || $values != "") { ], 'state' => 'succes', ]; - + $subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId); if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) { $jsonAnswer['device']['sleepTime'] = $device['sleep_time']; } echo json_encode($jsonAnswer); - header("HTTP/1.1 200 OK"); + header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); } else { //Vypis - //TODO: doděla uložení výpisu jinými slovy zda li byl comman vykonán $device = DeviceManager::getDeviceByToken($token); $deviceId = $device['device_id']; - + if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) { SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]); //RecordManager::create($deviceId, 'on/off', 0); } - + $subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id']; $subDeviceLastReord = RecordManager::getLastRecord($subDeviceId); $subDeviceLastReordValue = $subDeviceLastReord['value']; - + if ($subDeviceLastReord['execuded'] == 0){ $logManager->write("[API] subDevice id ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded']); RecordManager::setExecuted($subDeviceLastReord['record_id']); } - + echo json_encode(array( 'device' => [ 'hostname' => $device['name'], 'ipAddress' => $device['ip_address'], 'subnet' => $device['subnet'], 'gateway' => $device['gateway'], - ], - 'state' => 'succes', - 'value' => $subDeviceLastReordValue - )); - header("HTTP/1.1 200 OK"); - } + ], + 'state' => 'succes', + 'value' => $subDeviceLastReordValue + )); + header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); +} - unset($logManager); - Db::disconect(); - die(); +unset($logManager); +Db::disconect(); +die(); diff --git a/app/class/DeviceManager.php b/app/class/DeviceManager.php index 6ae72ae..6971bee 100644 --- a/app/class/DeviceManager.php +++ b/app/class/DeviceManager.php @@ -47,6 +47,15 @@ class DeviceManager{ } } + public function editByToken ($token, $values = []) { + try { + Db::edit ('devices', $values, 'WHERE token = ?', array($deviceId)); + } catch(PDOException $error) { + echo $error->getMessage(); + die(); + } + } + /** * [assignRoom Přiřazení zařízení do třídy] * @param [type] $roomId [číslo místnosti do kter se má zařízení přiřadit] diff --git a/app/templates/part/deviceEdit.phtml b/app/templates/part/deviceEdit.phtml index 11bfe39..a7f03e6 100644 --- a/app/templates/part/deviceEdit.phtml +++ b/app/templates/part/deviceEdit.phtml @@ -67,6 +67,10 @@
Type:
+
+
Mac Address:
+ +
IP:
@@ -85,6 +89,13 @@
DNS:
+ +

echo('t_deviceVersion'); ?>

+
+
echo('l_uploadFirmware'); ?>
+ +
+
diff --git a/app/views/Home.php b/app/views/Home.php index 11ef750..24e4f89 100644 --- a/app/views/Home.php +++ b/app/views/Home.php @@ -161,6 +161,7 @@ class Home extends Template 'room' => $deviceData['room_id'], 'token' => $deviceData['token'], 'type' => $deviceData['type'], + 'mac' => $deviceData['mac'], 'ip' => $deviceData['ip_address'], 'subnet' => $deviceData['subnet'], 'gateway' => $deviceData['gateway'], diff --git a/update.php b/update.php index ae83a66..e756b62 100644 --- a/update.php +++ b/update.php @@ -23,65 +23,49 @@ foreach($files as $file) { include './app/class/'. $file; } $logManager = new LogManager(); -header('Content-type: text/plain; charset=utf8', true); -/* -function check_header($name, $value = false) -{ - if (!isset($_SERVER[$name])) { - return false; - } - if ($value && $_SERVER[$name] != $value) { - return false; - } - return true; -}*/ +header('Content-type: text/plain; charset=utf8', true); function sendFile($path) { - header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK', true, 200); - header('Content-Type: application/octet-stream', true); - header('Content-Disposition: attachment; filename=' . basename($path)); - header('Content-Length: ' . filesize($path), true); - header('x-MD5: ' . md5_file($path), true); - readfile($path); + header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK', true, 200); + header('Content-Type: application/octet-stream', true); + header('Content-Disposition: attachment; filename=' . basename($path)); + header('Content-Length: ' . filesize($path), true); + header('x-MD5: ' . md5_file($path), true); + readfile($path); } - -/*if (!check_header('HTTP_USER_AGENT', 'ESP8266-http-Update')) { - header($_SERVER["SERVER_PROTOCOL"] . ' 403 Forbidden', true, 403); - echo "only for ESP8266 updater!\n"; - exit(); -} - -if ( - !check_header('HTTP_X_ESP8266_STA_MAC') || - !check_header('HTTP_X_ESP8266_AP_MAC') || - !check_header('HTTP_X_ESP8266_FREE_SPACE') || - !check_header('HTTP_X_ESP8266_SKETCH_SIZE') || - !check_header('HTTP_X_ESP8266_SKETCH_MD5') || - !check_header('HTTP_X_ESP8266_CHIP_SIZE') || - !check_header('HTTP_X_ESP8266_SDK_VERSION') -) { - header($_SERVER["SERVER_PROTOCOL"] . ' 403 Forbidden', true, 403); - echo "only for ESP8266 updater! (header)\n"; - exit(); -}*/ - - - - $localBinary = "./app/updater/" . str_replace(':', '', $_SERVER['HTTP_X_ESP8266_STA_MAC']) . ".bin"; -$logManager->write("[Update] url: " . $localBinary, LogRecordType::INFO); -$logManager->write("[Update] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordType::INFO); +$logManager->write("[Updater] url: " . $localBinary, LogRecordType::INFO); +$logManager->write("[Updater] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordType::INFO); + if (file_exists($localBinary)) { - $logManager->write("[Update] version PHP: " . md5_file($localBinary), LogRecordType::INFO); + $logManager->write("[Updater] version PHP: " . md5_file($localBinary), LogRecordType::INFO); if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) { - sendFile($localBinary); + sendFile($localBinary); + + //notification + $notificationMng = new NotificationManager; + $notificationData = [ + 'title' => 'Info', + 'body' => 'Someone device was just updated to new version', + 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', + ]; + + if ($notificationData != []) { + $subscribers = $notificationMng::getSubscription(); + foreach ($subscribers as $key => $subscriber) { + $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO); + $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); + } + } + } else { + header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304); + } } else { - header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304); + header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); } -} else { - header("HTTP/1.1 404 Not Found"); -} -die(); + header($_SERVER["SERVER_PROTOCOL"].' 500 no version for ESP MAC', true, 500); + die(); + \ No newline at end of file