text stringlengths 81 112k |
|---|
Get the contents of this file
:return: The contents of this file
:rtype: six.binary_type
def get_data(self):
"""Get the contents of this file
:return: The contents of this file
:rtype: six.binary_type
"""
target = DeviceTarget(self.device_id)
return se... |
Delete this file from the device
.. note::
After deleting the file, this object will no longer contain valid information
and further calls to delete or get_data will return :class:`~.ErrorInfo` objects
def delete(self):
"""Delete this file from the device
.. note::
... |
List the contents of this directory
:return: A LsInfo object that contains directories and files
:rtype: :class:`~.LsInfo` or :class:`~.ErrorInfo`
Here is an example usage::
# let dirinfo be a DirectoryInfo object
ldata = dirinfo.list_contents()
if isinstan... |
Parse the server response for this ls command
This will parse xml of the following form::
<ls hash="hash_type">
<file path="file_path" last_modified=last_modified_time ... />
...
<dir path="dir_path" last_modified=last_modified_time />
...
... |
Parse the server response for this get file command
This will parse xml of the following form::
<get_file>
<data>
asdfasdfasdfasdfasf
</data>
</get_file>
or with an error::
<get_file>
<error ... />... |
Parse the server response for this put file command
This will parse xml of the following form::
<put_file />
or with an error::
<put_file>
<error ... />
</put_file>
:param response: The XML root of the response for a put file command
... |
Send an arbitrary file system command block
The primary use for this method is to send multiple file system commands with a single
web service request. This can help to avoid throttling.
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sc... |
List all files and directories in the path on the target
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to list files and directories from
... |
Get the contents of a file on the device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to the file to retrieve
:param offset: Star... |
Put data into a file on the device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to the file to write to. If the file already exists it w... |
Delete a file from a device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to the file to delete.
:return: A dictionary with keys b... |
Get all files and directories from a path on the device modified since a given time
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to the d... |
Check if path refers to an existing path on the device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to check for existence.
:para... |
Iterates over each :class:`Device` for this device cloud account
Examples::
# get a list of all devices
all_devices = list(dc.devicecore.get_devices())
# build a mapping of devices by their vendor id using a
# dict comprehension
devices = dc.devicec... |
r"""Return the root group for this accounts' group tree
This will return the root group for this tree but with all links
between nodes (i.e. children starting from root) populated.
Examples::
# print the group hierarchy to stdout
dc.devicecore.get_group_tree_root().pri... |
Return an iterator over all groups in this device cloud account
Optionally, a condition can be specified to limit the number of
groups returned.
Examples::
# Get all groups and print information about them
for group in dc.devicecore.get_groups():
print ... |
Provision multiple devices with a single API call
This method takes an iterable of dictionaries where the values in the dictionary are
expected to match the arguments of a call to :meth:`provision_device`. The
contents of each dictionary will be validated.
:param list devices: An iter... |
Build and return a new Group object from json data (used internally)
def from_json(cls, json_data):
"""Build and return a new Group object from json data (used internally)"""
# Example Data:
# { "grpId": "11817", "grpName": "7603_Digi", "grpDescription": "7603_Digi root group",
# "grp... |
Print this group node and the subtree rooted at it
def print_subtree(self, fobj=sys.stdout, level=0):
"""Print this group node and the subtree rooted at it"""
fobj.write("{}{!r}\n".format(" " * (level * 2), self))
for child in self.get_children():
child.print_subtree(fobj, level + 1... |
Get the JSON metadata for this device as a python data structure
If ``use_cached`` is not True, then a web services request will be made
synchronously in order to get the latest device metatdata. This will
update the cached data for this device.
def get_device_json(self, use_cached=True):
... |
Get the list of tags for this device
def get_tags(self, use_cached=True):
"""Get the list of tags for this device"""
device_json = self.get_device_json(use_cached)
potential_tags = device_json.get("dpTags")
if potential_tags:
return list(filter(None, potential_tags.split(","... |
Return True if the device is currrently connect and False if not
def is_connected(self, use_cached=True):
"""Return True if the device is currrently connect and False if not"""
device_json = self.get_device_json(use_cached)
return int(device_json.get("dpConnectionStatus")) > 0 |
Get the connectware id of this device (primary key)
def get_connectware_id(self, use_cached=True):
"""Get the connectware id of this device (primary key)"""
device_json = self.get_device_json(use_cached)
return device_json.get("devConnectwareId") |
Get this device's device id
def get_device_id(self, use_cached=True):
"""Get this device's device id"""
device_json = self.get_device_json(use_cached)
return device_json["id"].get("devId") |
Get the last known IP of this device
def get_ip(self, use_cached=True):
"""Get the last known IP of this device"""
device_json = self.get_device_json(use_cached)
return device_json.get("dpLastKnownIp") |
Get the MAC address of this device
def get_mac(self, use_cached=True):
"""Get the MAC address of this device"""
device_json = self.get_device_json(use_cached)
return device_json.get("devMac") |
Get the last 4 characters in the device mac address hex (e.g. 00:40:9D:58:17:5B -> 175B)
This is useful for use as a short reference to the device. It is not guaranteed to
be unique (obviously) but will often be if you don't have too many devices.
def get_mac_last4(self, use_cached=True):
"""... |
Get the datetime of when this device was added to Device Cloud
def get_registration_dt(self, use_cached=True):
"""Get the datetime of when this device was added to Device Cloud"""
device_json = self.get_device_json(use_cached)
start_date_iso8601 = device_json.get("devRecordStartDate")
i... |
Get a tuple with device latitude and longitude... these may be None
def get_latlon(self, use_cached=True):
"""Get a tuple with device latitude and longitude... these may be None"""
device_json = self.get_device_json(use_cached)
lat = device_json.get("dpMapLat")
lon = device_json.get("dp... |
Add a device to a group, if the group doesn't exist it is created
:param group_path: Path or "name" of the group
def add_to_group(self, group_path):
"""Add a device to a group, if the group doesn't exist it is created
:param group_path: Path or "name" of the group
"""
if self... |
Add a tag to existing device tags. This method will not add a duplicate, if already in the list.
:param new_tags: the tag(s) to be added. new_tags can be a comma-separated string or list
def add_tag(self, new_tags):
"""Add a tag to existing device tags. This method will not add a duplicate, if already... |
Remove tag from existing device tags
:param tag: the tag to be removed from the list
:raises ValueError: If tag does not exist in list
def remove_tag(self, tag):
"""Remove tag from existing device tags
:param tag: the tag to be removed from the list
:raises ValueError: If ta... |
Get the hostname that this connection is associated with
def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] |
Return an iterator over JSON items from a paginated resource
Legacy resources (prior to V1) implemented a common paging interfaces for
several different resources. This method handles the details of iterating
over the paged result set, yielding only the JSON data for each item
within t... |
Perform an HTTP GET request of the specified path in Device Cloud
Make an HTTP GET request against Device Cloud with this accounts
credentials and base url. This method uses the
`requests <http://docs.python-requests.org/en/latest/>`_ library
`request method <http://docs.python-request... |
Perform an HTTP GET request with JSON headers of the specified path against Device Cloud
Make an HTTP GET request against Device Cloud with this accounts
credentials and base url. This method uses the
`requests <http://docs.python-requests.org/en/latest/>`_ library
`request method <htt... |
Perform an HTTP POST request of the specified path in Device Cloud
Make an HTTP POST request against Device Cloud with this accounts
credentials and base url. This method uses the
`requests <http://docs.python-requests.org/en/latest/>`_ library
`request method <http://docs.python-reque... |
Perform an HTTP PUT request of the specified path in Device Cloud
Make an HTTP PUT request against Device Cloud with this accounts
credentials and base url. This method uses the
`requests <http://docs.python-requests.org/en/latest/>`_ library
`request method <http://docs.python-request... |
Perform an HTTP DELETE request of the specified path in Device Cloud
Make an HTTP DELETE request against Device Cloud with this accounts
credentials and base url. This method uses the
`requests <http://docs.python-requests.org/en/latest/>`_ library
`request method <http://docs.python-r... |
Property providing access to the :class:`.StreamsAPI`
def streams(self):
"""Property providing access to the :class:`.StreamsAPI`"""
if self._streams_api is None:
self._streams_api = self.get_streams_api()
return self._streams_api |
Property providing access to the :class:`.FileDataAPI`
def filedata(self):
"""Property providing access to the :class:`.FileDataAPI`"""
if self._filedata_api is None:
self._filedata_api = self.get_filedata_api()
return self._filedata_api |
Property providing access to the :class:`.DeviceCoreAPI`
def devicecore(self):
"""Property providing access to the :class:`.DeviceCoreAPI`"""
if self._devicecore_api is None:
self._devicecore_api = self.get_devicecore_api()
return self._devicecore_api |
Property providing access to the :class:`.ServerCommandInterfaceAPI`
def sci(self):
"""Property providing access to the :class:`.ServerCommandInterfaceAPI`"""
if self._sci_api is None:
self._sci_api = self.get_sci_api()
return self._sci_api |
Property providing access to the :class:`.FileSystemServiceAPI`
def file_system_service(self):
"""Property providing access to the :class:`.FileSystemServiceAPI`"""
if self._fss_api is None:
self._fss_api = self.get_fss_api()
return self._fss_api |
Property providing access to the :class:`.MonitorAPI`
def monitor(self):
"""Property providing access to the :class:`.MonitorAPI`"""
if self._monitor_api is None:
self._monitor_api = self.get_monitor_api()
return self._monitor_api |
Returns a :class:`.DeviceCoreAPI` bound to this device cloud instance
This provides access to the same API as :attr:`.DeviceCloud.devicecore` but will create
a new object (with a new cache) each time called.
:return: devicecore API object bound to this device cloud account
:rtype: :cla... |
Query an asynchronous SCI job by ID
This is useful if the job was not created with send_sci_async().
:param int job_id: The job ID to query
:returns: The SCI response from GETting the job information
def get_async_job(self, job_id):
"""Query an asynchronous SCI job by ID
This... |
Send an asynchronous SCI request, and wraps the job in an object
to manage it
:param str operation: The operation is one of {send_message, update_firmware, disconnect, query_firmware_targets,
file_system, data_service, and reboot}
:param target: The device(s) to be targeted with thi... |
Send SCI request to 1 or more targets
:param str operation: The operation is one of {send_message, update_firmware, disconnect, query_firmware_targets,
file_system, data_service, and reboot}
:param target: The device(s) to be targeted with this request
:type target: :class:`~.Target... |
Write to stream using fmt and value if value is not None
def conditional_write(strm, fmt, value, *args, **kwargs):
"""Write to stream using fmt and value if value is not None"""
if value is not None:
strm.write(fmt.format(value, *args, **kwargs)) |
Given an ISO8601 string as returned by Device Cloud, convert to a datetime object
def iso8601_to_dt(iso8601):
"""Given an ISO8601 string as returned by Device Cloud, convert to a datetime object"""
# We could just use arrow.get() but that is more permissive than we actually want.
# Internal (but still publ... |
Convert ``input`` to either None or a datetime object
If the input is None, None will be returned.
If the input is a datetime object, it will be converted to a datetime
object with UTC timezone info. If the datetime object is naive, then
this method will assume the object is specified according to UTC... |
Return an ISO-8601 formatted string from the provided datetime object
def isoformat(dt):
"""Return an ISO-8601 formatted string from the provided datetime object"""
if not isinstance(dt, datetime.datetime):
raise TypeError("Must provide datetime.datetime object to isoformat")
if dt.tzinfo is None:... |
Return a generator over all results matching the provided condition
:param condition: An :class:`.Expression` which defines the condition
which must be matched on the filedata that will be retrieved from
file data store. If a condition is unspecified, the following condition
... |
Write a file to the file data store at the given path
:param str path: The path (directory) into which the file should be written.
:param str name: The name of the file to be written.
:param data: The binary data that should be written into the file.
:type data: str (Python2) or bytes (... |
Delete a file or directory from the filedata store
This method removes a file or directory (recursively) from
the filedata store.
:param path: The path of the file or directory to remove
from the file data store.
def delete_file(self, path):
"""Delete a file or directory f... |
Emulation of os.walk behavior against Device Cloud filedata store
This method will yield tuples in the form ``(dirpath, FileDataDirectory's, FileData's)``
recursively in pre-order (depth first from top down).
:param str root: The root path from which the search should commence. By default, th... |
Get the data associated with this filedata object
:returns: Data associated with this object or None if none exists
:rtype: str (Python2)/bytes (Python3) or None
def get_data(self):
"""Get the data associated with this filedata object
:returns: Data associated with this object or None... |
Write a file into this directory
This method takes the same arguments as :meth:`.FileDataAPI.write_file`
with the exception of the ``path`` argument which is not needed here.
def write_file(self, *args, **kwargs):
"""Write a file into this directory
This method takes the same argument... |
Creates a TCP Monitor instance in Device Cloud for a given list of topics
:param topics: a string list of topics (e.g. ['DeviceCore[U]',
'FileDataCore']).
:param batch_size: How many Msgs received before sending data.
:param batch_duration: How long to wait before sending batc... |
Creates a HTTP Monitor instance in Device Cloud for a given list of topics
:param topics: a string list of topics (e.g. ['DeviceCore[U]',
'FileDataCore']).
:param transport_url: URL of the customer web server.
:param transport_token: Credentials for basic authentication in the... |
Return an iterator over all monitors matching the provided condition
Get all inactive monitors and print id::
for mon in dc.monitor.get_monitors(MON_STATUS_ATTR == "DISABLED"):
print(mon.get_id())
Get all the HTTP monitors and print id::
for mon in dc.monitor.... |
Attempts to find a Monitor in device cloud that matches the provided topics
:param topics: a string list of topics (e.g. ``['DeviceCore[U]', 'FileDataCore'])``)
Returns a :class:`DeviceCloudMonitor` if found, otherwise None.
def get_monitor(self, topics):
"""Attempts to find a Monitor in devi... |
A function to get the python type to device cloud type converter function.
:param stream_type: The streams data type
:return: A function that when called with the python object will return the serializable
type for sending to the cloud. If there is no function for the given type, or the `stream_type`
i... |
A function to get Device Cloud type to python type converter function.
:param stream_type: The streams data type
:return: A function that when called with Device Cloud object will return the python
native type. If there is no function for the given type, or the `stream_type` is `None`
the returned func... |
Clear and update internal cache of stream objects
def _get_streams(self, uri_suffix=None):
"""Clear and update internal cache of stream objects"""
# TODO: handle paging, perhaps change this to be a generator
if uri_suffix is not None and not uri_suffix.startswith('/'):
uri_suffix = ... |
Create a new data stream on Device Cloud
This method will attempt to create a new data stream on Device Cloud.
This method will only succeed if the stream does not already exist.
:param str stream_id: The path/id of the stream being created on Device Cloud.
:param str data_type: The ty... |
Return a reference to a stream with the given ``stream_id`` if it exists
This works similar to :py:meth:`get_stream` but will return None if the
stream is not already created.
:param stream_id: The path of the stream on Device Cloud
:raises TypeError: if the stream_id provided is the w... |
Perform a bulk write (or set of writes) of a collection of data points
This method takes a list (or other iterable) of datapoints and writes them
to Device Cloud in an efficient manner, minimizing the number of HTTP
requests that need to be made.
As this call is performed from outside ... |
Create a new DataPoint object from device cloud JSON data
:param DataStream stream: The :class:`~DataStream` out of which this data is coming
:param dict json_data: Deserialized JSON data from Device Cloud about this device
:raises ValueError: if the data is malformed
:return: (:class:`... |
Rollup json data from the server looks slightly different
:param DataStream stream: The :class:`~DataStream` out of which this data is coming
:param dict json_data: Deserialized JSON data from Device Cloud about this device
:raises ValueError: if the data is malformed
:return: (:class:`... |
Set the stream id associated with this data point
def set_stream_id(self, stream_id):
"""Set the stream id associated with this data point"""
stream_id = validate_type(stream_id, type(None), *six.string_types)
if stream_id is not None:
stream_id = stream_id.lstrip('/')
self.... |
Set the description for this data point
def set_description(self, description):
"""Set the description for this data point"""
self._description = validate_type(description, type(None), *six.string_types) |
Set the quality for this sample
Quality is stored on Device Cloud as a 32-bit integer, so the input
to this function should be either None, an integer, or a string that can
be converted to an integer.
def set_quality(self, quality):
"""Set the quality for this sample
Quality i... |
Set the location for this data point
The location must be either None (if no location data is known) or a
3-tuple of floating point values in the form
(latitude-degrees, longitude-degrees, altitude-meters).
def set_location(self, location):
"""Set the location for this data point
... |
Set the data type for ths data point
The data type is actually associated with the stream itself and should
not (generally) vary on a point-per-point basis. That being said, if
creating a new stream by writing a datapoint, it may be beneficial to
include this information.
The ... |
Set the unit for this data point
Unit, as with data_type, are actually associated with the stream and not
the individual data point. As such, changing this within a stream is
not encouraged. Setting the unit on the data point is useful when the
stream might be created with the write o... |
Convert this datapoint into a form suitable for pushing to device cloud
An XML string will be returned that will contain all pieces of information
set on this datapoint. Values not set (e.g. quality) will be ommitted.
def to_xml(self):
"""Convert this datapoint into a form suitable for pushin... |
Retrieve metadata about this stream from Device Cloud
def _get_stream_metadata(self, use_cached):
"""Retrieve metadata about this stream from Device Cloud"""
if self._cached_data is None or not use_cached:
try:
self._cached_data = self._conn.get_json("/ws/DataStream/%s" % se... |
Get the data type of this stream if it exists
The data type is the type of data stored in this data stream. Valid types include:
* INTEGER - data can be represented with a network (= big-endian) 32-bit two's-complement integer. Data
with this type maps to a python int.
* LONG - data... |
Retrieve the dataTTL for this stream
The dataTtl is the time to live (TTL) in seconds for data points stored in the data stream.
A data point expires after the configured amount of time and is automatically deleted.
:param bool use_cached: If False, the function will always request the latest ... |
Retrieve the rollupTtl for this stream
The rollupTtl is the time to live (TTL) in seconds for the aggregate roll-ups of data points
stored in the stream. A roll-up expires after the configured amount of time and is
automatically deleted.
:param bool use_cached: If False, the function w... |
Return the most recent DataPoint value written to a stream
The current value is the last recorded data point for this stream.
:param bool use_cached: If False, the function will always request the latest from Device Cloud.
If True, the device will not make a request if it already has cache... |
Delete this stream from Device Cloud along with its history
This call will return None on success and raise an exception in the event of an error
performing the deletion.
:raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error
:raises devicecloud.streams.N... |
Delete the provided datapoint from this stream
:raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error
def delete_datapoint(self, datapoint):
"""Delete the provided datapoint from this stream
:raises devicecloud.DeviceCloudHttpException: in the case of an unexpec... |
Delete datapoints from this stream between the provided start and end times
If neither a start or end time is specified, all data points in the stream
will be deleted.
:param start_dt: The datetime after which data points should be deleted or None
if all data points from the beginn... |
Write some raw data to a stream using the DataPoint API
This method will mutate the datapoint provided to populate it with information
available from the stream as it is available (but without making any new HTTP
requests). For instance, we will add in information about the stream data
... |
Read one or more DataPoints from a stream
.. warning::
The data points from Device Cloud is a paged data set. When iterating over the
result set there could be delays when we hit the end of a page. If this is undesirable,
the caller should collect all results into a data stru... |
Return a single-quoted and escaped (percent-encoded) version of value
This function will also perform transforms of known data types to a representation
that will be handled by Device Cloud. For instance, datetime objects will be
converted to ISO8601.
def _quoted(value):
"""Return a single-quoted and... |
Compile this expression into a query string
def compile(self):
"""Compile this expression into a query string"""
return "{lhs}{sep}{rhs}".format(
lhs=self.lhs.compile(),
sep=self.sep,
rhs=self.rhs.compile(),
) |
Compile this expression into a query string
def compile(self):
"""Compile this expression into a query string"""
return "{attribute}{sep}{value}".format(
attribute=self.attribute,
sep=self.sep,
value=_quoted(self.value)
) |
Perform a read on input socket to consume headers and then return
a tuple of message type, message length.
:param session: Push Session to read data for.
Returns response type (i.e. PUBLISH_MESSAGE) if header was completely
read, otherwise None if header was not completely read.
def _read_msg_header(... |
Perform a read on input socket to consume message and then return the
payload and block_id in a tuple.
:param session: Push Session to read data for.
def _read_msg(session):
"""
Perform a read on input socket to consume message and then return the
payload and block_id in a tuple.
:param sessi... |
Sends a ConnectionRequest to the iDigi server using the credentials
established with the id of the monitor as defined in the monitor
member.
def send_connection_request(self):
"""
Sends a ConnectionRequest to the iDigi server using the credentials
established with the id of the ... |
Creates a TCP connection to Device Cloud and sends a ConnectionRequest message
def start(self):
"""Creates a TCP connection to Device Cloud and sends a ConnectionRequest message"""
self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id)
if self.socket is not None:
... |
Stop/Close this session
Close the socket associated with this session and puts Session
into a state such that it can be re-established later.
def stop(self):
"""Stop/Close this session
Close the socket associated with this session and puts Session
into a state such that it can... |
Creates a SSL connection to the iDigi Server and sends a
ConnectionRequest message.
def start(self):
"""
Creates a SSL connection to the iDigi Server and sends a
ConnectionRequest message.
"""
self.log.info("Starting SSL Session for Monitor %s."
% s... |
Continually blocks until data is on the internal queue, then calls
the session's registered callback and sends a PublishMessageReceived
if callback returned True.
def _consume_queue(self):
"""
Continually blocks until data is on the internal queue, then calls
the session's regis... |
Queues up a callback event to occur for a session with the given
payload data. Will block if the queue is full.
:param session: the session with a defined callback function to call.
:param block_id: the block_id of the message received.
:param data: the data payload of the message rece... |
Restarts and re-establishes session
:param session: The session to restart
def _restart_session(self, session):
"""Restarts and re-establishes session
:param session: The session to restart
"""
# remove old session key, if socket is None, that means the
# session was c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.