Usage Examples¶
These files can serve as reference implementations for a simplistic server and
client. In order to test them, run ./server.py
in one terminal, and use
./clientGET.py
and ./clientPUT.py
to interact with it.
The programs’ source code should give you a good starting point to get familiar with the library if you prefer reading code to reading tutorials. Otherwise, you might want to have a look at the Guided Tour through aiocoap, where the relevant concepts are introduced and explained step by step.
Note
These example programs are not shipped in library version of aiocoap. They are present if you followed the Development version section of the installation instructions; otherwise, you can download them from the project website.
Client¶
1import logging
2import asyncio
3
4from aiocoap import *
5
6logging.basicConfig(level=logging.INFO)
7
8async def main():
9 protocol = await Context.create_client_context()
10
11 request = Message(code=GET, uri='coap://localhost/time')
12
13 try:
14 response = await protocol.request(request).response
15 except Exception as e:
16 print('Failed to fetch resource:')
17 print(e)
18 else:
19 print('Result: %s\n%r'%(response.code, response.payload))
20
21if __name__ == "__main__":
22 asyncio.get_event_loop().run_until_complete(main())
1import logging
2import asyncio
3
4from aiocoap import *
5
6logging.basicConfig(level=logging.INFO)
7
8async def main():
9 """Perform a single PUT request to localhost on the default port, URI
10 "/other/block". The request is sent 2 seconds after initialization.
11
12 The payload is bigger than 1kB, and thus sent as several blocks."""
13
14 context = await Context.create_client_context()
15
16 await asyncio.sleep(2)
17
18 payload = b"The quick brown fox jumps over the lazy dog.\n" * 30
19 request = Message(code=PUT, payload=payload, uri="coap://localhost/other/block")
20
21 response = await context.request(request).response
22
23 print('Result: %s\n%r'%(response.code, response.payload))
24
25if __name__ == "__main__":
26 asyncio.get_event_loop().run_until_complete(main())
Server¶
1import datetime
2import logging
3
4import asyncio
5
6import aiocoap.resource as resource
7import aiocoap
8
9
10class BlockResource(resource.Resource):
11 """Example resource which supports the GET and PUT methods. It sends large
12 responses, which trigger blockwise transfer."""
13
14 def __init__(self):
15 super().__init__()
16 self.set_content(b"This is the resource's default content. It is padded "\
17 b"with numbers to be large enough to trigger blockwise "\
18 b"transfer.\n")
19
20 def set_content(self, content):
21 self.content = content
22 while len(self.content) <= 1024:
23 self.content = self.content + b"0123456789\n"
24
25 async def render_get(self, request):
26 return aiocoap.Message(payload=self.content)
27
28 async def render_put(self, request):
29 print('PUT payload: %s' % request.payload)
30 self.set_content(request.payload)
31 return aiocoap.Message(code=aiocoap.CHANGED, payload=self.content)
32
33
34class SeparateLargeResource(resource.Resource):
35 """Example resource which supports the GET method. It uses asyncio.sleep to
36 simulate a long-running operation, and thus forces the protocol to send
37 empty ACK first. """
38
39 def get_link_description(self):
40 # Publish additional data in .well-known/core
41 return dict(**super().get_link_description(), title="A large resource")
42
43 async def render_get(self, request):
44 await asyncio.sleep(3)
45
46 payload = "Three rings for the elven kings under the sky, seven rings "\
47 "for dwarven lords in their halls of stone, nine rings for "\
48 "mortal men doomed to die, one ring for the dark lord on his "\
49 "dark throne.".encode('ascii')
50 return aiocoap.Message(payload=payload)
51
52class TimeResource(resource.ObservableResource):
53 """Example resource that can be observed. The `notify` method keeps
54 scheduling itself, and calles `update_state` to trigger sending
55 notifications."""
56
57 def __init__(self):
58 super().__init__()
59
60 self.handle = None
61
62 def notify(self):
63 self.updated_state()
64 self.reschedule()
65
66 def reschedule(self):
67 self.handle = asyncio.get_event_loop().call_later(5, self.notify)
68
69 def update_observation_count(self, count):
70 if count and self.handle is None:
71 print("Starting the clock")
72 self.reschedule()
73 if count == 0 and self.handle:
74 print("Stopping the clock")
75 self.handle.cancel()
76 self.handle = None
77
78 async def render_get(self, request):
79 payload = datetime.datetime.now().\
80 strftime("%Y-%m-%d %H:%M").encode('ascii')
81 return aiocoap.Message(payload=payload)
82
83class WhoAmI(resource.Resource):
84 async def render_get(self, request):
85 text = ["Used protocol: %s." % request.remote.scheme]
86
87 text.append("Request came from %s." % request.remote.hostinfo)
88 text.append("The server address used %s." % request.remote.hostinfo_local)
89
90 claims = list(request.remote.authenticated_claims)
91 if claims:
92 text.append("Authenticated claims of the client: %s." % ", ".join(repr(c) for c in claims))
93 else:
94 text.append("No claims authenticated.")
95
96 return aiocoap.Message(content_format=0,
97 payload="\n".join(text).encode('utf8'))
98
99# logging setup
100
101logging.basicConfig(level=logging.INFO)
102logging.getLogger("coap-server").setLevel(logging.DEBUG)
103
104def main():
105 # Resource tree creation
106 root = resource.Site()
107
108 root.add_resource(['.well-known', 'core'],
109 resource.WKCResource(root.get_resources_as_linkheader))
110 root.add_resource(['time'], TimeResource())
111 root.add_resource(['other', 'block'], BlockResource())
112 root.add_resource(['other', 'separate'], SeparateLargeResource())
113 root.add_resource(['whoami'], WhoAmI())
114
115 asyncio.Task(aiocoap.Context.create_server_context(root))
116
117 asyncio.get_event_loop().run_forever()
118
119if __name__ == "__main__":
120 main()