Created
May 10, 2023 15:54
-
-
Save sdntechforum/052a2a92ad8473b71b332f83f7050c22 to your computer and use it in GitHub Desktop.
CoAP Python Client-Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CoAP (Constrained Application Protocol) an IoT protocol . CoAP is designed for use in constrained networks such as those found in IoT devices. We'll cover the basics of what CoAP is, how it works, and its key features, including its lightweight nature and support for asynchronous messaging. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import random | |
from aiocoap import * | |
async def main(): | |
context = await Context.create_client_context() | |
alarm_state = random.choice([True, False]) | |
payload = b"OFF" | |
if alarm_state: | |
payload = b"ON" | |
request = Message(code=PUT, payload=payload, uri="coap://127.0.0.1/alarm") | |
response = await context.request(request).response | |
print('Result: %s\n%r'%(response.code, response.payload)) | |
if __name__ == '__main__': | |
asyncio.get_event_loop().run_until_complete(main()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aiocoap | |
import aiocoap.resource as resource | |
class AlarmResource(resource.Resource): | |
"""This resource supports the PUT method. | |
PUT: Update state of alarm.""" | |
def __init__(self): | |
super().__init__() | |
self.state = "OFF" | |
async def render_put(self, request): | |
self.state = request.payload | |
print('Update alarm state: %s' % self.state) | |
return aiocoap.Message(code=aiocoap.CHANGED, payload=self.state) | |
import asyncio | |
def main(): | |
# Resource tree creation | |
root = resource.Site() | |
root.add_resource(['alarm'], AlarmResource()) | |
asyncio.Task(aiocoap.Context.create_server_context(root, bind=('0.0.0.0', 5683))) | |
asyncio.get_event_loop().run_forever() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Chekout the demo video - https://youtu.be/-Lab-QLUxjg