76 lines
2.1 KiB
Python
76 lines
2.1 KiB
Python
import logging
|
|
|
|
|
|
class Timer:
|
|
"""
|
|
Generic timer (ignores mcu and energy status)
|
|
"""
|
|
|
|
_vmstate = None
|
|
|
|
def __init__(self, name, interrupt_signal, period=0, periodic=False):
|
|
"""
|
|
Initializes a timer
|
|
:param name: name of the timer
|
|
:param interrupt_signal: interrupt signal to trigger when timer expires
|
|
:param period: period of the timer in seconds
|
|
:param periodic: whether the timer is periodic
|
|
"""
|
|
self._name = name
|
|
self._interrupt_signal = interrupt_signal
|
|
self._period = period
|
|
self._periodic = periodic
|
|
self._timer_stopped = True
|
|
self._timer_start_period = 0
|
|
|
|
def start(self):
|
|
"""
|
|
Starts the timer if the period is positive
|
|
"""
|
|
if self._period > 0:
|
|
logging.debug(f"Starting timer {self._name} ({self._period}s)")
|
|
self._timer_stopped = False
|
|
self._timer_start_period = self._get_current_time()
|
|
|
|
def stop(self):
|
|
"""
|
|
Stops the timer
|
|
"""
|
|
self._timer_stopped = True
|
|
|
|
def restart(self):
|
|
"""
|
|
Restart the timer
|
|
"""
|
|
self._timer_start_period = self._get_current_time()
|
|
|
|
def set_period(self, period):
|
|
"""
|
|
Updates the timer period
|
|
:param period: period of the timer in seconds
|
|
"""
|
|
self._period = period
|
|
|
|
def check(self):
|
|
"""
|
|
Checks if the timer has expired, triggers the associated interrupt, and restarts the timer if necessary
|
|
"""
|
|
if self._timer_stopped:
|
|
return
|
|
|
|
if (self._get_current_time() - self._timer_start_period) >= self._period:
|
|
logging.debug(f"Timer {self._name} elapsed... triggering {self._interrupt_signal}")
|
|
self._vmstate.interrupts_manager.trigger_interrupt(self._interrupt_signal)
|
|
|
|
if self._periodic:
|
|
self.restart()
|
|
else:
|
|
self.stop()
|
|
|
|
def _get_current_time(self):
|
|
"""
|
|
Returns current time in seconds
|
|
"""
|
|
return self._vmstate.config.analysis.energy.system_model.get_simulation_time()
|
|
|