Skip to content

Service Wrapper

opendxl edited this page Oct 17, 2016 · 8 revisions

This sample demonstrates how simple it is to wrap an existing service and expose it on the DXL fabric.

In this particular case, the http://openweathermap.org/ “current weather” data is exposed as a DXL service. This service wrapper delegates to the http://openweathermap.org/api REST API.

The code for the sample is broken into two main sections.

Register Callback to Receive Events

The first section is responsible for registering an EventCallback for a specific topic. The add_event_callback() method by default will also subscribe to the topic.

#
# Register callback and subscribe
#

# Create and add event listener
class MyEventCallback(EventCallback):
    def on_event(self, event):
        with event_count_condition:
            # Print the payload for the received event
            print "Received event: " + event.payload.decode()
            # Increment the count
            event_count[0] += 1
            # Notify that the count was increment
            event_count_condition.notify_all()

# Register the callback with the client
client.add_event_callback(EVENT_TOPIC, MyEventCallback())

Send Events

The second section sends a set amount of Event messages via the send_event() method of the DxlClient.

It then waits for all of the events to be received by the EventCallback that was previously registered.

#
# Send events
#

# Record the start time
start = time.time()

# Loop and send the events
for event_id in range(TOTAL_EVENTS):
    # Create the event
    event = Event(EVENT_TOPIC)
    # Set the payload
    event.payload = str(event_id).encode()
    # Send the event
    client.send_event(event)

# Wait until all events have been received
with event_count_condition:
    while event_count[0] < TOTAL_EVENTS:
        event_count_condition.wait()

# Print the elapsed time
print "Elapsed time (ms): " + str((time.time() - start) * 1000)

Output

The output should appear similar to the following:

Received event: 0
Received event: 1
Received event: 2
Received event: 3
Received event: 4
Received event: 5

...

Received event: 994
Received event: 995
Received event: 996
Received event: 997
Received event: 998
Received event: 999
Elapsed time (ms): 441.999912262