Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def fromdict(self, dikt):
s = dikt.copy()
start_addr = s.get('start_addr')
if start_addr is not None:
del s['start_addr']
for k in dict_keys_g(s):
if type(k) not in IntTypes or k < 0:
raise Valu... | [
"Load data from dictionary. Dictionary should contain int keys\n representing addresses. Values should be the data to be stored in\n those addresses in unsigned char form (i.e. not strings).\n The dictionary may contain the key, ``start_addr``\n to indicate the starting address of the da... |
Please provide a description of the function:def frombytes(self, bytes, offset=0):
for b in bytes:
self._buf[offset] = b
offset += 1 | [
"Load data from array or list of bytes.\n Similar to loadbin() method but works directly with iterable bytes.\n "
] |
Please provide a description of the function:def _get_start_end(self, start=None, end=None, size=None):
if (start,end) == (None,None) and self._buf == {}:
raise EmptyIntelHexError
if size is not None:
if None not in (start, end):
raise ValueError("tobinar... | [
"Return default values for start and end if they are None.\n If this IntelHex object is empty then it's error to\n invoke this method with both start and end as None.\n "
] |
Please provide a description of the function:def tobinarray(self, start=None, end=None, pad=_DEPRECATED, size=None):
''' Convert this object to binary form as array. If start and end
unspecified, they will be inferred from the data.
@param start start address of output bytes.
@param ... | [] |
Please provide a description of the function:def _tobinarray_really(self, start, end, pad, size):
if pad is None:
pad = self.padding
bin = array('B')
if self._buf == {} and None in (start, end):
return bin
if size is not None and size <= 0:
ra... | [
"Return binary array."
] |
Please provide a description of the function:def tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None):
''' Convert to binary form and return as binary string.
@param start start address of output bytes.
@param end end address of output bytes (inclusive).
@param pad ... | [] |
Please provide a description of the function:def tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None):
'''Convert to binary and write to file.
@param fobj file name or file object for writing output bytes.
@param start start address of output bytes.
@param end... | [] |
Please provide a description of the function:def todict(self):
'''Convert to python dictionary.
@return dict suitable for initializing another IntelHex object.
'''
r = {}
r.update(self._buf)
if self.start_addr:
r['start_addr'] = self.start_addr
... | [] |
Please provide a description of the function:def write_hex_file(self, f, write_start_addr=True, eolstyle='native', byte_count=16):
if byte_count > 255 or byte_count < 1:
raise ValueError("wrong byte_count value: %s" % byte_count)
fwrite = getattr(f, "write", None)
if fwrite:... | [
"Write data to file f in HEX format.\n\n @param f filename or file-like object for writing\n @param write_start_addr enable or disable writing start address\n record to file (enabled by default).\n If there is... |
Please provide a description of the function:def tofile(self, fobj, format):
if format == 'hex':
self.write_hex_file(fobj)
elif format == 'bin':
self.tobinfile(fobj)
else:
raise ValueError('format should be either "hex" or "bin";'
' go... | [
"Write data to hex or bin file. Preferred method over tobin or tohex.\n\n @param fobj file name or file-like object\n @param format file format (\"hex\" or \"bin\")\n "
] |
Please provide a description of the function:def gets(self, addr, length):
a = array('B', asbytes('\0'*length))
try:
for i in range_g(length):
a[i] = self._buf[addr+i]
except KeyError:
raise NotEnoughDataError(address=addr, length=length)
... | [
"Get string of bytes from given address. If any entries are blank\n from addr through addr+length, a NotEnoughDataError exception will\n be raised. Padding is not used.\n "
] |
Please provide a description of the function:def puts(self, addr, s):
a = array('B', asbytes(s))
for i in range_g(len(a)):
self._buf[addr+i] = a[i] | [
"Put string of bytes at given address. Will overwrite any previous\n entries.\n "
] |
Please provide a description of the function:def getsz(self, addr):
i = 0
try:
while True:
if self._buf[addr+i] == 0:
break
i += 1
except KeyError:
raise NotEnoughDataError(msg=('Bad access at 0x%X: '
... | [
"Get zero-terminated bytes string from given address. Will raise\n NotEnoughDataError exception if a hole is encountered before a 0.\n "
] |
Please provide a description of the function:def putsz(self, addr, s):
self.puts(addr, s)
self._buf[addr+len(s)] = 0 | [
"Put bytes string in object at addr and append terminating zero at end."
] |
Please provide a description of the function:def dump(self, tofile=None, width=16, withpadding=False):
if not isinstance(width,int) or width < 1:
raise ValueError('width must be a positive integer.')
# The integer can be of float type - does not work with bit operations
wid... | [
"Dump object content to specified file object or to stdout if None.\n Format is a hexdump with some header information at the beginning,\n addresses on the left, and data on right.\n\n @param tofile file-like object to dump to\n @param width number of bytes per line ... |
Please provide a description of the function:def merge(self, other, overlap='error'):
# check args
if not isinstance(other, IntelHex):
raise TypeError('other should be IntelHex object')
if other is self:
raise ValueError("Can't merge itself")
if overlap n... | [
"Merge content of other IntelHex object into current object (self).\n @param other other IntelHex object.\n @param overlap action on overlap of data or starting addr:\n - error: raising OverlapError;\n - ignore: ignore other data and keep current data\... |
Please provide a description of the function:def segments(self):
addresses = self.addresses()
if not addresses:
return []
elif len(addresses) == 1:
return([(addresses[0], addresses[0]+1)])
adjacent_differences = [(b - a) for (a, b) in zip(addresses[:-1], ... | [
"Return a list of ordered tuple objects, representing contiguous occupied data addresses.\n Each tuple has a length of two and follows the semantics of the range and xrange objects.\n The second entry of the tuple is always an integer greater than the first entry.\n "
] |
Please provide a description of the function:def get_memory_size(self):
n = sys.getsizeof(self)
n += sys.getsizeof(self.padding)
n += total_size(self.start_addr)
n += total_size(self._buf)
n += sys.getsizeof(self._offset)
return n | [
"Returns the approximate memory footprint for data."
] |
Please provide a description of the function:def tobinarray(self, start=None, end=None, size=None):
'''Convert this object to binary form as array (of 2-bytes word data).
If start and end unspecified, they will be inferred from the data.
@param start start address of output data.
@par... | [] |
Please provide a description of the function:def _from_bytes(bytes):
assert len(bytes) >= 4
# calculate checksum
s = (-sum(bytes)) & 0x0FF
bin = array('B', bytes + [s])
return ':' + asstr(hexlify(array_tobytes(bin))).upper() | [
"Takes a list of bytes, computes the checksum, and outputs the entire\n record as a string. bytes should be the hex record without the colon\n or final checksum.\n\n @param bytes list of byte values so far to pack into record.\n @return String representation of one HEX record\... |
Please provide a description of the function:def data(offset, bytes):
assert 0 <= offset < 65536
assert 0 < len(bytes) < 256
b = [len(bytes), (offset>>8)&0x0FF, offset&0x0FF, 0x00] + bytes
return Record._from_bytes(b) | [
"Return Data record. This constructs the full record, including\n the length information, the record type (0x00), the\n checksum, and the offset.\n\n @param offset load offset of first byte.\n @param bytes list of byte values to pack into record.\n\n @return String re... |
Please provide a description of the function:def start_segment_address(cs, ip):
b = [4, 0, 0, 0x03, (cs>>8)&0x0FF, cs&0x0FF,
(ip>>8)&0x0FF, ip&0x0FF]
return Record._from_bytes(b) | [
"Return Start Segment Address Record.\n @param cs 16-bit value for CS register.\n @param ip 16-bit value for IP register.\n\n @return String representation of Intel Hex SSA record.\n "
] |
Please provide a description of the function:def start_linear_address(eip):
b = [4, 0, 0, 0x05, (eip>>24)&0x0FF, (eip>>16)&0x0FF,
(eip>>8)&0x0FF, eip&0x0FF]
return Record._from_bytes(b) | [
"Return Start Linear Address Record.\n @param eip 32-bit linear address for the EIP register.\n\n @return String representation of Intel Hex SLA record.\n "
] |
Please provide a description of the function:def create_release_settings_action(target, source, env):
with open(str(source[0]), "r") as fileobj:
settings = json.load(fileobj)
settings['release'] = True
settings['release_date'] = datetime.datetime.utcnow().isoformat()
settings['dependency_... | [
"Copy module_settings.json and add release and build information\n "
] |
Please provide a description of the function:def copy_include_dirs(tile):
if 'products' not in tile.settings:
return
incdirs = tile.settings['products'].get('include_directories', [])
incdirs = map(lambda x: os.path.normpath(utilities.join_path(x)), incdirs)
incdirs = sorted(incdirs, key=... | [
"Copy all include directories that this tile defines as products in build/output/include\n "
] |
Please provide a description of the function:def copy_extra_files(tile):
env = Environment(tools=[])
outputbase = os.path.join('build', 'output')
for src, dest in tile.settings.get('copy_files', {}).items():
outputfile = os.path.join(outputbase, dest)
env.Command([outputfile], [src], ... | [
"Copy all files listed in a copy_files and copy_products section.\n\n Files listed in copy_files will be copied from the specified location\n in the current component to the specified path under the output\n folder.\n\n Files listed in copy_products will be looked up with a ProductResolver\n and copi... |
Please provide a description of the function:def copy_dependency_docs(tile):
env = Environment(tools=[])
outputbase = os.path.join('build', 'output', 'doc')
depbase = os.path.join('build', 'deps')
for dep in tile.dependencies:
depdir = os.path.join(depbase, dep['unique_id'], 'doc', dep['u... | [
"Copy all documentation from dependencies into build/output/doc folder"
] |
Please provide a description of the function:def copy_dependency_images(tile):
env = Environment(tools=[])
outputbase = os.path.join('build', 'output')
depbase = os.path.join('build', 'deps')
for dep in tile.dependencies:
depdir = os.path.join(depbase, dep['unique_id'])
outputdir ... | [
"Copy all documentation from dependencies into build/output/doc folder"
] |
Please provide a description of the function:def generate(env):
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
shared_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(... | [
"Add Builders and construction variables for masm to an Environment."
] |
Please provide a description of the function:def median(values):
values.sort()
n = int(len(values) / 2)
return values[n] | [
"Return median value for the list of values.\n @param values: list of values for processing.\n @return: median value.\n "
] |
Please provide a description of the function:def time_coef(tc, nc, tb, nb):
tc = float(tc)
nc = float(nc)
tb = float(tb)
nb = float(nb)
q = (tc * nb) / (tb * nc)
return q | [
"Return time coefficient relative to base numbers.\n @param tc: current test time\n @param nc: current test data size\n @param tb: base test time\n @param nb: base test data size\n @return: time coef.\n "
] |
Please provide a description of the function:def main(argv=None):
import getopt
# default values
test_read = None
test_write = None
n = 3 # number of repeat
if argv is None:
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, 'hn:rw', [])
for o,a ... | [
"Main function to run benchmarks.\n @param argv: command-line arguments.\n @return: exit code (0 is OK).\n "
] |
Please provide a description of the function:def measure_one(self, data):
_unused, hexstr, ih = data
tread, twrite = 0.0, 0.0
if self.read:
tread = run_readtest_N_times(intelhex.IntelHex, hexstr, self.n)[0]
if self.write:
twrite = run_writetest_N_times(ih... | [
"Do measuring of read and write operations.\n @param data: 3-tuple from get_test_data\n @return: (time readhex, time writehex)\n "
] |
Please provide a description of the function:def _get_key(cls, device_id):
var_name = "USER_KEY_{0:08X}".format(device_id)
if var_name not in os.environ:
raise NotFoundError("No user key could be found for devices", device_id=device_id,
expected_var... | [
"Attempt to get a user key from an environment variable\n "
] |
Please provide a description of the function:def sign_report(self, device_id, root, data, **kwargs):
report_key = self._verify_derive_key(device_id, root, **kwargs)
# We sign the SHA256 hash of the message
message_hash = hashlib.sha256(data).digest()
hmac_calc = hmac.new(repor... | [
"Sign a buffer of report data on behalf of a device.\n\n Args:\n device_id (int): The id of the device that we should encrypt for\n root (int): The root key type that should be used to generate the report\n data (bytearray): The data that we should sign\n **kwargs:... |
Please provide a description of the function:def verify_report(self, device_id, root, data, signature, **kwargs):
report_key = self._verify_derive_key(device_id, root, **kwargs)
message_hash = hashlib.sha256(data).digest()
hmac_calc = hmac.new(report_key, message_hash, hashlib.sha256)... | [
"Verify a buffer of report data on behalf of a device.\n\n Args:\n device_id (int): The id of the device that we should encrypt for\n root (int): The root key type that should be used to generate the report\n data (bytearray): The data that we should verify\n signa... |
Please provide a description of the function:def decrypt_report(self, device_id, root, data, **kwargs):
report_key = self._verify_derive_key(device_id, root, **kwargs)
try:
from Crypto.Cipher import AES
import Crypto.Util.Counter
except ImportError:
... | [
"Decrypt a buffer of report data on behalf of a device.\n\n Args:\n device_id (int): The id of the device that we should encrypt for\n root (int): The root key type that should be used to generate the report\n data (bytearray): The data that we should decrypt\n **k... |
Please provide a description of the function:def encrypt_report(self, device_id, root, data, **kwargs):
report_key = self._verify_derive_key(device_id, root, **kwargs)
try:
from Crypto.Cipher import AES
import Crypto.Util.Counter
except ImportError:
... | [
"Encrypt a buffer of report data on behalf of a device.\n\n Args:\n device_id (int): The id of the device that we should encrypt for\n root (int): The root key type that should be used to generate the report\n data (bytearray): The data that we should decrypt\n **k... |
Please provide a description of the function:def join_path(path):
if isinstance(path, str):
return path
return os.path.join(*path) | [
"If given a string, return it, otherwise combine a list into a string using os.path.join"
] |
Please provide a description of the function:def build_defines(defines):
return ['-D"%s=%s"' % (x, str(y)) for x, y in defines.items() if y is not None] | [
"Build a list of `-D` directives to pass to the compiler.\n\n This will drop any definitions whose value is None so that\n you can get rid of a define from another architecture by\n setting its value to null in the `module_settings.json`.\n "
] |
Please provide a description of the function:def connect_async(self, connection_id, connection_string, callback):
topics = MQTTTopicValidator(self.prefix + 'devices/{}'.format(connection_string))
key = self._generate_key()
name = self.name
conn_message = {'type': 'command', 'o... | [
"Connect to a device by its connection_string\n\n This function looks for the device on AWS IOT using the preconfigured\n topic prefix and looking for:\n <prefix>/devices/connection_string\n\n It then attempts to lock that device for exclusive access and\n returns a callback if su... |
Please provide a description of the function:def disconnect_async(self, conn_id, callback):
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
return
self.c... | [
"Asynchronously disconnect from a device that has previously been connected\n\n Args:\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n callback (callable): A function called as callback(conn_id, adapter_id, success,... |
Please provide a description of the function:def send_script_async(self, conn_id, data, progress_callback, callback):
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
... | [
"Asynchronously send a a script to this IOTile device\n\n Args:\n conn_id (int): A unique identifer that will refer to this connection\n data (string): the script to send to the device\n progress_callback (callable): A function to be called with status on our progress, called... |
Please provide a description of the function:def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback):
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information", 0... | [
"Asynchronously send an RPC to this IOTile device\n\n Args:\n conn_id (int): A unique identifier that will refer to this connection\n address (int): the address of the tile that we wish to send the RPC to\n rpc_id (int): the 16-bit id of the RPC we want to call\n p... |
Please provide a description of the function:def _open_interface(self, conn_id, iface, callback):
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
return
... | [
"Open an interface on this device\n\n Args:\n conn_id (int): the unique identifier for the connection\n iface (string): the interface name to open\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, f... |
Please provide a description of the function:def stop_sync(self):
conn_ids = self.conns.get_connections()
# If we have any open connections, try to close them here before shutting down
for conn in list(conn_ids):
try:
self.disconnect_sync(conn)
... | [
"Synchronously stop this adapter\n "
] |
Please provide a description of the function:def probe_async(self, callback):
topics = MQTTTopicValidator(self.prefix)
self.client.publish(topics.probe, {'type': 'command', 'operation': 'probe', 'client': self.name})
callback(self.id, True, None) | [
"Probe for visible devices connected to this DeviceAdapter.\n\n Args:\n callback (callable): A callback for when the probe operation has completed.\n callback should have signature callback(adapter_id, success, failure_reason) where:\n success: bool\n ... |
Please provide a description of the function:def periodic_callback(self):
while True:
try:
action = self._deferred.get(False)
action()
except queue.Empty:
break
except Exception:
self._logger.exception(... | [
"Periodically help maintain adapter internal state\n "
] |
Please provide a description of the function:def _bind_topics(self, topics):
# FIXME: Allow for these subscriptions to fail and clean up the previous ones
# so that this function is atomic
self.client.subscribe(topics.status, self._on_status_message)
self.client.subscribe(topi... | [
"Subscribe to all the topics we need to communication with this device\n\n Args:\n topics (MQTTTopicValidator): The topic validator for this device that\n we are connecting to.\n "
] |
Please provide a description of the function:def _unbind_topics(self, topics):
self.client.unsubscribe(topics.status)
self.client.unsubscribe(topics.tracing)
self.client.unsubscribe(topics.streaming)
self.client.unsubscribe(topics.response) | [
"Unsubscribe to all of the topics we needed for communication with device\n\n Args:\n topics (MQTTTopicValidator): The topic validator for this device that\n we have connected to.\n "
] |
Please provide a description of the function:def _find_connection(self, topic):
parts = topic.split('/')
if len(parts) < 3:
return None
slug = parts[-3]
return slug | [
"Attempt to find a connection id corresponding with a topic\n\n The device is found by assuming the topic ends in <slug>/[control|data]/channel\n\n Args:\n topic (string): The topic we received a message on\n\n Returns:\n int: The internal connect id (device slug) associat... |
Please provide a description of the function:def _on_report(self, sequence, topic, message):
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping report message that d... | [
"Process a report received from a device.\n\n Args:\n sequence (int): The sequence number of the packet received\n topic (string): The topic this message was received on\n message (dict): The message itself\n "
] |
Please provide a description of the function:def _on_trace(self, sequence, topic, message):
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping trace message that doe... | [
"Process a trace received from a device.\n\n Args:\n sequence (int): The sequence number of the packet received\n topic (string): The topic this message was received on\n message (dict): The message itself\n "
] |
Please provide a description of the function:def _on_status_message(self, sequence, topic, message):
self._logger.debug("Received message on (topic=%s): %s" % (topic, message))
try:
conn_key = self._find_connection(topic)
except ArgumentError:
self._logger.warn... | [
"Process a status message received\n\n Args:\n sequence (int): The sequence number of the packet received\n topic (string): The topic this message was received on\n message (dict): The message itself\n "
] |
Please provide a description of the function:def _on_response_message(self, sequence, topic, message):
try:
conn_key = self._find_connection(topic)
context = self.conns.get_context(conn_key)
except ArgumentError:
self._logger.warn("Dropping message that does... | [
"Process a response message received\n\n Args:\n sequence (int): The sequence number of the packet received\n topic (string): The topic this message was received on\n message (dict): The message itself\n "
] |
Please provide a description of the function:def build_args():
parser = argparse.ArgumentParser(description=u'Compile a sensor graph.')
parser.add_argument(u'sensor_graph', type=str, help=u"the sensor graph file to load and run.")
parser.add_argument(u'-f', u'--format', default=u"nodes", choices=[u'no... | [
"Create command line argument parser."
] |
Please provide a description of the function:def write_output(output, text=True, output_path=None):
if output_path is None and text is False:
print("ERROR: You must specify an output file using -o/--output for binary output formats")
sys.exit(1)
if output_path is not None:
if text... | [
"Write binary or text output to a file or stdout."
] |
Please provide a description of the function:def main():
arg_parser = build_args()
args = arg_parser.parse_args()
model = DeviceModel()
parser = SensorGraphFileParser()
parser.parse_file(args.sensor_graph)
if args.format == u'ast':
write_output(parser.dump_tree(), True, args.out... | [
"Main entry point for iotile-sgcompile."
] |
Please provide a description of the function:def load_external_components(typesys):
# Find all of the registered IOTile components and see if we need to add any type libraries for them
from iotile.core.dev.registry import ComponentRegistry
reg = ComponentRegistry()
modules = reg.list_components()... | [
"Load all external types defined by iotile plugins.\n\n This allows plugins to register their own types for type annotations and\n allows all registered iotile components that have associated type libraries to\n add themselves to the global type system.\n "
] |
Please provide a description of the function:def release(component=".", cloud=False):
comp = IOTile(component)
providers = _find_release_providers()
# If we were given a dev mode component that has been built, get its release mode version
if not comp.release and comp.release_date is not None:
... | [
"Release an IOTile component using release providers.\n\n Releasing an IOTile component means packaging up the products of its build process and storing\n them somewhere. The module_settings.json file of the IOTile component should have a\n \"release_steps\" key that lists the release providers that will ... |
Please provide a description of the function:def verify(self, obj):
if len(self._options) == 0:
raise ValidationError("No options", reason='no options given in options verifier, matching not possible',
object=obj)
exceptions = {}
for i, o... | [
"Verify that the object conforms to this verifier's schema\n\n Args:\n obj (object): A python object to verify\n\n Raises:\n ValidationError: If there is a problem verifying the dictionary, a\n ValidationError is thrown with at least the reason key set indicating\n... |
Please provide a description of the function:def add_recipe_folder(self, recipe_folder, whitelist=None):
if whitelist is not None:
whitelist = set(whitelist)
if recipe_folder == '':
recipe_folder = '.'
for yaml_file in [x for x in os.listdir(recipe_folder) if ... | [
"Add all recipes inside a folder to this RecipeManager with an optional whitelist.\n\n Args:\n recipe_folder (str): The path to the folder of recipes to add.\n whitelist (list): Only include files whose os.basename() matches something\n on the whitelist\n "
] |
Please provide a description of the function:def add_recipe_actions(self, recipe_actions):
for action_name, action in recipe_actions:
self._recipe_actions[action_name] = action | [
"Add additional valid recipe actions to RecipeManager\n\n args:\n recipe_actions (list): List of tuples. First value of tuple is the classname,\n second value of tuple is RecipeAction Object\n\n "
] |
Please provide a description of the function:def get_recipe(self, recipe_name):
if recipe_name.endswith('.yaml'):
recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name)
else:
recipe = self._recipes.get(recipe_nam... | [
"Get a recipe by name.\n\n Args:\n recipe_name (str): The name of the recipe to fetch. Can be either the\n yaml file name or the name of the recipe.\n "
] |
Please provide a description of the function:def _check_time_backwards(self):
now = time.time()
if now < self.start:
self.start = now
self.end = self.start + self.length | [
"Make sure a clock reset didn't cause time to go backwards\n "
] |
Please provide a description of the function:def expired(self):
if self._expired_latch:
return True
self._check_time_backwards()
if time.time() > self.end:
self._expired_latch = True
return True
return False | [
"Boolean property if this timeout has expired\n "
] |
Please provide a description of the function:def command(self, cmd_name, callback, *args):
cmd = JLinkCommand(cmd_name, args, callback)
self._commands.put(cmd) | [
"Run an asynchronous command.\n\n Args:\n cmd_name (int): The unique code for the command to execute.\n callback (callable): The optional callback to run when the command finishes.\n The signature should be callback(cmd_name, result, exception)\n *args: Any arg... |
Please provide a description of the function:def _send_rpc(self, device_info, control_info, address, rpc_id, payload, poll_interval, timeout):
write_address, write_data = control_info.format_rpc(address, rpc_id, payload)
self._jlink.memory_write32(write_address, write_data)
self._trig... | [
"Write and trigger an RPC."
] |
Please provide a description of the function:def _send_script(self, device_info, control_info, script, progress_callback):
for i in range(0, len(script), 20):
chunk = script[i:i+20]
self._send_rpc(device_info, control_info, 8, 0x2101, chunk, 0.001, 1.0)
if progress_... | [
"Send a script by repeatedly sending it as a bunch of RPCs.\n\n This function doesn't do anything special, it just sends a bunch of RPCs\n with each chunk of the script until it's finished.\n "
] |
Please provide a description of the function:def _trigger_rpc(self, device_info):
method = device_info.rpc_trigger
if isinstance(method, devices.RPCTriggerViaSWI):
self._jlink.memory_write32(method.register, [1 << method.bit])
else:
raise HardwareError("Unknown ... | [
"Trigger an RPC in a device specific way."
] |
Please provide a description of the function:def _find_control_structure(self, start_address, search_length):
words = self._read_memory(start_address, search_length, chunk_size=4, join=False)
found_offset = None
for i, word in enumerate(words):
if word == ControlStructure.... | [
"Find the control structure in RAM for this device.\n\n Returns:\n ControlStructure: The decoded contents of the shared memory control structure\n used for communication with this IOTile device.\n "
] |
Please provide a description of the function:def _verify_control_structure(self, device_info, control_info=None):
if control_info is None:
control_info = self._find_control_structure(device_info.ram_start, device_info.ram_size)
#FIXME: Actually reread the memory here to verify tha... | [
"Verify that a control structure is still valid or find one.\n\n Returns:\n ControlStructure: The verified or discovered control structure.\n "
] |
Please provide a description of the function:def save(self, out_path):
out = {
'selectors': [str(x) for x in self.selectors],
'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]
}
... | [
"Save an ascii representation of this simulation trace.\n\n Args:\n out_path (str): The output path to save this simulation trace.\n "
] |
Please provide a description of the function:def FromFile(cls, in_path):
with open(in_path, "rb") as infile:
in_data = json.load(infile)
if not ('trace', 'selectors') in in_data:
raise ArgumentError("Invalid trace file format", keys=in_data.keys(), expected=('trace', '... | [
"Load a previously saved ascii representation of this simulation trace.\n\n Args:\n in_path (str): The path of the input file that we should load.\n\n Returns:\n SimulationTrace: The loaded trace object.\n "
] |
Please provide a description of the function:def _on_scan(_loop, adapter, _adapter_id, info, expiration_time):
info['validity_period'] = expiration_time
adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info) | [
"Callback when a new device is seen."
] |
Please provide a description of the function:def _on_report(_loop, adapter, conn_id, report):
conn_string = None
if conn_id is not None:
conn_string = adapter._get_property(conn_id, 'connection_string')
if isinstance(report, BroadcastReport):
adapter.notify_event_nowait(conn_string, '... | [
"Callback when a report is received."
] |
Please provide a description of the function:def _on_trace(_loop, adapter, conn_id, trace):
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping trace data with unknown conn_id=%s", conn_id)
return
adapter.notify_eve... | [
"Callback when tracing data is received."
] |
Please provide a description of the function:def _on_disconnect(_loop, adapter, _adapter_id, conn_id):
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping disconnect notification with unknown conn_id=%s", conn_id)
return... | [
"Callback when a device disconnects unexpectedly."
] |
Please provide a description of the function:def _on_progress(adapter, operation, conn_id, done, total):
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
return
adapter.notify_progress(conn_string, operation, done, total) | [
"Callback when progress is reported."
] |
Please provide a description of the function:def get_config(self, name, default=_MISSING):
value = self._adapter.get_config(name, default)
if value is _MISSING:
raise ArgumentError("Config value did not exist", name=name)
return value | [
"Get a config value from this adapter by name\n\n Args:\n name (string): The name of the config variable\n default (object): The default value to return if config is not found\n\n Returns:\n object: the value associated with the name\n\n Raises:\n Arg... |
Please provide a description of the function:async def start(self):
self._loop.add_task(self._periodic_loop, name="periodic task for %s" % self._adapter.__class__.__name__,
parent=self._task)
self._adapter.add_callback('on_scan', functools.partial(_on_scan, self._l... | [
"Start the device adapter.\n\n See :meth:`AbstractDeviceAdapter.start`.\n "
] |
Please provide a description of the function:async def stop(self, _task=None):
self._logger.info("Stopping adapter wrapper")
if self._task.stopped:
return
for task in self._task.subtasks:
await task.stop()
self._logger.debug("Stopping underlying adapt... | [
"Stop the device adapter.\n\n See :meth:`AbstractDeviceAdapter.stop`.\n "
] |
Please provide a description of the function:async def connect(self, conn_id, connection_string):
self._logger.info("Inside connect, conn_id=%d, conn_string=%s", conn_id, connection_string)
try:
self._setup_connection(conn_id, connection_string)
resp = await self._exe... | [
"Connect to a device.\n\n See :meth:`AbstractDeviceAdapter.connect`.\n "
] |
Please provide a description of the function:async def disconnect(self, conn_id):
resp = await self._execute(self._adapter.disconnect_sync, conn_id)
_raise_error(conn_id, 'disconnect', resp)
self._teardown_connection(conn_id, force=True) | [
"Disconnect from a connected device.\n\n See :meth:`AbstractDeviceAdapter.disconnect`.\n "
] |
Please provide a description of the function:async def open_interface(self, conn_id, interface):
resp = await self._execute(self._adapter.open_interface_sync, conn_id, interface)
_raise_error(conn_id, 'open_interface', resp) | [
"Open an interface on an IOTile device.\n\n See :meth:`AbstractDeviceAdapter.open_interface`.\n "
] |
Please provide a description of the function:async def close_interface(self, conn_id, interface):
resp = await self._execute(self._adapter.close_interface_sync, conn_id, interface)
_raise_error(conn_id, 'close_interface', resp) | [
"Close an interface on this IOTile device.\n\n See :meth:`AbstractDeviceAdapter.close_interface`.\n "
] |
Please provide a description of the function:async def probe(self):
resp = await self._execute(self._adapter.probe_sync)
_raise_error(None, 'probe', resp) | [
"Probe for devices connected to this adapter.\n\n See :meth:`AbstractDeviceAdapter.probe`.\n "
] |
Please provide a description of the function:async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
resp = await self._execute(self._adapter.send_rpc_sync, conn_id, address, rpc_id, payload, timeout)
_raise_error(conn_id, 'send_rpc', resp)
status = resp.get('status')
... | [
"Send an RPC to a device.\n\n See :meth:`AbstractDeviceAdapter.send_rpc`.\n "
] |
Please provide a description of the function:async def debug(self, conn_id, name, cmd_args):
progress_callback = functools.partial(_on_progress, self, 'debug', conn_id)
resp = await self._execute(self._adapter.debug_sync, conn_id, name, cmd_args, progress_callback)
_raise_error(conn_i... | [
"Send a debug command to a device.\n\n See :meth:`AbstractDeviceAdapter.debug`.\n "
] |
Please provide a description of the function:async def send_script(self, conn_id, data):
progress_callback = functools.partial(_on_progress, self, 'script', conn_id)
resp = await self._execute(self._adapter.send_script_sync, conn_id, data, progress_callback)
_raise_error(conn_id, 'sen... | [
"Send a a script to a device.\n\n See :meth:`AbstractDeviceAdapter.send_script`.\n "
] |
Please provide a description of the function:def autobuild_shiparchive(src_file):
if not src_file.endswith('.tpl'):
raise BuildError("You must pass a .tpl file to autobuild_shiparchive", src_file=src_file)
env = Environment(tools=[])
family = ArchitectureGroup('module_settings.json')
tar... | [
"Create a ship file archive containing a yaml_file and its dependencies.\n\n If yaml_file depends on any build products as external files, it must\n be a jinja2 template that references the file using the find_product\n filter so that we can figure out where those build products are going\n and create t... |
Please provide a description of the function:def create_shipfile(target, source, env):
source_dir = os.path.dirname(str(source[0]))
recipe_name = os.path.basename(str(source[0]))[:-5]
resman = RecipeManager()
resman.add_recipe_actions(env['CUSTOM_STEPS'])
resman.add_recipe_folder(source_dir,... | [
"Create a .ship file with all dependencies."
] |
Please provide a description of the function:def record_trace(self, selectors=None):
if selectors is None:
selectors = [x.selector for x in self.sensor_graph.streamers]
self.trace = SimulationTrace(selectors=selectors)
for sel in selectors:
self.sensor_graph.s... | [
"Record a trace of readings produced by this simulator.\n\n This causes the property `self.trace` to be populated with a\n SimulationTrace object that contains all of the readings that\n are produced during the course of the simulation. Only readings\n that respond to specific selectors... |
Please provide a description of the function:def step(self, input_stream, value):
reading = IOTileReading(input_stream.encode(), self.tick_count, value)
self.sensor_graph.process_input(input_stream, reading, self.rpc_executor) | [
"Step the sensor graph through one since input.\n\n The internal tick count is not advanced so this function may\n be called as many times as desired to input specific conditions\n without simulation time passing.\n\n Args:\n input_stream (DataStream): The input stream to push... |
Please provide a description of the function:def run(self, include_reset=True, accelerated=True):
self._start_tick = self.tick_count
if self._check_stop_conditions(self.sensor_graph):
return
if include_reset:
pass # TODO: include a reset event here
#... | [
"Run this sensor graph until a stop condition is hit.\n\n Multiple calls to this function are useful only if\n there has been some change in the stop conditions that would\n cause the second call to not exit immediately.\n\n Args:\n include_reset (bool): Start the sensor graph... |
Please provide a description of the function:def _check_stop_conditions(self, sensor_graph):
for stop in self.stop_conditions:
if stop.should_stop(self.tick_count, self.tick_count - self._start_tick, sensor_graph):
return True
return False | [
"Check if any of our stop conditions are met.\n\n Args:\n sensor_graph (SensorGraph): The sensor graph we are currently simulating\n\n Returns:\n bool: True if we should stop the simulation\n "
] |
Please provide a description of the function:def stimulus(self, stimulus):
if not isinstance(stimulus, SimulationStimulus):
stimulus = SimulationStimulus.FromString(stimulus)
self.stimuli.append(stimulus)
self.stimuli.sort(key=lambda x:x.time) | [
"Add a simulation stimulus at a given time.\n\n A stimulus is a specific input given to the graph at a specific\n time to a specific input stream. The format for specifying a\n stimulus is:\n [time: ][system ]input X = Y\n where X and Y are integers.\n\n This will cause th... |
Please provide a description of the function:def stop_condition(self, condition):
# Try to parse this into a stop condition with each of our registered
# condition types
for cond_format in self._known_conditions:
try:
cond = cond_format.FromString(condition)... | [
"Add a stop condition to this simulation.\n\n Stop conditions are specified as strings and parsed into\n the appropriate internal structures.\n\n Args:\n condition (str): a string description of the stop condition\n "
] |
Please provide a description of the function:def dump(self):
walker = self.dump_walker
if walker is not None:
walker = walker.dump()
state = {
'storage': self.storage.dump(),
'dump_walker': walker,
'next_id': self.next_id
}
... | [
"Serialize the state of this subsystem into a dict.\n\n Returns:\n dict: The serialized state\n "
] |
Please provide a description of the function:def restore(self, state):
self.storage.restore(state.get('storage'))
dump_walker = state.get('dump_walker')
if dump_walker is not None:
dump_walker = self.storage.restore_walker(dump_walker)
self.dump_walker = dump_walk... | [
"Restore the state of this subsystem from a prior call to dump().\n\n Calling restore must be properly sequenced with calls to other\n subsystems that include stream walkers so that their walkers are\n properly restored.\n\n Args:\n state (dict): The results of a prior call to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.