withServiceAccount(storage_path('app/smartcab-8bb42-firebase-adminsdk-fbsvc-de33a8e45b.json')) ->withDatabaseUri(env('FIREBASE_DATABASE_URL')) ->createDatabase(); // Ambil data terbaru dari Firebase $securityData = $firebase->getReference('security')->getValue() ?? []; $smartcabData = $firebase->getReference('smartcab')->getValue() ?? []; $dht11Data = $firebase->getReference('dht11')->getValue() ?? []; // Baca history data yang sudah ada $historyData = []; if (Storage::exists('reports.json')) { $historyData = json_decode(Storage::get('reports.json'), true) ?: []; // Pastikan $historyData adalah array if (!is_array($historyData)) { $historyData = []; } } // Ambil data terakhir jika ada $lastEntry = !empty($historyData) ? end($historyData) : null; // Cek apakah ada perubahan pada security atau smartcab $hasChanges = false; if ($lastEntry === null) { // Jika belum ada data sama sekali, simpan data pertama $hasChanges = true; } else { // Bandingkan security dan smartcab dengan data terakhir $securityChanged = $this->hasDataChanged($lastEntry['security'] ?? [], $securityData); $smartcabChanged = $this->hasDataChanged($lastEntry['smartcab'] ?? [], $smartcabData); $hasChanges = $securityChanged || $smartcabChanged; } // Hanya simpan jika ada perubahan if ($hasChanges) { $newData = [ 'timestamp' => now()->toIso8601String(), 'security' => $securityData, 'smartcab' => $smartcabData ]; if (!empty($dht11Data)) { $newData['dht11'] = $dht11Data; } $historyData[] = $newData; Storage::put('reports.json', json_encode($historyData, JSON_PRETTY_PRINT)); $this->info('Data baru tersimpan karena ada perubahan pada security atau smartcab'); // Debug info if (isset($securityChanged) && $securityChanged) { $this->info('Perubahan terdeteksi pada security'); } if (isset($smartcabChanged) && $smartcabChanged) { $this->info('Perubahan terdeteksi pada smartcab'); } } else { $this->info('Tidak ada perubahan pada security atau smartcab, data tidak disimpan'); } } catch (\Exception $e) { $this->error('Error: ' . $e->getMessage()); } } private function hasDataChanged($oldData, $newData) { $flags = defined('JSON_SORT_KEYS') ? JSON_SORT_KEYS : 0; $oldJson = json_encode($oldData, $flags); $newJson = json_encode($newData, $flags); return $oldJson !== $newJson; } }