def send_message(): self.logger.info("Sending Message") request = CreateRequestIndication(path=path, resource=payload, content_type="application/json") split_path = path.split("/") get_index = split_path.index("applications") app_id = split_path[get_index + 1] request.targeted_appid = app_id request.originator = originator response = self.api.send_request_indication(request) response.then(resp_success, resp_error)
def create(self, path, instance): request_indication = CreateRequestIndication(path, instance) instance.path = self._send_request(request_indication).resourceURI self.logger.debug("Set instance path: %s", instance.path) instance._synced = False # self._attach_instance(instance) return instance
def create_container(self, path, container_id): if not path.endswith("/containers"): path += "/containers" container_object = Container(id=container_id, maxNrOfInstances=self.max_nr_of_instances) request = CreateRequestIndication(path=path, resource=container_object) response = self.api.handle_request_indication(request) return response
def handle_mgmtobjs(response): mgmtobj_exists = False for mgmtobj in response.resource.mgmtObjCollection: if mgmtobj.name == object_name + "_" + str(object_inst_id): mgmtobj_exists = True path = mgmtobj.path request = RetrieveRequestIndication(path) response = self.api.handle_request_indication(request) try: if res_name_res_inst_id in response.value.resource.flex_values: if response.value.resource.flex_values[ res_name_res_inst_id] == str(res_value): continue elif res_name in response.value.resource.flex_values: if response.value.resource.flex_values[ res_name] == str(res_value): continue except: pass resource = ('{"mgmtObjs" : ' + json.dumps(resources_dict) + '}') request = UpdateRequestIndication( path, resource, content_type="application/json") response = self.api.handle_request_indication(request) break if not mgmtobj_exists: mgmtobj_ = MgmtObj(id=str(object_name) + "_" + str(object_inst_id), moID=moID_value) path = response.resource.path request = CreateRequestIndication(path, mgmtobj_) response = self.api.handle_request_indication(request) response.then(add_parameters)
def handle_scl(response): scl_exists = False for _scl in response.resource.sclCollection: if _scl.name == preferred_scl: scl_exists = True if bool_attachedDevices: path = _scl.path + "/attachedDevices" else: path = _scl.path + "/mgmtObjs" request = RetrieveRequestIndication(path) response = self.api.handle_request_indication(request) if bool_attachedDevices: response.then(handle_attached_devices) else: response.then(handle_mgmtobjs) break if not scl_exists: scl_object = Scl(sclId=preferred_scl, link="127.0.0.1", sclType="GSCL", mgmtProtocolType="LWM2M") request = CreateRequestIndication(path="/m2m/scls", resource=scl_object) response = self.api.handle_request_indication(request) if bool_attachedDevices: response.then(retrieve_attached_devices) else: response.then(retrieve_mgmtobjs)
def _register_endpoint(endpoint): # create a M2mPoc with the endpoint as contact info in the NSCL # (onlineStatus=ONLINE) uri = self.nscl_uri + "/" + "scls/" + self.gscl_id + "/" + "m2mPocs" m2mpoc = M2mPoc() m2mpoc.onlineStatus = "ONLINE" m2mpoc.contactInfo = endpoint.base_uri m2mpoc.expirationTime = self._gscl.expirationTime rq = CreateRequestIndication(uri, m2mpoc) rq.requestingEntity = self.config.get("requesting_entity") p = self.api.send_request_indication(rq).then( lambda evt, m2mpoc=m2mpoc: _start_endpoint_refresher( evt, m2mpoc)) return p
def create_device_container(self, id): container_path = "/m2m/applications/" + self.app_name + "/containers/" + self.container_name + "/subcontainers" container = Container(id=id, searchStrings=[';rt="thing"'], maxNrOfInstances=self.max_nr_of_instances) request = CreateRequestIndication(path=container_path, resource=container) response = self.api.handle_request_indication(request) return response
def create_subcontainer(self, subcontainer_id, path, search_strings, contentType): subcontainer_object = Container(id=subcontainer_id, searchStrings=search_strings) req_indication = CreateRequestIndication(path = path, resource = subcontainer_object, #"{\"container\":{\"id\":\""+sub_subcontainer_id+"\"}}", content_type = contentType) result = self.api.handle_request_indication(req_indication)
def _push_content_instance(self, path, ci): if not path.endswith("/contentInstances"): path += "/contentInstances" request_indication = CreateRequestIndication(path=path, resource=ci, content_type="application/json") response = self.api.handle_request_indication(request_indication) return response
def create(self, path, resource): """Creates and serializes a CreateRequestIndication to a CoAP POST message and sends it using a CoapClient :param path: Resource path :param resource: Request payload :return: Corresponding CreateResponseConfirmation """ return self.send_request_indication( CreateRequestIndication(path, resource))
def _create_nscl(self, gscl): """ Creates an SCL resource for the NSCL. 1) Upon receiving a successful response, the Issuer SCL shall create a new local scl resource, using the <sclBase> of the Hosting SCL to identify the local resource. 2) The values of the attributes for the local <scl> resource shall be assigned default values initially. With the exception of the expirationTime ... 3) The Issuer SCL shall set the value of "link" for the local <scl> resource to the sclBase resource URI of the receiver SCL. In the following "Step 3" designates the step of waiting for the Create ResponseConfirm. 11) If the ResponseConfirm received in Step 3 contains a resource representation and the that resource representation contains a aPocHandling attribute value, then the issuer SCL shall set the aPocHandling attribute in its local <sclBase> resource to the received value. 12) If the ResponseConfirm received in Step 3 contains a resource representation and the that resource representation does not contain a aPocHandling attribute value, then the issuer SCL shall set the aPocHandling attribute in its local <sclBase> resource to "SHALLOW". """ def _done(data): return nscl self.logger.debug("retrieving NSCL resource.") path = "/m2m/scls" data = { "sclId": self.nscl_id, # "using the sclBase of the Hostring SCL"? "link": self.nscl_uri, # 3) "mgmtProtocolType": self.mgmt_protocol, "expirationTime": gscl.expirationTime or None, # 2) "aPocHandling": gscl.aPocHandling or "SHALLOW", # 11) and 12) "sclType": "NSCL", } nscl = Scl(path, **data) rq = CreateRequestIndication(path, nscl) rq.internal = True return self.api.handle_request_indication(rq).then(_done)
def register_app(self): self.logger.info("registering application [%s]" % (self.app_name)) path = "/m2m/applications/" self.app_path = path + self.app_name req_indication = CreateRequestIndication( path=path, resource="{\"application\":{\"appId\":\"" + self.app_name + "\"}}", content_type="application/json") promise = self.api.handle_request_indication(req_indication) promise.then(self.create_container)
def create_container(self, result): self.logger.info("registering application [%s] containers %s" % (self.app_name, self.container_name_list)) path = result.resourceURI + "/containers" container = self.container_name_list[0] req_indication = CreateRequestIndication( path=path, resource="{\"container\":{\"id\":\"" + container + "\"}}", content_type="application/json") promise = self.api.handle_request_indication(req_indication)
def init_scl_base(self): scl_base_name = self.config["etsi"]["scl_base"] scl_base = SclBase(path="/" + scl_base_name, aPocHandling="SHALLOW") db_session = self._api.start_etsi_session() ctrl = self._get_controller(SclBase, db_session, self.handle_request_indication) try: result = ctrl(CreateRequestIndication("/", scl_base), None, None) except Exception as error: self.logger.exception("Initialization error") db_session.rollback() raise error else: db_session.commit() return result
def handle_attached_devices(response): attached_device_exists = False for attached_device in response.resource.attachedDeviceCollection: if attached_device.name == attached_device_name: attached_device_exists = True path = attached_device.path + "/mgmtObjs" request = RetrieveRequestIndication(path) response = self.api.handle_request_indication(request) response.then(handle_mgmtobjs) break if not attached_device_exists: attached_device_object = AttachedDevice( id=attached_device_name) path = response.resource.path request = CreateRequestIndication( path=path, resource=attached_device_object) response = self.api.handle_request_indication(request) response.then(retrieve_mgmtobjs)
def create_contentInstances(self, result): content = { "traffic_group": { "nb_devices": NO_OF_DEVICES, "interval": INTERVAL, "data_size": DATA_SIZE }, "destination_path": DESTINATION_PATH } ci = ContentInstance(id=CONTENT_INST_ID, content={ "contentType": "application/json", "$t": b64encode(dumps(content)) }) path = result.resource.path + "/contentInstances" request = CreateRequestIndication(path=path, resource=ci, content_type="application/json") response = self.api.handle_request_indication(request)
def map_request_to_request_indication(request): path = request.path method = request.method if method == RequestMethod.create: req_ind = CreateRequestIndication(path=path, resource=request.payload, content_type=request.content_type) elif method == RequestMethod.retrieve: req_ind = RetrieveRequestIndication(path) if path.endswith(("/contentInstances", "/discovery")): args = request.params filter_criteria = {k: v for k, v in args.items() if k not in ("ifNoneMatch", "searchString", "contentType", "searchPrefix", "maxSize")} filter_criteria = FilterCriteria(**filter_criteria) if_none_match = args.getlist("ifNoneMatch") if if_none_match: filter_criteria.ifNoneMatch = if_none_match search_string = args.getlist("searchString") if search_string: filter_criteria.searchString = search_string content_type = args.getlist("contentType") if content_type: filter_criteria.contentType = content_type req_ind.filterCriteria = filter_criteria if path.endswith("/discovery"): req_ind.searchPrefix = args.get("searchPrefix") req_ind.maxSize = args.get("maxSize") # obtain some filter-criteria from HTTP headers, where appropriate # TODO: kca: not sure if this is actually standard compliant, but it # seems like common sense. Check if its in the standard, if not, # allow to turn it off via config # TODO: use generic format environ = request.metadata for n in ("if_None_Match", "if_Unmodified_Since", "if_Modified_Since"): try: header = environ["HTTP_" + n.upper()] except KeyError: pass else: filter_criteria.setdefault(n.replace("_", ""), header) elif method == RequestMethod.update: req_ind = UpdateRequestIndication(path=path, resource=request.payload, content_type=request.content_type) elif method == RequestMethod.delete: req_ind = DeleteRequestIndication(path) elif method == RequestMethod.notify: req_ind = NotifyRequestIndication(path=path, resource=request.payload, content_type=request.content_type) else: raise ErrorResponse(ResponseCode.method_not_allowed) # TODO: set correlationID, rcat, trpdt req_ind.requestingEntity = get_requesting_entity(request) via = request.via if via: req_ind.via = request.via return req_ind
def create_application(self, ): path = "/m2m/applications" app_object = Application(appId=self.app_name) request = CreateRequestIndication(path=path, resource=app_object) response = self.api.handle_request_indication(request) return response
def create_device_subcontainer(self, path=None, id=None, searchStrings=[]): container = Container(id=id, searchStrings=searchStrings, maxNrOfInstances=self.max_nr_of_instances) request = CreateRequestIndication(path=path, resource=container) response = self.api.handle_request_indication(request) return response
def create_gscl(): rq = CreateRequestIndication(uri, gscl) rq.requestingEntity = self.config.get("requesting_entity") return self.api.send_request_indication(rq)
def create(self, path, resource): return self._send_create(CreateRequestIndication(path, resource))
def create_container(self, result): path = result.resource.path + "/containers" container_object = Container(path=path, id=CONTAINER_ID) request = CreateRequestIndication(path=path, resource=container_object) response = self.api.handle_request_indication(request)
def create_application(self, ): path = "/m2m/applications" app_object = Application(path=path, appId=APP_ID) request = CreateRequestIndication(path=path, resource=app_object) response = self.api.handle_request_indication(request) response.then(self.create_container)
def push_content(self, container, content, fmt=None, text=None): """ Creates a ContentInstance resource in the given container, wrapping the content. Serialises content as JSON and base64 encodes it. NOTE: Will attempt to create the container, if not found. :param container: the Container :param content: the content data :param fmt: :param text: """ path = getattr(container, "path", container) if not path.endswith("/contentInstances"): path += "/contentInstances" if isinstance(content, (str, unicode)): fmt = 'text/plain' if fmt is None else fmt text = True if text is None else text elif isinstance(content, (dict, list)): fmt = 'application/json' if fmt is None else fmt text = False if text is None else text else: raise SCLNotImplemented("Only dict, list and str are supported!") if re.search(self.fmt_json_regex, fmt): if text: # TODO(rst): check if it should be with masked quotation marks # con = json_dumps(content) # cnf = fmt + ':' + str(EncodingTypeE.plain.value) raise SCLNotImplemented("Only json as b64 is supported!") else: ci = { "content": { "binaryContent": b64encode(json_dumps(content)), "contentType": fmt } } elif fmt == 'text/plain': if text: ci = {"content": {"textContent": content, "contentType": fmt}} raise SCLNotImplemented("Only json as b64 is supported!") else: ci = { "content": { "binaryContent": b64encode(content), "contentType": fmt } } raise SCLNotImplemented("Only json as b64 is supported!") else: # TODO(rst): add handling of other formats or raise not implemented raise SCLNotImplemented("Only json and text are supported!") request_indication = CreateRequestIndication( path=path, resource=ci, typename="contentInstance") try: return self.mapper.send_request(request_indication) except SCLNotFound: # where did the container go? or is it the application? self.logger.warn("NotFound: %s; attempting to restore.", container.path) container.expirationTime = self.get_expiration_time() self.__start_refresher(container) self.mapper.create(container.parent_path, container) return self.mapper.send_request(request_indication)
def send_create_annc(scl_uri, local_ar=None): annc = annc_model() endpoint = self.api.get_mid_uri(urlparse(scl_uri).scheme) # * searchStrings from the original resource; annc.searchStrings = resource.searchStrings # * accessRightID from the original resource; if local_ar: annc.accessRightID = urljoin(endpoint, urlparse( resource.accessRightID).path) elif local_ar is None: annc.accessRightID = local_ar else: annc.accessRightID = resource.accessRightID # * link is set to the URI of the original resource; annc.link = urljoin(endpoint, resource.path) # * requestingEntity is set to the application; # req_ent from from outer scope # * issuer is set to its own SCL ID (the local SCL performing the # action); # rst: not needed probably # * id of the resource shall be set to the id of the original # resource postfixed with Annc. I.e. if the original resource has id # "myApp", the announced resource shall have the id "myAppAnnc"; annc.id = annc_id # * expirationTime handling is to the discretion of the SCL # implementation. It is the responsibility of the local SCL to keep # the announced resource in sync with the lifetime of the original # resource, as long as the announcement is active. One strategy to # minimize signalling would be to request the same expiration from # the original resource. If this is accepted by the remote SCL, then # no explicit de-announce is needed in case of expiration of the # original resource; annc.expirationTime = resource.expirationTime # * targetID is set as follow. # TODO: inline def get_target_id(): scl_path = scl_uri + '/scls/' + self.scl_id apps_path = self._scl_base + '/applications/' if resource.typename == 'application': # is appAnnc return scl_path + '/applications/' else: try: parent = _special_parent_map[resource.typename] + '/' except KeyError: parent = resource.typename + 's/' if resource.path.find(apps_path) == 0: # is under appAnnc # todo: lookup appAnnc in self._announcements return (scl_path + '/applications/' + sub(apps_path, '', resource.path).split('/')[0] + 'Annc/' + parent) else: # is other Annc return scl_path + '/' + parent target_id = get_target_id() try: req_ent_mid = urljoin(endpoint, urlparse(req_ent).path) except AttributeError: # probably req_ent was not set due to debug self.logger.debug("Could not midify") req_ent_mid = None create_annc_req_ind = CreateRequestIndication( target_id, annc, requestingEntity=req_ent_mid) return self.api.send_request_indication(create_annc_req_ind)