fix props for plugin

This commit is contained in:
Manuel Fritsch 2021-02-02 21:22:59 +01:00
parent b3af77fdb8
commit 64dea90e3b
11 changed files with 255 additions and 34 deletions

View file

@ -1 +1 @@
__version__ = "4.0.0.13" __version__ = "4.0.0.14"

View file

@ -24,6 +24,7 @@ class ConfigController:
async def init(self): async def init(self):
this_directory = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2]) this_directory = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])
self.static = load_config("{}/config/config.yaml".format(this_directory)) self.static = load_config("{}/config/config.yaml".format(this_directory))
items = await self.model.get_all() items = await self.model.get_all()
for key, value in items.items(): for key, value in items.items():

View file

@ -28,6 +28,7 @@ from cbpi.eventbus import CBPiEventBus
from cbpi.http_endpoints.http_login import Login from cbpi.http_endpoints.http_login import Login
from cbpi.utils import * from cbpi.utils import *
from cbpi.websocket import CBPiWebSocket from cbpi.websocket import CBPiWebSocket
from cbpi.satellite import CBPiSatellite
from cbpi.http_endpoints.http_actor import ActorHttpEndpoints from cbpi.http_endpoints.http_actor import ActorHttpEndpoints
from cbpi.http_endpoints.http_config import ConfigHttpEndpoints from cbpi.http_endpoints.http_config import ConfigHttpEndpoints
@ -69,10 +70,12 @@ class CraftBeerPi:
def __init__(self): def __init__(self):
self.path = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-1]) # The path to the package dir self.path = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-1]) # The path to the package dir
self.version = __version__ self.version = __version__
self.static_config = load_config("{}/config/config.yaml".format(self.path)) self.static_config = load_config(os.path.join(".", 'config', "config.yaml"))
self.database_file = "{}/craftbeerpi.db".format(self.path) print(self.path, self.static_config)
self.database_file = os.path.join(".", 'config', "craftbeerpi.db")
logger.info("Init CraftBeerPI") logger.info("Init CraftBeerPI")
policy = auth.SessionTktAuthentication(urandom(32), 60, include_ip=True) policy = auth.SessionTktAuthentication(urandom(32), 60, include_ip=True)
@ -88,7 +91,7 @@ class CraftBeerPi:
self.job = JobController(self) self.job = JobController(self)
self.config = ConfigController(self) self.config = ConfigController(self)
self.ws = CBPiWebSocket(self) self.ws = CBPiWebSocket(self)
self.satellite = CBPiSatellite(self)
self.actor = ActorController(self) self.actor = ActorController(self)
self.sensor = SensorController(self) self.sensor = SensorController(self)
self.plugin = PluginController(self) self.plugin = PluginController(self)

View file

@ -3,6 +3,10 @@ import json
from cbpi.utils.encoder import ComplexEncoder from cbpi.utils.encoder import ComplexEncoder
from hbmqtt.mqtt.constants import QOS_0 from hbmqtt.mqtt.constants import QOS_0
from hbmqtt.client import MQTTClient from hbmqtt.client import MQTTClient
from hbmqtt.mqtt.constants import QOS_1, QOS_2
from asyncio_mqtt import Client, MqttError, Will
import asyncio
class CBPiMqttClient: class CBPiMqttClient:
@ -10,13 +14,18 @@ class CBPiMqttClient:
self.cbpi = cbpi self.cbpi = cbpi
self.cbpi.bus.register("#", self.listen) self.cbpi.bus.register("#", self.listen)
self.client = None self.client = None
self.cbpi.app.on_startup.append(self.init_client) self._loop = asyncio.get_event_loop()
self._loop.create_task(self.init_client(self.cbpi))
async def init_client(self, cbpi): async def init_client(self, cbpi):
self.client = MQTTClient() async with Client("localhost", will=Will(topic="cbpi/diconnect", payload="MY CLIENT"))as client:
await self.client.connect('mqtt://localhost:1883') async with client.filtered_messages("cbpi/#") as messages:
await client.subscribe("cbpi/#")
async for message in messages:
await self.cbpi.actor.on("YwGzXvWMpmbLb6XobesL8n")
print(message.topic, message.payload.decode())
async def listen(self, topic, **kwargs): async def listen(self, topic, **kwargs):
@ -31,10 +40,6 @@ def setup(cbpi):
:param cbpi: the cbpi core :param cbpi: the cbpi core
:return: :return:
''' '''
print("MQTT")
print("###################")
print("###################")
print("###################")
print("###################")
client = CBPiMqttClient(cbpi) client = CBPiMqttClient(cbpi)

View file

@ -1,3 +1,3 @@
name: MQTT name: MQTT
version: 4.0 version: 4.0
active: False active: false

View file

@ -0,0 +1,87 @@
# -*- coding: utf-8 -*-
import asyncio
import random
import re
import random
from aiohttp import web
from cbpi.api import *
import os, re, threading, time
class myThread (threading.Thread):
value = 0
def __init__(self, sensor_name):
threading.Thread.__init__(self)
self.value = 0
self.sensor_name = sensor_name
self.runnig = True
def shutdown(self):
pass
def stop(self):
self.runnig = False
def run(self):
while self.runnig:
try:
print("READ SENSOR")
except:
pass
time.sleep(1)
@parameters([])
class OneWire(CBPiSensor):
def __init__(self, cbpi, id, props):
super(OneWire, self).__init__(cbpi, id, props)
self.value = 0
async def start(self):
print("START")
await super().start()
self.t = myThread("ABC")
def shudown():
shudown.cb.shutdown()
shudown.cb = self.t
self.t.start()
pass
async def stop(self):
try:
self.t.stop()
except:
pass
async def run(self):
while self.running is True:
self.push_update(self.value)
await asyncio.sleep(10)
def get_state(self):
return dict(value=self.value)
def setup(cbpi):
'''
This method is called by the server during startup
Here you need to register your plugins at the server
:param cbpi: the cbpi core
:return:
'''
cbpi.plugin.register("OneWire", OneWire)

View file

@ -0,0 +1,3 @@
name: DummySensor
version: 4
active: true

88
cbpi/satellite.py Normal file
View file

@ -0,0 +1,88 @@
import logging
import weakref
from collections import defaultdict
import aiohttp
from aiohttp import web
from voluptuous import Schema
from cbpi.utils import json_dumps
class CBPiSatellite:
def __init__(self, cbpi) -> None:
self.cbpi = cbpi
self._callbacks = defaultdict(set)
self._clients = weakref.WeakSet()
self.logger = logging.getLogger(__name__)
self.cbpi.app.add_routes([web.get('/satellite', self.websocket_handler)])
self.cbpi.bus.register_object(self)
#if self.cbpi.config.static.get("ws_push_all", False):
self.cbpi.bus.register("#", self.listen)
async def listen(self, topic, **kwargs):
data = dict(topic=topic, data=dict(**kwargs))
self.logger.debug("PUSH %s " % data)
self.send(data)
def send(self, data):
self.logger.debug("broadcast to ws clients. Data: %s" % data)
for ws in self._clients:
async def send_data(ws, data):
await ws.send_json(data=data, dumps=json_dumps)
self.cbpi.app.loop.create_task(send_data(ws, data))
async def websocket_handler(self, request):
print("HALLO SATELLITE")
ws = web.WebSocketResponse()
await ws.prepare(request)
self._clients.add(ws)
try:
peername = request.transport.get_extra_info('peername')
if peername is not None:
print(peername)
host = peername[0]
port = peername[1]
else:
host, port = "Unknowen"
self.logger.info("Client Connected - Host: %s Port: %s - client count: %s " % (host, port, len(self._clients)))
except Exception as e:
print(e)
try:
await ws.send_json(data=dict(topic="connection/success"))
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
msg_obj = msg.json()
schema = Schema({"topic": str, "data": dict})
schema(msg_obj)
topic = msg_obj.get("topic")
data = msg_obj.get("data")
if topic == "close":
await ws.close()
else:
if data is not None:
await self.cbpi.bus.fire(topic=topic, **data)
else:
await self.cbpi.bus.fire(topic=topic)
elif msg.type == aiohttp.WSMsgType.ERROR:
self.logger.error('ws connection closed with exception %s' % ws.exception())
except Exception as e:
self.logger.error("%s - Received Data %s" % (str(e), msg.data))
finally:
self._clients.discard(ws)
self.logger.info("Web Socket Close")
return ws

View file

@ -9,7 +9,6 @@ twine upload dist/*
# Checkout Pull Request # Checkout Pull Request
git fetch origin pull/ID/head:BRANCHNAME git fetch origin pull/ID/head:BRANCHNAMEgit checkout BRANCHNAME
git checkout BRANCHNAME

View file

@ -1,22 +1,67 @@
{ {
"elements": [], "elements": [
{
"id": "fb8e005c-e936-4bd3-882e-ba4020496067",
"name": "Kettle",
"props": {
"heigth": "150",
"width": "100"
},
"type": "Kettle",
"x": 230,
"y": 70
},
{
"id": "84a4fb23-9226-4c3d-922b-24be78811c4a",
"name": "Actor",
"props": {
"actor": "YwGzXvWMpmbLb6XobesL8n"
},
"type": "ActorButton",
"x": 130,
"y": 250
}
],
"pathes": [ "pathes": [
{ {
"condition": [
"YwGzXvWMpmbLb6XobesL8n"
],
"coordinates": [ "coordinates": [
[ [
35, 70,
170 70
], ],
[ [
105, 40,
65 350
], ],
[ [
185, 200,
140 435
],
[
115,
530
] ]
], ],
"id": "d374b969-a94d-4d75-a529-1aafd4a79e04" "id": "23789f6d-ec5b-4704-8cc0-e6614b14b5c6"
},
{
"condition": [
"YwGzXvWMpmbLb6XobesL8n"
],
"coordinates": [
[
100,
180
],
[
220,
135
]
],
"id": "fa887fcf-69e6-4a25-bb42-b65a13cc4012"
} }
] ]
} }

View file

@ -1,13 +1,3 @@
{ {
"data": [ "data": []
{
"id": "8ohkXvFA9UrkHLsxQL38wu",
"name": "Sensor1",
"props": {},
"state": {
"value": 35
},
"type": "CustomSensor"
}
]
} }