def __init__(self, uri, client_port=None, *args, **kw):
     self.client = CoapClient(uri, client_port)
     self.logger.debug("CoapClient created with uri %s", uri)
     self.__serializer = JsonSerializer()
     self.methodmappers = {
         "create": self._send_create,
         "notify": self._send_notify,
         "update": self._send_update,
         "delete": self._send_delete,
         "retrieve": self._send_retrieve
     }
def test_get_all_properties(request_handler, logger, config, app_name):
    payload = {
        "method": "retrieve",
        "content_type": "application/json",
        "path": "/m2m/applications/" + app_name + "/containers",
        "replyAction": "intent://test_action",
        "requestId": "123"
    }
    #    reference = "someRef"
    #    subscriptionId = "someSubscrId"
    intentHandler = IntentHandler(logger, config)
    request = intentHandler.parseRequest("test_issuer", payload, None)
    result = intentHandler.handleParsedRequest(request, request_handler, None)
    logger.info("result is " + str(result))

    response = result["response"]
    if isinstance(response, RetrieveResponseConfirmation):
        if response.resource is not None:
            serializer = JsonSerializer()
            content = serializer.encode(response.resource)
            logger.info("response content is " + content)
Beispiel #3
0
 def __init__(self, action, issuer, logger, replyAction=None, *args, **kw):
     self.logger = logger
     self.client = IntentClient(issuer, action, logger, replyAction)
     self.__serializer = JsonSerializer()
     self.replyAction = replyAction
     #        self.__unserializer = JsonUnserializer()
     self.methodmappers = {
         "create": self._send_create,
         "update": self._send_update,
         "delete": self._send_delete,
         "retrieve": self._send_retrieve,
         "notify": self._send_notify
     }
 def __init__(self, config, logger, api):
     self.config = config
     self.logger = logger
     self.api = api
     self.wifi_manager = None
     self.serializer = JsonSerializer()
class ConnectivityMgm(LoggerMixin):
    def __init__(self, config, logger, api):
        self.config = config
        self.logger = logger
        self.api = api
        self.wifi_manager = None
        self.serializer = JsonSerializer()

    def create_lwm2m_mgm_resources(self):
        path = "/m2m/scls"
        request = RetrieveRequestIndication(path=path)
        result_promise = self.api.handle_request_indication(request)
        result = result_promise.get()
        self.logger.info("result for reading is: " + str(result))
        if result.resource is not None:
            content = self.serializer.encode(result.resource)
            self.logger.info("response content is " + content)
        else:
            self.logger.info("response content is None")

        path = "/m2m/scls/mgmtObjs"
        mgmtObj = MgmtObj(id="ConnectivityMonitoring",
                          moID="urn:oma:lwm2m:oma:4")
        key = "IP_Addresses"
        value = ""
        mgmtObj.__setattr__(key, value)
        request = CreateRequestIndication(path=path, resource=mgmtObj)
        result_promise = self.api.handle_request_indication(request)
        result = result_promise.get()
        self.logger.info(
            "result is for creating connectivity monitoring is: " +
            str(result))
        if result.resourceURI is not None:
            content = self.serializer.encode(result.resourceURI)
            self.logger.info("response content is " + content)
        else:
            self.logger.info("response content is None")

    def start(self):
        self.logger.info("config data is %s", str(self.config))
        if self.config["wifi"] and self.config["wifi"]["enabled"]:
            self.logger.info("config wifi " + str(self.config["wifi"]))
            self.logger.info("config wifi enabled " +
                             str(self.config["wifi"]["enabled"]))
            self.logger.info("wifi enabled")

            if self.config["platform"] and self.config["platform"][
                    "android"] and self.config["platform"]["android"][
                        "enabled"]:
                from android.AndroidWiFiManager import AndroidWiFiManager
                self.wifi_manager = AndroidWiFiManager(
                    config=self.config["wifi"],
                    logger=self.logger,
                    api=self.api)
            if self.wifi_manager is not None:
                self.wifi_manager.start()

    def process_connectivity_request(self, req_category, requested_ssid=None):
        self.logger.info(
            "processing connectivity request with request category " +
            str(req_category))
        p = Promise()
        if requested_ssid:
            ssid = requested_ssid
        else:
            #get the AN info for which the req_category can be served
            ssid = self.wifi_manager.get_ssid_for_req_category(req_category)
        self.logger.info("found suitable network with ssid %s", ssid)
        if ssid is not None:

            self.logger.info(
                "found suitable network with ssid %s, current ssid %s", ssid,
                self.wifi_manager.current_ssid)

            def conn_callback(dict_reply):
                if dict_reply is None:
                    self.logger.info("invalid conn_callback dict_reply")
                    #p.reject()
                self.logger.info(
                    "connectivity callback for trying to connect on " + ssid +
                    " has status " + dict_reply["status"])

                if dict_reply["ssid"].startswith('"'):
                    # Unquote
                    dict_reply["ssid"] = dict_reply["ssid"][1:-1]
                if dict_reply["status"] != "CONNECTED" or dict_reply[
                        "ssid"] != ssid:
                    self.logger.info(
                        "status is not CONNECTED or current ssid not %s rejecting... (%s instead)"
                        % (ssid, dict_reply["ssid"]))
                    #p.reject()
                else:
                    channel_tuple = (ssid, req_category)
                    self.logger.debug(
                        "Handover is done, fulfilling with ssid %s" % ssid)
                    p.fulfill(channel_tuple)
                    self.wifi_manager.removeConnectionAlert(conn_callback)

            if ssid == self.wifi_manager.current_ssid:
                self.logger.info(
                    "no need to handover, the current ssid is good enough")
                channel_tuple = (ssid, req_category)
                p.fulfill(channel_tuple)

            else:
                self.wifi_manager.addConnectionAlert(conn_callback)
                self.wifi_manager.connectToNetwork(ssid, conn_callback)
                self.logger.info("trying to connect on network with ssid %s",
                                 ssid)
        else:
            p.reject("no WiFi for request category " + req_category +
                     " available")
        return p
Beispiel #6
0
class IntentHandler(LoggerMixin):
    serializer = JsonSerializer()

    def __init__(self, logger, config):
        self.logger = logger
        self.config = config
        self.endpoint = Endpoint(base_uri="intent://", reference_point="dIa")

    def intent_extras_to_dict(self, intent_request):

        extras = intent_request.getExtras()
        if extras is None:
            return None

        request_dict = {}
        keySet = extras.keySet()
        iterator = keySet.iterator()

        while iterator.hasNext():
            key = iterator.next()
            elem = extras.get(key)
            request_dict[key] = elem

        return request_dict

    def parseRequest(self, issuer, request_dict, context=None):

        parsedRequest = IntentRequest(issuer, request_dict, context,
                                      self.logger)
        return parsedRequest

    def handleParsedRequest(self, parsedRequest, request_handler, queue):

        self.logger.info("handle parsed request: parsed req is " +
                         str(parsedRequest))
        self.logger.info("request handler is " + str(request_handler) +
                         " and queue is " + str(queue))
        if request_handler is not None:
            try:
                mapping_function = getattr(self,
                                           "_map_" + parsedRequest.method)
            except AttributeError:
                return IntentError()

            request_indication = mapping_function(parsedRequest.path,
                                                  parsedRequest)
            self.logger.info("request indication is " +
                             str(request_indication))

            result_promise = request_handler(request_indication,
                                             endpoint=self.endpoint)
            result_mapper = getattr(self,
                                    "_map_" + parsedRequest.method + "_result")
            try:
                result = result_promise.get()
                self.logger.info("result is : " + str(result))
                return result_mapper(parsedRequest, result,
                                     parsedRequest.context)
            except Exception as e:
                result = ErrorResponseConfirmation(500,
                                                   request_indication.method,
                                                   repr(e))
                self.logger.info("result is : " + str(result))
                self.handle_result(parsedRequest, result,
                                   parsedRequest.context)
                return {'request': request_indication, 'result': result}
                # return result_mapper(parsedRequest, result, parsedRequest.context)
        elif queue is not None:
            self.logger.info("adding a request to the queue ")
            queue.put(parsedRequest)

    def executeQueuedRequests(self, queue, request_handler):

        #        parsed_request = queue.get(block=True, timeout=None)
        #        result = self.handleParsedRequest(parsed_request, request_handler, None)
        #        self.handle_result(parsed_request, result, parsed_request.context)
        while True:
            try:
                parsed_request = queue.get(block=True, timeout=1)
                result = self.handleParsedRequest(parsed_request,
                                                  request_handler, None)
                self.handle_result(parsed_request, result,
                                   parsed_request.context)
            except:
                continue

    def get_optional_params(self, request):
        correlationID = None
        rcat = None
        trpdt = None
        contactURI = None
        if self.config.has_key("enable_store_and_forward"):
            if self.config["enable_store_and_forward"]["correlation_id"]:
                correlationID = request.intentRequestId
            if self.config["enable_store_and_forward"]["rcat"]:
                rcat = request.requestCategory
            if self.config["enable_store_and_forward"]["trpdt"]:
                trpdt = request.tolerantDelay
            if self.config["enable_store_and_forward"]["contact_uri"]:
                contactURI = request.contactURI
        return (correlationID, rcat, trpdt, contactURI)

    def handle_result(self, request, result, context=None):
        self.logger.info("request is " + str(request) + " and the result " +
                         str(result))

        self.logger.info("handling result")
        if context is not None:
            self.logger.info("context is not none")
            self.logger.info("replyAction: " + str(request.replyAction))
            self.logger.info("issuer: " + str(request.issuer))
            client = IntentClient(str(request.issuer),
                                  str(request.replyAction), self.logger, None)
            self.logger.info("created intent client ")

            if isinstance(result, ErrorResponseConfirmation):
                self.logger.info("error while processing request")
                client.send_IntentError(context, request, result)
            else:
                self.logger.info("sending ok result " + str(result))
                client.send_IntentResponse(context, request, result)
        else:
            self.logger.info("context is none")

    def _map_retrieve(self, path, request):
        filter_criteria = None
        if request.searchStrings is not None:
            self.logger.info("using searchStrings [" + request.searchStrings +
                             "] in retrieve")
            filter_criteria = {}
            filter_criteria["searchStrings"] = request.searchStrings
        optional_params = self.get_optional_params(request)
        return RetrieveRequestIndication(path,
                                         filterCriteria=filter_criteria,
                                         correlationID=optional_params[0],
                                         rcat=optional_params[1],
                                         trpdt=optional_params[2],
                                         contactURI=optional_params[3])

    def _map_retrieve_result(self, request, result, context=None):

        self.handle_result(request, result, context)

        return {"request": request, "response": result}

    def _map_create(self, path, request):
        self.logger.info("content_type is " + request.content_type)
        if request.content_type and request.content_type != "application/json":
            self.logger.error("application type is not application/json")
            # send error 400 Unhandled content type

        self.logger.info("resource is " + str(request.content))
        optional_params = self.get_optional_params(request)

        return CreateRequestIndication(path=path,
                                       resource=request.content,
                                       content_type=request.content_type,
                                       correlationID=optional_params[0],
                                       rcat=optional_params[1],
                                       trpdt=optional_params[2],
                                       contactURI=optional_params[3])

    def _map_create_result(self, request, result, context=None):
        # TODO: kca: I'm assuming here that result always is STATUS_CREATED, is that the case?
        # (not counting EXECUTE, which is just not handled yet)

        self.logger.info("sent Post request")
        self.logger.info("sent Post request, result is " + str(result))
        if hasattr(result, "resourceURI"):
            self.logger.info("result resource URI is " + result.resourceURI)
        # TODO:kca: Which Content-Type to set here?

        self.handle_result(request, result, context)
        result = {"request": request, "response": result}
        return result

    def _map_delete(self, path, request):
        optional_params = self.get_optional_params(request)
        return DeleteRequestIndication(path,
                                       correlationID=optional_params[0],
                                       rcat=optional_params[1],
                                       trpdt=optional_params[2],
                                       contactURI=optional_params[3])

    def _map_delete_result(self, request, result, context=None):
        self.logger.info("sent Delete request")
        self.handle_result(request, result, context)
        result = {"request": request, "response": result}
        return result

    def _map_update(self, path, request):
        self.logger.info("content_type is " + request.content_type)
        self.logger.info("resource is " + str(request.content))
        return UpdateRequestIndication(path=path,
                                       resource=request.content,
                                       content_type=request.content_type,
                                       correlationID=optional_params[0],
                                       rcat=optional_params[1],
                                       trpdt=optional_params[2],
                                       contactURI=optional_params[3])

    def _map_update_result(self, request, result, context=None):
        self.handle_result(request, result, context)
        result = {"request": request, "response": result}
        return result
class XIXCoap(LoggerMixin):
    def __init__(self, uri, client_port=None, *args, **kw):
        self.client = CoapClient(uri, client_port)
        self.logger.debug("CoapClient created with uri %s", uri)
        self.__serializer = JsonSerializer()
        self.methodmappers = {
            "create": self._send_create,
            "notify": self._send_notify,
            "update": self._send_update,
            "delete": self._send_delete,
            "retrieve": self._send_retrieve
        }

    def send_request_indication(self, request_indication):
        path = request_indication.path
        if path.startswith('/'):
            path = path[1:]

        mapper = self.methodmappers[request_indication.method]
        return mapper(request_indication, path)

    def _raise_error(self, method, response):
        try:
            status_code = _coap2etsi[response.code]
        except KeyError:
            self.logger.warning("Failed to map coap response code: %s",
                                response.code)
            status_code = openmtc.exc.STATUS_INTERNAL_SERVER_ERROR

        raise ErrorResponseConfirmation(
            statusCode=status_code,
            primitiveType=method,
            errorInfo=response.payload or "<no further information available>")

    def _send_create(self, request_indication, path):
        data = self.__serializer.encode_values(request_indication.typename,
                                               request_indication.resource)
        resp = self.client.post(path, data, content_type="application/json")
        if resp.code >= 100:
            self._raise_error("create", resp)
        return CreateResponseConfirmation(resp.payload)

    def _send_notify(self, request_indication, path):
        data = self.__serializer.encode_values(request_indication.typename,
                                               request_indication.resource)
        resp = self.client.post(path, data, content_type="application/json")
        if resp.code >= 100:
            self._raise_error("notify", resp)
        return NotifyResponseConfirmation()

    def _send_update(self, request_indication, path):
        data = self.__serializer.encode_values(request_indication.typename,
                                               request_indication.resource)
        resp = self.client.put(path, data, content_type="application/json")
        if resp.code >= 100:
            self._raise_error("create", resp)
        return UpdateResponseConfirmation()

    def _send_retrieve(self, request_indication, path):
        resp = self.client.get(path)
        if resp.code >= 100:
            self._raise_error("create", resp)

        return decode_result(request_indication.path, resp.payload,
                             resp.content_format)

    def _send_delete(self, request_indication, path):
        resp = self.client.delete(path)
        if resp.code >= 100:
            self._raise_error("create", resp)
        return DeleteResponseConfirmation()

    def create(self, path, resource):
        return self.send_request_indication(
            CreateRequestIndication(path, resource))

    def update(self, resource, fields=()):
        return self.send_request_indication(
            UpdateRequestIndication(resource.path, resource, fields=fields))

    def retrieve(self, path):
        return self.send_request_indication(RetrieveRequestIndication(path))

    def delete(self, path):
        return self.send_request_indication(DeleteRequestIndication(path))
Beispiel #8
0
class IntentClient():
    serializer = JsonSerializer()
    context = None

    def __init__(self, issuer, action, logger, replyAction=None):

        self.logger = logger
        self.intent = Intent()
        self.logger.info("creating intent client")
        self.context = PythonService.mService

        self.logger.info("intent action is " + str(action))
        self.intent.setAction(String(action))
        self.logger.info("intent issuer is " + str(issuer))
        self.intent.putExtra("Issuer", str(issuer))
        if replyAction:
            self.intent.putExtra("replyAction", str(replyAction))

        self.intent.putExtra("Issuer", str(issuer))
        self.logger.info("created intent client")
        #self.intent.setPackage(issuer)

    def send_IntentResponse(self, context, request, response):
        self.logger.info("send_intent_response called")
        if response is None:
            self.logger.info("response is None, ignore")
            return
        if isinstance(response, DeleteResponseConfirmation):
            self.logger.info("delete resp confirmation")
            self.intent.putExtra('status', String("200 OK"))

        if response.statusCode is not None:
            self.logger.info("response status code is " +
                             str(response.statusCode))
            self.logger.info("response status is " + response.status)
            status = String(
                str(response.statusCode) + " " + str(response.status))
            self.logger.info(
                "setting response status in the intent, action is  " +
                self.intent.getAction())
            self.intent.putExtra('status', status)
        else:
            self.logger.info("response status code is None")

        if isinstance(response, RetrieveResponseConfirmation):
            if response.resource is not None:
                content = self.serializer.encode(response.resource)
                self.logger.info("response content is " + content)
                self.intent.putExtra("content", String(content))
            else:
                self.logger.info("response content is None")

        if isinstance(response, CreateResponseConfirmation):
            if response.resourceURI is not None:
                self.logger.info("resourceURI is " + response.resourceURI)
                self.intent.putExtra("location", String(response.resourceURI))
        if request.intentRequestId is not None:
            self.logger.info("request id is " + request.intentRequestId)
            self.intent.putExtra('requestId',
                                 String(str(request.intentRequestId)))
        context.sendBroadcast(self.intent)
        self.logger.info("sent the reply to action " +
                         str(request.replyAction))
        #if request.issuer:
        #   self.intent.setPackage(request.issuer)

    def send_IntentError(self, context, request, response):
        if response.statusCode is not None:
            self.intent.putExtra('status', String("500 Error"))
        if response.errorInfo is not None:
            self.intent.putExtra('content', String(str(response.errorInfo)))
        if request.intentRequestId is not None:
            self.logger.info("request id is " + request.intentRequestId)
            self.intent.putExtra('requestId',
                                 String(str(request.intentRequestId)))
        context.sendBroadcast(self.intent)
        return

    def send_create(self, path, data, replyAction, correlationID=None):
        self.logger.info("send_create path is " + path + " data is " +
                         str(data))
        self.intent.putExtra("path", String(path))
        try:
            if data is not None:
                self.intent.putExtra("content", String(str(data)))
        except:
            self.logger.info("error on checking data")
        self.intent.putExtra("method", String("create"))
        # Add correlation id if present
        if correlationID:
            self.intent.putExtra("requestId", String(correlationID))
        else:
            self.intent.putExtra("requestId", String(str(int(time.time()))))
        if replyAction is not None:
            self.intent.putExtra("replyAction", String(replyAction))
        if self.context:
            self.logger.info("context is not none")
            self.context.sendBroadcast(self.intent)
        else:
            self.logger.info("context is none")
        #intent.putExtra('result', String('foobar123'))

    def send_update(self, path, data, replyAction):
        self.logger.info("calling client send_update")
        if replyAction is not None:
            self.intent.putExtra("replyAction", String(replyAction))
        if self.context:
            self.logger.info("context is not none")
            self.intent.putExtra("content", data)
            self.intent.putExtra("method", 'update')
            self.context.sendBroadcast(self.intent)
        else:
            self.logger.info("context is none")

    def send_read(self, path, data):
        if self.context:
            if data is not None:
                self.intent.putExtra("content", data)
            self.intent.putExtra("method", 'retrieve')
            self.intent.putExtra("path", path)
            self.context.sendBroadcast(self.intent)

    def send_delete(self, path):
        if self.context:
            self.intent.putExtra("path", path)
            self.context.sendBroadcast(self.intent)