Issue
I'm using aiocoap library to issue CoAP requests to an embedded device. The communications and the basic functionality seems to work fine, but the documentation doesn't say how to enable observations. The observe functionality does seem to be present in the source code, both server-side and client-side - I need client side.
This is what I have so far: a GET
request that creates the observe state on the server:
import asyncio, aiocoap
@asyncio.coroutine
def coap_get_with_observe():
protocol = yield from aiocoap.Context.create_client_context()
request = aiocoap.Message(code = aiocoap.GET)
request.set_request_uri('coap://[aaaa::212:4b00:a49:e903]/sensors/temp')
# set observe bit from None to 0
request.opt.observe = 0
try:
response = yield from protocol.request(request).response
except Exception as e:
print("request failed: %s" % str(e))
else:
print("request ok: %r" % response.payload)
event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(event_loop)
event_loop.create_task(coap_get_with_observe())
asyncio.get_event_loop().run_forever()
Output:
request ok: b'{"HDC_TEMP":2426}'
This prints just the first value received by the client; I want to print the subsequent values as well.
Solution
It helps to replace this line:
response = yield from protocol.request(request).response
with this:
protocol_request = protocol.request(request)
protocol_request.observation.register_callback(observation_callback)
response = yield from protocol_request.response
where observation_callback
is a function defined as:
def observation_callback(response):
print("callback: %r" % response.payload)
Now the message payload is printed whenever a new notification message is received from the server.
Answered By - kfx
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.