| 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/ |
Upload File : |
<?php
include 'config.php';
include 'database.php';
// Postavi CORS zaglavlja
header('Access-Control-Allow-Origin: ' . implode(', ', ALLOWED_ORIGINS));
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key');
header('Content-Type: application/json; charset=utf-8');
// Obradi OPTIONS zahtev za CORS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
// Provera HTTP metode
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
// Autentifikacija preko API ključa
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
if ($apiKey !== API_KEY) {
http_response_code(401);
echo json_encode(['error' => 'Invalid API key']);
logEvent('WARNING', 'Invalid API key attempt: ' . $apiKey);
exit;
}
// Provera Content-Type
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (stripos($contentType, 'application/json') === false) {
http_response_code(415);
echo json_encode(['error' => 'Unsupported Media Type. Use application/json']);
exit;
}
// Čitanje i parsiranje JSON podataka
$json = file_get_contents('php://input');
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON: ' . json_last_error_msg()]);
exit;
}
// Validacija obaveznih polja
$requiredFields = ['temperature', 'sensor_id'];
foreach ($requiredFields as $field) {
if (!isset($data[$field])) {
http_response_code(400);
echo json_encode(['error' => "Missing required field: $field"]);
exit;
}
}
$sensorId = $data['sensor_id'];
$temperature = floatval($data['temperature']);
$humidity = isset($data['humidity']) ? floatval($data['humidity']) : null;
$pressure = isset($data['pressure']) ? floatval($data['pressure']) : null;
// Provera da li je sensor dozvoljen
if (!in_array($sensorId, $allowedSensors)) {
http_response_code(403);
echo json_encode(['error' => 'Unauthorized sensor ID']);
logEvent('WARNING', "Unauthorized sensor attempt: $sensorId");
exit;
}
// Validacija temperature
if ($temperature < -50 || $temperature > 100) {
http_response_code(400);
echo json_encode(['error' => 'Temperature out of valid range (-50 to 100)']);
exit;
}
// Inicijalizacija baze
$db = new TemperatureDB();
// Dobijanje poslednjeg stanja grejanja za histerezu
$lastHeatingState = $db->getLastHeatingState($sensorId);
$lastHeatingOn = ($lastHeatingState === 'on');
// Logika za kontrolu grejanja sa histerezom
$heatingCommand = determineHeatingCommand($temperature, $lastHeatingOn);
// Snimanje u bazu
if ($db->logTemperature($sensorId, $temperature, $humidity, $pressure, $heatingCommand)) {
logEvent('INFO', "Sensor $sensorId: Temp=$temperature°C, Heating=$heatingCommand");
} else {
logEvent('ERROR', "Failed to log data for sensor $sensorId");
}
// Dodatne statistike
$stats = $db->getTemperatureStats($sensorId, 24);
// Generisanje odgovora
$response = [
'status' => 'success',
'data' => [
'received_temperature' => $temperature,
'received_humidity' => $humidity,
'received_pressure' => $pressure,
'sensor_id' => $sensorId
],
'command' => [
'heating' => $heatingCommand,
'message' => getHeatingMessage($heatingCommand, $temperature)
],
'thresholds' => [
'low_temp' => LOW_TEMP_THRESHOLD,
'high_temp' => HIGH_TEMP_THRESHOLD,
'hysteresis' => HYSTERESIS
],
'statistics' => $stats,
'timestamp' => date('Y-m-d H:i:s'),
'server_id' => gethostname()
];
http_response_code(200);
echo json_encode($response, JSON_PRETTY_PRINT);
// Funkcija za određivanje komande grejanja sa histerezom
function determineHeatingCommand($temperature, $isCurrentlyHeating) {
if ($isCurrentlyHeating) {
// Ako grejanje radi, gasi ga tek kada temperatura predje HIGH + histereza
if ($temperature > (HIGH_TEMP_THRESHOLD + HYSTERESIS)) {
return 'off';
}
return 'on';
} else {
// Ako grejanje ne radi, uključi ga kada temperatura padne ispod LOW - histereza
if ($temperature < (LOW_TEMP_THRESHOLD - HYSTERESIS)) {
return 'on';
}
return 'off';
}
}
// Funkcija za generisanje poruke
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.";
}
}
// Funkcija za logovanje
function logEvent($level, $message) {
$logEntry = sprintf(
"[%s] %s: %s\n",
date('Y-m-d H:i:s'),
$level,
$message
);
// Rotacija logova
if (file_exists(LOG_FILE) && filesize(LOG_FILE) > MAX_LOG_SIZE) {
$backupFile = LOG_FILE . '.' . date('Y-m-d_His');
rename(LOG_FILE, $backupFile);
}
file_put_contents(LOG_FILE, $logEntry, FILE_APPEND | LOCK_EX);
}
?>