def add_service(self, zeroconf, type, name): info = zeroconf.get_service_info(type, name) print("Service %s added, service info: %s" % (name, info)) coap_client = HelperClient((ip,port)) response = coap_client.discover()
client = InfluxDBClient(host='localhost', port=8086) client.switch_database('OpenMoteCC2538') client1 = [] port1 = 5683 host0 = '2801:1e:4007:c0da:212:4b00:60d:7fde' host1 = '2801:1e:4007:c0da:212:4b00:613:65c' host2 = '3333' host3 = '4444' host = (host0, host1, host2, host3) for i in [0, 1, 2, 3]: #Hacer un for o algo asi, para agregar los host a client client1.append(HelperClient(server=(host[i], port1))) path = "sensors/sht21" path1 = "sensors/max44009" #path2 ="sensors/adxl346" while True: for i in [0, 1]: response = client1[i].get(path) temp_hum = (response.pretty_print()) temp_hum = (temp_hum.split()) response1 = client1[i].get(path1) luz = (response1.pretty_print())
''' Created on Mar 6, 2020 @author: Naveen Rajendran ''' from coapthon.client.helperclient import HelperClient from coapthon.client.coap import CoAP import logging CoAP_HOST = "127.0.0.1" CoAP_PORT = 5683 path = "SensorData" CoAP_Server = HelperClient(server=( CoAP_HOST, CoAP_PORT)) # Establishing Connection to CoAP server with given properties ''' * Class module which connects to CoAP server & executes POST, DELETE, PUT & GET operations ''' class CoAPClientConnector: ''' * Class Constructor Function ''' post_flag = False put_flag = False get_flag = False del_flag = False def _init_(self): logging.info("python CoAP client started ") '''
def _create_coap_client(self, host, port): return HelperClient(server=(host, port))
def fechadura_aberta(host: str): client = HelperClient(server=(host, 5683)) res = client.get('lightled') return res.payload == '0'
def coap_setup(self, host, port): # Coap 서버와 연결, setupUi 함수 맨 앞에서 실행 됨 self.client = HelperClient(server=(host, port)) # 클래스 변수로 Client 객체 저장
def coap_setup(self, host, port): self.client = HelperClient(server=(host, port)) # 클래스 변수로 Client 객체 저장
def get_values(path): client = HelperClient(server=(hostArduino, port)) response = client.get(path) client.stop() return response._payload
def main(): # pragma: no cover global client op = None path = None payload = None proxy_uri = None try: opts, args = getopt.getopt(sys.argv[1:], "ho:p:P:f:", [ "help", "operation=", "path=", "payload=", "payload_file=", "proxy-uri-header=" ]) 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 ("-u", "--proxy-uri-header"): proxy_uri = a 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) if proxy_uri and not proxy_uri.startswith( "http://") and not proxy_uri.startswith("https://"): print "Proxy-Uri header must be conform to http[s]://host[:port]/path" usage() sys.exit(2) host, port, path = parse_uri(path) """ Idee sul controllo finale dell'url if path and not path.endswith("coap://"): print "errore nel passaggio" usage() sys.exit(2) """ 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, proxy_uri=proxy_uri) 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, proxy_uri=proxy_uri) 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, proxy_uri=proxy_uri) 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, proxy_uri=proxy_uri) print response.pretty_print() client.stop() elif op == "DISCOVER": response = client.discover() print response.pretty_print() client.stop() """test con implementazione in request layer""" elif op == "FETCH": print "FETCH CALLBACK OK" if path is None: print "Path cannot be empty for FETCH" usage() sys.exit(2) ##AGGIUNTA DEL PAYLOAD DA DOVE ARRIVA LA RICHIESTA if payload is None: print "Payload cannot be empty for a FETCH request" usage() sys.exit(2) response = client.fetch(path, payload, proxy_uri=proxy_uri) print response.pretty_print() client.stop() elif op == "PATCH": print "PATCH CALLBACK OK" if path is None: print "Path cannot be empty for FETCH" usage() sys.exit(2) response = client.patch(path, payload, proxy_uri=proxy_uri) print response.pretty_print() client.stop() else: print "Operation not recognized" usage() sys.exit(2)
def __init__(self, host): ''' ''' host, port, self.path = parse_uri(host) self.client = HelperClient(server=(host, port))
from coapthon.client.helperclient import HelperClient from datetime import datetime import requests import pdb URL = "https://samken600.me/temp" from config import hosts port = 5683 path = 'temp' clients = [] for host in hosts: client = HelperClient(server=(host['ip'], port)) hw_array = host['ip'].split(":")[-4:] hw_array[0] = "%x" % (int(hw_array[0], 16) + 512) hwaddr = "".join(hw_array) hwaddr = ":".join(hwaddr[i:i + 2] for i in range(0, len(hwaddr), 2)).upper() clients.append({ 'client': client, 'number': host['number'], 'hwaddr': hwaddr }) responses = [] for client in clients: now = datetime.utcnow() response = client['client'].get( path=path, timeout=15) # pretty sure timeout is in seconds if response is not None:
#!/usr/bin/python from coapthon.client.helperclient import HelperClient client = HelperClient(server=('192.168.1.102', 5683)) response = client.get('hello') print(response.pretty_print()) client.stop()
def outbound(host, port, value): print("outbound 1") client = HelperClient(server=(host, port)) print("outbound 2") response = client.put("action", value) print("response is " + response.__str__)
def main(): 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(str(err)) 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_observer(path) 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() else: print("Operation not recognized") usage() sys.exit(2)
def connect(self,option): global coap_client coap_client = HelperClient(server=(option['host'], option['port']))
from coapthon.client.helperclient import HelperClient import json client = HelperClient(server=("192.168.71.34", 5684)) response = client.get("things/Sensor1") if response.content_type == 0: #STRING data = response.payload elif response.content_type == 50: #JSON data = json.loads(response.payload) else: pass print(data) thing_api = data for property_name, metadata in thing_api['properties'].items(): print(metadata) client.stop()
def main(): argc = len(sys.argv) if argc != 3: print("Esse script funciona com 2 argumentos: <host> <port>") print("<host>: endereço IP do servidor") print("<port>: porta do servidor") exit(1) host = sys.argv[1] port = int(sys.argv[2]) signal.signal(signal.SIGINT, stop_node) MIFAREReader = MFRC522.MFRC522() #RFID pinouts TRIG1 = 16 #pin 16, GPIO 23 ECHO1 = 18 #pin 18, GPIO 24 TRIG2 = 8 #pin 8, GPIO 14 ECHO2 = 10 #pin 10, GPIO 15 MOTOR = 36 #pin 36, GPIO 16 GPIO.setup(TRIG1, GPIO.OUT) GPIO.setup(TRIG2, GPIO.OUT) GPIO.setup(ECHO1, GPIO.IN) GPIO.setup(ECHO2, GPIO.IN) GPIO.setup(MOTOR, GPIO.OUT) PWM = GPIO.PWM(MOTOR, 50) PWM.start(0) setAngle(90, MOTOR, PWM) GPIO.output(TRIG1, False) GPIO.output(TRIG2, False) time.sleep(2) print "Press Ctrl-C to stop." allowed = False while nonstop: #allowed = checkRFID(getRFID()) (status, TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) if status == MIFAREReader.MI_OK: print "RFID detectado" (status, uid) = MIFAREReader.MFRC522_Anticoll() client = HelperClient(server=(host, port)) payload = str(uid[0]) + "." + str(uid[1]) + "." + str( uid[2]) + "." + str(uid[3]) path = "/rfid" response = client.put(path, payload) #print response.pretty_print() client.stop() if response.payload == '1': allowed = True print "RFID conhecido" if response.payload == '0': allowed = False print "RFID nao conhecido" #for test #consultar RFID #if uid[0] == 192: # allowed = True if allowed: setAngle(0, MOTOR, PWM) #open time.sleep(8) setAngle(90, MOTOR, PWM) #close allowed = False distance1 = getDistance(TRIG1, ECHO1) distance2 = getDistance(TRIG2, ECHO2) if (distance1 < 20.0) and (distance2 < 20.0): print "Carro esperando" #if !allowed #getPicture #sendToServer #tirar a foto #enviar pro servidor setAngle(0, MOTOR, PWM) #open time.sleep(6) setAngle(90, MOTOR, PWM) #close
def main(): argc = len(sys.argv) if argc != 3: print("Esse script funciona com 2 argumentos: <host> <port>\n") print("<host>: endereço IP do servidor\n") print("<port>: porta do servidor\n") exit(1) host = sys.argv[1] port = int(sys.argv[2]) signal.signal(signal.SIGINT, stop_node) trig1 = 23 echo1 = 24 trig2 = 27 echo2 = 22 #stop GPIOs useds GPIO.cleanup() call(['./src/piio/build/ultrasonic', 'reset', str(trig1), str(echo1)]) call(['./src/piio/build/ultrasonic', 'reset', str(trig2), str(echo2)]) call(['./src/piio/build/servo', 'reset']) #setup sensors/actuators print('Iniciando sensor ultrassônico...\n') if 1 != call( ['./src/piio/build/ultrasonic', 'setup', str(trig1), str(echo1)]): print('Falha ao iniciar ultrassônico 1.\n') return -1 if 1 != call( ['./src/piio/build/ultrasonic', 'setup', str(trig2), str(echo2)]): print('Falha ao iniciar ultrassônico 2.\n') return -1 print('Iniciando motor servo...\n') if 1 != call(['./src/piio/build/servo', 'setup']): print('Falha ao iniciar motor servo.\n') return -1 print('Iniciando RFID...\n') MIFAREReader = MFRC522.MFRC522() call(['./src/piio/build/servo', 'rotate', '180']) time.sleep(1) allowed = False print('Iniciado.Pressione Ctrl-C para terminar.\n') while nonstop: (status, TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) if status == MIFAREReader.MI_OK: print('RFID detectado...\n') (status, uid) = MIFAREReader.MFRC522_Anticoll() if status == MIFAREReader.MI_OK: key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] MIFAREReader.MFRC522_SelectTag(uid) status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid) if status == MIFAREReader.MI_OK: MIFAREReader.MFRC522_Read(8) MIFAREReader.MFRC522_StopCrypto1() client = HelperClient(server=(host, port)) payload = str(uid[0]) + "." + str(uid[1]) + "." + str( uid[2]) + "." + str(uid[3]) path = '/rfid' response = client.put(path, payload) client.stop() if response.payload == '1': print('RFID conhecido...\n') open_gate() if response.payload == '0': print('RFID não conhecido...\n') distance1 = call( ['./src/piio/build/ultrasonic', 'read', str(trig1), str(echo1)]) distance2 = call( ['./src/piio/build/ultrasonic', 'read', str(trig2), str(echo2)]) #print(distance1) #print(distance2) if (distance1 < 20.0) and (distance2 < 20.0): print('Carro detectado...\n') print('Capturando imagem...\n') #capturar imagem client = HelperClient(server=(host, port)) payload = 'updated' path = '/img' response = client.put(path, payload) client.stop() open_gate()
def main(): # pragma: no cover global client op = None path = None payload = None content_type = None #ct = {'content_type': defines.Content_types["application/link-format"]} ct = {} ct['accept'] = 0 ct['ocf_accept_content_format_version'] = int(2048) ct['ocf_content_format_version'] = int(2048) try: opts, args = getopt.getopt(sys.argv[1:], "ho:p:P:f:c:", [ "help", "operation=", "path=", "payload=", "payload_file=", "content-type" ]) 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 ("-c", "--content-type"): ct['accept'] = a print("content type request : ", ct) 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, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types["application/json"]: json_data = json.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print("JSON ::") print(json_string) if response.content_type == defines.Content_types["application/cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print("JSON ::") print(json_string) if response.content_type == defines.Content_types[ "application/vnd.ocf+cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print("JSON ::") print(json_string) client.stop() elif op == "GETNONE": if path is None: print("Path cannot be empty for a GET-None request") usage() sys.exit(2) response = client.get_non(path, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types["application/json"]: json_data = json.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print("JSON ::") print(json_string) if response.content_type == defines.Content_types["application/cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print("JSON ::") print(json_string) if response.content_type == defines.Content_types[ "application/vnd.ocf+cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print("JSON ::") print(json_string) 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) print("payload for POST (ascii):", payload) print(ct['accept']) if ct['accept'] == str(defines.Content_types["application/cbor"]): json_data = json.loads(payload) cbor_data = cbor.dumps(json_data) payload = bytes(cbor_data) if ct['accept'] == str( defines.Content_types["application/vnd.ocf+cbor"]): json_data = json.loads(payload) cbor_data = cbor.loads(json_data) payload = cbor_data response = client.post(path, payload, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types["application/cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print(json_string) if response.content_type == defines.Content_types[ "application/vnd.ocf+cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print(json_string) 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(path, client_callback, None, **ct) #response = client.discover( path, None, None, **ct) if response is not None: print(response.pretty_print()) if response.content_type == defines.Content_types[ "application/cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print(json_string) if response.content_type == defines.Content_types[ "application/vnd.ocf+cbor"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print(json_string) try: while True: time.sleep(1) except KeyboardInterrupt: print("Client Shutdown") client.stop() else: print("Operation not recognized") usage() sys.exit(2)
def init_known_paths(self): # TODO: Instead of hack per app, receive flag from target_list.py self.known_paths = [] extracted_strings = [] response = None self.log("Extracting paths from AUT...") self.log("AUT-specific Strings (user-defined):\n" + str(self.opt_ext_list["string"])) self.summaryfile.write("AUT-specific Strings (user-defined):\n" + str(self.opt_ext_list["string"]) + '\n') # USER: Comment below for Contiki or Canopus hack client = HelperClient(server=(self.aut_host, self.aut_port)) try: response = client.discover(timeout=5) except: self.log("Retrying GET .well-known/core") try: response = client.discover(timeout=2) except: self.log( "Target doesn't implement discovery through GET .well-known/core" ) pass pass # USER: Uncomment below for Contiki or Canopus hack # class HackResp(object): # code = defines.Codes.CONTENT.number # # Contiki: # # payload = '</.well-known/core>;ct=40,</test>;title="Default test resource",</validate>;title="Validation test resource",</create1>;title="Creates on PUT",</create2>;title="Creates on POST",</create3>;title="Default test resource",</seg1/seg2/seg3>;title="Long path resource",</query>;title="Resource accepting query parameters",</location-query>;title="Resource accepting query parameters",</multi-format>;title="Resource providing text/plain and application/xml";ct="0 41",</link1>;rt="Type1 Type2";if="If1",</link2>;rt="Type2 Type3";if="If2",</link3>;rt="Type1 Type3";if="foo",</path>;title="Path test resource";ct="40",</separate>;title="Resource which cannot be served immediately and which cannot be acknowledged in a piggy-backed way",</large>;title="Large resource";rt="block";sz="2012",</large-update>;title="Large resource that can be updated using PUT method";rt="block";sz="2048",</large-create>;title="Large resource that can be created using POST method";rt="block",</obs>;title="Observable resource which changes every 5 seconds";obs,</mirror>;title="Returns your decoded message";rt="Debug"' # # Canopus: # payload = '</hello>,</basic>,</basic/json>,</watch/this>,</blockupload>,</.well-known/core>' # response = HackResp() if response and response.payload and (response.code != defines.Codes.NOT_FOUND.number): self.known_paths.extend([ path.strip('/') for path in re.findall(r'<(.*?)>', response.payload) ]) if '' in self.known_paths: self.known_paths.remove('') extracted_strings = list( set(re.split(',|;', re.sub(r'<(.*?)>', '', response.payload)))) if '' in extracted_strings: extracted_strings.remove('') self.opt_ext_list["string"].extend(extracted_strings) self.known_paths.extend(self.aut_default_uris) self.known_paths = list(set(self.known_paths)) time.sleep(1) self.log("Extracted Paths:\n" + str(self.known_paths)) self.summaryfile.write("Extracted Paths:\n" + str(self.known_paths) + '\n') self.log("Extracted Strings:\n" + str(extracted_strings) + '\n') self.summaryfile.write("Extracted Strings:\n" + str(extracted_strings) + '\n\n\n') time.sleep(1) # USER: Comment below for Contiki or Canopus hack client.stop()
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) host = socket.gethostbyname(host) 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)
import logging.config import os from coapthon.client.helperclient import HelperClient from MoteData import MoteData logging.config.fileConfig(os.path.join('logging.conf')) log = logging.getLogger("root") host = "fd00::202:2:2:2" def message_callback(response): log.debug("Got new message") if log.isEnabledFor(logging.DEBUG): packet_content = ":".join("{:02x}".format(ord(c)) for c in response.payload) log.debug(packet_content) log.debug("Payload length: {0}".format(len(response.payload))) mote_data = MoteData.make_from_bytes(response.source[0], response.payload) log.debug("=================================") coapClient.stop() coapClient = HelperClient(server=(host, 5683)) coapClient.get(path="g/bcollect", callback=message_callback) coapClient.stop()
def abrir_fechadura(host: str): client = HelperClient(server=(host, 5683)) res = client.post('lightled', '0')
def __init__(self, host, port, path): self.host = host self.port = port self.path = path self.client = HelperClient(server=(host, port))
from coapthon.client.helperclient import HelperClient def runMethod(method): if method == 'GET' : client.get(path) pass elif method == 'POST': client.post(path,payload=input("Payload: ")) pass elif method == 'PUT': client.put(path,payload=input("Payload: ")) pass elif method == 'DELETE': client.delete(path) pass else : print("INVALID METHOD") while True: method = input("METHOD: ").upper() path = input("PATH: ") client = HelperClient(server=('192.168.0.145', 5683)) # WAIT!!! IS THE IP SET CORRECTLY? runMethod(method) client.stop()
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) total = 0 count = 0 file = open('habijabi.txt', 'w') for i in range(100): 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(.3) print response.pretty_print() avgTime = total / 100 file.write('AVG RTT = ' + str(avgTime)) print('AVG=' + str(avgTime)) file.close() 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)
def main(): global client op = None payload_path = None payload = None proxy_uri = None try: opts, args = getopt.getopt(sys.argv[1:], "ho:p:P:f:", [ "help", "operation=", "path=", "payload=", "payload_file=", "proxy-uri-header=" ]) 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"): payload_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 ("-u", "--proxy-uri-header"): proxy_uri = a 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 payload_path is None: print "Path must be specified" usage() sys.exit(2) if not payload_path.startswith("coap://"): print "Path must be conform to coap://host[:port]/path" usage() sys.exit(2) #if proxy_uri and not proxy_uri.startswith("http://") and not proxy_uri.startswith("https://"): # print("Proxy-Uri header must be conform to http[s]://host[:port]/path") # usage() # sys.exit(2) host, port, payload_path = parse_uri(payload_path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass # Setup 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, keyfile=path.join(cert_path, "keycert.pem"), certfile=path.join(cert_path, "keycert.pem"), ca_certs=path.join(cert_path, "ca-cert.pem"), ciphers="RSA", ) client = HelperClient(server=(host, port), sock=_sock) if op == "GET": if payload_path is None: print "Path cannot be empty for a GET request" usage() sys.exit(2) response = client.get(payload_path) print response.pretty_print() client.stop() elif op == "OBSERVE": if payload_path is None: print "Path cannot be empty for a GET request" usage() sys.exit(2) client.observe(payload_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(payload_path) print response.pretty_print() client.stop() elif op == "POST": if payload_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(payload_path, payload) print response.pretty_print() client.stop() elif op == "PUT": if payload_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(payload_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)
#!/usr/bin/env python # -*- coding: utf-8 -*- from coapthon.client.helperclient import HelperClient import sys ip_servidor = sys.argv[1] # Recebendo o ip do servidor a ser conectado porta_servidor = int(sys.argv[2]) # Recebendo a porta do servidor global cliente cliente = HelperClient(server=(ip_servidor, porta_servidor)) # Criando um cliente CoaP temperatura_lim = sys.argv[ 3] # Recebendo a nova temperatura limite para ser enviada do cliente para o servidor pressao_lim = sys.argv[ 4] # Recebendo a nova pressão limite para ser enviada do cliente para o servidor # Definindo paths no servidor recurso_temperatura_lim = "limtemperatura" recurso_pressao_lim = "limpressao" try: # enviando a temperatura limite via POST response = cliente.post(recurso_temperatura_lim, temperatura_lim) print(response.pretty_print()) except: print("Deu erro no envio da temperatura limite!") try: # enviando pressão limite via POST response = cliente.post(recurso_pressao_lim, pressao_lim) print(response.pretty_print())
from coapthon.client.helperclient import HelperClient import random host = "192.168.0.121" port = 5683 path = "advanced/" n = random.randrange(0, 40) client = HelperClient(server=(host, port)) response = client.put(path, payload=str(n)) print(response.pretty_print()) response = client.get(path) print(response.pretty_print()) client.stop()
limiar_temp = float( limites[0]) #armazena a nova temperatura recebida do servidor limiar_pres = float( limites[1]) #armazena a nova pressao recebida do servidor print("Media dos limites atuais no servidor") print("Temperatura: {} C".format(limiar_temp) + " ---- Pressao: {} mbar".format(limiar_pres)) else: print("Nao ha valores armazenados") #Trata o argumento passado e separa em host e porta address = sys.argv[1] host, port = address.split(':') port = int(port) client = HelperClient(server=(host, port)) #instancia um Client resposta = client.get('sensor') #faz um get do recurso no servidor if (resposta.payload): limites = resposta.payload.split() limiar_temp = float( limites[0]) #armazena a temperatura recebida do servidor limiar_pres = float(limites[1]) #armazena a pressao recebida do servidor client.observe( 'sensor', callback) #observa o recurso e chama o callback quando ele e alterado while True: temp = sense.temperature #pega a temperatura atual do sensor pressure = sense.pressure #pega a pressao atual do sensor