class CoapClientConnector(object): ''' In the project, only use POST request to send data from Raspberry Pi to Gateway(laptop) ''' def __init__(self, host): ''' ''' host, port, self.path = parse_uri(host) self.client = HelperClient(server=(host, port)) def handleGET(self): response = self.client.get(self.path) print(response) def handlePOST(self, payload): response = self.client.post(self.path, payload) print(response) def handlePUT(self, payload): response = self.client.put(self.path, payload) print(response) def handleDELETE(self): response = self.client.delete(self.path) print(response) def test(self, payload): self.handlePUT(payload)
def __init__(self): self.SERVER = "192.168.0.3" # The server's IP address self.PORT = 5684 # The server's port for request self.SECPORT = 5688 # The server's port for authentication self.deviceID = "SA20200614_A2" # This device's ID self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.client = HelperClient(server=(self.SERVER, self.PORT))
def __init__(self): self.client = HelperClient(server=(Car.ip, Car.port)) # blocking listener to keyboard events with keyboard.Listener(on_press=self.key_press, on_release=self.key_release) as listener: listener.join()
def do_resource_get(self, resource): if isinstance(resource, Resource): return self.do_resource_get(resource.get_absolute_uri()) elif isinstance(resource, basestring): client = HelperClient(server=(self.__ip, self.__port)) LogUtil.log("GET : " + resource) response = client.get(resource, None, TIMEOUT_GET) client.close() if response is None: raise CoapException("No response received.") elif response.code == defines.Codes.CREATED.number or response.code == defines.Codes.DELETED.number or response.code == defines.Codes.VALID.number or response.code == defines.Codes.CHANGED.number or response.code == defines.Codes.CONTENT.number or response.code == defines.Codes.CONTINUE.number: format = None parser = None for option in response.options: if option.number == defines.OptionRegistry.CONTENT_TYPE.number: format = option.value break if format: parser = self.get_parser(format) request_text = str(response.payload) data = None if parser is None: data = ResourceDataGeneral(request_text) else: data = parser.parse(request_text) return data else: raise CoapException(response)
def create_monitor(self, query, event_handler): uri = URL_RD_MONITOR coapServer = MyCoapServer() rdm_payload = RDMonitorPayload(query.device_type, query.resource_type, query.device_id, query.with_rts, query.standard_type, query.group_ids) local_path = coapServer.add_rdevent_listener(rdm_payload, event_handler) purl = Utils.compose_purl("coap", local_path, coapServer.get_port()) rdm_payload.local_path = local_path rdm_payload.purl = purl client = HelperClient(server=(self.ip, self.port)) payload = (defines.Content_types["application/json"], rdm_payload.to_json()) response = client.post(uri, payload, None, timeout=TIMEOUT_GET) client.close() if response is None: coapServer.del_rdevent_listener(event_handler) LogUtil.log("No response received.") elif response.code == defines.Codes.CREATED.number or response.code == defines.Codes.DELETED.number or response.code == defines.Codes.VALID.number or response.code == defines.Codes.CHANGED.number or response.code == defines.Codes.CONTENT.number or response.code == defines.Codes.CONTINUE.number: monitor_id = str(response.payload) print "monitor_id is", monitor_id LogUtil.log("POST [" + self.__uri + uri + "] resp : " + monitor_id) rdm_payload.mid = monitor_id return monitor_id else: coapServer.del_rdevent_listener(event_handler) LogUtil.log("resp with error code: " + response.code())
def __init__(self, ip, port, path): self.ip = ip self.port = port self.path = path self.cnt = 0 self.client = HelperClient(server=(ip, port)) self.flag = True
def main(): # pragma: no cover global client config = None wait = 0 try: opts, args = getopt.getopt(sys.argv[1:], "hc:w", ["help", "config=", "wait="]) 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 ("-c", "--config"): config = a print("conf: " + str(a)) elif o in ("-w", "--wait"): print("dentro wait") wait = a print("wait: " + wait) elif o in ("-h", "--help"): usage() sys.exit() else: usage() sys.exit(2) if config is None: print("Config file must be specified") usage() sys.exit(2) config = open(config, "r") config = json.load(config) while True: for n in config["nodes"]: for i in parameters: path = "coap://" + n["ip"] + ":" + str( n["port"]) + "/" + str(i) print("path: " + path) host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass client = HelperClient(server=(host, port)) response = client.get(path, timeout=5.0) print "INSERT TO DB" try: print(response.pretty_print()) insert_to_db(response, i) client.stop() except AttributeError: pass try: time.sleep(float(wait)) except: time.sleep(30.0)
def main(): # pragma: no cover global client op = None path = None payload = None pathArray = ["aaaa::212:7406:6:606", "aaaa::212:7405:5:505"] total = 0 count = 0 file = open('services.txt', 'w') for i in range(2): path = "coap://[" + pathArray[count % 2] + "]:5683/" host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass client = HelperClient(server=(host, port)) start = time.time() print(count) response = client.discover() dtime = time.time() - start file.write(str(dtime) + '\n') total = total + dtime count = count + 1 time.sleep(0.6) print(response.pretty_print()) avgTime = total / 100 file.write('services = ' + str(response)) print('AVG=' + str(response)) file.close() client.stop()
def test_lookup_expired_ep(self): print("Expired endpoint lookup") client = HelperClient(self.server_address) path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683<=60" ct = {'content_type': defines.Content_types["application/link-format"]} payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";anchor="coap://spurious.example.com:5683",' \ '</sensors/light>;ct=41;rt="light-lux";if="sensor"' client.post(path, payload, None, None, **ct) client.stop() path = "rd-lookup/ep?ep=node1&rt=temperature-c" req = Request() req.code = defines.Codes.GET.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address req.content_type = 0 req.payload = None expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.CONTENT.number expected.token = None expected.content_type = defines.Content_types["application/link-format"] expected.payload = None self.current_mid += 1 # After 61 seconds the resource will be expired self._test_check([(req, expected)], 61)
def _test_with_client(self, message_list): # pragma: no cover client = HelperClient(self.server_address) for message, expected in message_list: if message is not None: received_message = client.send_request(message) if expected is not None: if expected.type is not None: self.assertEqual(received_message.type, expected.type) if expected.mid is not None: self.assertEqual(received_message.mid, expected.mid) self.assertEqual(received_message.code, expected.code) if expected.source is not None: self.assertEqual(received_message.source, self.server_address) if expected.token is not None: self.assertEqual(received_message.token, expected.token) if expected.payload is not None: self.assertEqual(received_message.payload, expected.payload) if expected.options: self.assertEqual(len(received_message.options), len(expected.options)) for o in expected.options: assert isinstance(o, Option) option_value = getattr(expected, o.name.lower().replace("-", "_")) option_value_rec = getattr(received_message, o.name.lower().replace("-", "_")) self.assertEqual(option_value, option_value_rec) client.stop()
def subscribe_by_id(self,resource_id): """ this function scbscribe message from resource by resource id :param id_name:resource id name """ global coap_client resources = resource_info['resources'] for res in resources: if (resource_id == str(res["resourceid"])) : try: path = str(res["topic"]) + str(coap_options['query']) print path def on_message(observer_json_data): data={ 'id':resource_id, 'message':observer_json_data.payload } self.trigger("message",data) s_client= HelperClient(server=(coap_options['host'], coap_options['port'])) self.subscribe_client.append(s_client) s_client.observe(path,on_message) except Exception, error: print "subscribe error" print error coap_client.observe(path,None) break elif res==resources[-1]: print "can't find the id " + resource_id + " in resourceinfo file"
def post_tag(tag_id): # Create CoAP client using library client = HelperClient(server=("192.168.43.75", 5683)) response = client.post("tags", tag_id) if response: print response.pretty_print() client.stop()
def main(): # pragma: no cover # global client try: op = "GET" path = "coap://127.0.0.1:7662/bearer" host, port, path = parse_uri(path) payload = "test" host = socket.gethostbyname(host) client = HelperClient(server=(host, port)) # response = client.post(path, payload) response = client.get_with_bearer(path,"ed1bedae-a186-4301-a15f-20e466db95e9") #response = client.get(path) # print type(response) # print "payload: " # print response.payload print response print response.pretty_print() client.stop() print response.active except KeyboardInterrupt: sys.exit()
def cache_token(self, response): # pragma: no cover print "Callback_observe" print "Callback_observe" print "Callback_observe" print "Callback_observe" print "Callback_observe" print "Callback_observe" print "Callback_observe" print "Callback_observe" print "Callback_observe" # print response print response.pretty_print() print response check = True # if response.active is True or response.error is None: if response.error is None: self.Bearer[str(response.bearer)] = str(response.active) if response.active is not None: print response.active == False print response.active == "False" if response.active == "False": host, port, path = parse_uri(self.AS_path) host = socket.gethostbyname(host) client = HelperClient(server=(host, port)) client.cancel_observing(response, True) print self.Bearer
class coap_adapter: port = 5683 path = "test" ip_addr = "" connected = False def stop(self): print "(not actually) stopping CoAP", self.ip_addr self.client.stop() def __init__(self, ip): self.ip_addr = ip try: self.client = HelperClient(server=(self.ip_addr, self.port)) response = self.client.get(self.path, timeout=0.2) if response: self.connected = True return print response.pretty_print() # ruin test data except Exception as e: raise e finally: if hasattr(self, 'client'): thread = Thread(target=lambda: self.client.stop()) thread.start()
def test_delete(self): print("Delete") client = HelperClient(self.server_address) path = "rd?ep=endpoint1<=500&con=coap://local-proxy-old.example.com:5683&et=oic.d.sensor" ct = {'content_type': defines.Content_types["application/link-format"]} payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";anchor="coap://spurious.example.com:5683",' \ '</sensors/light>;ct=41;rt="light-lux";if="sensor"' response = client.post(path, payload, None, None, **ct) loc_path = response.location_path client.stop() path = loc_path req = Request() req.code = defines.Codes.DELETE.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address req.content_type = 0 req.payload = None expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.DELETED.number expected.token = None expected.content_type = 0 expected.payload = None self.current_mid += 1 self._test_check([(req, expected)])
def main(): # pragma: no cover global client op = None path = None payload = None pathArray = ["aaaa::212:7402:2:202"] total = 0 count = 0 file = open('36nodes_06_ellipse_outside_1.txt', 'w') for i in range(100): path = "coap://[" + pathArray[0] + "]:5683/test/hello" host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass client = HelperClient(server=(host, port)) start = time.time() print(count) response = client.get(path) dtime = time.time() - start file.write(str(dtime) + '\n') total = total + dtime count = count + 1 time.sleep(0.6) print response.pretty_print() avgTime = total / 100 file.write('AVG RTT = ' + str(avgTime)) print('AVG=' + str(avgTime)) file.close() client.stop()
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the CoAPbit platform.""" ureg = UnitRegistry() dev = [] node_addr_list = [] try: retrieve_nodes(DEFAULT_BR_URI, node_addr_list) except: _LOGGER.error('Could not contact border router') return False for addr in node_addr_list: if addr == config.get(CONF_NODE_URI): # set coapbit's calendar calendar_client = HelperClient(server=(addr, config.get(CONF_COAP_PORT))) set_datetime(calendar_client,"Calendar") #for each client create one entity for each sensor for resource in config.get(CONF_MONITORED_RESOURCES): coap_client = HelperClient(server=(addr, config.get(CONF_COAP_PORT))) dev.append(CoAPbitSensor(coap_client, resource, ureg)) else: _LOGGER.error('Device not found at address: ' + config.get(CONF_NODE_URI)) return False async_add_entities(dev, True) return True
def pre_attack_init(self): try: assert PeniotCoAP.does_method_have_payload(self.method) and self.fuzzing_turn >= 2 except AssertionError as e: raise self.client = HelperClient(server=(self.host, self.port)) self.method = PeniotCoAP.get_coap_methods_by_name(self.method_string)
def cb_post_login(response): """ Callback do post de login. Processa a resposta do login e submete o segundo passo da autenticação multifator """ global client global auth_code global e logger.debug("dentro do callback do post do passo1") logger.debug("response dentro do callback do post do passo1:", response) a = JsonAdapter.convertToDict(response.payload) print(a) query = a["query"] if (query != 1): auth_code = a["auth_code"] resultado = QueryHelper.processQuery( query, DBClientDevices.db[indice]["uuid"]) logger.debug("dentro do callback do post do passo1 - resultado query:", resultado) query_result = CoapMessageStepTwo(str(resultado, "utf-8"), a["auth_code"]) #todo: consertar isso para funcionar com o mesmo client client2 = HelperClient(server=(HOST, PORT)) client2.post("step2", query_result.toJSON(), cb_post_passo2, 10) else: print("dentro do callback do post do passo1 - sem segundo fator") logger.debug("sinalizando para thread continuar...") e.set()
def run(self): log.info("CoAP Observe \"{0}\" started.".format(self.name)) print("") self.coap_client = HelperClient(server=(self.node, self.port)) self.coap_client.observe(path=self.resource, callback=self.message_callback) return
def activate_action(userid, deviceid, actionid): """Activates an action Args: userid (string): the id of the user deviceid (string): the id of the device actionid (string): the id of the action json (json): json object containing an accestoken Returns: returns 200 if action was successful, 400 if not. """ device = requests.get( "http://device-service:5400/v1/users/{0}/devices/{1}".format( userid, deviceid)).json() if 'actions' in device: for x in device["actions"]: actiondata = x.split(':') if actionid == actiondata[1]: action = actiondata[0] break token = device["deviceToken"].split(':') host = token[0] port = int(token[1]) client = HelperClient(server=(host, port)) client.put("action", action) else: make_response("Device has no actions", 400)
def test_fail_with_handshake_on_connect(self): """ Test an invalid CoAP sequence with DTLS encryption. The handshake is triggered from the client during the connect call. """ _logger.info("Called test_fail_with_handshake_on_connect ...") exchange = self._create_test_sequence(bValidResponse=False) # Set up a client side DTLS socket _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) _sock = wrap_client(_sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.pem['CA_CERT_WRONG'], ciphers="RSA", do_handshake_on_connect=True) # Connect the CoAP client to the newly created socket client = HelperClient(self.server_address, sock=_sock, cb_ignore_read_exception=self._cb_ignore_read_exception, cb_ignore_write_exception=self._cb_ignore_write_exception) # Do the communication try: self._test_with_client(client, exchange) except: raise # Stop the client (also closes the socket) finally: client.stop()
def __init__(self): config = ConfigUtil() config.loadConfig("../../../config/ConnectedDevicesConfig.props") self.host = config.getValue("coap.device", "host") self.port = int(config.getValue("coap.device", "port")) self.path = "Temp" self.client = HelperClient(server=(self.host, self.port))
def start_data_observer(self, query, event_handler): temp_uri = self.__uri + URL_REFRESHER coapServer = MyCoapServer() payload = MessageDataMonitor() payload.device_id = query.device_id payload.resource_uri = query.resource_uri payload.interval = query.interval payload.local_path = coapServer.add_data_listener( payload, event_handler) payload.push_url = Utils.compose_purl("coap", payload.local_path, str(coapServer.get_port())) payload.requester_name = query.requester payload.sequence = query.sequence payload.process = query.process LogUtil.log("POST : " + temp_uri + "payload: \n" + payload.to_json_string()) client = HelperClient(server=(self.__ip, self.__port)) response = client.post( URL_REFRESHER, payload.to_json_string(), None, TIMEOUT_GET) # content type = MediaTypeRegistry.APPLICATION_JSON client.close() if response is None: #delete later raise CoapException("No response received.") elif response.code == defines.Codes.CREATED.number or response.code == defines.Codes.DELETED.number or response.code == defines.Codes.VALID.number or response.code == defines.Codes.CHANGED.number or response.code == defines.Codes.CONTENT.number or response.code == defines.Codes.CONTINUE.number: monitor_id = str(response.payload) LogUtil.log("POST : " + temp_uri + " resp : " + monitor_id) payload.monitor_id = monitor_id return monitor_id
def do_resource_put(self, resource, format, payload): url = get_iagent_server_uri() if isinstance(resource, basestring): path = resource LogUtil.log("PUT : " + url) elif isinstance(resource, Resource): url += resource.get_absolute_uri() path = resource.get_absolute_uri() LogUtil.log("PUT : " + url) else: pass client = HelperClient(server=(self.__ip, self.__port)) print "property payload =" + payload data = (format, payload) response = client.put(path, data, None, TIMEOUT_GET) client.close() if response is None: raise CoapException("No response received.") elif response.code == defines.Codes.CREATED.number or response.code == defines.Codes.DELETED.number or response.code == defines.Codes.VALID.number or response.code == defines.Codes.CHANGED.number or response.code == defines.Codes.CONTENT.number or response.code == defines.Codes.CONTINUE.number: # if isinstance(resource, Resource): request_text = str(response.payload) print "response code =" + str(response.code) return True else: raise CoapException(response)
def test_wrong_ep(self): print("Endpoint name already exists") client = HelperClient(self.server_address) path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683<=60" ct = {'content_type': defines.Content_types["application/link-format"]} payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";anchor="coap://spurious.example.com:5683",' \ '</sensors/light>;ct=41;rt="light-lux";if="sensor"' client.post(path, payload, None, None, **ct) client.stop() path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683" req = Request() req.code = defines.Codes.POST.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address req.content_type = defines.Content_types["application/link-format"] req.payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";' \ 'anchor="coap://spurious.example.com:5683",</sensors/light>;ct=41;rt="light-lux";if="sensor"' expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.SERVICE_UNAVAILABLE.number expected.token = None expected.content_type = 0 expected.payload = None self.current_mid += 1 self._test_check([(req, expected)])
def main(): # pragma: no cover global client config = None wait = 0 try: opts, args = getopt.getopt(sys.argv[1:], "hc:w", ["help", "config=", "wait="]) 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 ("-c", "--config"): config = a print("conf: " + str(a)) elif o in ("-w", "--wait"): print("dentro wait") wait = a print("wait: " + wait) elif o in ("-h", "--help"): usage() sys.exit() else: usage() sys.exit(2) if config is None: print ("Config file must be specified") usage() sys.exit(2) config = open(config, "r") config = json.load(config) while True: for n in config["nodes"]: for i in parameters: path = "coap://" + n["ip"] + ":" + str(n["port"]) + "/" + str(i) print("path: " + path) host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass client = HelperClient(server=(host, port)) response = client.get(path, timeout=5.0) print "INSERT TO DB" try: print(response.pretty_print()) insert_to_db(response, i) client.stop() except AttributeError: pass try: time.sleep(float(wait)) except: time.sleep(30.0)
def __init__(self): self.SERVER = "192.168.0.3" # The server's IP address self.PORT = 5683 # The server's port self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP socket self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.client = HelperClient(server=(self.SERVER, self.PORT), sock=self.sock) # CoAP client
def __init__(self, jsondata): threading.Thread.__init__(self) self.jsondata = jsondata self.host = self.jsondata.getServerIp() self.port = self.jsondata.getPort() self.deviceid = self.jsondata.getDeviceId() self.client = HelperClient(server=(self.host, self.port)) return
def run(self): log.info("MoteConnector \"{0}\" started.".format(self.name)) self.coap_client = HelperClient(server=(self.host, self.port)) if self.is_observer: self.coap_client.observe(path=self.path, callback=self.message_callback) else: self.coap_client.get(path=self.path, callback=self.message_callback) return
def render_GET(self, request): # # for option in request.options: # # if option.number == defines.OptionRegistry.BEARER.number: # # str(request.bearer # self.num += 1 # self.payload = str(self.num) if str(request.bearer) in self.Bearer: if self.Bearer[str(request.bearer)] == str(True): # self.payload = str(self.Bearer[str(request.bearer)]) # return self pass else: self.payload = "invalid_token" # self.payload = "invalid_token" else: host, port, path = parse_uri(self.AS_path) host = socket.gethostbyname(host) client = HelperClient(server=(host, port)) # response = None # response = client.get(path) response = client.introspect(path, str(request.bearer), access_path="basic") client.introspect_observer(path, str(request.bearer), callback=self.cache_token, access_path="basic") # client.introspect_observer(path, str(request.bearer), access_path="basic") # for option in response.options: # if option.number == defines.OptionRegistry.BEARER.number: # self.Bearer[str(option.value)] = response.payload # # host = socket.gethostbyname(host) # client_2 = HelperClient(server=(host, port)) # client_2.stop() # # if response.active is True or response.error is None: if response.error is None: self.Bearer[str(request.bearer)] = str(response.active) # print "??" # print "??" # print "??" # print "??" # print "??" # print self.Bearer[str(request.bearer)] # self.payload = str(request.bearer) if response.error == 0: self.payload = "invalid_request" if response.error == 1 or response.active is False: self.payload = "invalid_token" if response.error == 2: self.payload = "insufficient_scope" # return self # self.payload = "Invalid access" return self
def initClient(self): try: self.client = HelperClient(server=("192.171.241.8", 5683)) print("Created Reference: " + str(self.client)) print(" coap://" + self.host + ":" + str(self.port)) except Exception: print("Failed to Connect to client: " + self.host) pass
def discover_remote(self, destination, name): assert (isinstance(destination, str)) if destination.startswith("["): split = destination.split("]", 1) host = split[0][1:] port = int(split[1][1:]) else: split = destination.split(":", 1) host = split[0] port = int(split[1]) server = (host, port) client = HelperClient(server) response = client.discover() client.stop() self.discover_remote_results(response, name)
def main(): host = "127.0.0.1" port = 5683 client = HelperClient(server=(host, port)) # Test discover path = "/.well-known/core" response = client.get(path) print response.pretty_print() # Create a registration resource path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683&et=oic.d.sensor" ct = {'content_type': defines.Content_types["application/link-format"]} payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";anchor="coap://spurious.example.com:5683",' \ '</sensors/light>;ct=41;rt="light-lux";if="sensor"' response = client.post(path, payload, None, None, **ct) location_path = response.location_path print response.pretty_print() # Resource lookup path = 'rd-lookup/res?if=sensor' response = client.get(path) print response.pretty_print() # Update a registration resource path = location_path + "?con=coaps://new.example.com:5684" response = client.post(path, '') print response.pretty_print() # Read endpoint links path = location_path response = client.get(path) print response.pretty_print() # Endpoint lookup path = 'rd-lookup/ep?et=oic.d.sensor' response = client.get(path) print response.pretty_print() # Delete a registration resource path = location_path response = client.delete(path) print response.pretty_print() client.stop()
def do_initial_operations(self): if not self.request_hc_path_corresponds(): # the http URI of the request is not the same of the one specified by the admin for the hc proxy, # so I do not answer # For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of # the requests asks for "http://127.0.0.1:8080:/another_hc_path/" return self.set_coap_uri() self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port))
def main(): if (len(sys.argv) != 5): print("Invalid arguments.") print("Pass arguments in correct order as below:") print("./coap-sender.py <host> <port> <resource> <payload>") sys.exit(1) # retrieving arguments host = str(sys.argv[1]) port = int(sys.argv[2]) resource = str(sys.argv[3]) payload = str(sys.argv[4]) client = HelperClient(server=(host, port)) response = client.put(resource, payload) print response.pretty_print() print("Payload published!") client.stop()
def _read_rd(self): client = HelperClient(self._rd) path = 'rd-lookup/res?rt=temperature' self._temperature_sensors["temperature"] = self._read_rd_sensor(client, path) path = 'rd-lookup/res?rt=humidity' self._temperature_sensors["humidity"] = self._read_rd_sensor(client, path) path = 'rd-lookup/res?rt=light' self._temperature_sensors["light"] = self._read_rd_sensor(client, path) for k, lst_v in self._temperature_sensors.items(): for v in lst_v: pattern = "coap://([0-9a-z.]*):([0-9]*)(/[a-zA-Z0-9/]*)" match = re.match(pattern=pattern, string=v) if match is not None: host = match.group(1) port = int(match.group(2)) path = match.group(3) client_sensor = HelperClient((host, port)) client_sensor.observe(path, self.client_callback_observe) self._clientPool.append(client_sensor)
class Agent(): def __init__(self, ip, port, path): self.ip = ip self.port = port self.path = path self.cnt = 0 self.client = HelperClient(server=(ip, port)) self.flag = True def getResource(self): response = self.client.get(self.path) logg.debug("getResouce response:{0}".format(response.pretty_print())) def putResource(self): msg = { "Banana23": { "k1": "v1", "serial": "0", "kn": "vn" } } while self.flag: if self.cnt >= 5: time.sleep(1000); else: msg["Banana23"]["serial"] = str(self.cnt) logg.debug("send msg:{0}".format(msg)) payload = json.dumps(msg) response = self.client.put(self.path, payload) logg.debug("putResouce response:{0}".format(response.pretty_print())) time.sleep(5); self.cnt += 1 if self.cnt > 20: self.flag = False def close(self): self.client.stop()
def discover_remote(self, destination, name): """ Discover resources on remote servers. :param destination: the remote server (ip, port) :type destination: tuple :param name: the name of the remote server :type name: String """ assert (isinstance(destination, str)) if destination.startswith("["): split = destination.split("]", 1) host = split[0][1:] port = int(split[1][1:]) else: split = destination.split(":", 1) host = split[0] port = int(split[1]) server = (host, port) client = HelperClient(server) response = client.discover() client.stop() self.discover_remote_results(response, name)
def test_wildcard_ep(self): print("Use wildcard * to find endpoints") client = HelperClient(self.server_address) path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683" ct = {'content_type': defines.Content_types["application/link-format"]} payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";anchor="coap://spurious.example.com:5683",' \ '</sensors/light>;ct=41;rt="light-lux";if="sensor"' response = client.post(path, payload, None, None, **ct) loc_path1 = response.location_path path = "rd?ep=node2&con=coap://[2001:db8:3::123]:61616" payload = '</temp>;rt="temperature";anchor="coap://[2001:db8:3::123]:61616"' response = client.post(path, payload, None, None, **ct) loc_path2 = response.location_path client.stop() path = "rd-lookup/ep?rt=temp*" req = Request() req.code = defines.Codes.GET.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address req.content_type = 0 req.payload = None expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.CONTENT.number expected.token = None expected.content_type = defines.Content_types["application/link-format"] expected.payload = '</' + loc_path1 + '>;con="coap://local-proxy-old.example.com:5683";ep="node1";lt=500,' \ '</' + loc_path2 + '>;con="coap://[2001:db8:3::123]:61616";' \ 'ep="node2";lt=500' self.current_mid += 1 self._test_check([(req, expected)])
def __init__(self, host, port, multicast=False): CoAP.__init__(self, (host, port), multicast) self.client = HelperClient(server=(defines.RD_HOST, defines.RD_PORT)) self.node_resource_schema = json.load(open(defines.NODE_RESOURCE_SCHEMA_PATH, "r")) self.node_name = self.node_resource_schema["node"]["name"]["value"] self.parameter_schema = json.load(open(defines.SERIAL_PARAMETER_SCHEMA_PATH, "r")) self.parameter_schema_lock = threading.Lock() serial_listener = threading.Thread(target=self.serial_listen) serial_listener.setDaemon(True) serial_listener.start() self.rd_discovery() print "CoAP Server start on " + host + ":" + str(port)
class CoAPServer(CoAP): def __init__(self, host, port, multicast=False): CoAP.__init__(self, (host, port), multicast) self.client = HelperClient(server=(defines.RD_HOST, defines.RD_PORT)) self.node_resource_schema = json.load(open(defines.NODE_RESOURCE_SCHEMA_PATH, "r")) self.node_name = self.node_resource_schema["node"]["name"]["value"] self.parameter_schema = json.load(open(defines.SERIAL_PARAMETER_SCHEMA_PATH, "r")) self.parameter_schema_lock = threading.Lock() serial_listener = threading.Thread(target=self.serial_listen) serial_listener.setDaemon(True) serial_listener.start() self.rd_discovery() print "CoAP Server start on " + host + ":" + str(port) def serial_listen(self): port = serial.Serial(defines.SERIAL_PORT) port.baudrate = defines.SERIAL_BAUDRATE while True: try: received_parameter_dict = json.loads(port.readline()) except ValueError: continue self.parameter_schema_lock.acquire() for key in self.parameter_schema: subresources = self.parameter_schema[key] for subkey in subresources: if subkey in received_parameter_dict: value = received_parameter_dict[subkey] typeof = subresources[subkey]["parameter"]["type"] if (typeof == "integer" and type(value) is int) or (typeof == "string" and type(value) is str): subresources[subkey]["parameter"]["value"] = value else: subresources[subkey]["parameter"]["value"] = -1 # error code self.parameter_schema_lock.release() print "schema parametri " + str(self.parameter_schema) def rd_discovery(self): # Test discover path = "/.well-known/core" response = self.client.get(path) print response.pretty_print() def register_rd_resource(self, resource_type, key): path = "rd?ep=" + self.node_name + "&con=coap://" + str(self.server_address[0]) + ":" + str(self.server_address[1]) ct = {'content_type': defines.Content_types["application/link-format"]} payload = '</' + key + '>;ct=41;' + resource_type + ';if="sensor";' response = self.client.post(path, payload, None, None, **ct) print response.pretty_print() return response.location_path def refresh_rd_resource(self, location_path): path = location_path response = self.client.post(path, '') print response.pretty_print()
class HCProxyHandler(BaseHTTPRequestHandler): def set_coap_uri(self): self.coap_uri = CoapUri(self.path[len(hc_path):]) def do_initial_operations(self): if not self.request_hc_path_corresponds(): # the http URI of the request is not the same of the one specified by the admin for the hc proxy, # so I do not answer # For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of # the requests asks for "http://127.0.0.1:8080:/another_hc_path/" return self.set_coap_uri() self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port)) def do_GET(self): self.do_initial_operations() coap_response = self.client.get(self.coap_uri.path) self.client.stop() print "Server response: ", coap_response.pretty_print() self.set_http_response(coap_response) def do_HEAD(self): self.do_initial_operations() # the HEAD method is not present in CoAP, so we treat it # like if it was a GET and then we exclude the body from the response # with send_body=False we say that we do not need the body, because it is a HEAD request coap_response = self.client.get(self.coap_uri.path) self.client.stop() print "Server response: ", coap_response.pretty_print() self.set_http_header(coap_response) def do_POST(self): # Doesn't do anything with posted data # print "uri: ", self.client_address, self.path self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: print "BAD POST REQUEST" self.send_error(BAD_REQUEST) return print payload coap_response = self.client.post(self.coap_uri.path, payload) self.client.stop() print "Server response: ", coap_response.pretty_print() self.set_http_response(coap_response) def do_PUT(self): self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: print "BAD PUT REQUEST" self.send_error(BAD_REQUEST) return print payload coap_response = self.client.put(self.coap_uri.path, payload) self.client.stop() print "Server response: ", coap_response.pretty_print() self.set_http_response(coap_response) def do_DELETE(self): self.do_initial_operations() coap_response = self.client.delete(self.coap_uri.path) self.client.stop() print "Server response: ", coap_response.pretty_print() self.set_http_response(coap_response) def do_CONNECT(self): self.send_error(NOT_IMPLEMENTED) def do_OPTIONS(self): self.send_error(NOT_IMPLEMENTED) def do_TRACE(self): self.send_error(NOT_IMPLEMENTED) def request_hc_path_corresponds(self): """ tells if the hc path of the request corresponds to that specified by the admin :return: a boolean that says if it corresponds or not """ uri_path = self.path.split(COAP_PREFACE) request_hc_path = uri_path[0] print "HCPATH: ", hc_path # print HC_PATH print "URI: ", request_hc_path if hc_path != request_hc_path: return False else: return True def set_http_header(self, coap_response): print "Server: ", coap_response.source print "codice risposta: ", coap_response.code print "PROXED: ", CoAP_HTTP[Codes.LIST[coap_response.code].name] print "payload risposta: ", coap_response.payload self.send_response(int(CoAP_HTTP[Codes.LIST[coap_response.code].name])) self.send_header('Content-type', 'text/html') self.end_headers() def set_http_body(self, coap_response): if coap_response.payload is not None: body = "<html><body><h1>", coap_response.payload, "</h1></body></html>" self.wfile.write("".join(body)) else: self.wfile.write("<html><body><h1>None</h1></body></html>") def set_http_response(self, coap_response): self.set_http_header(coap_response) self.set_http_body(coap_response) return
def main(): # pragma: no cover global client op = None path = None payload = None try: opts, args = getopt.getopt(sys.argv[1:], "ho:p:P:f:", ["help", "operation=", "path=", "payload=", "payload_file="]) 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 ("-o", "--operation"): op = a elif o in ("-p", "--path"): path = a elif o in ("-P", "--payload"): payload = a elif o in ("-f", "--payload-file"): with open(a, 'r') as f: payload = f.read() elif o in ("-h", "--help"): usage() sys.exit() else: usage() sys.exit(2) if op is None: print "Operation must be specified" usage() sys.exit(2) if path is None: print "Path must be specified" usage() sys.exit(2) if not path.startswith("coap://"): print "Path must be conform to coap://host[:port]/path" usage() sys.exit(2) host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass client = HelperClient(server=(host, port)) if op == "GET": if path is None: print "Path cannot be empty for a GET request" usage() sys.exit(2) response = client.get(path) print response.pretty_print() client.stop() elif op == "OBSERVE": if path is None: print "Path cannot be empty for a GET request" usage() sys.exit(2) client.observe(path, client_callback_observe) elif op == "DELETE": if path is None: print "Path cannot be empty for a DELETE request" usage() sys.exit(2) response = client.delete(path) print response.pretty_print() client.stop() elif op == "POST": if path is None: print "Path cannot be empty for a POST request" usage() sys.exit(2) if payload is None: print "Payload cannot be empty for a POST request" usage() sys.exit(2) response = client.post(path, payload) print response.pretty_print() client.stop() elif op == "PUT": if path is None: print "Path cannot be empty for a PUT request" usage() sys.exit(2) if payload is None: print "Payload cannot be empty for a PUT request" usage() sys.exit(2) response = client.put(path, payload) print response.pretty_print() client.stop() elif op == "DISCOVER": response = client.discover() print response.pretty_print() client.stop() else: print "Operation not recognized" usage() sys.exit(2)
# -*- encoding:utf-8 -*- # create by Administrator on 2018/7/18 from coapthon.client.helperclient import HelperClient host = "127.0.0.1" port = 5683 path = "basic" client = HelperClient(server=(host, port)) response = client.get(path) print response.pretty_print() client.stop()
class HCProxyHandler(BaseHTTPRequestHandler): """ It maps the requests from HTTP to CoAP """ coap_uri = None client = None def set_coap_uri(self): """ Create a CoAP Uri """ self.coap_uri = CoapUri(self.path[len(hc_path):]) def do_initial_operations(self): """ Setup the client for interact with remote server """ if not self.request_hc_path_corresponds(): # the http URI of the request is not the same of the one specified by the admin for the hc proxy, # so I do not answer # For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of # the requests asks for "http://127.0.0.1:8080:/another_hc_path/" return self.set_coap_uri() self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port)) def do_GET(self): """ Perform a GET request """ self.do_initial_operations() coap_response = self.client.get(self.coap_uri.path) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response) def do_HEAD(self): """ Perform a HEAD request """ self.do_initial_operations() # the HEAD method is not present in CoAP, so we treat it # like if it was a GET and then we exclude the body from the response # with send_body=False we say that we do not need the body, because it is a HEAD request coap_response = self.client.get(self.coap_uri.path) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_header(coap_response) def do_POST(self): """ Perform a POST request """ # Doesn't do anything with posted data # print "uri: ", self.client_address, self.path self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD POST REQUEST") self.send_error(BAD_REQUEST) return coap_response = self.client.post(self.coap_uri.path, payload) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response) def do_PUT(self): """ Perform a PUT request """ self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD PUT REQUEST") self.send_error(BAD_REQUEST) return logger.debug(payload) coap_response = self.client.put(self.coap_uri.path, payload) self.client.stop() logger.debug("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response) def do_DELETE(self): """ Perform a DELETE request """ self.do_initial_operations() coap_response = self.client.delete(self.coap_uri.path) self.client.stop() logger.debug("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response) def do_CONNECT(self): """ Perform a CONNECT request. Reply with error, not implemented in CoAP """ self.send_error(NOT_IMPLEMENTED) def do_OPTIONS(self): """ Perform a OPTIONS request. Reply with error, not implemented in CoAP """ self.send_error(NOT_IMPLEMENTED) def do_TRACE(self): """ Perform a TRACE request. Reply with error, not implemented in CoAP """ self.send_error(NOT_IMPLEMENTED) def request_hc_path_corresponds(self): """ Tells if the hc path of the request corresponds to that specified by the admin :return: a boolean that says if it corresponds or not """ uri_path = self.path.split(COAP_PREFACE) request_hc_path = uri_path[0] logger.debug("HCPATH: %s", hc_path) # print HC_PATH logger.debug("URI: %s", request_hc_path) if hc_path != request_hc_path: return False else: return True def set_http_header(self, coap_response): """ Sets http headers. :param coap_response: the coap response """ logger.debug( ("Server: %s\n"\ "codice risposta: %s\n"\ "PROXED: %s\n"\ "payload risposta: %s"), coap_response.source, coap_response.code, CoAP_HTTP[Codes.LIST[coap_response.code].name], coap_response.payload) self.send_response(int(CoAP_HTTP[Codes.LIST[coap_response.code].name])) self.send_header('Content-type', 'text/html') self.end_headers() def set_http_body(self, coap_response): """ Set http body. :param coap_response: the coap response """ if coap_response.payload is not None: body = "<html><body><h1>", coap_response.payload, "</h1></body></html>" self.wfile.write("".join(body)) else: self.wfile.write("<html><body><h1>None</h1></body></html>") def set_http_response(self, coap_response): """ Set http response. :param coap_response: the coap response """ self.set_http_header(coap_response) self.set_http_body(coap_response) return