code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return self.create_developer_certificate_with_http_info(authorization, body, **kwargs) # noqa: E501 else: (data) = self.create_developer_certificate_with_http_info(authorization, body, **kwargs) # noqa: E501 return data
def create_developer_certificate(self, authorization, body, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Create a new developer certificate to connect to the bootstrap server. # noqa: E501 This REST API is intended to be used by customers to get a developer certificate (a certificate that can be flashed into multiple devices to connect to bootstrap server). **Note:** The number of developer certificates allowed per account is limited. Please see [Using your own certificate authority](/docs/current/mbed-cloud-deploy/instructions-for-factory-setup-and-device-provision.html#using-your-own-certificate-authority-with-mbed-cloud). **Example usage:** curl -X POST \"http://api.us-east-1.mbedcloud.com/v3/developer-certificates\" -H \"accept: application/json\" -H \"Authorization: Bearer THE_ACCESS_TOKEN\" -H \"content-type: application/json\" -d \"{ \\\"name\\\": \\\"THE_CERTIFICATE_NAME\\\", \\\"description\\\": \\\"THE_CERTIFICATE_DESCRIPTION\\\"}\" # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.create_developer_certificate(authorization, body, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str authorization: Bearer {Access Token}. (required) :param DeveloperCertificateRequestData body: (required) :return: DeveloperCertificateResponseData If the method is called asynchronously, returns the request thread.
1.564859
2.059015
0.760004
return self.get_developer_certificate_with_http_info(developer_certificate_id, authorization, **kwargs) # noqa: E501 else: (data) = self.get_developer_certificate_with_http_info(developer_certificate_id, authorization, **kwargs) # noqa: E501 return data
def get_developer_certificate(self, developer_certificate_id, authorization, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Fetch an existing developer certificate to connect to the bootstrap server. # noqa: E501 This REST API is intended to be used by customers to fetch an existing developer certificate (a certificate that can be flashed into multiple devices to connect to bootstrap server). **Example usage:** curl -X GET \"http://api.us-east-1.mbedcloud.com/v3/developer-certificates/THE_CERTIFICATE_ID\" -H \"accept: application/json\" -H \"Authorization: Bearer THE_ACCESS_TOKEN\" # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_developer_certificate(developer_certificate_id, authorization, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str developer_certificate_id: A unique identifier for the developer certificate. (required) :param str authorization: Bearer {Access Token}. (required) :return: DeveloperCertificateResponseData If the method is called asynchronously, returns the request thread.
1.486633
1.883991
0.789087
if month is None: raise ValueError("Invalid value for `month`, must not be `None`") if month is not None and not re.search('^\\d{4}-\\d{2}$', month): raise ValueError("Invalid value for `month`, must be a follow pattern or equal to `/^\\d{4}-\\d{2}$/`") self._month = month
def month(self, month)
Sets the month of this ReportResponse. Month of requested billing report :param month: The month of this ReportResponse. :type: str
1.72508
1.568205
1.100035
return self.create_certificate_issuer_config_with_http_info(create_certificate_issuer_config, **kwargs) # noqa: E501 else: (data) = self.create_certificate_issuer_config_with_http_info(create_certificate_issuer_config, **kwargs) # noqa: E501 return data
def create_certificate_issuer_config(self, create_certificate_issuer_config, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Create certificate issuer configuration. # noqa: E501 Configure the certificate issuer to be used when creating the device custom certificates. <br> **Example usage:** ``` curl -X POST \\ -H 'authorization: <valid access token>' \\ -H 'content-type: application/json;charset=UTF-8' \\ https://api.us-east-1.mbedcloud.com/v3/certificate-issuer-configurations \\ -d '{ \"reference\": \"customer.dlms\", \"certificate_issuer_id\": \"01621a36719d507b9d48a91b00000000\" }' ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.create_certificate_issuer_config(create_certificate_issuer_config, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param CreateCertificateIssuerConfig create_certificate_issuer_config: Certificate issuer configuration request (required) :return: CertificateIssuerConfigResponse If the method is called asynchronously, returns the request thread.
1.458927
1.983205
0.735641
return self.delete_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs) # noqa: E501 else: (data) = self.delete_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs) # noqa: E501 return data
def delete_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Delete certificate issuer configuration. # noqa: E501 Delete the configured certificate issuer configuration. You can only delete the configurations of custom certificates. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.delete_certificate_issuer_config_by_id(certificate_issuer_configuration_id, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str certificate_issuer_configuration_id: The ID of the certificate issuer configuration. (required) :return: None If the method is called asynchronously, returns the request thread.
1.417825
1.788665
0.792672
return self.get_certificate_issuer_config_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_certificate_issuer_config_with_http_info(**kwargs) # noqa: E501 return data
def get_certificate_issuer_config(self, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Get certificate issuer configuration. # noqa: E501 Provides the configured certificate issuer to be used when creating device certificates for LwM2M communication.<br> # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_certificate_issuer_config(asynchronous=True) >>> result = thread.get() :param asynchronous bool :return: CertificateIssuerConfigResponse If the method is called asynchronously, returns the request thread.
1.611241
2.07392
0.776906
return self.get_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs) # noqa: E501 else: (data) = self.get_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs) # noqa: E501 return data
def get_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Get certificate issuer configuration. # noqa: E501 Provides the configured certificate issuer. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_certificate_issuer_config_by_id(certificate_issuer_configuration_id, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str certificate_issuer_configuration_id: The ID of the certificate issuer configuration. (required) :return: CertificateIssuerConfigResponse If the method is called asynchronously, returns the request thread.
1.420715
1.791735
0.792927
return self.get_certificate_issuer_configs_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_certificate_issuer_configs_with_http_info(**kwargs) # noqa: E501 return data
def get_certificate_issuer_configs(self, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Get certificate issuer configurations. # noqa: E501 Get certificate issuer configurations, optionally filtered by reference. <br> **Example usage:** ``` curl \\ -H 'authorization: <valid access token>' \\ -H 'content-type: application/json;charset=UTF-8' \\ https://api.us-east-1.mbedcloud.com/v3/certificate-issuer-configurations \\ ``` ``` curl \\ -H 'authorization: <valid access token>' \\ -H 'content-type: application/json;charset=UTF-8' \\ https://api.us-east-1.mbedcloud.com/v3/certificate-issuer-configurations?reference__eq=dlms \\ ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_certificate_issuer_configs(asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str reference__eq: The certificate name to which the certificate issuer configuration applies. :return: CertificateIssuerConfigListResponse If the method is called asynchronously, returns the request thread.
1.614049
2.203791
0.732397
return self.update_certificate_issuer_config_with_http_info(certificate_issuer_config_request, **kwargs) # noqa: E501 else: (data) = self.update_certificate_issuer_config_with_http_info(certificate_issuer_config_request, **kwargs) # noqa: E501 return data
def update_certificate_issuer_config(self, certificate_issuer_config_request, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Update certificate issuer configuration. # noqa: E501 Configure the certificate issuer to be used when creating device certificates for LwM2M communication. <br> **Example usage:** ``` curl -X PUT \\ -H 'authorization: <valid access token>' \\ -H 'content-type: application/json;charset=UTF-8' \\ https://api.us-east-1.mbedcloud.com/v3/certificate-issuer-configurations/lwm2m \\ -d '{ \"certificate_issuer_id\": \"01621a36719d507b9d48a91b00000000\" }' ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.update_certificate_issuer_config(certificate_issuer_config_request, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param CertificateIssuerConfigRequest certificate_issuer_config_request: Certificate Issuer Configuration Request (required) :return: CertificateIssuerConfigResponse If the method is called asynchronously, returns the request thread.
1.496701
2.038493
0.734219
return self.update_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, certificate_issuer_config_request, **kwargs) # noqa: E501 else: (data) = self.update_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, certificate_issuer_config_request, **kwargs) # noqa: E501 return data
def update_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, certificate_issuer_config_request, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Update certificate issuer configuration. # noqa: E501 Update the configured certificate issuer configuration. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.update_certificate_issuer_config_by_id(certificate_issuer_configuration_id, certificate_issuer_config_request, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str certificate_issuer_configuration_id: The ID of the certificate issuer configuration. (required) :param CertificateIssuerConfigRequest certificate_issuer_config_request: Certificate issuer configuration request (required) :return: CertificateIssuerConfigResponse If the method is called asynchronously, returns the request thread.
1.377834
1.619368
0.850847
if active_devices is None: raise ValueError("Invalid value for `active_devices`, must not be `None`") if active_devices is not None and active_devices < 0: raise ValueError("Invalid value for `active_devices`, must be a value greater than or equal to `0`") self._active_devices = active_devices
def active_devices(self, active_devices)
Sets the active_devices of this ReportBillingData. :param active_devices: The active_devices of this ReportBillingData. :type: int
1.64216
1.554548
1.056359
if firmware_updates is None: raise ValueError("Invalid value for `firmware_updates`, must not be `None`") if firmware_updates is not None and firmware_updates < 0: raise ValueError("Invalid value for `firmware_updates`, must be a value greater than or equal to `0`") self._firmware_updates = firmware_updates
def firmware_updates(self, firmware_updates)
Sets the firmware_updates of this ReportBillingData. :param firmware_updates: The firmware_updates of this ReportBillingData. :type: int
1.653292
1.530564
1.080185
last_known = '0' if os.path.isfile(metafile): with open(metafile) as fh: last_known = fh.read() import mbed_cloud current = mbed_cloud.__version__ # how significant a change in version scheme should trigger a new changelog entry # (api major, api minor, sdk major, sdk minor, sdk patch) sigfigs = 4 current_version = LooseVersion(current).version last_known_version = LooseVersion(last_known).version should_towncrier = current_version[:sigfigs] != last_known_version[:sigfigs] print('%s -- %s :: current vs previous changelog build' % (current, last_known)) if should_towncrier: print('%s >> %s :: running changelog build' % (current, last_known)) subprocess.check_call( ['towncrier', '--yes'], cwd=os.path.join(PROJECT_ROOT, 'docs', 'changelog') ) with open(metafile, 'w') as fh: fh.write(current)
def main()
Writes out newsfile if significant version bump
4.585385
4.349026
1.054347
filename = '.mbed_cloud_config.json' return [ # Global config in /etc for *nix users "/etc/%s" % filename, # Config file in home directory os.path.join(os.path.expanduser("~"), filename), # Config file in current directory os.path.join(os.getcwd(), filename), # Config file specified using environment variable os.environ.get(self.path_from_env_key) ]
def paths(self)
Get list of paths to look in for configuration data
5.116341
4.435963
1.153378
# Go through in order and override the config (`.mbed_cloud_config.json` loader) for path in self.paths(): if not path: continue abs_path = os.path.abspath(os.path.expanduser(path)) if not os.path.isfile(abs_path): self._using_paths.append('missing: %s' % abs_path) continue self._using_paths.append(' exists: %s' % abs_path) with open(abs_path) as fh: self.update(json.load(fh)) # New dotenv loader - requires explicit instructions to use current working directory load_dotenv(find_dotenv(usecwd=True)) # Pluck config values out of the environment for env_var, key in {ENVVAR_API_HOST: 'host', ENVVAR_API_KEY: 'api_key'}.items(): env_value = os.getenv(env_var) if env_value is not None: self[key] = env_value if updates: self.update(updates) self.validate()
def load(self, updates)
Load configuration data
4.27637
4.273951
1.000566
if not self.get('api_key'): raise ValueError("api_key not found in config. Please see documentation.") host = self.get('host') or DEFAULT_CLOUD_HOST if host: # remove extraneous slashes and force to byte string # otherwise msg += message_body in httplib will fail in python2 # when message_body contains binary data, and url is unicode # remaining failure modes include at least: # passing bytes in python3 will fail as we try to strip unicode '/' characters # passing unicode code points in python2 will fail due to httplib host.encode('ascii') host = host.strip('/') if not isinstance(host, str): host = host.encode('utf-8') self['host'] = host self.setdefault('autostart_notification_thread', True)
def validate(self)
Validate / fix up the current config
12.31094
12.041867
1.022345
to_product = [] for key, values in sorted(d.items()): # if we sort the inputs here, itertools.product will keep a stable sort order for us later key_values = sorted([(key, v) for v in utils.ensure_listable(values) if v is not None]) if key_values: to_product.append(key_values) return list(itertools.product(*to_product))
def expand_dict_as_keys(d)
Expands a dictionary into a list of immutables with cartesian product :param d: dictionary (of strings or lists) :returns: cartesian product of list parts
5.764772
5.733288
1.005491
for route in routes: self._routes.setdefault(route, set()).add(item) return item
def create_route(self, item, routes)
Stores a new item in routing map
4.802633
4.203586
1.142509
for route in routes: items = self._routes.get(route) try: items.remove(item) LOG.debug('removed item from route %s', route) except ValueError: pass if not items: self._routes.pop(route) LOG.debug('removed route %s', route)
def remove_routes(self, item, routes)
Removes item from matching routes
2.501112
2.387211
1.047713
return list(set( item for items in self._routes.values() for item in items ))
def list_all(self)
All items
10.242002
9.602864
1.066557
keys = subscription_channel.get_routing_keys() # watch keys are unique sets of keys that we will attempt to extract from inbound items self.watch_keys.add(frozenset({k_v[0] for key in keys for k_v in key})) self.create_route(subscription_channel, keys) subscription_channel._configure(self, self.connect_api, observer_params) return subscription_channel
def get_channel(self, subscription_channel, **observer_params)
Get or start the requested channel
9.423124
9.132936
1.031774
return self.get_channel(subscription_channel, **observer_params).ensure_started().observer
def subscribe(self, subscription_channel, **observer_params)
Subscribe to a channel This adds a channel to the router, configures it, starts it, and returns its observer
10.429105
8.451774
1.233955
# channels that this individual item has already triggered # (dont want to trigger them again) triggered_channels = set() for key_set in self.watch_keys: # only pluck keys if they exist plucked = { key_name: item[key_name] for key_name in key_set if key_name in item } route_keys = expand_dict_as_keys(plucked) for route in route_keys: channels = self.get_route_items(route) or {} LOG.debug('route table match: %s -> %s', route, channels) if not channels: LOG.debug( 'no subscribers for message.\nkey %s\nroutes: %s', route, self._routes ) for channel in channels: if channel in triggered_channels: LOG.debug('skipping dispatch to %s', channel) continue LOG.debug('routing dispatch to %s: %s', channel, item) try: channel.notify(item) and triggered_channels.add(channel) except Exception: # noqa LOG.exception('Channel notification failed') return triggered_channels
def _notify_single_item(self, item)
Route inbound items to individual channels
4.984571
4.665235
1.06845
triggered_channels = [] for channel_name, items in data.items(): for item in items or []: LOG.debug('notify received: %s', item) try: # some channels return strings rather than objects (e.g. de-registrations), # normalize them here item = {'value': item} if isinstance(item, six.string_types) else dict(item) # inject the channel name to the data (so channels can filter on it) item['channel'] = channel_name triggered_channels.extend(list(self._notify_single_item(item))) except Exception: # noqa LOG.exception('Subscription notification failed') return triggered_channels
def notify(self, data)
Notify subscribers that data was received
5.471972
5.438836
1.006092
for channel in self.list_all(): channel.ensure_stopped() self.connect_api.stop_notifications()
def unsubscribe_all(self)
Unsubscribes all channels
18.050678
16.490755
1.094594
if type is None: raise ValueError("Invalid value for `type`, must not be `None`") allowed_values = ["reservation", "reservation_release", "reservation_termination", "package_renewal", "package_creation", "package_termination"] if type not in allowed_values: raise ValueError( "Invalid value for `type` ({0}), must be one of {1}" .format(type, allowed_values) ) self._type = type
def type(self, type)
Sets the type of this AggregatedQuotaUsageReport. Type of quota usage entry. :param type: The type of this AggregatedQuotaUsageReport. :type: str
2.377511
2.236477
1.063061
kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Campaign, True) api = self._get_api(update_service.DefaultApi) return PaginatedResponse(api.update_campaign_list, lwrap_type=Campaign, **kwargs)
def list_campaigns(self, **kwargs)
List all update campaigns. :param int limit: number of campaigns to retrieve :param str order: sort direction of campaigns when ordered by creation time (desc|asc) :param str after: get campaigns after given campaign ID :param dict filters: Dictionary of filters to apply :return: List of :py:class:`Campaign` objects :rtype: PaginatedResponse
9.912691
8.180993
1.211673
api = self._get_api(update_service.DefaultApi) return Campaign(api.update_campaign_retrieve(campaign_id))
def get_campaign(self, campaign_id)
Get existing update campaign. :param str campaign_id: Campaign ID to retrieve (Required) :return: Update campaign object matching provided ID :rtype: Campaign
14.631974
11.995106
1.219829
device_filter = filters.legacy_filter_formatter( dict(filter=device_filter), Device._get_attributes_map() ) campaign = Campaign._create_request_map(kwargs) if 'when' in campaign: # FIXME: randomly validating an input here is a sure route to nasty surprises elsewhere campaign['when'] = force_utc(campaign['when']) body = UpdateCampaignPostRequest( name=name, device_filter=device_filter['filter'], **campaign) api = self._get_api(update_service.DefaultApi) return Campaign(api.update_campaign_create(body))
def add_campaign(self, name, device_filter, **kwargs)
Add new update campaign. Add an update campaign with a name and device filtering. Example: .. code-block:: python device_api, update_api = DeviceDirectoryAPI(), UpdateAPI() # Get a filter to use for update campaign query_obj = device_api.get_query(query_id="MYID") # Create the campaign new_campaign = update_api.add_campaign( name="foo", device_filter=query_obj.filter ) :param str name: Name of the update campaign (Required) :param str device_filter: The device filter to use (Required) :param str manifest_id: ID of the manifest with description of the update :param str description: Description of the campaign :param int scheduled_at: The timestamp at which update campaign is scheduled to start :param str state: The state of the campaign. Values: "draft", "scheduled", "devicefetch", "devicecopy", "publishing", "deploying", "deployed", "manifestremoved", "expired" :return: newly created campaign object :rtype: Campaign
10.661022
11.516378
0.925727
api = self._get_api(update_service.DefaultApi) if campaign_object: campaign_id = campaign_object.id campaign_object = campaign_object._create_patch_request() else: campaign_object = Campaign._create_request_map(kwargs) if 'device_filter' in campaign_object: campaign_object["device_filter"] = filters.legacy_filter_formatter( dict(filter=campaign_object["device_filter"]), Device._get_attributes_map() )['filter'] if 'when' in campaign_object: # FIXME: randomly validating an input here is a sure route to nasty surprises elsewhere campaign_object['when'] = force_utc(campaign_object['when']) return Campaign(api.update_campaign_update(campaign_id=campaign_id, campaign=campaign_object))
def update_campaign(self, campaign_object=None, campaign_id=None, **kwargs)
Update an update campaign. :param :class:`Campaign` campaign_object: Campaign object to update (Required) :return: updated campaign object :rtype: Campaign
6.585897
6.906027
0.953645
api = self._get_api(update_service.DefaultApi) api.update_campaign_destroy(campaign_id) return
def delete_campaign(self, campaign_id)
Delete an update campaign. :param str campaign_id: Campaign ID to delete (Required) :return: void
11.258131
12.124599
0.928536
kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, CampaignDeviceState, True) kwargs["campaign_id"] = campaign_id api = self._get_api(update_service.DefaultApi) return PaginatedResponse(api.update_campaign_metadata_list, lwrap_type=CampaignDeviceState, **kwargs)
def list_campaign_device_states(self, campaign_id, **kwargs)
List campaign devices status. :param str campaign_id: Id of the update campaign (Required) :param int limit: number of devices state to retrieve :param str order: sort direction of device state when ordered by creation time (desc|asc) :param str after: get devices state after given id :return: List of :py:class:`CampaignDeviceState` objects :rtype: PaginatedResponse
7.904451
7.157974
1.104286
api = self._get_api(update_service.DefaultApi) return FirmwareImage(api.firmware_image_retrieve(image_id))
def get_firmware_image(self, image_id)
Get a firmware image with provided image_id. :param str image_id: The firmware ID for the image to retrieve (Required) :return: FirmwareImage
10.240928
13.444721
0.761706
kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, FirmwareImage, True) api = self._get_api(update_service.DefaultApi) return PaginatedResponse(api.firmware_image_list, lwrap_type=FirmwareImage, **kwargs)
def list_firmware_images(self, **kwargs)
List all firmware images. :param int limit: number of firmware images to retrieve :param str order: ordering of images when ordered by time. 'desc' or 'asc' :param str after: get firmware images after given `image_id` :param dict filters: Dictionary of filters to apply :return: list of :py:class:`FirmwareImage` objects :rtype: PaginatedResponse
7.867954
8.18856
0.960847
kwargs.update({'name': name}) firmware_image = FirmwareImage._create_request_map(kwargs) firmware_image.update({'datafile': datafile}) api = self._get_api(update_service.DefaultApi) return FirmwareImage( api.firmware_image_create(**firmware_image) )
def add_firmware_image(self, name, datafile, **kwargs)
Add a new firmware reference. :param str name: Firmware file short name (Required) :param str datafile: The file object or *path* to the firmware image file (Required) :param str description: Firmware file description :return: the newly created firmware file object :rtype: FirmwareImage
5.614983
6.469511
0.867915
api = self._get_api(update_service.DefaultApi) api.firmware_image_destroy(image_id=image_id) return
def delete_firmware_image(self, image_id)
Delete a firmware image. :param str image_id: image ID for the firmware to remove/delete (Required) :return: void
8.55305
10.435995
0.819572
api = self._get_api(update_service.DefaultApi) return FirmwareManifest(api.firmware_manifest_retrieve(manifest_id=manifest_id))
def get_firmware_manifest(self, manifest_id)
Get manifest with provided manifest_id. :param str manifest_id: ID of manifest to retrieve (Required) :return: FirmwareManifest
8.86587
11.182713
0.792819
kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, FirmwareManifest, True) api = self._get_api(update_service.DefaultApi) return PaginatedResponse(api.firmware_manifest_list, lwrap_type=FirmwareManifest, **kwargs)
def list_firmware_manifests(self, **kwargs)
List all manifests. :param int limit: number of manifests to retrieve :param str order: sort direction of manifests when ordered by time. 'desc' or 'asc' :param str after: get manifests after given `image_id` :param dict filters: Dictionary of filters to apply :return: list of :py:class:`FirmwareManifest` objects :rtype: PaginatedResponse
7.965815
8.106055
0.982699
kwargs.update({ 'name': name, 'url': datafile, # really it's the datafile }) if key_table_file is not None: kwargs.update({'key_table_url': key_table_file}) # really it's the key_table firmware_manifest = FirmwareManifest._create_request_map(kwargs) api = self._get_api(update_service.DefaultApi) return FirmwareManifest( api.firmware_manifest_create(**firmware_manifest) )
def add_firmware_manifest(self, name, datafile, key_table_file=None, **kwargs)
Add a new manifest reference. :param str name: Manifest file short name (Required) :param str datafile: The file object or path to the manifest file (Required) :param str key_table_file: The file object or path to the key_table file (Optional) :param str description: Manifest file description :return: the newly created manifest file object :rtype: FirmwareManifest
4.600141
4.798664
0.95863
api = self._get_api(update_service.DefaultApi) return api.firmware_manifest_destroy(manifest_id)
def delete_firmware_manifest(self, manifest_id)
Delete an existing manifest. :param str manifest_id: Manifest file ID to delete (Required) :return: void
10.572062
14.308103
0.738886
if isinstance(self._device_filter, str): return self._decode_query(self._device_filter) return self._device_filter
def device_filter(self)
The device filter to use. :rtype: dict
4.440135
5.121882
0.866895
if reason is None: raise ValueError("Invalid value for `reason`, must not be `None`") allowed_values = ["reservation", "reservation_release", "reservation_termination", "package_creation", "package_renewal", "package_termination"] if reason not in allowed_values: raise ValueError( "Invalid value for `reason` ({0}), must be one of {1}" .format(reason, allowed_values) ) self._reason = reason
def reason(self, reason)
Sets the reason of this ServicePackageQuotaHistoryItem. Type of quota usage entry. :param reason: The reason of this ServicePackageQuotaHistoryItem. :type: str
2.371184
2.337013
1.014622
if endpoint_name is None: raise ValueError("Invalid value for `endpoint_name`, must not be `None`") if endpoint_name is not None and not re.search('^[ -~]{16,64}$', endpoint_name): raise ValueError("Invalid value for `endpoint_name`, must be a follow pattern or equal to `/^[ -~]{16,64}$/`") self._endpoint_name = endpoint_name
def endpoint_name(self, endpoint_name)
Sets the endpoint_name of this PreSharedKey. The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters. :param endpoint_name: The endpoint_name of this PreSharedKey. :type: str
1.769807
1.610068
1.099213
if secret_hex is None: raise ValueError("Invalid value for `secret_hex`, must not be `None`") if secret_hex is not None and not re.search('^(0[xX])?[0-9a-fA-F]{32,64}$', secret_hex): raise ValueError("Invalid value for `secret_hex`, must be a follow pattern or equal to `/^(0[xX])?[0-9a-fA-F]{32,64}$/`") self._secret_hex = secret_hex
def secret_hex(self, secret_hex)
Sets the secret_hex of this PreSharedKey. The secret of the pre-shared key in hexadecimal. It is not case sensitive; 4a is same as 4A, and it is allowed with or without 0x in the beginning. The minimum length of the secret is 128 bits and maximum 256 bits. :param secret_hex: The secret_hex of this PreSharedKey. :type: str
1.699808
1.567009
1.084747
return self.delete_pre_shared_key_with_http_info(endpoint_name, **kwargs) # noqa: E501 else: (data) = self.delete_pre_shared_key_with_http_info(endpoint_name, **kwargs) # noqa: E501 return data
def delete_pre_shared_key(self, endpoint_name, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Remove a pre-shared key. # noqa: E501 Remove a pre-shared key. **Example usage:** ``` curl -H \"authorization: Bearer ${API_TOKEN}\" -X DELETE https://api.us-east-1.mbedcloud.com/v2/device-shared-keys/my-endpoint-0001 ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.delete_pre_shared_key(endpoint_name, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str endpoint_name: The unique endpoint identifier that this pre-shared key applies to. [Reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters) must be percent-encoded. (required) :return: None If the method is called asynchronously, returns the request thread.
1.480536
1.93265
0.766065
return self.get_pre_shared_key_with_http_info(endpoint_name, **kwargs) # noqa: E501 else: (data) = self.get_pre_shared_key_with_http_info(endpoint_name, **kwargs) # noqa: E501 return data
def get_pre_shared_key(self, endpoint_name, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Get a pre-shared key. # noqa: E501 Check if a pre-shared key for an endpoint exists or not. The response does not contain the secret itself. **Example usage:** ``` curl -H \"authorization: Bearer ${API_TOKEN}\" https://api.us-east-1.mbedcloud.com/v2/device-shared-keys/my-endpoint-0001 ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_pre_shared_key(endpoint_name, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str endpoint_name: The unique endpoint identifier that this pre-shared key applies to. [Reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters) must be percent-encoded. (required) :return: PreSharedKeyWithoutSecret If the method is called asynchronously, returns the request thread.
1.468232
1.848996
0.79407
return self.list_pre_shared_keys_with_http_info(**kwargs) # noqa: E501 else: (data) = self.list_pre_shared_keys_with_http_info(**kwargs) # noqa: E501 return data
def list_pre_shared_keys(self, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
List pre-shared keys. # noqa: E501 List pre-shared keys with pagination and default page size of 50 entries. **Example usage:** ``` curl -H \"authorization: Bearer ${API_TOKEN}\" https://api.us-east-1.mbedcloud.com/v2/device-shared-keys ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.list_pre_shared_keys(asynchronous=True) >>> result = thread.get() :param asynchronous bool :param int limit: The number of entries per page :param str after: An offset token for fetching a specific page. Provided by the server. :return: ListOfPreSharedKeysWithoutSecret If the method is called asynchronously, returns the request thread.
1.59886
2.152423
0.742818
return self.upload_pre_shared_key_with_http_info(body, **kwargs) # noqa: E501 else: (data) = self.upload_pre_shared_key_with_http_info(body, **kwargs) # noqa: E501 return data
def upload_pre_shared_key(self, body, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Upload a pre-shared key to Pelion Device Management. # noqa: E501 Upload a pre-shared key (PSK) for an endpoint to allow it to bootstrap. The existing key will not be overwritten but needs to be deleted first in case of re-setting PSK for an endpoint. **Note**: The PSK APIs are available only to accounts that have this feature enabled. **Example usage:** ``` curl -H \"authorization: Bearer ${API_TOKEN}\" -H \"content-type: application/json\" -X POST https://api.us-east-1.mbedcloud.com/v2/device-shared-keys \\ -d '{\"endpoint_name\": \"my-endpoint-0001\", \"secret_hex\": \"4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a\" }' ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.upload_pre_shared_key(body, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param PreSharedKey body: Pre-shared key to be uploaded. (required) :return: None If the method is called asynchronously, returns the request thread.
1.554458
2.114267
0.735223
length_value = byte & length_type_mask return LengthTypes.to_ints.get(length_value, byte & length_mask)
def get_value_length(byte)
Length of the value, in bytes (value can be 8/16/24/custom bits) :param byte: :return:
12.630856
15.666755
0.80622
bytes_count = len(bytearr) result = 0b0 for index, byt in enumerate(bytearr): offset_bytes = bytes_count - index - 1 result += byt << (8 * offset_bytes) return result
def combine_bytes(bytearr)
Given some bytes, join them together to make one long binary (e.g. 00001000 00000000 -> 0000100000000000) :param bytearr: :return:
3.414252
3.827274
0.892084
result = {} if result is None else result if not binary_string: return result byte = binary_string[0] kind = byte & type_mask id_length = get_id_length(byte) payload_length = get_value_length(byte) # start after the type indicator offset = 1 item_id = str(combine_bytes(binary_string[offset:offset + id_length])) offset += id_length # get length of payload from specifier value_length = payload_length if byte & length_type_mask != LengthTypes.SET_BYTE: value_length = combine_bytes(binary_string[offset:offset + payload_length]) offset += payload_length if kind == Types.MULTI: binary_tlv_to_python( binary_string[offset:offset + value_length], result.setdefault(item_id, {}) ) else: value_binary = binary_string[offset: offset + value_length] result[item_id] = ( combine_bytes(value_binary) if not all(value_binary) else value_binary.decode('utf8') ) offset += value_length binary_tlv_to_python(binary_string[offset:], result) return result
def binary_tlv_to_python(binary_string, result=None)
Recursively decode a binary string and store output in result object :param binary_string: a bytearray object of tlv data :param result: result store for recursion :return:
3.170745
3.267748
0.970315
if not payload: return None binary = b64decoder(payload) if decode_b64 else payload if content_type and 'tlv' in content_type.lower(): return binary_tlv_to_python(bytearray(binary)) return binary
def maybe_decode_payload(payload, content_type='application/nanoservice-tlv', decode_b64=True)
If the payload is tlv, decode it, otherwise passthrough :param payload: some data :param content_type: http content type :param decode_b64: by default, payload is assumed to be b64 encoded :return:
3.656742
4.107893
0.890174
if after is not None and len(after) > 32: raise ValueError("Invalid value for `after`, length must be less than or equal to `32`") if after is not None and len(after) < 32: raise ValueError("Invalid value for `after`, length must be greater than or equal to `32`") self._after = after
def after(self, after)
Sets the after of this ServicePackageQuotaHistoryResponse. After which quota history ID this paged response is fetched. :param after: The after of this ServicePackageQuotaHistoryResponse. :type: str
1.721892
1.77094
0.972304
if object is None: raise ValueError("Invalid value for `object`, must not be `None`") allowed_values = ["service-package-quota-history"] if object not in allowed_values: raise ValueError( "Invalid value for `object` ({0}), must be one of {1}" .format(object, allowed_values) ) self._object = object
def object(self, object)
Sets the object of this ServicePackageQuotaHistoryResponse. Always set to 'service-package-quota-history'. :param object: The object of this ServicePackageQuotaHistoryResponse. :type: str
2.406335
1.53264
1.570059
if total_count is None: raise ValueError("Invalid value for `total_count`, must not be `None`") if total_count is not None and total_count < 0: raise ValueError("Invalid value for `total_count`, must be a value greater than or equal to `0`") self._total_count = total_count
def total_count(self, total_count)
Sets the total_count of this ServicePackageQuotaHistoryResponse. Sum of all quota history entries that should be returned :param total_count: The total_count of this ServicePackageQuotaHistoryResponse. :type: int
1.495032
1.525078
0.980299
if issuer_type is None: raise ValueError("Invalid value for `issuer_type`, must not be `None`") allowed_values = ["GLOBAL_SIGN", "CFSSL_AUTH"] if issuer_type not in allowed_values: raise ValueError( "Invalid value for `issuer_type` ({0}), must be one of {1}" .format(issuer_type, allowed_values) ) self._issuer_type = issuer_type
def issuer_type(self, issuer_type)
Sets the issuer_type of this CertificateIssuerInfo. The type of the certificate issuer. - GLOBAL_SIGN: Certificates are issued by GlobalSign service. The users must provide their own GlobalSign account credentials. - CFSSL_AUTH: Certificates are issued by CFSSL authenticated signing service. The users must provide their own CFSSL host_url and credentials. :param issuer_type: The issuer_type of this CertificateIssuerInfo. :type: str
2.045078
1.475529
1.385996
allowed_values = [400, 401, 404] if code not in allowed_values: raise ValueError( "Invalid value for `code` ({0}), must be one of {1}" .format(code, allowed_values) ) self._code = code
def code(self, code)
Sets the code of this ErrorResponse. Response code. :param code: The code of this ErrorResponse. :type: int
2.054237
1.782185
1.15265
if request_id is not None and not re.search('^[A-Za-z0-9]{32}', request_id): raise ValueError("Invalid value for `request_id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`") self._request_id = request_id
def request_id(self, request_id)
Sets the request_id of this ErrorResponse. Request ID. :param request_id: The request_id of this ErrorResponse. :type: str
1.993674
2.122103
0.93948
with self._notifications_lock: if self.has_active_notification_thread: return api = self._get_api(mds.NotificationsApi) self._notifications_thread = NotificationsThread( self._db, self._queues, b64decode=self.b64decode, notifications_api=api, subscription_manager=self.subscribe, ) self._notifications_thread.daemon = True self._notifications_thread.start()
def start_notifications(self)
Start the notifications thread. If an external callback is not set up (using `update_webhook`) then calling this function is mandatory to get or set resource. .. code-block:: python >>> api.start_notifications() >>> print(api.get_resource_value(device, path)) Some value >>> api.stop_notifications() :returns: void
5.177744
5.878483
0.880796
with self._notifications_lock: if not self.has_active_notification_thread: return thread = self._notifications_thread self._notifications_thread = None stopping = thread.stop() api = self._get_api(mds.NotificationsApi) api.delete_long_poll_channel() return stopping.wait()
def stop_notifications(self)
Stop the notifications thread. :returns:
6.934913
7.126432
0.973125
# TODO(pick one of these) filter_or_filters = 'filter' if 'filter' in kwargs else 'filters' kwargs.setdefault(filter_or_filters, {}).setdefault('state', {'$eq': 'registered'}) kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Device, True) api = self._get_api(device_directory.DefaultApi) return PaginatedResponse(api.device_list, lwrap_type=Device, **kwargs)
def list_connected_devices(self, **kwargs)
List connected devices. Example usage, listing all registered devices in the catalog: .. code-block:: python filters = { 'created_at': {'$gte': datetime.datetime(2017,01,01), '$lte': datetime.datetime(2017,12,31) } } devices = api.list_connected_devices(order='asc', filters=filters) for idx, device in enumerate(devices): print(device) ## Other example filters # Directly connected devices (not via gateways): filters = { 'host_gateway': {'$eq': ''}, 'device_type': {'$eq': ''} } # Devices connected via gateways: filters = { 'host_gateway': {'$neq': ''} } # Gateway devices: filters = { 'device_type': {'$eq': 'MBED_GW'} } :param int limit: The number of devices to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get devices after/starting at given `device_id` :param filters: Dictionary of filters to apply. :returns: a list of connected :py:class:`Device` objects. :rtype: PaginatedResponse
7.24259
7.148704
1.013133
api = self._get_api(mds.EndpointsApi) return [Resource(r) for r in api.get_endpoint_resources(device_id)]
def list_resources(self, device_id)
List all resources registered to a connected device. .. code-block:: python >>> for r in api.list_resources(device_id): print(r.name, r.observable, r.uri) None,True,/3/0/1 Update,False,/5/0/3 ... :param str device_id: The ID of the device (Required) :returns: A list of :py:class:`Resource` objects for the device :rtype: list
9.810977
14.144503
0.693625
resources = self.list_resources(device_id) for r in resources: if r.path == resource_path: return r raise CloudApiException("Resource not found")
def get_resource(self, device_id, resource_path)
Get a resource. :param str device_id: ID of the device (Required) :param str path: Path of the resource to get (Required) :returns: Device resource :rtype Resource
3.215184
4.179037
0.76936
self.ensure_notifications_thread() api = self._get_api(mds.DeviceRequestsApi) async_id = async_id or utils.new_async_id() device_request = mds.DeviceRequest(**params) api.create_async_request( device_id, async_id=async_id, body=device_request, ) return AsyncConsumer(async_id, self._db) if _wrap_with_consumer else async_id
def _mds_rpc_post(self, device_id, _wrap_with_consumer=True, async_id=None, **params)
Helper for using RPC endpoint
4.143468
4.0174
1.031381
return self._mds_rpc_post(device_id=device_id, method='GET', uri=resource_path)
def get_resource_value_async(self, device_id, resource_path, fix_path=True)
Get a resource value for a given device and resource path. Will not block, but instead return an AsyncConsumer. Example usage: .. code-block:: python a = api.get_resource_value_async(device, path) while not a.is_done: time.sleep(0.1) if a.error: print("Error", a.error) print("Current value", a.value) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to get (Required) :param bool fix_path: strip leading / of path if present :returns: Consumer object to control asynchronous request :rtype: AsyncConsumer
8.417459
15.905815
0.529206
return self.get_resource_value_async(device_id, resource_path, fix_path).wait(timeout)
def get_resource_value(self, device_id, resource_path, fix_path=True, timeout=None)
Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) print("Current value", v) except CloudAsyncError, e: print("Error", e) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to get (Required) :param fix_path: if True then the leading /, if found, will be stripped before doing request to backend. This is a requirement for the API to work properly :param timeout: Seconds to request value for before timeout. If not provided, the program might hang indefinitely. :raises: CloudAsyncError, CloudTimeoutError :returns: The resource value for the requested resource path :rtype: str
3.318636
4.306269
0.770652
self.ensure_notifications_thread() return self.set_resource_value_async( device_id, resource_path, resource_value ).wait(timeout)
def set_resource_value(self, device_id, resource_path, resource_value, fix_path=True, timeout=None)
Set resource value for given resource path, on device. Will block and wait for response to come through. Usage: .. code-block:: python try: v = api.set_resource_value(device, path, value) print("Success, new value:", v) except AsyncError, e: print("Error", e) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to update (Required) :param str resource_value: The new value to set for given path :param fix_path: Unused :param timeout: Timeout in seconds :raises: AsyncError :returns: The value of the new resource :rtype: str
5.300538
6.466913
0.81964
payload_b64 = self._base64_encode(resource_value) if not resource_path.startswith("/"): resource_path = "/" + resource_path return self._mds_rpc_post( device_id, method='PUT', uri=resource_path, content_type="text/plain", payload_b64=payload_b64 )
def set_resource_value_async(self, device_id, resource_path, resource_value=None, fix_path=True)
Set resource value for given resource path, on device. Will not block. Returns immediately. Usage: .. code-block:: python a = api.set_resource_value_async(device, path, value) while not a.is_done: time.sleep(0.1) if a.error: print("Error", a.error) print("Success, new value:", a.value) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to update (Required) :param str resource_value: The new value to set for given path :param fix_path: Unused :returns: An async consumer object holding reference to request :rtype: AsyncConsumer
3.500461
4.244399
0.824725
self.ensure_notifications_thread() return self.execute_resource_async(device_id, resource_path).wait(timeout)
def execute_resource(self, device_id, resource_path, fix_path=True, timeout=None)
Execute a function on a resource. Will block and wait for response to come through. Usage: .. code-block:: python try: v = api.execute_resource(device, path) print("Success, returned value:", v) except AsyncError, e: print("Error", e) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to update (Required) :param str resource_function: Unused :param fix_path: Unused :param timeout: Timeout in seconds :raises: AsyncError :returns: The value returned from the function executed on the resource :rtype: str
7.32061
8.485654
0.862704
if not resource_path.startswith("/"): resource_path = "/" + resource_path return self._mds_rpc_post(device_id=device_id, method='POST', uri=resource_path)
def execute_resource_async(self, device_id, resource_path, fix_path=True)
Execute a function on a resource. Will not block. Returns immediately. Usage: .. code-block:: python a = api.execute_resource_async(device, path) while not a.is_done: time.sleep(0.1) if a.error: print("Error", a.error) print("Success, returned value:", a.value) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to update (Required) :param fix_path: Unused :returns: An async consumer object holding reference to request :rtype: AsyncConsumer
4.757167
5.925226
0.802867
# When path starts with / we remove the slash, as the API can't handle //. # Keep the original path around however, as we use that for queue registration. fixed_path = resource_path if fix_path and resource_path.startswith("/"): fixed_path = resource_path[1:] # Create the queue and register it with the dict holding all queues q = queue.Queue(queue_size) if queue_size > 0 else None # FIXME: explicit behaviour on replacing an existing queue self._queues[device_id][resource_path] = q # Send subscription request self._add_subscription(device_id, fixed_path) # Return the Queue object to the user return q
def add_resource_subscription(self, device_id, resource_path, fix_path=True, queue_size=5)
Subscribe to resource updates. When called on a valid device and resource path a subscription is setup so that any update on the resource path value triggers a new element on the FIFO queue. The returned object is a native Python Queue object. :param device_id: Name of device to subscribe on (Required) :param resource_path: The resource path on device to observe (Required) :param fix_path: Removes leading / on resource_path if found :param queue_size: Sets the Queue size. If set to 0, no queue object will be created :returns: a queue of resource updates :rtype: Queue
6.520417
6.589214
0.989559
queue = self.add_resource_subscription(device_id, resource_path, fix_path, queue_size) # Setup daemon thread for callback function t = threading.Thread(target=self._subscription_handler, args=[queue, device_id, resource_path, callback_fn]) t.daemon = True t.start()
def add_resource_subscription_async(self, device_id, resource_path, callback_fn, fix_path=True, queue_size=5)
Subscribe to resource updates with callback function. When called on a valid device and resource path a subscription is setup so that any update on the resource path value triggers an update on the callback function. :param device_id: Name of device to set the subscription on (Required) :param resource_path: The resource path on device to observe (Required) :param callback_fn: Callback function to be executed on update to subscribed resource :param fix_path: Removes leading / on resource_path if found :param queue_size: Sets the Queue size. If set to 0, no queue object will be created :returns: void
2.723921
3.508427
0.776394
# When path starts with / we remove the slash, as the API can't handle //. # Keep the original path around however, as we use that for queue registration. fixed_path = resource_path if fix_path and resource_path.startswith("/"): fixed_path = resource_path[1:] api = self._get_api(mds.SubscriptionsApi) try: api.check_resource_subscription(device_id, fixed_path) except Exception as e: if e.status == 404: return False raise return True
def get_resource_subscription(self, device_id, resource_path, fix_path=True)
Read subscription status. :param device_id: Name of device to set the subscription on (Required) :param resource_path: The resource path on device to observe (Required) :param fix_path: Removes leading / on resource_path if found :returns: status of subscription
5.735717
5.892108
0.973457
api = self._get_api(mds.SubscriptionsApi) presubscriptions_list = [] for presubscription in presubscriptions: if not isinstance(presubscription, dict): presubscription = presubscription.to_dict() presubscription = { "endpoint_name": presubscription.get("device_id", None), "endpoint_type": presubscription.get("device_type", None), "_resource_path": presubscription.get("resource_paths", None) } presubscriptions_list.append(PresubscriptionData(**presubscription)) return api.update_pre_subscriptions(presubscriptions_list)
def update_presubscriptions(self, presubscriptions)
Update pre-subscription data. Pre-subscription data will be removed for empty list. :param presubscriptions: list of `Presubscription` objects (Required) :returns: None
3.081341
2.941017
1.047713
warnings.warn('This could be slow for large numbers of connected devices.' 'If possible, explicitly delete subscriptions known to have been created.') for device in self.list_connected_devices(): try: self.delete_device_subscriptions(device_id=device.id) except CloudApiException as e: LOG.warning('failed to remove subscription for %s: %s', device.id, e) continue
def delete_subscriptions(self)
Remove all subscriptions. Warning: This could be slow for large numbers of connected devices. If possible, explicitly delete subscriptions known to have been created. :returns: None
6.225473
3.263477
1.90762
api = self._get_api(mds.SubscriptionsApi) resp = api.get_pre_subscriptions(**kwargs) return [Presubscription(p) for p in resp]
def list_presubscriptions(self, **kwargs)
Get a list of pre-subscription data :returns: a list of `Presubscription` objects :rtype: list of mbed_cloud.presubscription.Presubscription
6.779697
7.411043
0.91481
api = self._get_api(mds.SubscriptionsApi) resp = api.get_endpoint_subscriptions(device_id, **kwargs) return resp.split("\n")
def list_device_subscriptions(self, device_id, **kwargs)
Lists all subscribed resources from a single device :param device_id: ID of the device (Required) :returns: a list of subscribed resources :rtype: list of str
7.394139
7.851312
0.941771
api = self._get_api(mds.SubscriptionsApi) return api.delete_endpoint_subscriptions(device_id)
def delete_device_subscriptions(self, device_id)
Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None
9.718042
10.411736
0.933374
devices = [_f for _f in [device_id] if _f] if not device_id: devices = list(self._queues.keys()) resource_paths = [resource_path] if not resource_path: resource_paths = [] for e in devices: resource_paths.extend(list(self._queues[e].keys())) # Delete the subscriptions for e in devices: for r in resource_paths: # Fix the path, if required. fixed_path = r if fix_path and r.startswith("/"): fixed_path = r[1:] # Make request to API, ignoring result self._delete_subscription(device_id, fixed_path) # Remove Queue from dictionary del self._queues[e][r] return
def delete_resource_subscription(self, device_id=None, resource_path=None, fix_path=True)
Unsubscribe from device and/or resource_path updates. If device_id or resource_path is None, or this method is called without arguments, all subscriptions are removed. Calling it with only device_id removes subscriptions for all resources on the given device. :param device_id: device to unsubscribe events from. If not provided, all registered devices will be unsubscribed. :param resource_path: resource_path to unsubscribe events from. If not provided, all resource paths will be unsubscribed. :param fix_path: remove trailing / in resouce path to ensure API works. :return: void
3.574608
3.723059
0.960127
class PayloadContainer: # noqa # bodge to give attribute lookup data = payload notification = self._get_api(mds.NotificationsApi).api_client.deserialize( PayloadContainer, mds.NotificationMessage.__name__ ) handle_channel_message( db=self._db, queues=self._queues, b64decode=self.b64decode, notification_object=notification )
def notify_webhook_received(self, payload)
Callback function for triggering notification channel handlers. Use this in conjunction with a webserver to complete the loop when using webhooks as the notification channel. :param str payload: the encoded payload, as sent by the notification channel
13.096797
17.949736
0.729637
api = self._get_api(mds.NotificationsApi) return Webhook(api.get_webhook())
def get_webhook(self)
Get the current callback URL if it exists. :return: The currently set webhook
19.312157
24.178331
0.798738
headers = headers or {} api = self._get_api(mds.NotificationsApi) # Delete notifications channel api.delete_long_poll_channel() # Send the request to register the webhook webhook_obj = WebhookData(url=url, headers=headers) api.register_webhook(webhook_obj) return
def update_webhook(self, url, headers=None)
Register new webhook for incoming subscriptions. If a webhook is already set, this will do an overwrite. :param str url: the URL with listening webhook (Required) :param dict headers: K/V dict with additional headers to send with request :return: void
8.04459
8.410196
0.956528
api = self._get_api(mds.NotificationsApi) api.deregister_webhook() # Every subscription will be deleted, so we can clear the queues too. self._queues.clear() return
def delete_webhook(self)
Delete/remove registered webhook. If no webhook is registered, an exception (404) will be raised. Note that every registered subscription will be deleted as part of deregistering a webhook. :return: void
17.025253
16.303226
1.044287
self._verify_arguments(interval, kwargs) include = Metric._map_includes(include) kwargs.update(dict(include=include, interval=interval)) api = self._get_api(statistics.StatisticsApi) return PaginatedResponse(api.get_metrics, lwrap_type=Metric, **kwargs)
def list_metrics(self, include=None, interval="1d", **kwargs)
Get statistics. :param list[str] include: List of fields included in response. None, or an empty list will return all fields. Fields: transactions, successful_api_calls, failed_api_calls, successful_handshakes, pending_bootstraps, successful_bootstraps, failed_bootstraps, registrations, updated_registrations, expired_registrations, deleted_registrations :param str interval: Group data by this interval in days, weeks or hours. Sample values: 2h, 3w, 4d. :param datetime start: Fetch the data with timestamp greater than or equal to this value. The parameter is not mandatory, if the period is specified. :param datetime end: Fetch the data with timestamp less than this value. The parameter is not mandatory, if the period is specified. :param str period: Period. Fetch the data for the period in days, weeks or hours. Sample values: 2h, 3w, 4d. The parameter is not mandatory, if the start and end time are specified :param int limit: The number of devices to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get metrics after/starting at given metric ID :returns: a list of :py:class:`Metric` objects :rtype: PaginatedResponse
7.267873
7.318351
0.993102
if enrollment_identity is None: raise ValueError("Invalid value for `enrollment_identity`, must not be `None`") if enrollment_identity is not None and not re.search('^A-[A-Za-z0-9:]{95}$', enrollment_identity): raise ValueError("Invalid value for `enrollment_identity`, must be a follow pattern or equal to `/^A-[A-Za-z0-9:]{95}$/`") self._enrollment_identity = enrollment_identity
def enrollment_identity(self, enrollment_identity)
Sets the enrollment_identity of this EnrollmentId. Enrollment identity. :param enrollment_identity: The enrollment_identity of this EnrollmentId. :type: str
1.856297
1.83166
1.013451
for filter_key, filter_value in (self._optional_filters or {}).items(): data_value = data.get(filter_key) LOG.debug( 'optional keys filter %s: %s (%s)', filter_key, filter_value, data_value ) if data_value is None or data_value != filter_value: LOG.debug( 'optional keys filter rejecting %s: %s (%s)', filter_key, filter_value, data_value ) return False return True
def _filter_optional_keys(self, data)
Filtering for this channel, based on key-value matching
2.559354
2.442625
1.047788
for filter_function in self._filters: if not filter_function(data): return False self._notify(data) return True
def notify(self, data)
Notify this channel of inbound data
4.24603
4.487774
0.946133
self._manager = manager self._api = connect_api_instance self._observer_params = self._observer_params or {} self._observer_params.update(observer_params)
def _configure(self, manager, connect_api_instance, observer_params)
Configure behind-the-scenes settings for the channel These are required in addition to the parameters provided on instantiation
2.583942
2.773496
0.931655
if self.active: return self self._observer = self._observer_class(**self._observer_params) self.start() self._active = True return self
def ensure_started(self)
Idempotent channel start
5.88881
5.216389
1.128905
if not self.active: return self self.stop() self.observer.cancel() self._manager.remove_routes(self, self.get_routing_keys()) self._active = False return self
def ensure_stopped(self)
Idempotent channel stop
7.959023
6.838028
1.163935
return self.delete_resource_path_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 else: (data) = self.delete_resource_path_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 return data
def delete_resource_path(self, device_id, _resource_path, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Delete a resource path # noqa: E501 A request to delete a resource path must be handled by both Device Management Client and Device Management Connect. All resource APIs are asynchronous. These APIs respond only if the device is turned on and connected to Device Management Connect and there is an active notification channel. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/endpoints/{device-id}/{resourcePath} \\ -H 'authorization: Bearer {api-key}' # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.delete_resource_path(device_id, _resource_path, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required) :param str _resource_path: The URL of the resource. (required) :param bool no_resp: <br/><br/><b>Non-confirmable requests</b><br/> All resource APIs have the parameter noResp. If you make a request with `noResp=true`, Device Management Connect makes a CoAP non-confirmable request to the device. Such requests are not guaranteed to arrive in the device, and you do not get back an async-response-id. If calls with this parameter enabled succeed, they return with the status code `204 No Content`. If the underlying protocol does not support non-confirmable requests, or if the endpoint is registered in queue mode, the response is status code `409 Conflict`. :return: AsyncID If the method is called asynchronously, returns the request thread.
1.465019
1.828588
0.801175
return self.execute_or_create_resource_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 else: (data) = self.execute_or_create_resource_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 return data
def execute_or_create_resource(self, device_id, _resource_path, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Execute a function on a Resource or create new Object instance # noqa: E501 With this API, you can [execute a function](/docs/current/connecting/handle-resource-webapp.html#the-execute-operation) on an existing resource and create new Object instance to the device. The resource-path does not have to exist - it can be created by the call. The maximum length of resource-path is 255 characters. All resource APIs are asynchronous. These APIs respond only if the device is turned on and connected to Device Management Connect and there is an active notification channel. Supported content types depend on the device and its resource. Device Management translates HTTP to equivalent CoAP content type. **Example usage:** This example resets the min and max values of the [temperature sensor](http://www.openmobilealliance.org/tech/profiles/lwm2m/3303.xml) instance 0 by executing the Resource 5605 'Reset Min and Max Measured Values'. curl -X POST \\ https://api.us-east-1.mbedcloud.com/v2/endpoints/{device-id}/3303/0/5605 \\ -H 'authorization: Bearer {api-key}' # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.execute_or_create_resource(device_id, _resource_path, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required) :param str _resource_path: The URL of the resource. (required) :param str resource_function: This value is not needed. Most of the time resources do not accept a function but they have their own functions predefined. You can use this to trigger them. If a function is included, the body of this request is passed as a char* to the function in Device Management Client. :param bool no_resp: <br/><br/><b>Non-confirmable requests</b><br/> All resource APIs have the parameter noResp. If you make a request with `noResp=true`, Device Management Connect makes a CoAP non-confirmable request to the device. Such requests are not guaranteed to arrive in the device, and you do not get back an async-response-id. If calls with this parameter enabled succeed, they return with the status code `204 No Content`. If the underlying protocol does not support non-confirmable requests, or if the endpoint is registered in queue mode, the response is status code `409 Conflict`. :return: AsyncID If the method is called asynchronously, returns the request thread.
1.397135
1.655586
0.843892
return self.get_resource_value_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 else: (data) = self.get_resource_value_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 return data
def get_resource_value(self, device_id, _resource_path, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Read from a resource # noqa: E501 Requests the resource value and when the response is available, an `AsyncIDResponse` json object is received in the notification channel. The preferred way to get resource values is to use the **subscribe** and **callback** methods. All resource APIs are asynchronous. These APIs only respond if the device is turned on and connected to Device Management. Please refer to [Lightweight Machine to Machine Technical specification](http://www.openmobilealliance.org/release/LightweightM2M/V1_0-20170208-A/OMA-TS-LightweightM2M-V1_0-20170208-A.pdf) for more inforamtion. **Example usage:** curl -X GET \\ https://api.us-east-1.mbedcloud.com/v2/endpoints/{device-id}/{resourcePath} \\ -H 'authorization: Bearer {api-key}' # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_resource_value(device_id, _resource_path, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str device_id: Unique Device Management device ID for the endpoint. Note that the ID needs to be an exact match. You cannot use wildcards here. (required) :param str _resource_path: The URL of the resource. (required) :param bool cache_only: If true, the response comes only from the cache. Default: false. Device Management Connect caches the received resource values for the time of [max_age](/docs/current/connecting/working-with-the-resources.html) defined in the client side. :param bool no_resp: <br/><br/><b>Non-confirmable requests</b><br/> All resource APIs have the parameter `noResp`. If a request is made with `noResp=true`, Device Management Connect makes a CoAP non-confirmable request to the device. Such requests are not guaranteed to arrive in the device, and you do not get back an async-response-id. If calls with this parameter enabled succeed, they return with the status code `204 No Content`. If the underlying protocol does not support non-confirmable requests, or if the endpoint is registered in queue mode, the response is status code `409 Conflict`. :return: None If the method is called asynchronously, returns the request thread.
1.444283
1.755838
0.822561
return self.update_resource_value_with_http_info(device_id, _resource_path, resource_value, **kwargs) # noqa: E501 else: (data) = self.update_resource_value_with_http_info(device_id, _resource_path, resource_value, **kwargs) # noqa: E501 return data
def update_resource_value(self, device_id, _resource_path, resource_value, **kwargs): # noqa: E501 kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous')
Write to a resource or use write-attributes for a resource # noqa: E501 With this API, you can [write a new value to existing resources](/docs/current/connecting/handle-resource-webapp.html) or [use the write-attributes](/docs/current/connecting/resource-change-webapp.html) for a resource. This API can also be used to transfer files to the device. Device Management Connect LwM2M server implements the Option 1 from RFC7959. The maximum block size is 1024 bytes. The block size versus transferred file size is something to note in low quality networks. The customer application needs to know what type of file is transferred (for example txt) and the payload can be encrypted by the customer. The maximum size of payload is 1048576 bytes. All resource APIs are asynchronous. These APIs respond only if the device is turned on and connected to Device Management Connect and there is an active notification channel. Supported content types depend on the device and its resource. Device Management translates HTTP to equivalent CoAP content type. **Example usage:** This example sets the alarm on a buzzer. The command writes the [Buzzer](http://www.openmobilealliance.org/tech/profiles/lwm2m/3338.xml) instance 0, \"On/Off\" boolean resource to '1'. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/endpoints/{device-id}/3338/0/5850 -H \"content-type: text/plain\" \\ -H 'authorization: Bearer {api-key}' -d '1' # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.update_resource_value(device_id, _resource_path, resource_value, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required) :param str _resource_path: Resource URL. (required) :param str resource_value: The value to be set to the resource. (required) :param bool no_resp: <br/><br/><b>Non-confirmable requests</b><br/> All resource APIs have the parameter noResp. If you make a request with `noResp=true`, Device Management Connect makes a CoAP non-confirmable request to the device. Such requests are not guaranteed to arrive in the device, and you do not get back an async-response-id. If calls with this parameter enabled succeed, they return with the status code `204 No Content`. If the underlying protocol does not support non-confirmable requests, or if the endpoint is registered in queue mode, the response is status code `409 Conflict`. :return: AsyncID If the method is called asynchronously, returns the request thread.
1.411715
1.777339
0.794286
api = self._get_api(billing.DefaultApi) quota = api.get_service_package_quota() return None if quota is None else int(quota.quota)
def get_quota_remaining(self)
Get the remaining value
9.466011
9.602713
0.985764
kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, ServicePackage) api = self._get_api(billing.DefaultApi) return PaginatedResponse( api.get_service_package_quota_history, lwrap_type=QuotaHistory, **kwargs )
def get_quota_history(self, **kwargs)
Get quota usage history
7.609528
7.729458
0.984484
api = self._get_api(billing.DefaultApi) package_response = api.get_service_packages() packages = [] for state in PACKAGE_STATES: # iterate states in order items = getattr(package_response, state) or [] for item in ensure_listable(items): params = item.to_dict() params['state'] = state packages.append(ServicePackage(params)) return packages
def get_service_packages(self)
Get all service packages
5.919821
5.752144
1.02915
if not date_time: date_time = datetime.datetime.utcnow() if isinstance(date_time, datetime.datetime): date_time = '%s-%02d' % (date_time.year, date_time.month) return date_time
def _month_converter(self, date_time)
Returns Billing API format YYYY-DD
2.358134
2.076219
1.135783
path = user_path or os.path.join(os.getcwd(), 'billing_reports', os.path.sep) dir_specified = path.endswith(os.sep) if dir_specified: path = os.path.join(path, file_name) path = os.path.abspath(path) directory = os.path.dirname(path) if not os.path.isdir(directory): os.makedirs(directory) if os.path.exists(path): raise IOError('SDK will not write into an existing path: %r' % path) return path
def _filepath_converter(self, user_path, file_name)
Logic for obtaining a file path :param user_path: a path as provided by the user. perhaps a file or directory? :param file_name: the name of the remote file :return:
3.43736
3.741333
0.918753
api = self._get_api(billing.DefaultApi) month = self._month_converter(month) response = api.get_billing_report(month=month) if file_path and response: content = api.api_client.sanitize_for_serialization(response.to_dict()) with open(file_path, 'w') as fh: fh.write( json.dumps( content, sort_keys=True, indent=2, ) ) return response
def get_report_overview(self, month, file_path)
Downloads a report overview :param month: month as datetime instance, or string in YYYY-MM format :type month: str or datetime :param str file_path: location to store output file :return: outcome :rtype: True or None
3.345529
3.598746
0.929637