f37d4ab Mar 12, 2018
3 contributors

Users who have contributed to this file

@chrysn @mwasilak @aellwein
executable file 118 lines (87 sloc) 3.84 KB
#!/usr/bin/env python3
# This file is part of the Python aiocoap library project.
# Copyright (c) 2012-2014 Maciej Wasilak <>,
# 2013-2014 Christian Amsüss <>
# aiocoap is free software, this file is published under the MIT license as
# described in the accompanying LICENSE file.
"""This is a usage example of aiocoap that demonstrates how to implement a
simple server. See the "Usage Examples" section in the aiocoap documentation
for some more information."""
import datetime
import logging
import asyncio
import aiocoap.resource as resource
import aiocoap
class BlockResource(resource.Resource):
"""Example resource which supports the GET and PUT methods. It sends large
responses, which trigger blockwise transfer."""
def __init__(self):
self.set_content(b"This is the resource's default content. It is padded "\
b"with numbers to be large enough to trigger blockwise "\
def set_content(self, content):
self.content = content
while len(self.content) <= 1024:
self.content = self.content + b"0123456789\n"
async def render_get(self, request):
return aiocoap.Message(payload=self.content)
async def render_put(self, request):
print('PUT payload: %s' % request.payload)
return aiocoap.Message(code=aiocoap.CHANGED, payload=self.content)
class SeparateLargeResource(resource.Resource):
"""Example resource which supports the GET method. It uses asyncio.sleep to
simulate a long-running operation, and thus forces the protocol to send
empty ACK first. """
def get_link_description(self):
# Publish additional data in .well-known/core
return dict(**super().get_link_description(), title="A large resource")
async def render_get(self, request):
await asyncio.sleep(3)
payload = "Three rings for the elven kings under the sky, seven rings "\
"for dwarven lords in their halls of stone, nine rings for "\
"mortal men doomed to die, one ring for the dark lord on his "\
"dark throne.".encode('ascii')
return aiocoap.Message(payload=payload)
class TimeResource(resource.ObservableResource):
"""Example resource that can be observed. The `notify` method keeps
scheduling itself, and calles `update_state` to trigger sending
def __init__(self):
self.handle = None
def notify(self):
def reschedule(self):
self.handle = asyncio.get_event_loop().call_later(5, self.notify)
def update_observation_count(self, count):
if count and self.handle is None:
print("Starting the clock")
if count == 0 and self.handle:
print("Stopping the clock")
self.handle = None
async def render_get(self, request):
payload =\
strftime("%Y-%m-%d %H:%M").encode('ascii')
return aiocoap.Message(payload=payload)
# logging setup
def main():
# Resource tree creation
root = resource.Site()
root.add_resource(('.well-known', 'core'),
root.add_resource(('time',), TimeResource())
root.add_resource(('other', 'block'), BlockResource())
root.add_resource(('other', 'separate'), SeparateLargeResource())
if __name__ == "__main__":