Skip to content

Basic Service Example

opendxl edited this page Oct 17, 2016 · 5 revisions

This sample demonstrates how to register a DXL service to receive Request messages and send Response messages back to an invoking DxlClient.

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

Register Callback to Receive Events

The first section is responsible for creating a RequestCallback that will be invoked for a specific topic associated with the service. The callback will send back a Response message with a payload of pong for any Request messages that are received.

It then creates a ServiceRegistrationInfo instance and registers the request callback with it via the ServiceRegistrationInfo.add_topic() method.

Finally it registers the service with the fabric via the register_service_sync() method of the DxlClient.

#
# Register the service
#

# Create incoming request callback
class MyRequestCallback(RequestCallback):
    def on_request(self, request):
        # Extract information from request
        print "Service received request payload: " + request.payload.decode()
        # Create the response message
        res = Response(request)
        # Populate the response payload
        res.payload = "pong".encode()
        # Send the response
        client.send_response(res)

# Create service registration object
info = ServiceRegistrationInfo(client, "myService")

# Add a topic for the service to respond to
info.add_topic(SERVICE_TOPIC, MyRequestCallback())

# Register the service with the fabric (wait up to 10 seconds for registration to complete)
client.register_service_sync(info, 10)

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

Clone this wiki locally