Пример #1
0
 def discover_remote(self, destination):
     request = Request()
     assert (isinstance(destination, str))
     split = destination.split(":", 1)
     host = split[0]
     port = int(split[1])
     server = (host, port)
     request.destination = (host, port)
     request.type = defines.inv_types["CON"]
     request._mid = (self._currentMID + 1) % (1 << 16)
     request.code = defines.inv_codes["GET"]
     uri = "/" + defines.DISCOVERY_URL
     request.proxy_uri = uri
     client = HelperClient(server, True)
     token = self.generate_token()
     function = client.protocol.get
     args = (uri,)
     kwargs = {"Token": str(token)}
     callback = self.discover_remote_results
     err_callback = self.discover_remote_error
     operations = [(function, args, kwargs, (callback, err_callback))]
     key = hash(str(host) + str(port) + str(token))
     self._forward[key] = request
     key = hash(str(host) + str(port) + str((client.starting_mid + 1) % (1 << 16)))
     self._forward_mid[key] = request
     client.start(operations)
Пример #2
0
def main():
    global client
    op = None
    path = None
    payload = None
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:p:P:", ["help", "operation=", "path=", "payload="])
    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 ("-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)
    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)
        function = client.protocol.get
        args = (path,)
        kwargs = {}
        callback = client_callback
    elif op == "OBSERVE":
        if path is None:
            print "Path cannot be empty for a GET request"
            usage()
            sys.exit(2)
        function = client.protocol.observe
        args = (path,)
        kwargs = {}
        callback = client_callback_observe
    elif op == "DELETE":
        if path is None:
            print "Path cannot be empty for a DELETE request"
            usage()
            sys.exit(2)
        function = client.protocol.delete
        args = (path,)
        kwargs = {}
        callback = client_callback
    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)
        function = client.protocol.post
        args = (path, payload)
        kwargs = {}
        callback = client_callback
    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)
        function = client.protocol.put
        args = (path, payload)
        kwargs = {}
        callback = client_callback
    elif op == "DISCOVER":
        function = client.protocol.discover
        args = ()
        kwargs = {}
        callback = client_callback
    else:
        print "Operation not recognized"
        usage()
        sys.exit(2)

    operations = [(function, args, kwargs, callback)]
    client.start(operations)
 def __init__(self, channel, queued):
     ProxyRequest.__init__(self, channel, queued)
     self.coap_client = HelperClient(server=("127.0.0.1", 5683), forward=True)
class HTTPCoaPProxyRequest(proxy.ProxyRequest):
    def __init__(self, channel, queued):
        ProxyRequest.__init__(self, channel, queued)
        self.coap_client = HelperClient(server=("127.0.0.1", 5683), forward=True)

    def process(self):
        coap_uri = self.get_coap_uri(self)
        print "Request from %s for %s" % (
            self.getClientIP(), coap_uri)

        if not coap_uri.startswith("coap://"):
            self.channel.transport.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
            return

        client_uri = self.parse_uri(coap_uri)
        if self.method == "GET" or self.method == "HEAD":
            function = self.coap_client.protocol.get
            args = (client_uri,)
            kwargs = {}
            callback = self.responseReceived
        elif self.method == "POST":
            function = self.coap_client.protocol.post
            args = (client_uri, self.args)
            kwargs = {}
            callback = self.responseReceived
        elif self.method == "PUT":
            function = self.coap_client.protocol.put
            args = (client_uri, self.args)
            kwargs = {}
            callback = self.responseReceived
        elif self.method == "DELETE":
            function = self.coap_client.protocol.delete
            args = (client_uri, )
            kwargs = {}
            callback = self.responseReceived
        else:
            self.channel.transport.write(b"HTTP/1.1 501 Not Implemented\r\n\r\n")
            return

        operations = [(function, args, kwargs, callback)]
        self.coap_client.start(operations)

    def requestReceived(self, command, path, version):
        ProxyRequest.requestReceived(self, command, path, version)

    def responseReceived(self, response):
        self.write(response.payload)
        self.finish()

    @staticmethod
    def get_coap_uri(request):
        assert(isinstance(request, ProxyRequest))
        ret = request.uri[4:]
        return ret

    @staticmethod
    def parse_uri(uri):
        t = uri.split("://")
        tmp = t[1]
        t = tmp.split("/")
        hostname = t[0]
        path = t[1]
        return path