Skip to content
Snippets Groups Projects
Commit 6afdd8c0 authored by Francesco Pham's avatar Francesco Pham
Browse files

implement RemoteResource inheriting the same Resource class


now when running get_resources_from_rd it returns a list of RemoteResource objects that are Resource objects that can be called as if they are local resources.

Signed-off-by: default avatarFrancesco Pham <francesco.pham@huawei.com>
parent 884a9058
Branches main
No related tags found
No related merge requests found
__pycache__
\ No newline at end of file
......@@ -7,6 +7,7 @@ import aiocoap.resource as resource
import aiocoap
from aiocoap.util import linkformat
from aiocoap import error
from remote_resource import RemoteResource
import logging
......@@ -58,7 +59,17 @@ class EddieEndpoint:
async def start_server(self):
self.server_context = await aiocoap.Context.create_server_context(self.root, bind=("::", 0))
port = 8683
found_available_port = False
while not found_available_port:
try:
self.server_context = await aiocoap.Context.create_server_context(self.root, bind=("::", port))
found_available_port = True
except OSError as e:
port += 1
if found_available_port: print(f"server bound to port: {port}")
else: print("could not start server")
async def discover_resource_directory(self):
# resource directory is discovered by sending a request to .well-known/core following a heuristic:
......@@ -114,6 +125,7 @@ class EddieEndpoint:
logging.error(e)
return None
logging.debug('Get resoruces response: %s\n%r'%(response.code, response.payload))
logging.debug('Get resources response: %s\n%r'%(response.code, response.payload))
parsed = link_format_from_message(response)
return parsed
\ No newline at end of file
remote_resources = [RemoteResource(link, self.server_context) for link in parsed.links]
return remote_resources
\ No newline at end of file
......@@ -7,16 +7,18 @@ import asyncio
from eddie_endpoint import EddieEndpoint
import aiocoap
import logging
from pprint import pprint
logging.getLogger().setLevel(logging.DEBUG)
ENDPOINT_NAME = "eddie-python-node"
ENDPOINT_NAME = "eddie-lamp-node"
# This is a simple example of a Eddie resource that mocks a lamp
# The code to retrieve lamp status and actually turn on and off
# the lamp should be in render_{get/put}
class EddieLamp(aiocoap.resource.Resource):
def __init__(self):
super().__init__()
self.lamp_status = False
self.rt = "eddie.lamp"
......@@ -38,7 +40,9 @@ async def main():
await my_endpoint.publish_resources_to_rd()
discovered_resources = await my_endpoint.get_resources_from_rd(resource_type="eddie.lamp")
print("Discovered resources: " + str(discovered_resources))
print("lamps status: ")
for resource in discovered_resources:
print(resource)
# Run forever
await asyncio.get_running_loop().create_future()
......
#
# SPDX-License-Identifier: Apache-2.0
#
# SPDX-FileCopyrightText: Huawei Inc.
#
import asyncio
from eddie_endpoint import EddieEndpoint
import aiocoap
import logging
from pprint import pprint
logging.getLogger().setLevel(logging.DEBUG)
ENDPOINT_NAME = "eddie-temp-node"
class EddieTemp(aiocoap.resource.Resource):
def __init__(self):
super().__init__()
self.lamp_status = False
self.rt = "eddie.temp"
self.temperature = b"23"
async def render_get(self, request):
return aiocoap.Message(payload=self.temperature)
async def main():
my_endpoint = EddieEndpoint(ENDPOINT_NAME)
my_endpoint.add_resource(['temp1'], EddieTemp())
await my_endpoint.start_server()
await my_endpoint.publish_resources_to_rd()
discovered_resources = await my_endpoint.get_resources_from_rd(resource_type="eddie.lamp")
print("discovered resoruces:")
for resource in discovered_resources:
lamp_status = await resource.render_get(aiocoap.Message())
print(f"{resource} - lamp status: {lamp_status.payload}")
# Run forever
await asyncio.get_running_loop().create_future()
if __name__ == "__main__":
asyncio.run(main())
\ No newline at end of file
import aiocoap
from aiocoap.util import linkformat
class RemoteResource(aiocoap.resource.Resource):
def __init__(self, resource_link: linkformat.Link, client_context: aiocoap.Context):
self.client_context = client_context
self.resource_link = resource_link
self.rt = resource_link.rt if resource_link.rt else "eddie.remote"
def __str__(self) -> str:
return str(self.resource_link)
async def render_get(self, request):
request = aiocoap.Message(code=aiocoap.GET, uri=self.resource_link.href)
try:
response = await self.client_context.request(request).response
except Exception as e:
print(e)
return None
return response
async def render_post(self, request):
request = aiocoap.Message(code=aiocoap.POST, uri=self.resource_link.href)
try:
response = await self.client_context.request(request).response
except Exception as e:
print(e)
return None
return response
async def render_put(self, request):
request = aiocoap.Message(code=aiocoap.PUT, uri=self.resource_link.href)
try:
response = await self.client_context.request(request).response
except Exception as e:
print(e)
return None
return response
async def render_delete(self, request):
request = aiocoap.Message(code=aiocoap.DELETE, uri=self.resource_link.href)
try:
response = await self.client_context.request(request).response
except Exception as e:
print(e)
return None
return response
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment