2021-03-14 11:52:46 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import asyncio
|
2021-03-18 19:27:03 +01:00
|
|
|
|
|
|
|
from cbpi.api import parameters, Property, CBPiSensor
|
2021-03-14 11:52:46 +01:00
|
|
|
|
|
|
|
|
|
|
|
@parameters([Property.Text(label="Topic", configurable=True)])
|
|
|
|
class MQTTSensor(CBPiSensor):
|
2021-03-18 19:27:03 +01:00
|
|
|
|
2021-03-14 11:52:46 +01:00
|
|
|
async def on_message(self, message):
|
|
|
|
try:
|
2021-03-18 19:27:03 +01:00
|
|
|
self.value = float(message)
|
2021-03-14 11:52:46 +01:00
|
|
|
self.log_data(self.value)
|
2021-03-18 19:27:03 +01:00
|
|
|
self.push_update(self.value)
|
2021-03-14 11:52:46 +01:00
|
|
|
except Exception as e:
|
|
|
|
print(e)
|
|
|
|
|
|
|
|
def __init__(self, cbpi, id, props):
|
|
|
|
super(MQTTSensor, self).__init__(cbpi, id, props)
|
|
|
|
self.mqtt_task = self.cbpi.satellite.subcribe(self.props.Topic, self.on_message)
|
2021-03-18 19:27:03 +01:00
|
|
|
self.value: int = 0
|
|
|
|
|
2021-03-14 11:52:46 +01:00
|
|
|
async def run(self):
|
2021-03-18 19:27:03 +01:00
|
|
|
while self.running:
|
2021-03-14 11:52:46 +01:00
|
|
|
await asyncio.sleep(1)
|
|
|
|
|
|
|
|
def get_state(self):
|
|
|
|
return dict(value=self.value)
|
|
|
|
|
|
|
|
async def on_stop(self):
|
|
|
|
if self.mqtt_task.done() is False:
|
|
|
|
self.mqtt_task.cancel()
|
|
|
|
try:
|
|
|
|
await self.mqtt_task
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2021-03-18 19:27:03 +01:00
|
|
|
def setup(cbpi):
|
2021-03-14 11:52:46 +01:00
|
|
|
'''
|
2021-03-18 19:27:03 +01:00
|
|
|
This method is called by the server during startup
|
2021-03-14 11:52:46 +01:00
|
|
|
Here you need to register your plugins at the server
|
2021-03-18 19:27:03 +01:00
|
|
|
|
|
|
|
:param cbpi: the cbpi core
|
|
|
|
:return:
|
2021-03-14 11:52:46 +01:00
|
|
|
'''
|
|
|
|
if cbpi.static_config.get("mqtt", False) is True:
|
|
|
|
cbpi.plugin.register("MQTTSensor", MQTTSensor)
|