craftbeerpi4-pione/core/controller/sensor_controller.py

49 lines
1.6 KiB
Python
Raw Normal View History

2018-12-29 00:27:19 +01:00
import json
2018-11-01 19:50:04 +01:00
import logging
2019-01-01 15:35:35 +01:00
2018-11-01 19:50:04 +01:00
from core.controller.crud_controller import CRUDController
from core.database.model import SensorModel
from core.http_endpoints.http_api import HttpAPI
2019-01-01 15:35:35 +01:00
from core.job.aiohttp import get_scheduler_from_app
from core.utils.encoder import ComplexEncoder
2018-11-01 19:50:04 +01:00
class SensorController(CRUDController, HttpAPI):
model = SensorModel
2018-11-01 21:25:42 +01:00
def __init__(self, cbpi):
self.cbpi = cbpi
self.cbpi.register(self, "/sensor")
2018-11-01 19:50:04 +01:00
self.service = self
2018-11-18 15:40:10 +01:00
self.types = {}
2019-01-01 15:35:35 +01:00
self.logger = logging.getLogger(__name__)
2018-11-18 23:09:17 +01:00
self.sensors = {}
2018-11-16 20:35:59 +01:00
2018-12-29 00:27:19 +01:00
def info(self):
2018-11-16 20:35:59 +01:00
2018-12-29 00:27:19 +01:00
return json.dumps(dict(name="SensorController", types=self.types), cls=ComplexEncoder)
2018-11-01 19:50:04 +01:00
2018-11-18 15:40:10 +01:00
async def init(self):
'''
This method initializes all actors during startup. It creates actor instances
:return:
'''
await super(SensorController, self).init()
2018-12-29 00:27:19 +01:00
2019-01-01 15:35:35 +01:00
2018-11-18 15:40:10 +01:00
for id, value in self.cache.items():
if value.type in self.types:
cfg = value.config.copy()
cfg.update(dict(cbpi=self.cbpi, id=id, name=value.name))
clazz = self.types[value.type]["class"];
self.cache[id].instance = clazz(**cfg)
scheduler = get_scheduler_from_app(self.cbpi.app)
self.cache[id].instance.job = await scheduler.spawn(self.cache[id].instance.run(self.cbpi), value.name, "sensor")
2019-01-01 15:35:35 +01:00
else:
self.logger.error("Sensor type '%s' not found (Available Sensor Types: %s)" % (value.type, ', '.join(self.types.keys())))
2018-11-04 01:55:54 +01:00
2018-11-18 23:09:17 +01:00
async def get_value(self, id):
return self.cache[id].instance.value