Skip to content

Commit

Permalink
Created proper Event class
Browse files Browse the repository at this point in the history
  • Loading branch information
jtc42 committed May 4, 2020
1 parent 282d6c0 commit 463ce8c
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 18 deletions.
2 changes: 1 addition & 1 deletion src/labthings/server/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def wrapped(*args, **kwargs):

if current_labthing():
current_labthing().emit(
{property_name: property_value}, type="propertyStatus"
"propertyStatus", {property_name: property_value},
)

return original_response
Expand Down
18 changes: 18 additions & 0 deletions src/labthings/server/event.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import datetime


class Event:
def __init__(self, name, schema=None):
self.name = name
self.schema = schema

self.events = [] # TODO: Make rotating

def emit(self, data):
response = {
"messageType": self.name,
"timestamp": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
"data": data,
} # TODO: Format data with schema
self.events.append(response)
return response
25 changes: 17 additions & 8 deletions src/labthings/server/labthing.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from .spec.td import ThingDescription
from .decorators import tag
from .sockets import Sockets
from .event import Event

from .view.builder import property_of, action_from

Expand Down Expand Up @@ -55,6 +56,8 @@ def __init__(

self.extensions = {}

self.events = {}

self.views = []
self._property_views = {}
self._action_views = {}
Expand Down Expand Up @@ -163,6 +166,10 @@ def init_app(self, app):
self.sockets = Sockets(app)
self._create_base_sockets()

# Create base events
self.add_event("propertyStatus")
self.add_event("logging")

def _create_base_routes(self):
# Add root representation
self.add_view(RootView, "/", endpoint="root")
Expand Down Expand Up @@ -320,17 +327,19 @@ def _register_view(self, app, view, *urls, endpoint=None, **kwargs):
self._property_views[view.endpoint] = view

# Event stuff
def emit(self, data: dict, type="event"):
"""Emit an event to all subscribers
def add_event(self, name, schema=None):
# TODO: Handle schema
# TODO: Add view for event, returning list of Event.events
self.events[name] = Event(name, schema=schema)
self.thing_description.event(self.events[name])

Arguments:
data {dict} -- Event data
Keyword Arguments:
type {str} -- Event type (default: {"event"})
def emit(self, event_type: str, data: dict):
"""
Emit an event to all subscribers
"""
event_response = self.events[event_type].emit(data)
for sub in self.subscribers:
sub.emit({"messageType": type, "data": data})
sub.emit(event_response)

# Utilities

Expand Down
10 changes: 2 additions & 8 deletions src/labthings/server/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,7 @@ def emit(self, record):

# Broadcast to subscribers
if current_labthing():
current_labthing().emit(log_event)
current_labthing().emit("logging", log_event)

def rest_format_record(self, record):
data = {
"data": str(record.msg),
"timestamp": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
}
level_string = record.levelname.lower()

return {level_string: data}
return {"message": str(record.msg), "level": record.levelname.lower()}
9 changes: 9 additions & 0 deletions src/labthings/server/spec/td.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import weakref

from ..view import View
from ..event import Event

from .utilities import get_spec, convert_schema, schema_to_json, get_topmost_spec_attr
from .paths import rule_to_params, rule_to_path
Expand Down Expand Up @@ -92,12 +93,17 @@ def to_dict(self):
"description": current_labthing().description,
"properties": self.properties,
"actions": self.actions,
# "events": self.events, # TODO: Enable once properly populated
"links": self.links,
# TODO: Add proper security schemes
"securityDefinitions": {"nosec_sc": {"scheme": "nosec"}},
"security": ["nosec_sc"],
}

def event_to_thing_event(self, event: Event):
# TODO: Include event schema
return {"forms": []}

def view_to_thing_property(self, rules: list, view: View):
prop_urls = [rule_to_path(rule) for rule in rules]

Expand Down Expand Up @@ -237,3 +243,6 @@ def build_forms_for_view(self, rules: list, view: View, op: list):
forms.append({"op": op, "href": url, "contentType": content_type})

return forms

def event(self, event: Event):
self.events[event.name] = self.event_to_thing_event(event)
2 changes: 1 addition & 1 deletion tests/test_server_default_views_socket_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ def test_socket_handler(thing_ctx, fake_websocket):
socket_handler(ws)
# Only responses should be announcing new subscribers
for response in ws.responses:
assert '"data": "Added subscriber' in response
assert '"message": "Added subscriber' in response

0 comments on commit 463ce8c

Please sign in to comment.