craftbeerpi4-pione/cbpi/api/step.py

100 lines
2.1 KiB
Python
Raw Normal View History

2019-01-05 20:43:48 +01:00
import asyncio
2021-02-16 20:37:51 +01:00
import json
2019-01-05 20:43:48 +01:00
import logging
2021-02-16 20:37:51 +01:00
import time
from abc import ABCMeta, abstractmethod
from enum import Enum
2021-02-10 07:38:55 +01:00
from cbpi.api.base import CBPiBase
2021-02-16 20:37:51 +01:00
from cbpi.api.config import ConfigType
__all__ = ["StepResult", "StepState", "StepMove", "CBPiStep"]
2021-02-10 07:38:55 +01:00
from enum import Enum
2021-01-17 22:49:18 +01:00
2021-02-16 20:37:51 +01:00
class StepResult(Enum):
STOP=1
NEXT=2
DONE=3
ERROR=4
class StepState(Enum):
INITIAL="I"
DONE="D"
ACTIVE="A"
ERROR="E"
STOP="S"
2021-02-10 07:38:55 +01:00
2021-02-16 20:37:51 +01:00
class StepMove(Enum):
UP=-1
DOWN=1
2021-02-16 20:37:51 +01:00
class CBPiStep(CBPiBase):
def __init__(self, cbpi, id, name, props, on_done) -> None:
self.name = name
2021-01-17 22:49:18 +01:00
self.cbpi = cbpi
self.id = id
2021-02-16 20:37:51 +01:00
self.timer = None
self._done_callback = on_done
self.props = props
self.cancel_reason: StepResult = None
self.summary = ""
2021-02-10 07:38:55 +01:00
2021-02-16 20:37:51 +01:00
def _done(self, task):
self._done_callback(self, task.result())
2021-02-10 07:38:55 +01:00
async def start(self):
2021-02-16 20:37:51 +01:00
self.task = asyncio.create_task(self._run())
self.task.add_done_callback(self._done)
async def next(self):
self.cancel_reason = StepResult.NEXT
self.task.cancel()
await self.task
2021-01-17 22:49:18 +01:00
2021-02-16 20:37:51 +01:00
async def stop(self):
try:
self.cancel_reason = StepResult.STOP
self.task.cancel()
await self.task
except:
pass
async def reset(self):
pass
async def on_props_update(self, props):
self.props = {**self.props, **props}
2021-03-07 23:52:20 +01:00
async def save_props(self):
await self.cbpi.step.save()
2021-02-10 07:38:55 +01:00
2021-02-16 20:37:51 +01:00
async def push_update(self):
self.cbpi.step.push_udpate()
2021-02-10 07:38:55 +01:00
2021-02-16 20:37:51 +01:00
async def on_start(self):
pass
2021-01-17 22:49:18 +01:00
2021-02-16 20:37:51 +01:00
async def on_stop(self):
pass
2021-01-17 22:49:18 +01:00
2021-02-16 20:37:51 +01:00
async def _run(self):
2021-02-10 07:38:55 +01:00
try:
2021-02-16 20:37:51 +01:00
await self.on_start()
await self.run()
self.cancel_reason = StepResult.DONE
except asyncio.CancelledError as e:
pass
finally:
await self.on_stop()
2021-02-07 13:08:13 +01:00
2021-02-16 20:37:51 +01:00
return self.cancel_reason
2021-01-17 22:49:18 +01:00
@abstractmethod
2021-02-16 20:37:51 +01:00
async def run(self):
2021-01-17 22:49:18 +01:00
pass
2019-01-05 20:43:48 +01:00
2021-02-16 20:37:51 +01:00
def __str__(self):
return "name={} props={}, type={}".format(self.name, self.props, self.__class__.__name__)