def setUp(self): root = resource.CoAPResource() text = TextResource() root.putChild('text', text) server_endpoint = resource.Endpoint(root) self.server_protocol = coap.Coap(server_endpoint) client_endpoint = resource.Endpoint(None) self.client_protocol = coap.Coap(client_endpoint) self.server_transport = FakeTwoWayDatagramTransport(recipient=self.client_protocol, address=SERVER_ADDRESS, port=SERVER_PORT) self.client_transport = FakeTwoWayDatagramTransport(recipient=self.server_protocol, address=CLIENT_ADDRESS, port=CLIENT_PORT) self.client_protocol.transport = self.client_transport self.server_protocol.transport = self.server_transport
def main(): serverThread=threading.Thread(target=startServer,args=(host,port,)) serverThread.start() serverThread.join() # Resource tree creation log.startLogging(sys.stdout) root = resource.CoAPResource() well_known = resource.CoAPResource() root.putChild('.well-known', well_known) core = CoreResource(root) well_known.putChild('core', core) #counter = CounterResource(5000) #root.putChild('counter', counter) #time = TimeResource() #root.putChild('time', time) #other = resource.CoAPResource() #root.putChild('other', other) data = BlockResource() root.putChild('Node', data) cmd = BlockResource() root.putChild('CMD',cmd ) #separate = SeparateLargeResource() #other.putChild('separate', separate) print("between") endpoint = resource.Endpoint(root) reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint)) #, interface="::") reactor.run() print("at the end ")
def CANCEL_OBSERVE(self, to_node, uri, token, callback): protocol = coap.Coap(resource.Endpoint(None)) ver = netaddr.IPAddress(to_node.ip).version if ver == 6: reactor.listenUDP(0, protocol, interface='::') else: reactor.listenUDP(0, protocol) tmp = uri.split('?') for req in self.observers[to_node]: tmp_path = "" first_item = True for x in req.opt.uri_path: if not first_item: tmp_path += "/" tmp_path += x first_item = False if len(tmp) > 0 and tmp_path == tmp[0]: req.opt.observe = 1 requester = coap.Requester(protocol, req, observeCallback=None, block1Callback=None, block2Callback=None, observeCallbackArgs=None, block1CallbackArgs=None, block2CallbackArgs=None, observeCallbackKeywords=None, block1CallbackKeywords=None, block2CallbackKeywords=None) if callback is not None: requester.deferred.addCallback(callback) self.forget(token)
def main(): """ Just start all 3 protos """ # WS listener ws_factory = WebSocketServerFactory(u"ws://52.34.209.113:8000") ws_factory.protocol = WSProto reactor.listenTCP(8000, ws_factory) # MQTT listener mqtt_factory = MQTTFactory(profile=MQTTFactory.SUBSCRIBER) mqtt_endpoint = clientFromString(reactor, BROKER) mqtt_serv = MQTTProto(mqtt_endpoint, mqtt_factory) mqtt_serv.startService() # CoAP listener coap_root = resource.CoAPResource() coap_ovh = CoAPProto() coap_root.putChild('test', coap_ovh) coap_endpoint = resource.Endpoint(coap_root) reactor.listenUDP(coap.COAP_PORT, coap.Coap(coap_endpoint)) # run the program reactor.run()
def main(host='127.0.0.1', port=5684, uri='sensorReading2', payload='OFF'): log.startLogging(sys.stdout) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) client = SensorAgent(protocol, host, port, uri, payload) reactor.listenUDP(61648, protocol) reactor.run()
def main(num=None): if num is None: num = random.randint(1,3) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) client = SensorAgent(protocol, str(num), os.environ['rmt_host'], 5684) reactor.listenUDP(61617, protocol) reactor.run()
def main(num=None): if num is None: num = random.randint(1,3) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) client = SensorAgent(protocol, '127.0.0.1', '5683', 'reading1', 'WORKING', str(num)) reactor.listenUDP(61651, protocol) reactor.run()
def __init__(self, host, port, uri): self.host = host self.port = port self.uri = uri endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) self.protocol = protocol reactor.listenUDP(61661, protocol) reactor.callLater(0, self.requestResource)
def simulate_to_sensor(host='127.0.0.1', port=5683, uri='reading', payload='OFF'): log.startLogging(sys.stdout) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) client = SensorAgent(protocol, host, port, uri, payload) reactor.listenUDP(61619, protocol) reactor.run()
def processResponse(self, response): print 'Sensor Address Obtained: ' + response.payload import json json_obj = json.loads(str(response.payload)) host = json_obj['host'] port = int(json_obj['port']) uri = json_obj['uri'] endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) client = SensorAgent(protocol, host, port, uri) print colored( 'Establishing the connection to the sensor', 'red',)
def build(self): self.remote_ip = self.config.get("OSD_RGBW_Led_App", "IP") self.send_coap = True self.dont_change = False self.need_to_set_leds = None endpoint = resource.Endpoint(None) self.protocol = coap.Coap(endpoint) reactor.listenUDP(0, self.protocol, interface="::0") self.turned_off = False self.root = RGBW_Led_Widget() self.COLORS = eval(self.config.get("OSD_RGBW_Led_App", "COLORS")) print self.COLORS for btn in self.root.buttoncontainer.children: idx = btn.idx val = self.COLORS.get(idx) if val: # set button background red, green, blue, white, bri = val bri = bri / 255.0 red = int(red * bri) green = int(green * bri) blue = int(blue * bri) # white = int (white * bri) btn.color_set = True with btn.canvas.before: Color \ ( red / 255.0 , green / 255.0 , blue / 255.0 , 1 ) else: with btn.canvas.before: Color \ ( 32 , 32 , 32 , 1 ) self.root.switch.bind(active=self.color_changed) self.root.status.text = "fetching current color ..." self.prepare_request(method=coap.GET) return self.root
def run(self): if self.flag_alive: logg.info('CoapListerner is running') print 'CoapListerner is running' self.endpoint = resource.Endpoint(self.root) reactor.listenUDP(self.port, coap.Coap(self.endpoint)) Thread(target=reactor.run, name="CoapListerner_Thread", args=(False, )).start() while self.flag_alive: time.sleep(100) logg.info("Thread exits: %s" % str(self.name)) else: logg.info("Thread exits: %s" % str(self.name))
def start(self): # Resource tree creation log.startLogging(sys.stdout) root = resource.CoAPResource() well_known = resource.CoAPResource() root.putChild('.well-known', well_known) core = Coap2Xively.CoreResource(root) well_known.putChild('core', core) post = Coap2Xively.xivelyGatewayResource() root.putChild('postSensorData', post) endpoint = resource.Endpoint(root) reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint)) #, interface="::") reactor.run() print "DONE"
def main(): # start log to the console log.startLogging(sys.stdout) # Resource tree creation # coap://<host>:<port> root = resource.CoAPResource() # coap://<host>:<port>/.well-known well_known = resource.CoAPResource() root.putChild('.well-known', well_known) # coap://<host>:<port>/core core = CoreResource(root) well_known.putChild('core', core) # coap://<host>:<port>/time time = TimeResource() root.putChild('time', time) # ---------------------------------------------------------------------- # # sensors root URL # coap://<host>:<port>/sensors sensors = resource.CoAPResource() root.putChild('sensors', sensors) # sensors child URL # coap://<host>:<port>/sensors/register #register = RegistryResource() #sensors.putChild('register', register) # sensors dynamic URL # coap://<host>:<port>/sensors/dht/<temperature/humidity> dynamic_url = DynamicURLResource() sensors.putChild('dht', dynamic_url) # /--------------------------------------------------------------------- # endpoint = resource.Endpoint(root) reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint)) # , interface="::") reactor.run()
def __init__(self, ip_port, name=None, simulator=None): super(CoapSimulator, self).__init__(name=name) str_list = ip_port.split(':') self.ip = str(str_list[0]) if str_list[1] == "" or str_list[1] == None: logg.error("No port is specified!") self.port = coap.COAP_PORT else: self.port = int(str_list[1]) logg.debug("coap_init:{0}:{1}".format(self.ip, self.port)) self.simulator = simulator #log.startLogging(sys.stdout) self.endpoint = resource.Endpoint(None) self.protocol = coap.Coap(self.endpoint) self.client = Agent(self.protocol, self.ip, self.port) logg.debug("CoapSimulator is initialized") print "CoapSimulator is initialized" self.flag_alive = True self.start()
def build(self): # Resource tree creation root = resource.CoAPResource() well_known = resource.CoAPResource() root.putChild('.well-known', well_known) core = CoreResource(root) well_known.putChild('core', core) counter = MOTDResource(self, 0) root.putChild('motd', counter) endpoint = resource.Endpoint(root) reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint)) # Kivy screen initialization self.label = Label(text="") self.display_counter(0) self.messagebox = TextInput(size_hint_y=.1, multiline=False) self.messagebox.text = "Message of the day" self.layout = BoxLayout(orientation='vertical', padding=10) self.layout.add_widget(self.label) self.layout.add_widget(self.messagebox) return self.layout
@staticmethod def printResponse(response): print 'CoAP result: ' + response.payload @staticmethod def noResponse(failure): print 'Failed to fetch resource:%s' % failure if __name__ == '__main__': if len(sys.argv) == 3: addr = sys.argv[1] url = sys.argv[2] else: print 'Usage : %s <IP address> <url>' % sys.argv[0] print 'The url argument should not start with a "/", but use' print '"/" characters to separate later portions' sys.exit(1) log.startLogging(sys.stdout) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) client = CoapClient(addr, url) reactor.listenUDP(61616, protocol) # Run the Twisted event loop reactor.run()
return defer.succeed(response) # Resource tree creation log.startLogging(sys.stdout) root = resource.CoAPResource() ###IOT addition pause = PauseResource() root.putChild('pause', pause) play = PlayResource() root.putChild('play', play) stop = StopResource() root.putChild('stop', stop) addToQueue = addToQueueResource() root.putChild('add', addToQueue) repResource = RepeatResource() root.putChild('repeat', repResource) skip = SkipResource() root.putChild('skip', skip) ### endpoint = resource.Endpoint(root) reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint)) #, interface="::") reactor.run()
response = coap.Message(code=coap.CHANGED, payload=payload) return defer.succeed(response) # Resource tree creation log.startLogging(sys.stdout) root = resource.CoAPResource() well_known = resource.CoAPResource() root.putChild('.well-known', well_known) core = CoreResource(root) well_known.putChild('core', core) ################### lamp1 = Lamp("1") root.putChild('lamp1', lamp1) #lamp2 = Lamp("2") #root.putChild('lamp2',lamp2) #lamp3 = Lamp("3") #root.putChild('lamp3',lamp3) ################## endpoint = resource.Endpoint(root) reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint), interface="10.1.0.20") reactor.run()
def request(self, to_node, operation, uri, token, callback, payload=None): if not payload: payload = '' tmp = uri.split('?') if operation == coap.OBSERVE and to_node in self.observers: for req in self.observers[to_node]: tmp_path = "" first_item = True for x in req.opt.uri_path: if not first_item: tmp_path += "/" tmp_path += x first_item = False if len(tmp) > 0 and tmp_path == tmp[0]: return request = coap.Message( mtype=coap.CON, code=operation if operation != coap.OBSERVE else coap.GET, token=token, payload=payload) request.opt.uri_path = tmp[0].split('/') if len(tmp) == 2: request.opt.uri_query = tmp[1].split('&') request.remote = (to_node.ip, to_node.port) #request.opt.accept = coap.media_types_rev['application/json'] #request.opt.content_format = coap.media_types_rev['application/json'] protocol = coap.Coap(resource.Endpoint(None)) ver = netaddr.IPAddress(to_node.ip).version if ver == 6: reactor.listenUDP(0, protocol, interface='::') else: reactor.listenUDP(0, protocol) if operation == coap.OBSERVE: request.opt.observe = 0 requester = coap.Requester(protocol, request, observeCallback=callback, block1Callback=None, block2Callback=None, observeCallbackArgs=None, block1CallbackArgs=None, block2CallbackArgs=None, observeCallbackKeywords=None, block1CallbackKeywords=None, block2CallbackKeywords=None) if to_node not in self.observers: self.observers[to_node] = [request] else: self.observers[to_node] += [request] else: requester = coap.Requester(protocol, request, observeCallback=None, block1Callback=None, block2Callback=None, observeCallbackArgs=None, block1CallbackArgs=None, block2CallbackArgs=None, observeCallbackKeywords=None, block1CallbackKeywords=None, block2CallbackKeywords=None) if callback is not None: requester.deferred.addCallback(callback) self.tickets[requester.app_request.token] = token self.start()
def create_protocol(self): endpoint = resource.Endpoint(None) self.protocol = coap.Coap(endpoint) reactor.listenUDP(60000, self.protocol) #, interface="::")
def render_GET(self, request): data = [] self.root.generateResourceList(data, "") payload = ",".join(data) print payload response = coap.Message(code=coap.CONTENT, payload=payload) response.opt.content_format = coap.media_types_rev[ 'application/link-format'] return defer.succeed(response) if __name__ == '__main__': log.startLogging(sys.stdout) root = resource.CoAPResource() well_known = resource.CoAPResource() root.putChild('.well-known', well_known) core = CoreResource(root) well_known.putChild('core', core) temperature_resouce = TempResource() root.putChild('temperature', temperature_resouce) endpoint = resource.Endpoint(root) # Listen on default CoAP port 5683 reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint)) # Run Twister'd event loop reactor.run()
def main(): # pragma: no cover server_ip = None server_port = None api_key = None device_id = None event_type = None endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) try: opts, args = getopt.getopt(sys.argv[1:], "he:", ["help", "event="]) except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) for o, a in opts: if o in ("-e", "--event"): event_type = a elif o in ("-h", "--help"): usage() sys.exit() else: usage() sys.exit(2) if event_type is None: print "Event type must be specified" usage() sys.exit(2) if conf.COAP_SERVER_IP is not None: server_ip = conf.COAP_SERVER_IP else: server_ip = "127.0.0.1" print 'Can\'t read COAP_SERVER_IP from opengate_config.py using default value ' + server_ip if conf.COAP_SERVER_PORT is not None: server_port = conf.COAP_SERVER_PORT else: server_port = 56830 print 'Can\'t read COAP_SERVER_IP from opengate_config.py using default value ' + str( server_port) if conf.API_KEY is not None: api_key = conf.API_KEY else: print 'Can\'t read API_KEY from opengate_config.py' sys.exit(2) if conf.DEFAULT_DEVICE_ID is not None: device_id = conf.DEFAULT_DEVICE_ID else: try: DEVICE_ID_FILE = open('.device_id', 'r') device_id = DEVICE_ID_FILE.read().strip() except IOError: print 'Can\'t read device_id file neither from .device_id file nor opengate_config.py' sys.exit(2) path = "v80/devices/" payload = None command = coap.POST if event_type == "DMM": path = path + "collect/dmm" payload = json.dumps(getDmmPayload(device_id), indent=2) elif event_type == "IOT": path = path + "collect/iot" payload = json.dumps(getIotPayload(device_id), indent=2) elif event_type == "ALARM": path = path + "events/alarms" payload = json.dumps(getAlarmPayload(device_id), indent=2) elif event_type == "TEST": path = path + "test" command = coap.GET else: print "Event type " + event_type + " not recognized" usage() sys.exit(2) reactor.callLater(1, requestResource, protocol, command, server_ip, server_port, api_key, path, payload, device_id) reactor.listenUDP(61617, protocol) # , interface="::") reactor.run()
get the total resource usage of an agent """ return agents_dic[ session_id ]["detail_agents"][agent_address_port]["total_resource_usage"] def get_detail_agents_service_name( session_id, agent_address_port ): """ get the service name related to the agent """ return agents_dic[ session_id ]["detail_agents"][agent_address_port]["service_name"] #---------------------------------------------------------------------- # Metering Proxy Coap class #---------------------------------------------------------------------- endpoint = resource.Endpoint(None) protocol_coap = coap.Coap(endpoint) class MeteringPrxCoap: """ The coap metering proxy class """ def __init__(self, ptr, metering, transport, req_avps, req_type, agentDic, agent_host, agent_port = coap.COAP_PORT ): self.ptr = ptr self.transport = transport self.avps = req_avps self.metering = metering self.agentDic = agentDic self.agent_host = agent_host