76 lines
2.7 KiB
PHP
76 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Device;
|
|
use App\Models\Entity;
|
|
use App\Services\NotificationService;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
/**
|
|
* Sweeps for alert conditions (device offline, low battery) and e-mails the SMTP add-on when a NEW
|
|
* one appears. A per-condition cache flag dedups, so you get one mail when it happens — not one
|
|
* every sweep — and the flag clears once the condition resolves (with hysteresis for batteries).
|
|
*/
|
|
class NotificationsSweepCommand extends Command
|
|
{
|
|
protected $signature = 'notifications:sweep';
|
|
|
|
protected $description = 'E-mail on new alert conditions (device offline, low battery).';
|
|
|
|
public function handle(NotificationService $notifier): int
|
|
{
|
|
// Nothing to do unless SMTP is configured.
|
|
if ($notifier->config() === null) {
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
$this->sweepOffline($notifier);
|
|
$this->sweepBatteries($notifier);
|
|
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
private function sweepOffline(NotificationService $notifier): void
|
|
{
|
|
foreach (Device::where('status', 'active')->where('demo', false)->get() as $device) {
|
|
$key = "notified:offline:{$device->id}";
|
|
|
|
if (! $device->isOnline()) {
|
|
if (! Cache::has($key) && $notifier->notify('device_offline',
|
|
__('notifications.device_offline_subject', ['name' => $device->name]),
|
|
__('notifications.device_offline_body', ['name' => $device->name]))) {
|
|
Cache::put($key, true, now()->addDay());
|
|
}
|
|
} else {
|
|
Cache::forget($key);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function sweepBatteries(NotificationService $notifier): void
|
|
{
|
|
$batteries = Entity::where('type', 'battery')->with('device', 'state')->get();
|
|
|
|
foreach ($batteries as $entity) {
|
|
if ($entity->device === null || $entity->device->demo) {
|
|
continue;
|
|
}
|
|
|
|
$pct = (int) data_get($entity->state, 'state.percent', 100);
|
|
$key = "notified:battery:{$entity->id}";
|
|
|
|
if ($pct > 0 && $pct < 20) {
|
|
if (! Cache::has($key) && $notifier->notify('low_battery',
|
|
__('notifications.low_battery_subject', ['name' => $entity->device->name]),
|
|
__('notifications.low_battery_body', ['name' => $entity->device->name, 'percent' => $pct]))) {
|
|
Cache::put($key, true, now()->addDay());
|
|
}
|
|
} elseif ($pct >= 25) {
|
|
Cache::forget($key); // hysteresis so it doesn't flap around the threshold
|
|
}
|
|
}
|
|
}
|
|
}
|