2017-11-05 12:41:00 +01:00
< ? php
2018-04-11 19:49:35 +02:00
namespace Grocy\Services ;
class BatteriesService extends BaseService
2017-11-05 12:41:00 +01:00
{
2018-04-11 19:49:35 +02:00
public function GetCurrent ()
2017-11-05 12:41:00 +01:00
{
$sql = 'SELECT * from batteries_current' ;
2018-04-11 19:49:35 +02:00
return $this -> DatabaseService -> ExecuteDbQuery ( $sql ) -> fetchAll ( \PDO :: FETCH_OBJ );
2017-11-05 12:41:00 +01:00
}
2018-04-11 19:49:35 +02:00
public function GetNextChargeTime ( int $batteryId )
2017-11-05 12:41:00 +01:00
{
2018-04-22 14:25:08 +02:00
if ( ! $this -> BatteryExists ( $batteryId ))
{
throw new \Exception ( 'Battery does not exist' );
}
2018-04-11 19:49:35 +02:00
$battery = $this -> Database -> batteries ( $batteryId );
$batteryLastLogRow = $this -> DatabaseService -> ExecuteDbQuery ( " SELECT * from batteries_current WHERE battery_id = $batteryId LIMIT 1 " ) -> fetch ( \PDO :: FETCH_OBJ );
2017-11-05 12:41:00 +01:00
if ( $battery -> charge_interval_days > 0 )
{
return date ( 'Y-m-d H:i:s' , strtotime ( '+' . $battery -> charge_interval_days . ' day' , strtotime ( $batteryLastLogRow -> last_tracked_time )));
}
else
{
return date ( 'Y-m-d H:i:s' );
}
return null ;
}
2018-04-11 19:49:35 +02:00
public function GetBatteryDetails ( int $batteryId )
2017-11-05 12:41:00 +01:00
{
2018-04-22 14:25:08 +02:00
if ( ! $this -> BatteryExists ( $batteryId ))
{
throw new \Exception ( 'Battery does not exist' );
}
2018-04-11 19:49:35 +02:00
$battery = $this -> Database -> batteries ( $batteryId );
$batteryChargeCylcesCount = $this -> Database -> battery_charge_cycles () -> where ( 'battery_id' , $batteryId ) -> count ();
$batteryLastChargedTime = $this -> Database -> battery_charge_cycles () -> where ( 'battery_id' , $batteryId ) -> max ( 'tracked_time' );
2017-11-05 12:41:00 +01:00
return array (
'battery' => $battery ,
'last_charged' => $batteryLastChargedTime ,
'charge_cycles_count' => $batteryChargeCylcesCount
);
}
2018-04-11 19:49:35 +02:00
public function TrackChargeCycle ( int $batteryId , string $trackedTime )
2017-11-05 12:41:00 +01:00
{
2018-04-22 14:25:08 +02:00
if ( ! $this -> BatteryExists ( $batteryId ))
{
throw new \Exception ( 'Battery does not exist' );
}
2018-04-11 19:49:35 +02:00
$logRow = $this -> Database -> battery_charge_cycles () -> createRow ( array (
2017-11-05 12:41:00 +01:00
'battery_id' => $batteryId ,
'tracked_time' => $trackedTime
));
$logRow -> save ();
return true ;
}
2018-04-22 14:25:08 +02:00
private function BatteryExists ( $batteryId )
{
$batteryRow = $this -> Database -> batteries () -> where ( 'id = :1' , $batteryId ) -> fetch ();
return $batteryRow !== null ;
}
2017-11-05 12:41:00 +01:00
}