Fix to improve accuracy of timer

Timer was not accurate as it was depending on the asyncio.sleep function which is most liklely not exactly one second depending on other functions running in parallel.

Now the timer is comparable to cbpi3 where it runs until an end time is reached.

This is to address issue #66 and has been tested
This commit is contained in:
avollkopf 2021-04-08 14:40:47 +02:00
parent 5cb0ce76de
commit 28f4113f2f

View file

@ -13,27 +13,29 @@ class Timer(object):
self._callback = on_done self._callback = on_done
self._update = on_update self._update = on_update
self.start_time = None self.start_time = None
self.end_time = None
def done(self, task): def done(self, task):
if self._callback is not None: if self._callback is not None:
asyncio.create_task(self._callback(self)) asyncio.create_task(self._callback(self))
async def _job(self): async def _job(self):
self.start_time = time.time() self.start_time = int(time.time())
self.count = int(round(self._timemout, 0)) self.end_time = self.start_time + int(round(self._timemout, 0))
self.count = self.end_time - self.start_time
try: try:
while self.count > 0: while self.count > 0:
self.count -= 1 self.count = (self.end_time - int(time.time()))
if self._update is not None: if self._update is not None:
await self._update(self,self.count) await self._update(self,self.count)
await asyncio.sleep(1) await asyncio.sleep(1)
except asyncio.CancelledError: except asyncio.CancelledError:
end = time.time() end = int(time.time())
duration = end - self.start_time duration = end - self.start_time
self._timemout = self._timemout - duration self._timemout = self._timemout - duration
async def add(self, seconds): async def add(self, seconds):
self.count = self.count + seconds self.end_time = self.end_time + seconds
def start(self): def start(self):
self._task = asyncio.create_task(self._job()) self._task = asyncio.create_task(self._job())