Tanganelli / CoAPthon

CoAPthon is a python library to the CoAP protocol aligned with the RFC
MIT License
222 stars 131 forks source link

How to dynamically add a new resorce to a running server? #95

Open pk00095 opened 6 years ago

pk00095 commented 6 years ago

from coapthon.resources.resource import Resource from coapthon.server.coap import CoAP

class Sensor(Resource):

def __init__(self,name="Sensor",coap_server=None): super(Sensor,self).__init__(name,coap_server,visible=True,observable=True,allow_children=True) self.payload = "This is a new sensor" self.resource_type = "rt1" self.content_type = "application/json" self.interface_type = "if1" self.var = 0

def render_GET(self,request): self.payload = "new sensor value ::{}".format(str(int(self.var+1))) self.var +=1 return self

class Actuator(Resource): def __init__(self,name="Actuator",coap_server=None): super(Actuator,self).__init__(name,coap_server,visible=True,observable=True) self.payload="This is an actuator" self.resource_type="rt1" def render_GET(self,request): return self

class CoAPServer(CoAP): def __init__(self, host, port, multicast=False): CoAP.__init__(self,(host,port),multicast) self.add_resource('sens-Me/',Sensor()) self.add_resource('act-Me/',Actuator()) print "CoAP server started on {}:{}".format(str(host),str(port)) print self.root.dump()

def main(): ip = "0.0.0.0" port = 5683 multicast=False server = CoAPServer(ip,port,multicast) try: server.listen(10) print "executed after listen" except KeyboardInterrupt: server.close()

if __name__=="__main__": main()

the above code has two resources Sensor and actuator .I want that if I press the A key, a new instance of actuator should be added to the server, likewise If i Press S for Sensor .

Tanganelli commented 6 years ago

Hi, take a look to the POST method of the BasicResource in the exampleresource.py file. Specifically the init_resource function should answer to your question.

Let me know if you find out the solution.