feat: add sleep mode

This commit is contained in:
Benjamin Nussbaum 2025-07-04 21:47:55 +02:00
parent f767d39c8f
commit 4b748b102b
5 changed files with 232 additions and 59 deletions

View file

@ -23,6 +23,10 @@ class Device extends Model
'height' => 'integer',
'rotate' => 'integer',
'last_refreshed_at' => 'datetime',
'sleep_mode_enabled' => 'boolean',
'sleep_mode_from' => 'datetime:H:i',
'sleep_mode_to' => 'datetime:H:i',
'special_function' => 'string',
];
public function getBatteryPercentAttribute()
@ -185,4 +189,36 @@ class Device extends Model
{
return $this->belongsTo(User::class);
}
public function isSleepModeActive(?\DateTimeInterface $now = null): bool
{
if (!$this->sleep_mode_enabled || !$this->sleep_mode_from || !$this->sleep_mode_to) {
return false;
}
$now = $now ? \Carbon\Carbon::instance($now) : now();
$from = $this->sleep_mode_from instanceof \Carbon\Carbon ? $this->sleep_mode_from : \Carbon\Carbon::createFromFormat('H:i:s', $this->sleep_mode_from);
$to = $this->sleep_mode_to instanceof \Carbon\Carbon ? $this->sleep_mode_to : \Carbon\Carbon::createFromFormat('H:i:s', $this->sleep_mode_to);
// Handle overnight ranges (e.g. 22:00 to 06:00)
return $from < $to
? $now->between($from, $to)
: ($now->gte($from) || $now->lte($to));
}
public function getSleepModeEndsInSeconds(?\DateTimeInterface $now = null): ?int
{
if (!$this->sleep_mode_enabled || !$this->sleep_mode_from || !$this->sleep_mode_to) {
return null;
}
$now = $now ? \Carbon\Carbon::instance($now) : now();
$from = $this->sleep_mode_from instanceof \Carbon\Carbon ? $this->sleep_mode_from : \Carbon\Carbon::createFromFormat('H:i:s', $this->sleep_mode_from);
$to = $this->sleep_mode_to instanceof \Carbon\Carbon ? $this->sleep_mode_to : \Carbon\Carbon::createFromFormat('H:i:s', $this->sleep_mode_to);
// Handle overnight ranges (e.g. 22:00 to 06:00)
if ($from < $to) {
return $now->between($from, $to) ? $now->diffInSeconds($to, false) : null;
} else {
return ($now->gte($from) || $now->lt($to)) ? $now->diffInSeconds($to->addDay(), false) : null;
}
}
}