def set_uri(id_t, id_p): global path_t, path_p uri_t = "coap://" + sys.argv[1] + ":" + sys.argv[2] + "/" + id_t uri_p = "coap://" + sys.argv[1] + ":" + sys.argv[2] + "/" + id_p host, port, path_t = parse_uri(uri_t) host, port, path_p = parse_uri(uri_p)
def main(): global client host, port, path = parse_uri("coap://[::1]:5683/lights") try: tmp = socket.gethostbyname(host) host = tmp print "Host:", tmp except socket.gaierror: print("Exception") pass msg = Message() # msg.source = (host, port) # msg.destination = ('192.168.103.137', 5683) # msg.type = defines.Types['CON'] msg.payload = '{"message": "Hello"}' # msg.code = 2 # print msg.pretty_print() try: client = HelperClient(server=(host, port)) response = client.get(path) print response.pretty_print() response = client.post(path, msg.payload, timeout=10) print response.pretty_print() response = client.delete(path) print response.pretty_print() client.close() # client = CoAPclient(host, port, msg) except Exception as e: print "Exception: ", str(e) client.close()
def __init__(self): self.config = ConfigUtil.ConfigUtil() self.dataMsgListener = None self.coapClient = None # read config self.host = self.config.getProperty(ConfigConst.COAP_GATEWAY_SERVICE, ConfigConst.HOST_KEY, ConfigConst.DEFAULT_HOST) self.port = self.config.getInteger(ConfigConst.COAP_GATEWAY_SERVICE, ConfigConst.PORT_KEY, ConfigConst.DEFAULT_COAP_PORT) # log logging.info('\tCoAP Server Host: ' + self.host) logging.info('\tCoAP Server Port: ' + str(self.port)) # url self.url = "coap://" + self.host + ":" + str(self.port) + "/" try: logging.info("Parsing URL: " + self.url) self.host, self.port, self.path = parse_uri(self.url) # get host address tmpHost = socket.gethostbyname(self.host) # init client if parsing url successfully if tmpHost: self.host = tmpHost self._initClient() else: logging.error("Can't resolve host: " + self.host) except socket.gaierror: logging.info("Failed to resolve host: " + self.host)
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 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()
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
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 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 __init__(self, host, port, path): if host and not host.isspace(): self.host = host else: self.host = "localhost" if port >= 1024: self.port = port else: self.port = 5683 self.serverAddr = (self.host, self.port) if path and not path.isspace(): self.path = path else: self.path = "test" self.url = "coap://" + self.host + ":" + str(self.port) + "/" + self.path try: print("Parsing URL: " + self.url) self.host, self.port, self.path = parse_uri(self.url) tmpHost = socket.gethostbyname(self.host) if tmpHost: self.host = tmpHost else: print("Can't resolve host: " + self.host) pass except socket.gaierror: print("Failed to resolve host: " + self.host)
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 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 __init__(self, host): self.sensorData = SensorData self.sensorData.addValue(self.sensorData, 23.34) self.data = DataUtil.toJsonFromSensorData(self, self.sensorData) logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) logging.info("Json to send: " + self.data) host, port, self.path = parse_uri(host) self.client = HelperClient(server=(host, port))
def main(argv): ip = "0.0.0.0" port = 5683 multicast = False server = None name = "MyName" path = None try: opts, args = getopt.getopt( argv, "hi:p:m:n:s", ["ip=", "port=", "multicast", "name=", "server="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ("-i", "--ip"): ip = arg elif opt in ("-p", "--port"): port = int(arg) elif opt in ("-m", "--multicast"): multicast = True elif opt in ("-n", "--name"): name = arg elif opt in ("-s", "--server"): server = arg if server is None: print( "Working in standalone mode... indicate the server address to connect to a server" ) usage() else: host, port, path = parse_uri(server) print("server = " + server) print("host = " + host) print("port = " + str(port)) print("path = " + path) payload = "coap://" + ip + ":" + str(port) client = HelperClient(server=(host, port)) response = client.post(path, payload) print(response) server = CoAPServer(ip, port, multicast) try: t1 = threading.Thread(target=actuator_observer) t1.start() server.listen(10) except KeyboardInterrupt: print("Server Shutdown") server.close() print("Exiting...")
def main(argv): operation = None path = None payload = None try: opts, args = getopt.getopt(argv[1:], "ho:p:P:", ["help", "operation=", "path=" "payload="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit(2) elif opt in ("-o", "--operation"): operation = arg elif opt in ("-p", "--path"): path = arg elif opt in ("-P", "--payload"): payload = arg else: usage() sys.exit(2) host, port, path = parse_uri(path) try: host = socket.gethostbyname(host) except socket.gaierror: pass client = HelperClient(server=(host, port)) if operation == "GET": response = client.get(path) print(response.pretty_print()) client.stop() elif operation == "POST": response = client.post(path, payload) print(response.pretty_print()) client.stop() elif operation == "PUT": response = client.put(path, payload) print(response.pretty_print()) client.stop() elif operation == "DELETE": response = client.delete(path) print(response.pretty_print()) client.stop() else: print("Operation not recognized") usage() sys.exit(2)
def main(op,path): global client 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) client.stop() return response
def __init__(self): # self.authenticate_request = False #It will change in the future. self.access_token = None self.auth_token = None self.refresh_token = {} self.scope = None self.token_type = "" self.path = "coap://127.0.0.1:5683/basic" self.host, self.port, self.path = parse_uri(self.path) self.payload = "test" self.host = socket.gethostbyname(self.host) self.client = HelperClient(server=(self.host, self.port))
def receive_request(self, transaction): """ :type transaction: Transaction :param transaction: :rtype : Transaction """ uri = transaction.request.proxy_uri host, port, path = parse_uri(uri) path = str("/" + path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token return self._forward_request(transaction, (host, port), path)
def receive_request(self, transaction): """ Setup the transaction for forwarding purposes on Forward Proxies. :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction """ uri = transaction.request.proxy_uri host, port, path = parse_uri(uri) path = str("/" + path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token return self._forward_request(transaction, (host, port), path)
def render_POST(self, request): # res = self.init_resource(request, BasicResource()) # update text on LCD setText(request.payload) # path = "coap://192.168.1.8:5683/lookup-matric"; host, port, path = parse_uri(path) client = HelperClient(server=(host, port)) response = client.post(path, request.payload) print response.pretty_print() client.stop() #setText("Message sent to " + path + ": " + request.payload); return self
def __init__(self, resource, path=None): if path is None: ip = getServerIp() path = "coap://" + ip + ":" + str(5683) + "/" + resource else: path = path + "/" + resource self.host, self.port, self.resource = parse_uri(path) try: tmp = socket.gethostbyname(self.host) self.host = tmp except socket.gaierror: pass self.client = HelperClient(server=(self.host, self.port)) self.id = None
def main(path, acks, size, discover): if discover: try: discover_client = Client(server=('224.0.1.187', 5683)) responses = discover_client.multicast_discover() for response in responses: print(response.source[0], response.payload) except KeyboardInterrupt: print("Stopping") finally: discover_client.stop() else: try: host, port, path = parse_uri(path) except Exception: print("Not a valid path: {}".format(path)) print("example: coap://127.0.0.1/data") return try: client = Client(server=(host, port)) response = client.get(path, payload=struct.pack('!HH', int(acks), int(size))) try: data = json.loads(response.payload.decode()) pprint(data) except Exception as e: print("Unable to unpack payload:", response.payload) print(e) except KeyboardInterrupt: print("Stopping") finally: client.stop()
def main(): # pragma: no cover global client config = None try: opts, args = getopt.getopt(sys.argv[1:], "hc:", ["help", "config="]) 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 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) for n in config["nodes"]: path = "coap://" + n["ip"] + ":" + str(n["port"]) + "/radio" 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) print((response.pretty_print())) client.stop()
def __init__(self): """ Use the ConfigUtil configuration information for the CoAP Gateway to retrieve the host and port information. """ self.config = ConfigUtil() self.dataMsgListener = None self.coapClient = None self.host = self.config.getProperty(ConfigConst.COAP_GATEWAY_SERVICE, ConfigConst.HOST_KEY, ConfigConst.DEFAULT_HOST) self.port = self.config.getInteger(ConfigConst.COAP_GATEWAY_SERVICE, ConfigConst.PORT_KEY, ConfigConst.DEFAULT_COAP_PORT) logging.info('\tCoAP Server Host: ' + self.host) logging.info('\tCoAP Server Port: ' + str(self.port)) """ Validate the url information """ self.url = "coap://" + self.host + ":" + str(self.port) + "/" try: logging.info("Parsing URL: " + self.url) self.host, self.port, self.path = parse_uri(self.url) tmpHost = socket.gethostbyname(self.host) if tmpHost: self.host = tmpHost self._initClient() else: logging.error("Can't resolve host: " + self.host) except socket.gaierror: logging.info("Failed to resolve host: " + self.host) self._initClient()
def main(): # pragma: no cover # global client try: # op = "GET" op = "OBSERVE" # path = "coap://127.0.0.1:5683/obs" 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), port=5683) # response = client.post(path, payload) # response = client.get_with_bearer(path,"ed1bedae-a186-4301-a15f-20e466db95e9") response = client.introspect(path, "ed1bedae-a186-4301-a15f-20e466db95e9", None) # response = client.observe(path,None) # response = client.get(path) print type(response) print "payload: " print response.payload # path = "coap://127.0.0.1:5683/obs" # client.observe(path, client_callback_observe) # print response # print response.pretty_print() # print response.active client.stop() except KeyboardInterrupt: sys.exit()
def receive_request(self, transaction): """ Setup the transaction for forwarding purposes on Forward Proxies. :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction """ uri = transaction.request.proxy_uri if uri is None: transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token transaction.response.type = defines.Types["RST"] transaction.response.code = defines.Codes.BAD_REQUEST.number return transaction host, port, path = parse_uri(uri) path = str("/" + path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token return self._forward_request(transaction, (host, port), path)
def __init__(self): """ Constructor of CoAP Client Init CoAP Client with host and port from config. """ self.config = ConfigUtil.ConfigUtil() self.dataMsgListener = None self.coapClient: HelperClient = None self.host = self.config.getProperty(ConfigConst.COAP_GATEWAY_SERVICE, ConfigConst.HOST_KEY, ConfigConst.DEFAULT_HOST) self.port = self.config.getInteger(ConfigConst.COAP_GATEWAY_SERVICE, ConfigConst.PORT_KEY, ConfigConst.DEFAULT_COAP_PORT) self.url = "coap://" + self.host + ":" + str(self.port) + "/" try: logging.info("Parsing URL: " + self.url) self.host, self.port, self.path = parse_uri(self.url) tmpHost = socket.gethostbyname(self.host) if tmpHost: self.host = tmpHost self._initClient() else: logging.error("Can't resolve host: " + self.host) except socket.gaierror: logging.info("Failed to resolve host: " + self.host) logging.info('\tCoAP Server Host: ' + self.host) logging.info('\tCoAP Server Port: ' + str(self.port)) pass
def coap_action(message): # 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 message: 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() return response.payload 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() return response.payload 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) elif payload == "Passed": payload = "{\"response\":\"Success\",\"result\":\"OK\"}" response = client.post(path, payload) print response.pretty_print() return response.payload 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() return response.payload client.stop() elif op == "DISCOVER": response = client.discover() print response.pretty_print() client.stop() else: print "Operation not recognized" usage() sys.exit(2) update_coap_response(response.payload)
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)
import socket, os, time, Takephoto import json from cv2 import cv2 import sqlite3 from coapthon.client.helperclient import HelperClient from coapthon.utils import parse_uri from pybase64 import b64encode from Crypto.Cipher import AES from Crypto.Util.Padding import pad url = "coap://192.168.1.2:5683/" # default path host, port, path = parse_uri(url) client = HelperClient(server=(host, port)) result = {'id': 0, 'uid': '', 'nom': '', 'prenom': ''} key = 'abcdefghijklmnop' recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainner/trainner.yml') cascadePath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascadePath) def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
def __init__(self, coap_uri): self.uri = coap_uri self.host, self.port, self.path = parse_uri(coap_uri)
client = None #cria o emulador sensehat e defini as cores sense = SenseHat() vermelho = (255, 0, 0) branco = (255, 255, 255) pixels = [None] * 64 #variaveis usadas para compara com os valores de temperatura e pressao medidos no sensehat #sao iniciadas com valores altos a fim de deixar os LEDs na cor branca caso nao haja nenhum limite armazenado no servidor limiar_pres = 2000 limiar_temp = 2000 #separa host, porta e path passados no argumento do comando path = sys.argv[2] host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass #verifica se ha valores limites armazenados no servidor client = HelperClient(server=(host, port)) resposta = client.get(path) if (resposta.payload): limites = resposta.payload.split() limiar_temp = float(limites[0]) limiar_pres = float(limites[1])
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)
import socket import sys import time from coapthon.client.helperclient import HelperClient from coapthon.utils import parse_uri from sense_emu import SenseHat sense = SenseHat() red = (255, 0, 0) white = (255, 255, 255) path = "coap://" + sys.argv[1] + ":" + sys.argv[2] + "/atuador" host, port, path_atuador = parse_uri(path) pixels = [None] * 64 client = HelperClient(server=(host, port)) # callback do observer def atuador_observer(): # pragma: no cover print 'Atuador Value Updated' global client response = client.get(path_atuador) for i in range(64): pixels[i] = white if response.payload[i] == "1": pixels[i] = red