def http_server(): """Builds an HTTPServer instance that contains an ExposedThing.""" exposed_thing = ExposedThing(servient=Servient(), thing=Thing(id=uuid.uuid4().urn)) exposed_thing.add_property(uuid.uuid4().hex, PropertyFragmentDict({ "type": "number", "observable": True }), value=Faker().pyint()) exposed_thing.add_property(uuid.uuid4().hex, PropertyFragmentDict({ "type": "number", "observable": True }), value=Faker().pyint()) exposed_thing.add_event(uuid.uuid4().hex, EventFragmentDict({"type": "object"})) action_name = uuid.uuid4().hex @tornado.gen.coroutine def triple(parameters): input_value = parameters.get("input") yield tornado.gen.sleep(0) raise tornado.gen.Return(input_value * 3) exposed_thing.add_action( action_name, ActionFragmentDict({ "input": { "type": "number" }, "output": { "type": "number" } }), triple) port = find_free_port() server = HTTPServer(port=port) server.add_exposed_thing(exposed_thing) @tornado.gen.coroutine def start(): yield server.start() tornado.ioloop.IOLoop.current().run_sync(start) yield server @tornado.gen.coroutine def stop(): yield server.stop() tornado.ioloop.IOLoop.current().run_sync(stop)
def events(self): """The events optional attribute represents a dictionary with keys that correspond to Event names and values of type EventFragment.""" return { key: EventFragmentDict(val) for key, val in six.iteritems(self._init.get("events", {})) }
def _build_event_fragment(): """Builds and returns a random Event init fragment.""" return EventFragmentDict({ "description": Faker().sentence(), "data": { "type": "string" } })
def add_event(self, name, event_init): """Adds an event to the Thing object as defined by the event argument of type ThingEventInit and updates the Thing Description.""" if isinstance(event_init, dict): event_init = EventFragmentDict(event_init) event = Event(thing=self._thing, name=name, init_dict=event_init) self._thing.add_interaction(event) event_data = ThingDescriptionChangeEventInit( td_change_type=TDChangeType.EVENT, method=TDChangeMethod.ADD, name=name, data=event_init.to_dict(), description=ThingDescription.from_thing(self.thing).to_dict()) self._events_stream.on_next( ThingDescriptionChangeEmittedEvent(init=event_data))
def mqtt_server(request): """Builds a MQTTServer instance that contains an ExposedThing.""" from wotpy.protocols.mqtt.server import MQTTServer from tests.protocols.mqtt.broker import get_test_broker_url exposed_thing = ExposedThing(servient=Servient(), thing=Thing(id=uuid.uuid4().urn)) exposed_thing.add_property(uuid.uuid4().hex, PropertyFragmentDict({ "type": "string", "observable": True }), value=Faker().sentence()) exposed_thing.add_event(uuid.uuid4().hex, EventFragmentDict({"type": "number"})) action_name = uuid.uuid4().hex @tornado.gen.coroutine def handler(parameters): input_value = parameters.get("input") yield tornado.gen.sleep(random.random() * 0.1) raise tornado.gen.Return("{:f}".format(input_value)) exposed_thing.add_action( action_name, ActionFragmentDict({ "input": { "type": "number" }, "output": { "type": "string" } }), handler) server = MQTTServer(broker_url=get_test_broker_url(), **request.param) server.add_exposed_thing(exposed_thing) @tornado.gen.coroutine def start(): yield server.start() tornado.ioloop.IOLoop.current().run_sync(start) yield server @tornado.gen.coroutine def stop(): yield server.stop() tornado.ioloop.IOLoop.current().run_sync(stop)
def test_event_fragment(): """Event fragment dictionaries can be represented and serialized.""" init = { "description": "Lamp reaches a critical temperature (overheating)", "data": { "type": "string" }, "forms": [{ "href": "coaps://mylamp.example.com/oh", "contentType": "application/json" }], "uriVariables": { "p": { "type": "integer", "minimum": 0, "maximum": 16 }, "d": { "type": "integer", "minimum": 0, "maximum": 1 } } } event_fragment = EventFragmentDict(init) assert event_fragment.description == init["description"] assert isinstance(event_fragment.data, DataSchemaDict) assert isinstance(next(six.itervalues(event_fragment.uri_variables)), DataSchemaDict) assert event_fragment.to_dict( )["forms"][0]["href"] == init["forms"][0]["href"] assert json.dumps(event_fragment.to_dict())
def client_test_on_event(servient, protocol_client_cls): """Helper function to test observation of Events on bindings clients.""" exposed_thing = next(servient.exposed_things) event_name = uuid.uuid4().hex exposed_thing.add_event(event_name, EventFragmentDict({ "type": "number" })) servient.refresh_forms() td = ThingDescription.from_thing(exposed_thing.thing) @tornado.gen.coroutine def test_coroutine(): protocol_client = protocol_client_cls() payloads = [Faker().pyint() for _ in range(10)] future_payloads = {key: tornado.concurrent.Future() for key in payloads} @tornado.gen.coroutine def emit_next(): next_value = next(val for val, fut in six.iteritems(future_payloads) if not fut.done()) exposed_thing.events[event_name].emit(next_value) def on_next(ev): if ev.data in future_payloads and not future_payloads[ev.data].done(): future_payloads[ev.data].set_result(True) observable = protocol_client.on_event(td, event_name) subscription = observable.subscribe_on(IOLoopScheduler()).subscribe(on_next) periodic_emit = tornado.ioloop.PeriodicCallback(emit_next, 10) periodic_emit.start() yield list(future_payloads.values()) periodic_emit.stop() subscription.dispose() run_test_coroutine(test_coroutine)
def websocket_server(): """Builds a WebsocketServer instance with some ExposedThings.""" servient = Servient() thing_01_id = uuid.uuid4().urn thing_02_id = uuid.uuid4().urn exposed_thing_01 = ExposedThing(servient=servient, thing=Thing(id=thing_01_id)) exposed_thing_02 = ExposedThing(servient=servient, thing=Thing(id=thing_02_id)) prop_name_01 = uuid.uuid4().hex prop_name_02 = uuid.uuid4().hex prop_name_03 = uuid.uuid4().hex event_name_01 = uuid.uuid4().hex action_name_01 = uuid.uuid4().hex prop_value_01 = Faker().sentence() prop_value_02 = Faker().sentence() prop_value_03 = Faker().sentence() prop_init_01 = PropertyFragmentDict({"type": "string", "observable": True}) prop_init_02 = PropertyFragmentDict({"type": "string", "observable": True}) prop_init_03 = PropertyFragmentDict({"type": "string", "observable": True}) event_init_01 = EventFragmentDict({"type": "object"}) action_init_01 = ActionFragmentDict({ "input": { "type": "string" }, "output": { "type": "string" } }) def async_lower(parameters): loop = tornado.ioloop.IOLoop.current() input_value = parameters.get("input") return loop.run_in_executor(None, lambda x: time.sleep(0.1) or x.lower(), input_value) exposed_thing_01.add_property(prop_name_01, prop_init_01, value=prop_value_01) exposed_thing_01.add_property(prop_name_02, prop_init_02, value=prop_value_02) exposed_thing_01.add_event(event_name_01, event_init_01) exposed_thing_01.add_action(action_name_01, action_init_01, async_lower) exposed_thing_02.add_property(prop_name_03, prop_init_03, value=prop_value_03) ws_port = find_free_port() ws_server = WebsocketServer(port=ws_port) ws_server.add_exposed_thing(exposed_thing_01) ws_server.add_exposed_thing(exposed_thing_02) @tornado.gen.coroutine def start(): yield ws_server.start() tornado.ioloop.IOLoop.current().run_sync(start) url_thing_01 = build_websocket_url(exposed_thing_01, ws_server, ws_port) url_thing_02 = build_websocket_url(exposed_thing_02, ws_server, ws_port) yield { "exposed_thing_01": exposed_thing_01, "exposed_thing_02": exposed_thing_02, "prop_name_01": prop_name_01, "prop_init_01": prop_init_01, "prop_value_01": prop_value_01, "prop_name_02": prop_name_02, "prop_init_02": prop_init_02, "prop_value_02": prop_value_02, "prop_name_03": prop_name_03, "prop_init_03": prop_init_03, "prop_value_03": prop_value_03, "event_name_01": event_name_01, "event_init_01": event_init_01, "action_name_01": action_name_01, "action_init_01": action_init_01, "ws_server": ws_server, "url_thing_01": url_thing_01, "url_thing_02": url_thing_02, "ws_port": ws_port } @tornado.gen.coroutine def stop(): yield ws_server.stop() tornado.ioloop.IOLoop.current().run_sync(stop)