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.run(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.run(main())

Server

  1import datetime
  2import logging
  3
  4import asyncio
  5
  6import aiocoap.resource as resource
  7from aiocoap.numbers.contentformat import ContentFormat
  8import aiocoap
  9
 10class Welcome(resource.Resource):
 11    representations = {
 12            ContentFormat.TEXT: b"Welcome to the demo server",
 13            ContentFormat.LINKFORMAT: b"</.well-known/core>,ct=40",
 14            # ad-hoc for application/xhtml+xml;charset=utf-8
 15            ContentFormat(65000):
 16                b'<html xmlns="http://www.w3.org/1999/xhtml">'
 17                b'<head><title>aiocoap demo</title></head>'
 18                b'<body><h1>Welcome to the aiocoap demo server!</h1>'
 19                b'<ul><li><a href="time">Current time</a></li>'
 20                b'<li><a href="whoami">Report my network address</a></li>'
 21                b'</ul></body></html>',
 22            }
 23
 24    default_representation = ContentFormat.TEXT
 25
 26    async def render_get(self, request):
 27        cf = self.default_representation if request.opt.accept is None else request.opt.accept
 28        try:
 29            return aiocoap.Message(payload=self.representations[cf], content_format=cf)
 30        except KeyError:
 31            raise aiocoap.error.UnsupportedContentFormat
 32
 33class BlockResource(resource.Resource):
 34    """Example resource which supports the GET and PUT methods. It sends large
 35    responses, which trigger blockwise transfer."""
 36
 37    def __init__(self):
 38        super().__init__()
 39        self.set_content(b"This is the resource's default content. It is padded "
 40                b"with numbers to be large enough to trigger blockwise "
 41                b"transfer.\n")
 42
 43    def set_content(self, content):
 44        self.content = content
 45        while len(self.content) <= 1024:
 46            self.content = self.content + b"0123456789\n"
 47
 48    async def render_get(self, request):
 49        return aiocoap.Message(payload=self.content)
 50
 51    async def render_put(self, request):
 52        print('PUT payload: %s' % request.payload)
 53        self.set_content(request.payload)
 54        return aiocoap.Message(code=aiocoap.CHANGED, payload=self.content)
 55
 56
 57class SeparateLargeResource(resource.Resource):
 58    """Example resource which supports the GET method. It uses asyncio.sleep to
 59    simulate a long-running operation, and thus forces the protocol to send
 60    empty ACK first. """
 61
 62    def get_link_description(self):
 63        # Publish additional data in .well-known/core
 64        return dict(**super().get_link_description(), title="A large resource")
 65
 66    async def render_get(self, request):
 67        await asyncio.sleep(3)
 68
 69        payload = "Three rings for the elven kings under the sky, seven rings "\
 70                "for dwarven lords in their halls of stone, nine rings for "\
 71                "mortal men doomed to die, one ring for the dark lord on his "\
 72                "dark throne.".encode('ascii')
 73        return aiocoap.Message(payload=payload)
 74
 75class TimeResource(resource.ObservableResource):
 76    """Example resource that can be observed. The `notify` method keeps
 77    scheduling itself, and calles `update_state` to trigger sending
 78    notifications."""
 79
 80    def __init__(self):
 81        super().__init__()
 82
 83        self.handle = None
 84
 85    def notify(self):
 86        self.updated_state()
 87        self.reschedule()
 88
 89    def reschedule(self):
 90        self.handle = asyncio.get_event_loop().call_later(5, self.notify)
 91
 92    def update_observation_count(self, count):
 93        if count and self.handle is None:
 94            print("Starting the clock")
 95            self.reschedule()
 96        if count == 0 and self.handle:
 97            print("Stopping the clock")
 98            self.handle.cancel()
 99            self.handle = None
100
101    async def render_get(self, request):
102        payload = datetime.datetime.now().\
103                strftime("%Y-%m-%d %H:%M").encode('ascii')
104        return aiocoap.Message(payload=payload)
105
106class WhoAmI(resource.Resource):
107    async def render_get(self, request):
108        text = ["Used protocol: %s." % request.remote.scheme]
109
110        text.append("Request came from %s." % request.remote.hostinfo)
111        text.append("The server address used %s." % request.remote.hostinfo_local)
112
113        claims = list(request.remote.authenticated_claims)
114        if claims:
115            text.append("Authenticated claims of the client: %s." % ", ".join(repr(c) for c in claims))
116        else:
117            text.append("No claims authenticated.")
118
119        return aiocoap.Message(content_format=0,
120                payload="\n".join(text).encode('utf8'))
121
122# logging setup
123
124logging.basicConfig(level=logging.INFO)
125logging.getLogger("coap-server").setLevel(logging.DEBUG)
126
127async def main():
128    # Resource tree creation
129    root = resource.Site()
130
131    root.add_resource(['.well-known', 'core'],
132            resource.WKCResource(root.get_resources_as_linkheader))
133    root.add_resource([], Welcome())
134    root.add_resource(['time'], TimeResource())
135    root.add_resource(['other', 'block'], BlockResource())
136    root.add_resource(['other', 'separate'], SeparateLargeResource())
137    root.add_resource(['whoami'], WhoAmI())
138
139    await aiocoap.Context.create_server_context(root)
140
141    # Run forever
142    await asyncio.get_running_loop().create_future()
143
144if __name__ == "__main__":
145    asyncio.run(main())