sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def __handle_low_seq_resend(self, msg, req): """special error case - low sequence number (update sequence number & resend if applicable). Returns True if a resend was scheduled, False otherwise. MUST be called within self.__requests lock.""" if msg[M_TYPE] == E_FAILED and msg[M_PAYLOAD][P_CODE] == E_FAILED_CODE_LOWSEQNUM: with self.__seqnum_lock: self.__seqnum = int(msg[M_PAYLOAD][P_MESSAGE]) # return value indicating shutdown not useful here since this is run in receiver thread self.__retry_enqueue(PreparedMessage(req._inner_msg_out, req.id_)) return True return False
special error case - low sequence number (update sequence number & resend if applicable). Returns True if a resend was scheduled, False otherwise. MUST be called within self.__requests lock.
entailment
def __decode_data_time(self, payload): """Extract time and decode payload (based on mime type) from payload. Applies to E_FEEDDATA and E_RECENTDATA. Returns tuple of data, mime, time.""" data, mime = self.__bytes_to_share_data(payload) try: time = datetime.strptime(payload.get(P_TIME), self.__share_time_fmt) except (ValueError, TypeError): logger.warning('Share payload from container has invalid timestamp (%s), will use naive local time', payload.get(P_TIME)) time = datetime.utcnow() return data, mime, time
Extract time and decode payload (based on mime type) from payload. Applies to E_FEEDDATA and E_RECENTDATA. Returns tuple of data, mime, time.
entailment
def __perform_unsolicited_callbacks(self, msg): """Callbacks for which a client reference is either optional or does not apply at all""" type_ = msg[M_TYPE] payload = msg[M_PAYLOAD] # callbacks for responses which might be unsolicited (e.g. created or deleted) if type_ in _RSP_PAYLOAD_CB_MAPPING: self.__fire_callback(_RSP_PAYLOAD_CB_MAPPING[type_], msg) # Perform callbacks for feed data elif type_ == E_FEEDDATA: self.__simulate_feeddata(payload[P_FEED_ID], *self.__decode_data_time(payload)) # Perform callbacks for unsolicited subscriber message elif type_ == E_SUBSCRIBED: self.__fire_callback(_CB_SUBSCRIPTION, payload) else: logger.error('Unexpected message type for unsolicited callback %s', type_)
Callbacks for which a client reference is either optional or does not apply at all
entailment
def roles(self, roles_list): ''' Set the roles for the current launch. Full list of roles can be found here: http://www.imsglobal.org/LTI/v1p1/ltiIMGv1p1.html#_Toc319560479 LIS roles include: * Student * Faculty * Member * Learner * Instructor * Mentor * Staff * Alumni * ProspectiveStudent * Guest * Other * Administrator * Observer * None ''' if roles_list and isinstance(roles_list, list): self.roles = [].extend(roles_list) elif roles_list and isinstance(roles_list, basestring): self.roles = [role.lower() for role in roles_list.split(',')]
Set the roles for the current launch. Full list of roles can be found here: http://www.imsglobal.org/LTI/v1p1/ltiIMGv1p1.html#_Toc319560479 LIS roles include: * Student * Faculty * Member * Learner * Instructor * Mentor * Staff * Alumni * ProspectiveStudent * Guest * Other * Administrator * Observer * None
entailment
def process_params(self, params): ''' Populates the launch data from a dictionary. Only cares about keys in the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or 'ext_'. ''' for key, val in params.items(): if key in LAUNCH_DATA_PARAMETERS and val != 'None': if key == 'roles': if isinstance(val, list): # If it's already a list, no need to parse self.roles = list(val) else: # If it's a ',' delimited string, split self.roles = val.split(',') else: setattr(self, key, touni(val)) elif 'custom_' in key: self.custom_params[key] = touni(val) elif 'ext_' in key: self.ext_params[key] = touni(val)
Populates the launch data from a dictionary. Only cares about keys in the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or 'ext_'.
entailment
def to_params(self): ''' Createa a new dictionary with all launch data. Custom / Extension keys will be included. Roles are set as a ',' separated string. ''' params = {} custom_params = {} for key in self.custom_params: custom_params[key] = self.custom_params[key] ext_params = {} for key in self.ext_params: ext_params[key] = self.ext_params[key] for key in LAUNCH_DATA_PARAMETERS: if hasattr(self, key): params[key] = getattr(self, key) params.update(custom_params) params.update(ext_params) return params
Createa a new dictionary with all launch data. Custom / Extension keys will be included. Roles are set as a ',' separated string.
entailment
def write_longstr(self, s): """Write a string up to 2**32 bytes long after encoding. If passed a unicode string, encode as UTF-8. """ self._flushbits() if isinstance(s, text_t): s = s.encode('utf-8') self.write_long(len(s)) self.out.write(s)
Write a string up to 2**32 bytes long after encoding. If passed a unicode string, encode as UTF-8.
entailment
def run(self, background=False): """Runs `on_startup`, `main` and `on_shutdown`, blocking until finished, unless background is set.""" if self.__bgthread: raise Exception('run has already been called (since last stop)') self.__shutdown.clear() if background: self.__bgthread = Thread(target=self.__run, name=('bg_' + self.__client.agent_id)) self.__bgthread.daemon = True self.__bgthread.start() else: self.__run()
Runs `on_startup`, `main` and `on_shutdown`, blocking until finished, unless background is set.
entailment
def stop(self, timeout=None): """Requests device to stop running, waiting at most the given timout in seconds (fractional). Has no effect if `run()` was not called with background=True set. Returns True if successfully stopped (or already not running). """ stopped = True self.__shutdown.set() if self.__bgthread: logger.debug('Stopping bgthread') self.__bgthread.join(timeout) if self.__bgthread.is_alive(): logger.warning('bgthread did not finish within timeout') stopped = False self.__bgthread = None return stopped
Requests device to stop running, waiting at most the given timout in seconds (fractional). Has no effect if `run()` was not called with background=True set. Returns True if successfully stopped (or already not running).
entailment
def add_message_to_queue(self, payload, **attributes): """ Given a payload (a dict) and any optional message attributes (also a dict), add it to the queue. """ return self.queue.send_message(MessageBody=json.dumps(payload), MessageAttributes={k: {"StringValue": v} for k, v in attributes.items()})
Given a payload (a dict) and any optional message attributes (also a dict), add it to the queue.
entailment
def receive_messages_from_queue(self, wait_time=15, num_messages=1): """ Returns the first (according to FIFO) element in the queue; if none, then returns None.""" return self.queue.receive_messages(MaxNumberOfMessages=num_messages, WaitTimeSeconds=wait_time)
Returns the first (according to FIFO) element in the queue; if none, then returns None.
entailment
def save_json(self, jsonfn=None, pretty=True): """Write a .json file with the units tree jsonfn='path/file.name' default os.getcwd() + 'units.json' pretty=True use JSON dumps pretty print for human readability """ if jsonfn is None: jsonfn = os.path.join(os.getcwd(), 'units.json') # jsondump = None sort_keys = False indent = 0 if pretty: sort_keys = True indent = 4 jsondump = json.dumps(self.units, sort_keys=sort_keys, indent=indent) # with open(jsonfn, 'w') as f: f.write(jsondump) return True return False
Write a .json file with the units tree jsonfn='path/file.name' default os.getcwd() + 'units.json' pretty=True use JSON dumps pretty print for human readability
entailment
def accumulate_metric(cls, name, value): """ Accumulate a custom metric (name and value) in the metrics cache. """ metrics_cache = cls._get_metrics_cache() metrics_cache.setdefault(name, 0) metrics_cache.set(name, value)
Accumulate a custom metric (name and value) in the metrics cache.
entailment
def _batch_report(cls, request): """ Report the collected custom metrics to New Relic. """ if not newrelic: return metrics_cache = cls._get_metrics_cache() try: newrelic.agent.add_custom_parameter('user_id', request.user.id) except AttributeError: pass for key, value in metrics_cache.data.items(): newrelic.agent.add_custom_parameter(key, value)
Report the collected custom metrics to New Relic.
entailment
def process_request(self, request): """ Store memory data to log later. """ if self._is_enabled(): self._cache.set(self.guid_key, six.text_type(uuid4())) log_prefix = self._log_prefix(u"Before", request) self._cache.set(self.memory_data_key, self._memory_data(log_prefix))
Store memory data to log later.
entailment
def process_response(self, request, response): """ Logs memory data after processing response. """ if self._is_enabled(): log_prefix = self._log_prefix(u"After", request) new_memory_data = self._memory_data(log_prefix) log_prefix = self._log_prefix(u"Diff", request) cached_memory_data_response = self._cache.get_cached_response(self.memory_data_key) old_memory_data = cached_memory_data_response.get_value_or_default(None) self._log_diff_memory_data(log_prefix, new_memory_data, old_memory_data) return response
Logs memory data after processing response.
entailment
def _log_prefix(self, prefix, request): """ Returns a formatted prefix for logging for the given request. """ # After a celery task runs, the request cache is cleared. So if celery # tasks are running synchronously (CELERY_ALWAYS _EAGER), "guid_key" # will no longer be in the request cache when process_response executes. cached_guid_response = self._cache.get_cached_response(self.guid_key) cached_guid = cached_guid_response.get_value_or_default(u"without_guid") return u"{} request '{} {} {}'".format(prefix, request.method, request.path, cached_guid)
Returns a formatted prefix for logging for the given request.
entailment
def _memory_data(self, log_prefix): """ Returns a dict with information for current memory utilization. Uses log_prefix in log statements. """ machine_data = psutil.virtual_memory() process = psutil.Process() process_data = { 'memory_info': process.get_memory_info(), 'ext_memory_info': process.get_ext_memory_info(), 'memory_percent': process.get_memory_percent(), 'cpu_percent': process.get_cpu_percent(), } log.info(u"%s Machine memory usage: %s; Process memory usage: %s", log_prefix, machine_data, process_data) return { 'machine_data': machine_data, 'process_data': process_data, }
Returns a dict with information for current memory utilization. Uses log_prefix in log statements.
entailment
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data): """ Computes and logs the difference in memory utilization between the given old and new memory data. """ def _vmem_used(memory_data): return memory_data['machine_data'].used def _process_mem_percent(memory_data): return memory_data['process_data']['memory_percent'] def _process_rss(memory_data): return memory_data['process_data']['memory_info'].rss def _process_vms(memory_data): return memory_data['process_data']['memory_info'].vms if new_memory_data and old_memory_data: log.info( u"%s Diff Vmem used: %s, Diff percent memory: %s, Diff rss: %s, Diff vms: %s", prefix, _vmem_used(new_memory_data) - _vmem_used(old_memory_data), _process_mem_percent(new_memory_data) - _process_mem_percent(old_memory_data), _process_rss(new_memory_data) - _process_rss(old_memory_data), _process_vms(new_memory_data) - _process_vms(old_memory_data), )
Computes and logs the difference in memory utilization between the given old and new memory data.
entailment
def data(self, namespace): """ Gets the thread.local data (dict) for a given namespace. Args: namespace (string): The namespace, or key, of the data dict. Returns: (dict) """ assert namespace if namespace in self._data: return self._data[namespace] new_data = {} self._data[namespace] = new_data return new_data
Gets the thread.local data (dict) for a given namespace. Args: namespace (string): The namespace, or key, of the data dict. Returns: (dict)
entailment
def get_cached_response(self, key): """ Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value. """ cached_value = self.data.get(key, _CACHE_MISS) is_found = cached_value is not _CACHE_MISS return CachedResponse(is_found, key, cached_value)
Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value.
entailment
def get_cached_response(cls, key): """ Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value. """ request_cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(key) if not request_cached_response.is_found: django_cached_response = cls._get_cached_response_from_django_cache(key) cls._set_request_cache_if_django_cache_hit(key, django_cached_response) return django_cached_response return request_cached_response
Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value.
entailment
def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT): """ Caches the value for the provided key in both the request cache and the django cache. Args: key (string) value (object) django_cache_timeout (int): (Optional) Timeout used to determine if and for how long to cache in the django cache. A timeout of 0 will skip the django cache. If timeout is provided, use that timeout for the key; otherwise use the default cache timeout. """ DEFAULT_REQUEST_CACHE.set(key, value) django_cache.set(key, value, django_cache_timeout)
Caches the value for the provided key in both the request cache and the django cache. Args: key (string) value (object) django_cache_timeout (int): (Optional) Timeout used to determine if and for how long to cache in the django cache. A timeout of 0 will skip the django cache. If timeout is provided, use that timeout for the key; otherwise use the default cache timeout.
entailment
def _get_cached_response_from_django_cache(key): """ Retrieves a CachedResponse for the given key from the django cache. If the request was set to force cache misses, then this will always return a cache miss response. Args: key (string) Returns: A CachedResponse with is_found status and value. """ if TieredCache._should_force_django_cache_miss(): return CachedResponse(is_found=False, key=key, value=None) cached_value = django_cache.get(key, _CACHE_MISS) is_found = cached_value is not _CACHE_MISS return CachedResponse(is_found, key, cached_value)
Retrieves a CachedResponse for the given key from the django cache. If the request was set to force cache misses, then this will always return a cache miss response. Args: key (string) Returns: A CachedResponse with is_found status and value.
entailment
def _set_request_cache_if_django_cache_hit(key, django_cached_response): """ Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse) """ if django_cached_response.is_found: DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)
Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse)
entailment
def _get_and_set_force_cache_miss(request): """ Gets value for request query parameter FORCE_CACHE_MISS and sets it in the default request cache. This functionality is only available for staff. Example: http://clobert.com/api/v1/resource?force_cache_miss=true """ if not (request.user and request.user.is_active and request.user.is_staff): force_cache_miss = False else: force_cache_miss = request.GET.get(FORCE_CACHE_MISS_PARAM, 'false').lower() == 'true' DEFAULT_REQUEST_CACHE.set(SHOULD_FORCE_CACHE_MISS_KEY, force_cache_miss)
Gets value for request query parameter FORCE_CACHE_MISS and sets it in the default request cache. This functionality is only available for staff. Example: http://clobert.com/api/v1/resource?force_cache_miss=true
entailment
def _should_force_django_cache_miss(cls): """ Returns True if the tiered cache should force a cache miss for the django cache, and False otherwise. """ cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(SHOULD_FORCE_CACHE_MISS_KEY) return False if not cached_response.is_found else cached_response.value
Returns True if the tiered cache should force a cache miss for the django cache, and False otherwise.
entailment
def check_convert_string(obj, name=None, no_leading_trailing_whitespace=True, no_whitespace=False, no_newline=True, whole_word=False, min_len=1, max_len=0): """Ensures the provided object can be interpreted as a unicode string, optionally with additional restrictions imposed. By default this means a non-zero length string which does not begin or end in whitespace.""" if not name: name = 'Argument' obj = ensure_unicode(obj, name=name) if no_whitespace: if _PATTERN_WHITESPACE.match(obj): raise ValueError('%s cannot contain whitespace' % name) elif no_leading_trailing_whitespace and _PATTERN_LEAD_TRAIL_WHITESPACE.match(obj): raise ValueError('%s contains leading/trailing whitespace' % name) if (min_len and len(obj) < min_len) or (max_len and len(obj) > max_len): raise ValueError('%s too short/long (%d/%d)' % (name, min_len, max_len)) if whole_word: if not _PATTERN_WORD.match(obj): raise ValueError('%s can only contain alphanumeric (unicode) characters, numbers and the underscore' % name) # whole words cannot contain newline so additional check not required elif no_newline and '\n' in obj: raise ValueError('%s cannot contain line breaks' % name) return obj
Ensures the provided object can be interpreted as a unicode string, optionally with additional restrictions imposed. By default this means a non-zero length string which does not begin or end in whitespace.
entailment
def guid_check_convert(guid, allow_none=False): """Take a GUID in the form of hex string "32" or "8-4-4-4-12". Returns hex string "32" or raises ValueError: badly formed hexadecimal UUID string """ if isinstance(guid, string_types): return ensure_unicode(UUID(guid).hex) elif guid is None and allow_none: return None else: raise ValueError('guid must be a string')
Take a GUID in the form of hex string "32" or "8-4-4-4-12". Returns hex string "32" or raises ValueError: badly formed hexadecimal UUID string
entailment
def tags_check_convert(cls, tags): """Accept one tag as string or multiple tags in list of strings. Returns list (with tags in unicode form) or raises ValueError """ # single string check comes first since string is also a Sequence if isinstance(tags, string_types): return [cls.__tag_check_convert(tags)] elif isinstance(tags, Sequence): if not tags: raise ValueError("Tag list is empty") return [cls.__tag_check_convert(tag) for tag in tags] else: raise ValueError("tags must be a single string or list of sequence of strings")
Accept one tag as string or multiple tags in list of strings. Returns list (with tags in unicode form) or raises ValueError
entailment
def __valid_url(cls, url): """Expects input to already be a valid string""" bits = urlparse(url) return ((bits.scheme == "http" or bits.scheme == "https") and _PATTERN_URL_PART.match(bits.netloc) and _PATTERN_URL_PART.match(bits.path))
Expects input to already be a valid string
entailment
def location_check(lat, lon): """For use by Core client wrappers""" if not (isinstance(lat, number_types) and -90 <= lat <= 90): raise ValueError("Latitude: '{latitude}' invalid".format(latitude=lat)) if not (isinstance(lon, number_types) and -180 <= lon <= 180): raise ValueError("Longitude: '{longitude}' invalid".format(longitude=lon))
For use by Core client wrappers
entailment
def search_location_check(cls, location): """Core.Client.request_search location parameter should be a dictionary that contains lat, lon and radius floats """ if not (isinstance(location, Mapping) and set(location.keys()) == _LOCATION_SEARCH_ARGS): raise ValueError('Search location should be mapping with keys: %s' % _LOCATION_SEARCH_ARGS) cls.location_check(location['lat'], location['long']) radius = location['radius'] if not (isinstance(radius, number_types) and 0 < radius <= 20038): # half circumference raise ValueError("Radius: '{radius}' is invalid".format(radius=radius))
Core.Client.request_search location parameter should be a dictionary that contains lat, lon and radius floats
entailment
def __search_text_check_convert(cls, text): """Converts and keeps only words in text deemed to be valid""" text = cls.check_convert_string(text, name='text', no_leading_trailing_whitespace=False) if len(text) > VALIDATION_META_SEARCH_TEXT: raise ValueError("Search text can contain at most %d characters" % VALIDATION_META_SEARCH_TEXT) text = ' '.join(_PATTERN_WORDS.findall(text)) if not text: raise ValueError('Search text must contain at least one non-whitespace term (word)') return text
Converts and keeps only words in text deemed to be valid
entailment
def callable_check(func, arg_count=1, arg_value=None, allow_none=False): """Check whether func is callable, with the given number of positional arguments. Returns True if check succeeded, False otherwise.""" if func is None: if not allow_none: raise ValueError('callable cannot be None') elif not arg_checker(func, *[arg_value for _ in range(arg_count)]): raise ValueError('callable %s invalid (for %d arguments)' % (func, arg_count))
Check whether func is callable, with the given number of positional arguments. Returns True if check succeeded, False otherwise.
entailment
def list_feeds(self, limit=500, offset=0): """List `all` the feeds on this Thing. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many Point details `offset` (optional) (integer) Return Point details starting at this offset """ return self.__list(R_FEED, limit=limit, offset=offset)['feeds']
List `all` the feeds on this Thing. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many Point details `offset` (optional) (integer) Return Point details starting at this offset
entailment
def list_controls(self, limit=500, offset=0): """List `all` the controls on this Thing. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many Point details `offset` (optional) (integer) Return Point details starting at this offset """ return self.__list(R_CONTROL, limit=limit, offset=offset)['controls']
List `all` the controls on this Thing. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many Point details `offset` (optional) (integer) Return Point details starting at this offset
entailment
def set_public(self, public=True): """Sets your Thing to be public to all. If `public=True`. This means the tags, label and description of your Thing are now searchable by anybody, along with its location and the units of any values on any Points. If `public=False` the metadata of your Thing is no longer searchable. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `public` (optional) (boolean) Whether (or not) to allow your Thing's metadata to be searched by anybody """ logger.info("set_public(public=%s) [lid=%s]", public, self.__lid) evt = self._client._request_entity_meta_setpublic(self.__lid, public) self._client._wait_and_except_if_failed(evt)
Sets your Thing to be public to all. If `public=True`. This means the tags, label and description of your Thing are now searchable by anybody, along with its location and the units of any values on any Points. If `public=False` the metadata of your Thing is no longer searchable. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `public` (optional) (boolean) Whether (or not) to allow your Thing's metadata to be searched by anybody
entailment
def rename(self, new_lid): """Rename the Thing. `ADVANCED USERS ONLY` This can be confusing. You are changing the local id of a Thing to `new_lid`. If you create another Thing using the "old_lid", the system will oblige, but it will be a completely _new_ Thing. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `new_lid` (required) (string) the new local identifier of your Thing """ logger.info("rename(new_lid=\"%s\") [lid=%s]", new_lid, self.__lid) evt = self._client._request_entity_rename(self.__lid, new_lid) self._client._wait_and_except_if_failed(evt) self.__lid = new_lid self._client._notify_thing_lid_change(self.__lid, new_lid)
Rename the Thing. `ADVANCED USERS ONLY` This can be confusing. You are changing the local id of a Thing to `new_lid`. If you create another Thing using the "old_lid", the system will oblige, but it will be a completely _new_ Thing. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `new_lid` (required) (string) the new local identifier of your Thing
entailment
def reassign(self, new_epid): """Reassign the Thing from one agent to another. `ADVANCED USERS ONLY` This will lead to any local instances of a Thing being rendered useless. They won't be able to receive control requests, feed data or to share any feeds as they won't be in this agent. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `new_epid` (required) (string) the new agent id to which your Thing should be assigned. If None, current agent will be chosen. If False, existing agent will be unassigned. """ logger.info("reassign(new_epid=\"%s\") [lid=%s]", new_epid, self.__lid) evt = self._client._request_entity_reassign(self.__lid, new_epid) self._client._wait_and_except_if_failed(evt)
Reassign the Thing from one agent to another. `ADVANCED USERS ONLY` This will lead to any local instances of a Thing being rendered useless. They won't be able to receive control requests, feed data or to share any feeds as they won't be in this agent. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `new_epid` (required) (string) the new agent id to which your Thing should be assigned. If None, current agent will be chosen. If False, existing agent will be unassigned.
entailment
def create_tag(self, tags): """Create tags for a Thing in the language you specify. Tags can only contain alphanumeric (unicode) characters and the underscore. Tags will be stored lower-cased. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `tags` (mandatory) (list) - the list of tags you want to add to your Thing, e.g. `["garden", "soil"]` """ if isinstance(tags, str): tags = [tags] evt = self._client._request_entity_tag_update(self.__lid, tags, delete=False) self._client._wait_and_except_if_failed(evt)
Create tags for a Thing in the language you specify. Tags can only contain alphanumeric (unicode) characters and the underscore. Tags will be stored lower-cased. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `tags` (mandatory) (list) - the list of tags you want to add to your Thing, e.g. `["garden", "soil"]`
entailment
def delete_tag(self, tags): """Delete tags for a Thing in the language you specify. Case will be ignored and any tags matching lower-cased will be deleted. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `tags` (mandatory) (list) - the list of tags you want to delete from your Thing, e.g. `["garden", "soil"]` """ if isinstance(tags, str): tags = [tags] evt = self._client._request_entity_tag_update(self.__lid, tags, delete=True) self._client._wait_and_except_if_failed(evt)
Delete tags for a Thing in the language you specify. Case will be ignored and any tags matching lower-cased will be deleted. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `tags` (mandatory) (list) - the list of tags you want to delete from your Thing, e.g. `["garden", "soil"]`
entailment
def list_tag(self, limit=500, offset=0): """List `all` the tags for this Thing Returns lists of tags, as below #!python [ "mytag1", "mytag2" "ein_name", "nochein_name" ] - OR... Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return at most this many tags `offset` (optional) (integer) Return tags starting at this offset """ evt = self._client._request_entity_tag_list(self.__lid, limit=limit, offset=offset) self._client._wait_and_except_if_failed(evt) return evt.payload['tags']
List `all` the tags for this Thing Returns lists of tags, as below #!python [ "mytag1", "mytag2" "ein_name", "nochein_name" ] - OR... Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return at most this many tags `offset` (optional) (integer) Return tags starting at this offset
entailment
def get_meta(self): """Get the metadata object for this Thing Returns a [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) object """ rdf = self.get_meta_rdf(fmt='n3') return ThingMeta(self, rdf, self._client.default_lang, fmt='n3')
Get the metadata object for this Thing Returns a [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) object
entailment
def get_meta_rdf(self, fmt='n3'): """Get the metadata for this Thing in rdf fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object Returns the RDF in the format you specify. - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `fmt` (optional) (string) The format of RDF you want returned. Valid formats are: "xml", "n3", "turtle" """ evt = self._client._request_entity_meta_get(self.__lid, fmt=fmt) self._client._wait_and_except_if_failed(evt) return evt.payload['meta']
Get the metadata for this Thing in rdf fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object Returns the RDF in the format you specify. - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `fmt` (optional) (string) The format of RDF you want returned. Valid formats are: "xml", "n3", "turtle"
entailment
def set_meta_rdf(self, rdf, fmt='n3'): """Set the metadata for this Thing in RDF fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `fmt` (optional) (string) The format of RDF you have sent. Valid formats are: "xml", "n3", "turtle" """ evt = self._client._request_entity_meta_set(self.__lid, rdf, fmt=fmt) self._client._wait_and_except_if_failed(evt)
Set the metadata for this Thing in RDF fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `fmt` (optional) (string) The format of RDF you have sent. Valid formats are: "xml", "n3", "turtle"
entailment
def get_feed(self, pid): """Get the details of a newly created feed. This only applies to asynchronous creation of feeds and the new feed instance can only be retrieved once. `NOTE` - Destructive Read. Once you've called get_feed once, any further calls will raise a `KeyError` Returns a [Feed](Point.m.html#IoticAgent.IOT.Point.Feed) object, which corresponds to the cached entry for this local feed id `pid` (required) (string) Point id - local identifier of your feed. Raises `KeyError` if the feed has not been newly created (or has already been retrieved by a previous call) """ with self.__new_feeds: try: return self.__new_feeds.pop(pid) except KeyError as ex: raise_from(KeyError('Feed %s not know as new' % pid), ex)
Get the details of a newly created feed. This only applies to asynchronous creation of feeds and the new feed instance can only be retrieved once. `NOTE` - Destructive Read. Once you've called get_feed once, any further calls will raise a `KeyError` Returns a [Feed](Point.m.html#IoticAgent.IOT.Point.Feed) object, which corresponds to the cached entry for this local feed id `pid` (required) (string) Point id - local identifier of your feed. Raises `KeyError` if the feed has not been newly created (or has already been retrieved by a previous call)
entailment
def get_control(self, pid): """Get the details of a newly created control. This only applies to asynchronous creation of feeds and the new control instance can only be retrieved once. `NOTE` - Destructive Read. Once you've called get_control once, any further calls will raise a `KeyError` Returns a [Control](Point.m.html#IoticAgent.IOT.Point.Control) object, which corresponds to the cached entry for this local control id `pid` (required) (string) local identifier of your control. Raises `KeyError` if the control has not been newly created (or has already been retrieved by a previous call) """ with self.__new_controls: try: return self.__new_controls.pop(pid) except KeyError as ex: raise_from(KeyError('Control %s not know as new' % pid), ex)
Get the details of a newly created control. This only applies to asynchronous creation of feeds and the new control instance can only be retrieved once. `NOTE` - Destructive Read. Once you've called get_control once, any further calls will raise a `KeyError` Returns a [Control](Point.m.html#IoticAgent.IOT.Point.Control) object, which corresponds to the cached entry for this local control id `pid` (required) (string) local identifier of your control. Raises `KeyError` if the control has not been newly created (or has already been retrieved by a previous call)
entailment
def create_feed(self, pid, save_recent=0): """Create a new Feed for this Thing with a local point id (pid). Returns a new [Feed](Point.m.html#IoticAgent.IOT.Point.Feed) object, or the existing one, if the Feed already exists Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local id of your Feed `save_recent` (optional) (int) how many shares to store for later retrieval. If not supported by container, this argument will be ignored. A value of zero disables this feature whilst a negative value requests the maximum sample store amount. See also [Feed.set_recent_config](./Point.m.html#IoticAgent.IOT.Point.Feed.set_recent_config). """ logger.info("create_feed(pid=\"%s\") [lid=%s]", pid, self.__lid) return self.__create_point(R_FEED, pid, save_recent=save_recent)
Create a new Feed for this Thing with a local point id (pid). Returns a new [Feed](Point.m.html#IoticAgent.IOT.Point.Feed) object, or the existing one, if the Feed already exists Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local id of your Feed `save_recent` (optional) (int) how many shares to store for later retrieval. If not supported by container, this argument will be ignored. A value of zero disables this feature whilst a negative value requests the maximum sample store amount. See also [Feed.set_recent_config](./Point.m.html#IoticAgent.IOT.Point.Feed.set_recent_config).
entailment
def create_control(self, pid, callback, callback_parsed=None): """Create a control for this Thing with a local point id (pid) and a control request feedback Returns a new [Control](Point.m.html#IoticAgent.IOT.Point.Control) object or the existing one if the Control already exists Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local id of your Control `callback` (required) (function reference) callback function to invoke on receipt of a control request. The callback receives a single dict argument, with keys of: #!python 'data' # (decoded or raw bytes) 'mime' # (None, unless payload was not decoded and has a mime type) 'subId' # (the global id of the associated subscripion) 'entityLid' # (local id of the Thing to which the control belongs) 'lid' # (local id of control) 'confirm' # (whether a confirmation is expected) 'requestId' # (required for sending confirmation) `callback_parsed` (optional) (function reference) callback function to invoke on receipt of control data. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. `NOTE`: `callback_parsed` can only be used if `auto_encode_decode` is enabled for the client instance. """ logger.info("create_control(pid=\"%s\", control_cb=%s) [lid=%s]", pid, callback, self.__lid) if callback_parsed: callback = self._client._get_parsed_control_callback(callback_parsed, callback) return self.__create_point(R_CONTROL, pid, control_cb=callback)
Create a control for this Thing with a local point id (pid) and a control request feedback Returns a new [Control](Point.m.html#IoticAgent.IOT.Point.Control) object or the existing one if the Control already exists Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local id of your Control `callback` (required) (function reference) callback function to invoke on receipt of a control request. The callback receives a single dict argument, with keys of: #!python 'data' # (decoded or raw bytes) 'mime' # (None, unless payload was not decoded and has a mime type) 'subId' # (the global id of the associated subscripion) 'entityLid' # (local id of the Thing to which the control belongs) 'lid' # (local id of control) 'confirm' # (whether a confirmation is expected) 'requestId' # (required for sending confirmation) `callback_parsed` (optional) (function reference) callback function to invoke on receipt of control data. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. `NOTE`: `callback_parsed` can only be used if `auto_encode_decode` is enabled for the client instance.
entailment
def delete_feed(self, pid): """Delete a feed, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local identifier of your feed you want to delete """ logger.info("delete_feed(pid=\"%s\") [lid=%s]", pid, self.__lid) return self.__delete_point(R_FEED, pid)
Delete a feed, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local identifier of your feed you want to delete
entailment
def delete_control(self, pid): """Delete a control, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local identifier of your control you want to delete """ logger.info("delete_control(pid=\"%s\") [lid=%s]", pid, self.__lid) return self.__delete_point(R_CONTROL, pid)
Delete a control, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `pid` (required) (string) local identifier of your control you want to delete
entailment
def __sub_add_reference(self, key): """Used by __sub_make_request to save reference for pending sub request""" new_subs = self.__new_subs with new_subs: # don't allow multiple subscription requests to overwrite internal reference if key in new_subs: raise ValueError('subscription for given args pending: %s' % str(key)) new_subs[key] = None try: yield except: # don't preserve reference if request creation failed with new_subs: new_subs.pop(key, None) raise
Used by __sub_make_request to save reference for pending sub request
entailment
def __sub_del_reference(self, req, key): """Blindly clear reference to pending subscription on failure.""" if not req.success: try: self.__new_subs.pop(key) except KeyError: logger.warning('No sub ref %s', key)
Blindly clear reference to pending subscription on failure.
entailment
def __sub_make_request(self, foc, gpid, callback): """Make right subscription request depending on whether local or global - used by __sub*""" # global if isinstance(gpid, string_types): gpid = uuid_to_hex(gpid) ref = (foc, gpid) with self.__sub_add_reference(ref): req = self._client._request_sub_create(self.__lid, foc, gpid, callback=callback) # local elif isinstance(gpid, Sequence) and len(gpid) == 2: ref = (foc, tuple(gpid)) with self.__sub_add_reference(ref): req = self._client._request_sub_create_local(self.__lid, foc, *gpid, callback=callback) else: raise ValueError('gpid must be string or two-element tuple') req._run_on_completion(self.__sub_del_reference, ref) return req
Make right subscription request depending on whether local or global - used by __sub*
entailment
def follow(self, gpid, callback=None, callback_parsed=None): """Create a subscription (i.e. follow) a Feed/Point with a global point id (gpid) and a feed data callback Returns a new [RemoteFeed](RemotePoint.m.html#IoticAgent.IOT.RemotePoint.RemoteFeed) object or the existing one if the subscription already exists - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `gpid` (required) (uuid) global id of the Point you want to follow `-OR-` `gpid` (required) (lid,pid) tuple of `(thing_localid, point_localid)` for local subscription `callback` (optional) (function reference) callback function to invoke on receipt of feed data. The callback receives a single dict argument, with keys of: #!python 'data' # (decoded or raw bytes) 'mime' # (None, unless payload was not decoded and has a mime type) 'pid' # (the global id of the feed from which the data originates) 'time' # (datetime representing UTC timestamp of share) `callback_parsed` (optional) (function reference) callback function to invoke on receipt of feed data. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. `NOTE`: `callback_parsed` can only be used if `auto_encode_decode` is enabled for the client instance. """ if callback_parsed: callback = self._client._get_parsed_feed_callback(callback_parsed, callback) return self.__sub(R_FEED, gpid, callback=callback)
Create a subscription (i.e. follow) a Feed/Point with a global point id (gpid) and a feed data callback Returns a new [RemoteFeed](RemotePoint.m.html#IoticAgent.IOT.RemotePoint.RemoteFeed) object or the existing one if the subscription already exists - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `gpid` (required) (uuid) global id of the Point you want to follow `-OR-` `gpid` (required) (lid,pid) tuple of `(thing_localid, point_localid)` for local subscription `callback` (optional) (function reference) callback function to invoke on receipt of feed data. The callback receives a single dict argument, with keys of: #!python 'data' # (decoded or raw bytes) 'mime' # (None, unless payload was not decoded and has a mime type) 'pid' # (the global id of the feed from which the data originates) 'time' # (datetime representing UTC timestamp of share) `callback_parsed` (optional) (function reference) callback function to invoke on receipt of feed data. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. `NOTE`: `callback_parsed` can only be used if `auto_encode_decode` is enabled for the client instance.
entailment
def list_connections(self, limit=500, offset=0): """List Points to which this Things is subscribed. I.e. list all the Points this Thing is following and controls it's attached to Returns subscription list e.g. #!python { "<Subscription GUID 1>": { "id": "<Control GUID>", "entityId": "<Control's Thing GUID>", "type": 3 # R_CONTROL from IoticAgent.Core.Const }, "<Subscription GUID 2>": { "id": "<Feed GUID>", "entityId": "<Feed's Thing GUID>", "type": 2 # R_FEED from IoticAgent.Core.Const } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure Note: For Things following a Point see [list_followers](./Point.m.html#IoticAgent.IOT.Point.Point.list_followers) """ evt = self._client._request_sub_list(self.__lid, limit=limit, offset=offset) self._client._wait_and_except_if_failed(evt) return evt.payload['subs']
List Points to which this Things is subscribed. I.e. list all the Points this Thing is following and controls it's attached to Returns subscription list e.g. #!python { "<Subscription GUID 1>": { "id": "<Control GUID>", "entityId": "<Control's Thing GUID>", "type": 3 # R_CONTROL from IoticAgent.Core.Const }, "<Subscription GUID 2>": { "id": "<Feed GUID>", "entityId": "<Feed's Thing GUID>", "type": 2 # R_FEED from IoticAgent.Core.Const } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure Note: For Things following a Point see [list_followers](./Point.m.html#IoticAgent.IOT.Point.Point.list_followers)
entailment
def _cb_created(self, payload, duplicated): """Indirect callback (via Client) for point & subscription creation responses""" if payload[P_RESOURCE] in _POINT_TYPE_TO_CLASS: store = self.__new_feeds if payload[P_RESOURCE] == R_FEED else self.__new_controls cls = _POINT_TYPE_TO_CLASS[payload[P_RESOURCE]] with store: store[payload[P_LID]] = cls(self._client, payload[P_ENTITY_LID], payload[P_LID], payload[P_ID]) logger.debug('Added %s: %s (for %s)', foc_to_str(payload[P_RESOURCE]), payload[P_LID], payload[P_ENTITY_LID]) elif payload[P_RESOURCE] == R_SUB: # local if P_POINT_ENTITY_LID in payload: key = (payload[P_POINT_TYPE], (payload[P_POINT_ENTITY_LID], payload[P_POINT_LID])) # global else: key = (payload[P_POINT_TYPE], payload[P_POINT_ID]) new_subs = self.__new_subs with new_subs: if key in new_subs: cls = RemoteFeed if payload[P_POINT_TYPE] == R_FEED else RemoteControl new_subs[key] = cls(self._client, payload[P_ID], payload[P_POINT_ID], payload[P_ENTITY_LID]) else: logger.warning('Ignoring subscription creation for unexpected %s: %s', foc_to_str(payload[P_POINT_TYPE]), key[1]) else: logger.error('Resource creation of type %d unhandled', payload[P_RESOURCE])
Indirect callback (via Client) for point & subscription creation responses
entailment
def wait(self, allowed_methods=None): """Wait for a method that matches our allowed_methods parameter (the default value of None means match any method), and dispatch to it.""" method_sig, args, content = self.connection._wait_method( self.channel_id, allowed_methods) return self.dispatch_method(method_sig, args, content)
Wait for a method that matches our allowed_methods parameter (the default value of None means match any method), and dispatch to it.
entailment
def get_recent(self, count): """Get the last instance(s) of feeddata from the feed. Useful if the remote Thing doesn't publish very often. Returns an iterable of dicts (in chronologically ascending order) containing: #!python 'data' # (decoded or raw bytes) 'mime' # (None, unless payload was not decoded and has a mime type) 'time' # (datetime representing UTC timestamp of share) `count` (mandatory) (integer) How many recent instances to retrieve. High values might be floored to a maximum as defined by the container. Note: Feed data is iterable as soon as it arrives, rather than when the request completes. """ queue = Queue() evt = self.get_recent_async(count, queue.put) timeout_time = monotonic() + self._client.sync_timeout while True: try: yield queue.get(True, .1) except Empty: if evt.is_set() or monotonic() >= timeout_time: break self._client._except_if_failed(evt)
Get the last instance(s) of feeddata from the feed. Useful if the remote Thing doesn't publish very often. Returns an iterable of dicts (in chronologically ascending order) containing: #!python 'data' # (decoded or raw bytes) 'mime' # (None, unless payload was not decoded and has a mime type) 'time' # (datetime representing UTC timestamp of share) `count` (mandatory) (integer) How many recent instances to retrieve. High values might be floored to a maximum as defined by the container. Note: Feed data is iterable as soon as it arrives, rather than when the request completes.
entailment
def get_recent_async(self, count, callback): """Similar to `get_recent` except instead of returning an iterable, passes each dict to the given function which must accept a single argument. Returns the request. `callback` (mandatory) (function) instead of returning an iterable, pass each dict (as described above) to the given function which must accept a single argument. Nothing is returned. """ validate_nonnegative_int(count, 'count') Validation.callable_check(callback, allow_none=True) evt = self._client._request_sub_recent(self.subid, count=count) self._client._add_recent_cb_for(evt, callback) return evt
Similar to `get_recent` except instead of returning an iterable, passes each dict to the given function which must accept a single argument. Returns the request. `callback` (mandatory) (function) instead of returning an iterable, pass each dict (as described above) to the given function which must accept a single argument. Nothing is returned.
entailment
def simulate(self, data, mime=None): """Simulate the arrival of feeddata into the feed. Useful if the remote Thing doesn't publish very often. `data` (mandatory) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime type of your data. See: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) """ self._client.simulate_feeddata(self.__pointid, data, mime)
Simulate the arrival of feeddata into the feed. Useful if the remote Thing doesn't publish very often. `data` (mandatory) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime type of your data. See: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share)
entailment
def ask(self, data, mime=None): """Request a remote control to do something. Ask is "fire-and-forget" in that you won't receive any notification of the success or otherwise of the action at the far end. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (as applicable) The data you want to share `mime` (optional) (string) The mime type of the data you're sharing. See: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) """ evt = self.ask_async(data, mime=mime) self._client._wait_and_except_if_failed(evt)
Request a remote control to do something. Ask is "fire-and-forget" in that you won't receive any notification of the success or otherwise of the action at the far end. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (as applicable) The data you want to share `mime` (optional) (string) The mime type of the data you're sharing. See: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share)
entailment
def tell(self, data, timeout=10, mime=None): """Order a remote control to do something. Tell is confirmed in that you will receive a notification of the success or otherwise of the action at the far end via a callback `Example` #!python data = {"thermostat":18.0} retval = r_thermostat.tell(data, timeout=10, mime=None) if retval is not True: print("Thermostat not reset - reason: {reason}".format(reason=retval)) Returns True on success or else returns the reason (string) one of: #!python "timeout" # The request-specified timeout has been reached. "unreachable" # The remote control is not associated with an agent # or is not reachable in some other way. "failed" # The remote control indicates it did not perform # the request. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (as applicable) The data you want to share `timeout` (optional) (int) Default 10. The delay in seconds before your tell request times out. `mime` (optional) (string) See: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) """ evt = self.tell_async(data, timeout=timeout, mime=mime) # No point in waiting longer than supplied timeout (as opposed to waiting for sync timeout) try: self._client._wait_and_except_if_failed(evt, timeout=timeout) except IOTSyncTimeout: return 'timeout' return True if evt.payload['success'] else evt.payload['reason']
Order a remote control to do something. Tell is confirmed in that you will receive a notification of the success or otherwise of the action at the far end via a callback `Example` #!python data = {"thermostat":18.0} retval = r_thermostat.tell(data, timeout=10, mime=None) if retval is not True: print("Thermostat not reset - reason: {reason}".format(reason=retval)) Returns True on success or else returns the reason (string) one of: #!python "timeout" # The request-specified timeout has been reached. "unreachable" # The remote control is not associated with an agent # or is not reachable in some other way. "failed" # The remote control indicates it did not perform # the request. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (as applicable) The data you want to share `timeout` (optional) (int) Default 10. The delay in seconds before your tell request times out. `mime` (optional) (string) See: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share)
entailment
def tell_async(self, data, timeout=10, mime=None): """Asyncronous version of [tell()](./RemotePoint.m.html#IoticAgent.IOT.RemotePoint.RemoteControl.tell) `Note` payload contains the success and reason keys they are not separated out as in the synchronous version """ logger.info("tell(timeout=%s) [subid=%s]", timeout, self.subid) if mime is None and isinstance(data, PointDataObject): data = data.to_dict() return self._client._request_sub_tell(self.subid, data, timeout, mime=mime)
Asyncronous version of [tell()](./RemotePoint.m.html#IoticAgent.IOT.RemotePoint.RemoteControl.tell) `Note` payload contains the success and reason keys they are not separated out as in the synchronous version
entailment
def rename(self, new_pid): """Rename the Point. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `new_pid` (required) (string) the new local identifier of your Point """ logger.info("rename(new_pid=\"%s\") [lid=%s, pid=%s]", new_pid, self.__lid, self.__pid) evt = self._client._request_point_rename(self._type, self.__lid, self.__pid, new_pid) self._client._wait_and_except_if_failed(evt) self.__pid = new_pid
Rename the Point. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `new_pid` (required) (string) the new local identifier of your Point
entailment
def list(self, limit=50, offset=0): """List `all` the values on this Point. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many value details `offset` (optional) (integer) Return value details starting at this offset """ logger.info("list(limit=%s, offset=%s) [lid=%s,pid=%s]", limit, offset, self.__lid, self.__pid) evt = self._client._request_point_value_list(self.__lid, self.__pid, self._type, limit=limit, offset=offset) self._client._wait_and_except_if_failed(evt) return evt.payload['values']
List `all` the values on this Point. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many value details `offset` (optional) (integer) Return value details starting at this offset
entailment
def list_followers(self): """list followers for this point, i.e. remote follows for feeds and remote attaches for controls. Returns QAPI subscription list function payload #!python { "<Subscription GUID 1>": "<GUID of follower1>", "<Subscription GUID 2>": "<GUID of follower2>" } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many value details `offset` (optional) (integer) Return value details starting at this offset """ evt = self._client._request_point_list_detailed(self._type, self.__lid, self.__pid) self._client._wait_and_except_if_failed(evt) return evt.payload['subs']
list followers for this point, i.e. remote follows for feeds and remote attaches for controls. Returns QAPI subscription list function payload #!python { "<Subscription GUID 1>": "<GUID of follower1>", "<Subscription GUID 2>": "<GUID of follower2>" } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return this many value details `offset` (optional) (integer) Return value details starting at this offset
entailment
def get_meta(self): """Get the metadata object for this Point Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure """ rdf = self.get_meta_rdf(fmt='n3') return PointMeta(self, rdf, self._client.default_lang, fmt='n3')
Get the metadata object for this Point Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure
entailment
def get_meta_rdf(self, fmt='n3'): """Get the metadata for this Point in rdf fmt Advanced users who want to manipulate the RDF for this Point directly without the [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) helper object Returns the RDF in the format you specify. - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `fmt` (optional) (string) The format of RDF you want returned. Valid formats are: "xml", "n3", "turtle" """ evt = self._client._request_point_meta_get(self._type, self.__lid, self.__pid, fmt=fmt) self._client._wait_and_except_if_failed(evt) return evt.payload['meta']
Get the metadata for this Point in rdf fmt Advanced users who want to manipulate the RDF for this Point directly without the [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) helper object Returns the RDF in the format you specify. - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `fmt` (optional) (string) The format of RDF you want returned. Valid formats are: "xml", "n3", "turtle"
entailment
def set_meta_rdf(self, rdf, fmt='n3'): """Set the metadata for this Point in rdf fmt """ evt = self._client._request_point_meta_set(self._type, self.__lid, self.__pid, rdf, fmt=fmt) self._client._wait_and_except_if_failed(evt)
Set the metadata for this Point in rdf fmt
entailment
def create_tag(self, tags): """Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters and the underscore. Tags will be stored lower-cased. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure tags (mandatory) (list) - the list of tags you want to add to your Point, e.g. ["garden", "soil"] """ if isinstance(tags, str): tags = [tags] evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=False) self._client._wait_and_except_if_failed(evt)
Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters and the underscore. Tags will be stored lower-cased. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure tags (mandatory) (list) - the list of tags you want to add to your Point, e.g. ["garden", "soil"]
entailment
def delete_tag(self, tags): """Delete tags for a Point in the language you specify. Case will be ignored and any tags matching lower-cased will be deleted. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `tags` (mandatory) (list) - the list of tags you want to delete from your Point, e.g. ["garden", "soil"] """ if isinstance(tags, str): tags = [tags] evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=True) self._client._wait_and_except_if_failed(evt)
Delete tags for a Point in the language you specify. Case will be ignored and any tags matching lower-cased will be deleted. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `tags` (mandatory) (list) - the list of tags you want to delete from your Point, e.g. ["garden", "soil"]
entailment
def list_tag(self, limit=50, offset=0): """List `all` the tags for this Point Returns list of tags, as below #!python [ "mytag1", "mytag2" "ein_name", "nochein_name" ] - OR... Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return at most this many tags `offset` (optional) (integer) Return tags starting at this offset """ evt = self._client._request_point_tag_list(self._type, self.__lid, self.__pid, limit=limit, offset=offset) self._client._wait_and_except_if_failed(evt) return evt.payload['tags']
List `all` the tags for this Point Returns list of tags, as below #!python [ "mytag1", "mytag2" "ein_name", "nochein_name" ] - OR... Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `limit` (optional) (integer) Return at most this many tags `offset` (optional) (integer) Return tags starting at this offset
entailment
def create_value(self, label, vtype, lang=None, description=None, unit=None): """Create a value on this Point. Values are descriptions in semantic metadata of the individual data items you are sharing (or expecting to receive, if this Point is a control). This will help others to search for your feed or control. If a value with the given label (and language) already exists, its fields are updated with the provided ones (or unset, if None). Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `label` (mandatory) (string) the label for this value e.g. "Temperature". The label must be unique for this Point. E.g. You can't have two data values called "Volts" but you can have "volts1" and "volts2". `lang` (optional) (string) The two-character ISO 639-1 language code to use for the description. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) `vtype` (mandatory) (xsd:datatype) the datatype of the data you are describing, e.g. dateTime We recommend you use a Iotic Labs-defined constant from [Datatypes](../Datatypes.m.html#IoticAgent.Datatypes.Datatypes) such as: [DECIMAL](../Datatypes.m.html#IoticAgent.Datatypes.DECIMAL) `description` (optional) (string) The longer descriptive text for this value. `unit` (optional) (ontology url) The url of the ontological description of the unit of your value We recommend you use a constant from [Units](../Units.m.html#IoticAgent.Units.Units), such as: [CELSIUS](../Units.m.html#IoticAgent.Units.Units.CELSIUS) #!python # example with no units as time is unit-less my_feed.create_value("timestamp", Datatypes.DATETIME, "en", "time of reading") # example with a unit from the Units class my_feed.create_value("temperature", Datatypes.DECIMAL, "en", "Fish-tank temperature in celsius", Units.CELSIUS) """ evt = self._client._request_point_value_create(self.__lid, self.__pid, self._type, label, vtype, lang, description, unit) self._client._wait_and_except_if_failed(evt)
Create a value on this Point. Values are descriptions in semantic metadata of the individual data items you are sharing (or expecting to receive, if this Point is a control). This will help others to search for your feed or control. If a value with the given label (and language) already exists, its fields are updated with the provided ones (or unset, if None). Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `label` (mandatory) (string) the label for this value e.g. "Temperature". The label must be unique for this Point. E.g. You can't have two data values called "Volts" but you can have "volts1" and "volts2". `lang` (optional) (string) The two-character ISO 639-1 language code to use for the description. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) `vtype` (mandatory) (xsd:datatype) the datatype of the data you are describing, e.g. dateTime We recommend you use a Iotic Labs-defined constant from [Datatypes](../Datatypes.m.html#IoticAgent.Datatypes.Datatypes) such as: [DECIMAL](../Datatypes.m.html#IoticAgent.Datatypes.DECIMAL) `description` (optional) (string) The longer descriptive text for this value. `unit` (optional) (ontology url) The url of the ontological description of the unit of your value We recommend you use a constant from [Units](../Units.m.html#IoticAgent.Units.Units), such as: [CELSIUS](../Units.m.html#IoticAgent.Units.Units.CELSIUS) #!python # example with no units as time is unit-less my_feed.create_value("timestamp", Datatypes.DATETIME, "en", "time of reading") # example with a unit from the Units class my_feed.create_value("temperature", Datatypes.DECIMAL, "en", "Fish-tank temperature in celsius", Units.CELSIUS)
entailment
def delete_value(self, label=None): """Delete the labelled value (or all values) on this Point Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `label` (optional) (string) the label for the value you want to delete. If not specified, all values for this point will be removed. """ evt = self._client._request_point_value_delete(self.__lid, self.__pid, self._type, label=label) self._client._wait_and_except_if_failed(evt)
Delete the labelled value (or all values) on this Point Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `label` (optional) (string) the label for the value you want to delete. If not specified, all values for this point will be removed.
entailment
def share(self, data, mime=None, time=None): """Share some data from this Feed Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (as applicable) The data you want to share `mime` (optional) (string) The mime type of the data you're sharing. There are some Iotic Labs-defined default values: `"idx/1"` - Corresponds to "application/ubjson" - the recommended way to send mixed data. Share a python dictionary as the data and the agent will to the encoding and decoding for you. #!python data = {} data["temperature"] = self._convert_to_celsius(ADC.read(1)) # ...etc... my_feed.share(data) `"idx/2"` Corresponds to "text/plain" - the recommended way to send textual data. Share a utf8 string as data and the agent will pass it on, unchanged. #!python my_feed.share(u"string data") `"text/xml"` or any other valid mime type. To show the recipients that you're sending something more than just bytes #!python my_feed.share("<xml>...</xml>".encode('utf8'), mime="text/xml") `time` (optional) (datetime) UTC time for this share. If not specified, the container's time will be used. Thus it makes almost no sense to specify `datetime.utcnow()` here. This parameter can be used to indicate that the share time does not correspond to the time to which the data applies, e.g. to populate recent storgage with historical data. """ evt = self.share_async(data, mime=mime, time=time) self._client._wait_and_except_if_failed(evt)
Share some data from this Feed Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (as applicable) The data you want to share `mime` (optional) (string) The mime type of the data you're sharing. There are some Iotic Labs-defined default values: `"idx/1"` - Corresponds to "application/ubjson" - the recommended way to send mixed data. Share a python dictionary as the data and the agent will to the encoding and decoding for you. #!python data = {} data["temperature"] = self._convert_to_celsius(ADC.read(1)) # ...etc... my_feed.share(data) `"idx/2"` Corresponds to "text/plain" - the recommended way to send textual data. Share a utf8 string as data and the agent will pass it on, unchanged. #!python my_feed.share(u"string data") `"text/xml"` or any other valid mime type. To show the recipients that you're sending something more than just bytes #!python my_feed.share("<xml>...</xml>".encode('utf8'), mime="text/xml") `time` (optional) (datetime) UTC time for this share. If not specified, the container's time will be used. Thus it makes almost no sense to specify `datetime.utcnow()` here. This parameter can be used to indicate that the share time does not correspond to the time to which the data applies, e.g. to populate recent storgage with historical data.
entailment
def get_recent_info(self): """Retrieves statistics and configuration about recent storage for this Feed. Returns QAPI recent info function payload #!python { "maxSamples": 0, "count": 0 } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure """ evt = self._client._request_point_recent_info(self._type, self.lid, self.pid) self._client._wait_and_except_if_failed(evt) return evt.payload['recent']
Retrieves statistics and configuration about recent storage for this Feed. Returns QAPI recent info function payload #!python { "maxSamples": 0, "count": 0 } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure
entailment
def set_recent_config(self, max_samples=0): """Update/configure recent data settings for this Feed. If the container does not support recent storage or it is not enabled for this owner, this function will have no effect. `max_samples` (optional) (int) how many shares to store for later retrieval. If not supported by container, this argument will be ignored. A value of zero disables this feature whilst a negative value requests the maximum sample store amount. Returns QAPI recent config function payload #!python { "maxSamples": 0 } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure """ evt = self._client._request_point_recent_config(self._type, self.lid, self.pid, max_samples) self._client._wait_and_except_if_failed(evt) return evt.payload
Update/configure recent data settings for this Feed. If the container does not support recent storage or it is not enabled for this owner, this function will have no effect. `max_samples` (optional) (int) how many shares to store for later retrieval. If not supported by container, this argument will be ignored. A value of zero disables this feature whilst a negative value requests the maximum sample store amount. Returns QAPI recent config function payload #!python { "maxSamples": 0 } Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure
entailment
def filter_by(self, text=(), types=(), units=(), include_unset=False): """Return subset of values which match the given text, types and/or units. For a value to be matched, at least one item from each specified filter category has to apply to a value. Each of the categories must be specified as a sequence of strings. If `include_unset` is set, unset values will also be considered.""" if not (isinstance(text, Sequence) and all(isinstance(phrase, string_types) for phrase in text)): raise TypeError('text should be sequence of strings') values = ([self.__values[name] for name in self.__filter.filter_by(types=types, units=units) if include_unset or not self.__values[name].unset] if types or units else self.__values) if text: # avoid unexpected search by individual characters if a single string was specified if isinstance(text, string_types): text = (ensure_unicode(text),) text = [phrase.lower() for phrase in text] new_values = [] for value in values: label = value.label.lower() description = value.description.lower() if value.description else '' if any(phrase in label or (description and phrase in description) for phrase in text): new_values.append(value) values = new_values return values
Return subset of values which match the given text, types and/or units. For a value to be matched, at least one item from each specified filter category has to apply to a value. Each of the categories must be specified as a sequence of strings. If `include_unset` is set, unset values will also be considered.
entailment
def to_dict(self): """Converts the set of values into a dictionary. Unset values are excluded.""" return {value.label: value.value for value in self.__values if not value.unset}
Converts the set of values into a dictionary. Unset values are excluded.
entailment
def _from_dict(cls, values, value_filter, dictionary, allow_unset=True): """Instantiates new PointDataObject, populated from the given dictionary. With allow_unset=False, a ValueError will be raised if any value has not been set. Used by PointDataObjectHandler""" if not isinstance(dictionary, Mapping): raise TypeError('dictionary should be mapping') obj = cls(values, value_filter) values = obj.__values for name, value in dictionary.items(): if not isinstance(name, string_types): raise TypeError('Key %s is not a string' % str(name)) setattr(values, name, value) if obj.missing and not allow_unset: raise ValueError('%d value(s) are unset' % len(obj.missing)) return obj
Instantiates new PointDataObject, populated from the given dictionary. With allow_unset=False, a ValueError will be raised if any value has not been set. Used by PointDataObjectHandler
entailment
def set(self): """Pushes the RDF metadata description back to the infrastructure. This will be searchable if you have called [set_public()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.set_public) at any time `Example 1` Use of python `with` syntax and XXXXmeta class. `Recommended` #!python # using with calls set() for you so you don't forget with thing_solar_panels.get_meta() as meta_thing_solar_panels: meta_thing_solar_panels.set_label("Mark's Solar Panels") meta_thing_solar_panels.set_description("Solar Array 3.3kW") meta_thing_solar_panels.set_location(52.1965071,0.6067687) `Example 2` Explicit use of set #!python meta_thing_solar_panels = thing_solar_panels.get_meta() meta_thing_solar_panels.set_label("Mark's Solar Panels") meta_thing_solar_panels.set_description("Solar Array 3.3kW") meta_thing_solar_panels.set_location(52.1965071,0.6067687) meta_thing_solar_panels.set() Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure Raises rdflib.plugins.parsers.notation3.`BadSyntax` Exception if the RDF is badly formed `n3` Raises xml.sax._exceptions.`SAXParseException` if the RDF is badly formed `xml` """ self.__parent.set_meta_rdf(self._graph.serialize(format=self.__fmt).decode('utf8'), fmt=self.__fmt)
Pushes the RDF metadata description back to the infrastructure. This will be searchable if you have called [set_public()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.set_public) at any time `Example 1` Use of python `with` syntax and XXXXmeta class. `Recommended` #!python # using with calls set() for you so you don't forget with thing_solar_panels.get_meta() as meta_thing_solar_panels: meta_thing_solar_panels.set_label("Mark's Solar Panels") meta_thing_solar_panels.set_description("Solar Array 3.3kW") meta_thing_solar_panels.set_location(52.1965071,0.6067687) `Example 2` Explicit use of set #!python meta_thing_solar_panels = thing_solar_panels.get_meta() meta_thing_solar_panels.set_label("Mark's Solar Panels") meta_thing_solar_panels.set_description("Solar Array 3.3kW") meta_thing_solar_panels.set_location(52.1965071,0.6067687) meta_thing_solar_panels.set() Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure Raises rdflib.plugins.parsers.notation3.`BadSyntax` Exception if the RDF is badly formed `n3` Raises xml.sax._exceptions.`SAXParseException` if the RDF is badly formed `xml`
entailment
def update(self): """Gets the latest version of your metadata from the infrastructure and updates your local copy Returns `True` if successful, `False` otherwise - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure """ graph = Graph() graph.parse(data=self.__parent.get_meta_rdf(fmt=self.__fmt), format=self.__fmt) self._graph = graph
Gets the latest version of your metadata from the infrastructure and updates your local copy Returns `True` if successful, `False` otherwise - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure
entailment
def set_label(self, label, lang=None): """Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any other labels in this language are removed before adding this one Raises `ValueError` containing an error message if the parameters fail validation `label` (mandatory) (string) the new text of the label `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) """ label = Validation.label_check_convert(label) lang = Validation.lang_check_convert(lang, default=self._default_lang) # remove any other labels with this language before adding self.delete_label(lang) subj = self._get_uuid_uriref() self._graph.add((subj, self._labelPredicate, Literal(label, lang)))
Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any other labels in this language are removed before adding this one Raises `ValueError` containing an error message if the parameters fail validation `label` (mandatory) (string) the new text of the label `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
entailment
def delete_label(self, lang=None): """Deletes all the `label` metadata properties on your Thing/Point for this language Raises `ValueError` containing an error message if the parameters fail validation `lang` (optional) (string) The two-character ISO 639-1 language code to identify your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) """ self._remove_properties_by_language(self._labelPredicate, Validation.lang_check_convert(lang, default=self._default_lang))
Deletes all the `label` metadata properties on your Thing/Point for this language Raises `ValueError` containing an error message if the parameters fail validation `lang` (optional) (string) The two-character ISO 639-1 language code to identify your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
entailment
def set_description(self, description, lang=None): """Sets the `description` metadata property on your Thing/Point. Only one description is allowed per language, so any other descriptions in this language are removed before adding this one Raises `ValueError` containing an error message if the parameters fail validation `description` (mandatory) (string) the new text of the description `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) """ description = Validation.description_check_convert(description) lang = Validation.lang_check_convert(lang, default=self._default_lang) # remove any other descriptions with this language before adding self.delete_description(lang) subj = self._get_uuid_uriref() self._graph.add((subj, self._commentPredicate, Literal(description, lang)))
Sets the `description` metadata property on your Thing/Point. Only one description is allowed per language, so any other descriptions in this language are removed before adding this one Raises `ValueError` containing an error message if the parameters fail validation `description` (mandatory) (string) the new text of the description `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
entailment
def delete_description(self, lang=None): """Deletes all the `label` metadata properties on your Thing/Point for this language Raises `ValueError` containing an error message if the parameters fail validation `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) """ self._remove_properties_by_language(self._commentPredicate, Validation.lang_check_convert(lang, default=self._default_lang))
Deletes all the `label` metadata properties on your Thing/Point for this language Raises `ValueError` containing an error message if the parameters fail validation `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label. None means use the default language for your agent. See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
entailment
def bool_from(obj, default=False): """Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is None, 'default' is used. """ return str(obj).lower() not in ('0', 'false') if obj is not None else bool(default)
Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is None, 'default' is used.
entailment
def private_name_for(var_name, cls): """Returns mangled variable name (if applicable) for the given variable and class instance. See https://docs.python.org/3/tutorial/classes.html#private-variables""" if not (isinstance(var_name, string_types) and var_name): raise TypeError('var_name must be non-empty string') if not (isinstance(cls, type) or isinstance(cls, string_types)): # pylint: disable=consider-merging-isinstance raise TypeError('cls not a class or string') if __PRIVATE_NAME_PATTERN.match(var_name): class_name = cls.__name__ if isinstance(cls, type) else cls return '_%s%s' % (class_name.lstrip('_'), var_name) else: return var_name
Returns mangled variable name (if applicable) for the given variable and class instance. See https://docs.python.org/3/tutorial/classes.html#private-variables
entailment
def private_names_for(cls, names): """Returns iterable of private names using privateNameFor()""" if not isinstance(names, Iterable): raise TypeError('names must be an interable') return (private_name_for(item, cls) for item in names)
Returns iterable of private names using privateNameFor()
entailment
def acquire(self, blocking=True, timeout=-1): """Acquire a lock, blocking or non-blocking. Blocks until timeout, if timeout a positive float and blocking=True. A timeout value of -1 blocks indefinitely, unless blocking=False.""" if not isinstance(timeout, (int, float)): raise TypeError('a float is required') if blocking: # blocking indefinite if timeout == -1: with self.__condition: while not self.__lock.acquire(False): # condition with timeout is interruptable self.__condition.wait(60) return True # same as non-blocking elif timeout == 0: return self.__lock.acquire(False) elif timeout < 0: raise ValueError('timeout value must be strictly positive (or -1)') # blocking finite else: start = time() waited_time = 0 with self.__condition: while waited_time < timeout: if self.__lock.acquire(False): return True else: self.__condition.wait(timeout - waited_time) waited_time = time() - start return False elif timeout != -1: raise ValueError('can\'t specify a timeout for a non-blocking call') else: # non-blocking return self.__lock.acquire(False)
Acquire a lock, blocking or non-blocking. Blocks until timeout, if timeout a positive float and blocking=True. A timeout value of -1 blocks indefinitely, unless blocking=False.
entailment
def release(self): """Release a lock.""" self.__lock.release() with self.__condition: self.__condition.notify()
Release a lock.
entailment
def set_config(self, config): ''' Set launch data from a ToolConfig. ''' if self.launch_url == None: self.launch_url = config.launch_url self.custom_params.update(config.custom_params)
Set launch data from a ToolConfig.
entailment
def has_required_params(self): ''' Check if required parameters for a tool launch are set. ''' return self.consumer_key and\ self.consumer_secret and\ self.resource_link_id and\ self.launch_url
Check if required parameters for a tool launch are set.
entailment
def _sent_without_response(self, send_time_before): """Used internally to determine whether the request has not received any response from the container and was send before the given time. Unsent requests are not considered.""" return not self._messages and self._send_time and self._send_time < send_time_before
Used internally to determine whether the request has not received any response from the container and was send before the given time. Unsent requests are not considered.
entailment
def is_set(self): """Returns True if the request has finished or False if it is still pending. Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a network related problem. """ if self.__event.is_set(): if self.exception is not None: # todo better way to raise errors on behalf of other Threads? raise self.exception # pylint: disable=raising-bad-type return True return False
Returns True if the request has finished or False if it is still pending. Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a network related problem.
entailment
def _set(self): """Called internally by Client to indicate this request has finished""" self.__event.set() if self._complete_func: self.__run_completion_func(self._complete_func, self.id_)
Called internally by Client to indicate this request has finished
entailment
def _run_on_completion(self, func, *args, **kwargs): """Function to call when request has finished, after having been _set(). The first argument passed to func will be the request itself. Additional parameters are NOT validated. If the request is already finished, the given function will be run immediately (in same thread). """ if self._complete_func is not None: raise ValueError('Completion function already set for %s: %s' % (self.id_, self._complete_func)) if not self.__event.is_set(): self._complete_func = partial(func, self, *args, **kwargs) else: self.__run_completion_func(partial(func, self, *args, **kwargs), self.id_)
Function to call when request has finished, after having been _set(). The first argument passed to func will be the request itself. Additional parameters are NOT validated. If the request is already finished, the given function will be run immediately (in same thread).
entailment
def wait(self, timeout=None): """Wait for the request to finish, optionally timing out. Returns True if the request has finished or False if it is still pending. Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a network related problem. """ if self.__event.wait(timeout): if self.exception is not None: # todo better way to raise errors on behalf of other Threads? raise self.exception # pylint: disable=raising-bad-type return True return False
Wait for the request to finish, optionally timing out. Returns True if the request has finished or False if it is still pending. Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a network related problem.
entailment