from coapthon.resources.resource import Resourcefrom 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 +=1return 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()
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 .
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.
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 .