| Server IP : 93.86.61.54 / Your IP : 216.73.216.60 Web Server : Apache/2.4.62 (Ubuntu) System : Linux rasin.ddns.net 6.8.0-124-generic #124~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Tue May 26 21:05:19 UTC x86_64 User : www-data ( 33) PHP Version : 8.4.22 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/html/projects/tempcontrol/backup/ |
Upload File : |
<?php
// temperature_handler.php - Kompletan kod sa bazom podataka
// ================= KONFIGURACIJA =================
define('API_KEY', 'esp32-secure-key-2024');
define('LOW_TEMP_THRESHOLD', 18.0);
define('HIGH_TEMP_THRESHOLD', 25.0);
define('HYSTERESIS', 1.0);
define('LOG_FILE', __DIR__ . '/temperature.log');
// Konfiguracija baze podataka
define('DB_HOST', 'localhost');
define('DB_NAME', 'temperature_db');
define('DB_USER', 'temperature_user');
define('DB_PASS', 'secure_password_123');
define('DB_CHARSET', 'utf8mb4');
// Dozvoljeni sensor IDs
$allowedSensors = ['esp32-bme280-01', 'esp32-bme280-02'];
// ================= INICIJALIZACIJA =================
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key');
// Obradi OPTIONS zahtev za CORS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
// Funkcija za logovanje
function logEvent($level, $message) {
$logEntry = sprintf(
"[%s] [%s] %s\n",
date('Y-m-d H:i:s'),
$level,
$message
);
@file_put_contents(LOG_FILE, $logEntry, FILE_APPEND | LOCK_EX);
}
// Funkcija za slanje JSON greške
function sendJsonError($message, $code = 500) {
http_response_code($code);
echo json_encode([
'status' => 'error',
'message' => $message,
'timestamp' => date('Y-m-d H:i:s')
], JSON_UNESCAPED_UNICODE);
exit;
}
// Provera HTTP metode
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
sendJsonError('Samo POST zahtevi su dozvoljeni', 405);
}
// ================= AUTENTIFIKACIJA =================
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
if (empty($apiKey)) {
sendJsonError('API ključ je obavezan', 401);
}
if ($apiKey !== API_KEY) {
sendJsonError('Nevažeći API ključ', 401);
}
// ================= KONEKCIJA SA BAZOM =================
try {
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
logEvent('INFO', 'Uspešna konekcija sa bazom podataka');
} catch (PDOException $e) {
logEvent('ERROR', 'Greška pri konekciji sa bazom: ' . $e->getMessage());
sendJsonError('Database connection failed', 500);
}
// ================= OBRADA ZAHTEVA =================
try {
$json = file_get_contents('php://input');
if (empty($json)) {
sendJsonError('JSON podaci su prazni', 400);
}
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
sendJsonError('Nevažeći JSON format: ' . json_last_error_msg(), 400);
}
// Validacija obaveznih polja
if (!isset($data['temperature']) || !isset($data['sensor_id'])) {
sendJsonError('Nedostaje temperatura ili sensor_id', 400);
}
$sensorId = trim($data['sensor_id']);
$temperature = floatval($data['temperature']);
$humidity = isset($data['humidity']) ? floatval($data['humidity']) : null;
$pressure = isset($data['pressure']) ? floatval($data['pressure']) : null;
// Provera dozvoljenog senzora
if (!in_array($sensorId, $allowedSensors)) {
sendJsonError('Nedozvoljeni sensor ID: ' . $sensorId, 403);
}
// Validacija temperature
if ($temperature < -50 || $temperature > 100) {
sendJsonError('Temperatura van opsega (-50 do 100)', 400);
}
// ================= LOGIKA ZA GREJANJE =================
$lastHeatingState = getLastHeatingState($pdo, $sensorId);
$isCurrentlyHeating = ($lastHeatingState === 'on');
// Određivanje komande sa histerezom
$heatingCommand = determineHeatingCommand($temperature, $isCurrentlyHeating);
// Snimanje podataka u bazu
$insertSuccess = saveTemperatureData($pdo, $sensorId, $temperature, $humidity, $pressure, $heatingCommand);
if (!$insertSuccess) {
logEvent('ERROR', 'Greška pri snimanju u bazu za sensor: ' . $sensorId);
sendJsonError('Database insert failed', 500);
}
// ================= GENERISANJE ODGOVORA =================
$response = [
'status' => 'success',
'received_data' => [
'temperature' => $temperature,
'humidity' => $humidity,
'pressure' => $pressure,
'sensor_id' => $sensorId,
'timestamp' => date('Y-m-d H:i:s')
],
'heating_command' => $heatingCommand,
'message' => getHeatingMessage($heatingCommand, $temperature),
'database' => [
'insert_id' => $pdo->lastInsertId(),
'rows_affected' => $insertSuccess
],
'threshold_info' => [
'low_threshold' => LOW_TEMP_THRESHOLD,
'high_threshold' => HIGH_TEMP_THRESHOLD,
'hysteresis' => HYSTERESIS,
'current_temperature' => $temperature
]
];
http_response_code(200);
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
logEvent('INFO', "Uspeh - Sensor $sensorId: Temp={$temperature}°C, Cmd=$heatingCommand, ID: " . $pdo->lastInsertId());
} catch (Exception $e) {
logEvent('ERROR', 'Exception: ' . $e->getMessage());
sendJsonError('Internal server error: ' . $e->getMessage(), 500);
}
// ================= POMOĆNE FUNKCIJE =================
function determineHeatingCommand($temperature, $isCurrentlyHeating) {
if ($isCurrentlyHeating) {
return ($temperature > (HIGH_TEMP_THRESHOLD + HYSTERESIS)) ? 'off' : 'on';
} else {
return ($temperature < (LOW_TEMP_THRESHOLD - HYSTERESIS)) ? 'on' : 'off';
}
}
function getHeatingMessage($command, $temperature) {
if ($command === 'on') {
return "Grejanje UKLJUČENO. Temperatura ($temperature°C) je ispod donjeg praga.";
} else {
return "Grejanje ISKLJUČENO. Temperatura ($temperature°C) je iznad gornjeg praga.";
}
}
function getLastHeatingState($pdo, $sensorId) {
try {
$stmt = $pdo->prepare("
SELECT heating_command FROM temperature_logs
WHERE sensor_id = ?
ORDER BY created_at DESC
LIMIT 1
");
$stmt->execute([$sensorId]);
$result = $stmt->fetch();
return $result ? $result['heating_command'] : 'off';
} catch (PDOException $e) {
logEvent('WARNING', 'getLastHeatingState error: ' . $e->getMessage());
return 'off';
}
}
function saveTemperatureData($pdo, $sensorId, $temperature, $humidity, $pressure, $command) {
try {
$stmt = $pdo->prepare("
INSERT INTO temperature_logs
(sensor_id, temperature, humidity, pressure, heating_command)
VALUES (?, ?, ?, ?, ?)
");
return $stmt->execute([$sensorId, $temperature, $humidity, $pressure, $command]);
} catch (PDOException $e) {
logEvent('ERROR', 'saveTemperatureData error: ' . $e->getMessage());
return false;
}
}
?>