id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,300 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py | RemoteBridgeMixin.reset_script | def reset_script(self):
"""Clear any partially received script."""
self.remote_bridge.status = BRIDGE_STATUS.IDLE
self.remote_bridge.error = 0
self.remote_bridge.parsed_script = None
self._device.script = bytearray()
return [0] | python | def reset_script(self):
self.remote_bridge.status = BRIDGE_STATUS.IDLE
self.remote_bridge.error = 0
self.remote_bridge.parsed_script = None
self._device.script = bytearray()
return [0] | [
"def",
"reset_script",
"(",
"self",
")",
":",
"self",
".",
"remote_bridge",
".",
"status",
"=",
"BRIDGE_STATUS",
".",
"IDLE",
"self",
".",
"remote_bridge",
".",
"error",
"=",
"0",
"self",
".",
"remote_bridge",
".",
"parsed_script",
"=",
"None",
"self",
"."... | Clear any partially received script. | [
"Clear",
"any",
"partially",
"received",
"script",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L129-L137 |
23,301 | iotile/coretools | iotilebuild/iotile/build/utilities/template.py | render_template_inplace | def render_template_inplace(template_path, info, dry_run=False, extra_filters=None, resolver=None):
"""Render a template file in place.
This function expects template path to be a path to a file
that ends in .tpl. It will be rendered to a file in the
same directory with the .tpl suffix removed.
Args:
template_path (str): The path to the template file
that we want to render in place.
info (dict): A dictionary of variables passed into the template to
perform substitutions.
dry_run (bool): Whether to actually render the output file or just return
the file path that would be generated.
extra_filters (dict of str -> callable): An optional group of filters that
will be made available to the template. The dict key will be the
name at which callable is made available.
resolver (ProductResolver): The specific ProductResolver class to use in the
find_product filter.
Returns:
str: The path to the output file generated.
"""
filters = {}
if resolver is not None:
filters['find_product'] = _create_resolver_filter(resolver)
if extra_filters is not None:
filters.update(extra_filters)
basedir = os.path.dirname(template_path)
template_name = os.path.basename(template_path)
if not template_name.endswith('.tpl'):
raise ArgumentError("You must specify a filename that ends in .tpl", filepath=template_path)
out_path = os.path.join(basedir, template_name[:-4])
if basedir == '':
basedir = '.'
env = Environment(loader=FileSystemLoader(basedir),
trim_blocks=True, lstrip_blocks=True)
# Load any filters the user wants us to use
for name, func in filters.items():
env.filters[name] = func
template = env.get_template(template_name)
result = template.render(info)
if not dry_run:
with open(out_path, 'wb') as outfile:
outfile.write(result.encode('utf-8'))
return out_path | python | def render_template_inplace(template_path, info, dry_run=False, extra_filters=None, resolver=None):
filters = {}
if resolver is not None:
filters['find_product'] = _create_resolver_filter(resolver)
if extra_filters is not None:
filters.update(extra_filters)
basedir = os.path.dirname(template_path)
template_name = os.path.basename(template_path)
if not template_name.endswith('.tpl'):
raise ArgumentError("You must specify a filename that ends in .tpl", filepath=template_path)
out_path = os.path.join(basedir, template_name[:-4])
if basedir == '':
basedir = '.'
env = Environment(loader=FileSystemLoader(basedir),
trim_blocks=True, lstrip_blocks=True)
# Load any filters the user wants us to use
for name, func in filters.items():
env.filters[name] = func
template = env.get_template(template_name)
result = template.render(info)
if not dry_run:
with open(out_path, 'wb') as outfile:
outfile.write(result.encode('utf-8'))
return out_path | [
"def",
"render_template_inplace",
"(",
"template_path",
",",
"info",
",",
"dry_run",
"=",
"False",
",",
"extra_filters",
"=",
"None",
",",
"resolver",
"=",
"None",
")",
":",
"filters",
"=",
"{",
"}",
"if",
"resolver",
"is",
"not",
"None",
":",
"filters",
... | Render a template file in place.
This function expects template path to be a path to a file
that ends in .tpl. It will be rendered to a file in the
same directory with the .tpl suffix removed.
Args:
template_path (str): The path to the template file
that we want to render in place.
info (dict): A dictionary of variables passed into the template to
perform substitutions.
dry_run (bool): Whether to actually render the output file or just return
the file path that would be generated.
extra_filters (dict of str -> callable): An optional group of filters that
will be made available to the template. The dict key will be the
name at which callable is made available.
resolver (ProductResolver): The specific ProductResolver class to use in the
find_product filter.
Returns:
str: The path to the output file generated. | [
"Render",
"a",
"template",
"file",
"in",
"place",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/utilities/template.py#L20-L76 |
23,302 | iotile/coretools | iotilebuild/iotile/build/utilities/template.py | render_template | def render_template(template_name, info, out_path=None):
"""Render a template using the variables in info.
You can optionally render to a file by passing out_path.
Args:
template_name (str): The name of the template to load. This must
be a file in config/templates inside this package
out_path (str): An optional path of where to save the output
file, otherwise it is just returned as a string.
info (dict): A dictionary of variables passed into the template to
perform substitutions.
Returns:
string: The rendered template data.
"""
env = Environment(loader=PackageLoader('iotile.build', 'config/templates'),
trim_blocks=True, lstrip_blocks=True)
template = env.get_template(template_name)
result = template.render(info)
if out_path is not None:
with open(out_path, 'wb') as outfile:
outfile.write(result.encode('utf-8'))
return result | python | def render_template(template_name, info, out_path=None):
env = Environment(loader=PackageLoader('iotile.build', 'config/templates'),
trim_blocks=True, lstrip_blocks=True)
template = env.get_template(template_name)
result = template.render(info)
if out_path is not None:
with open(out_path, 'wb') as outfile:
outfile.write(result.encode('utf-8'))
return result | [
"def",
"render_template",
"(",
"template_name",
",",
"info",
",",
"out_path",
"=",
"None",
")",
":",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"PackageLoader",
"(",
"'iotile.build'",
",",
"'config/templates'",
")",
",",
"trim_blocks",
"=",
"True",
",",
... | Render a template using the variables in info.
You can optionally render to a file by passing out_path.
Args:
template_name (str): The name of the template to load. This must
be a file in config/templates inside this package
out_path (str): An optional path of where to save the output
file, otherwise it is just returned as a string.
info (dict): A dictionary of variables passed into the template to
perform substitutions.
Returns:
string: The rendered template data. | [
"Render",
"a",
"template",
"using",
"the",
"variables",
"in",
"info",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/utilities/template.py#L79-L106 |
23,303 | iotile/coretools | iotilebuild/iotile/build/utilities/template.py | render_recursive_template | def render_recursive_template(template_folder, info, out_folder, preserve=None, dry_run=False):
"""Copy a directory tree rendering all templates found within.
This function inspects all of the files in template_folder recursively. If
any file ends .tpl, it is rendered using render_template and the .tpl
suffix is removed. All other files are copied without modification.
out_folder is not cleaned before rendering so you must delete its contents
yourself if you want that behavior.
If you just want to see all of the file paths that would be generated,
call with dry_run=True. This will not render anything but just inspect
what would be generated.
Args:
template_folder (str): A relative path from config/templates with the
folder that should be rendered recursively.
info (dict): A dictionary of variables to be substituted into any
templates found in template_folder.
out_folder (str): The path to the output folder where the template will
be generated.
dry_run (bool): Whether to actually render output files or just return
the files that would be generated.
preserve (list of str): A list of file names relative to the start of the
template folder that we are rendering that end in .tpl but should not
be rendered and should not have their .tpl suffix removed. This allows
you to partially render a template so that you can render a specific
file later.
Returns:
dict, list: The dict is map of output file path (relative to
out_folder) to the absolute path of the input file that it depends
on. This result is suitable for using in a dependency graph like
SCons. The list is a list of all of the directories that would need
to be created to hold these files (not including out_folder).
"""
if isinstance(preserve, str):
raise ArgumentError("You must pass a list of strings to preserve, not a string", preserve=preserve)
if preserve is None:
preserve = []
preserve = set(preserve)
template_dir = resource_path('templates', expect='folder')
indir = os.path.join(template_dir, template_folder)
if not os.path.exists(indir):
raise ArgumentError("Input template folder for recursive template not found",
template_folder=template_folder, absolute_path=indir)
elif not os.path.isdir(indir):
raise ArgumentError("Input template folder is not a directory",
template_folder=template_folder, absolute_path=indir)
create_dirs = []
file_map = {}
# Walk over all input files
for dirpath, dirs, files in os.walk(indir):
for file in files:
in_abspath = os.path.abspath(os.path.join(dirpath, file))
in_path = os.path.relpath(os.path.join(dirpath, file), start=indir)
if file.endswith(".tpl") and not in_path in preserve:
out_path = in_path[:-4]
else:
out_path = in_path
file_map[out_path] = (in_path, in_abspath)
for folder in dirs:
dir_path = os.path.relpath(os.path.join(dirpath, folder), start=indir)
create_dirs.append(dir_path)
# Actually render / copy all files if we are not doing a dry run
if not dry_run:
for folder in create_dirs:
out_path = os.path.join(out_folder, folder)
if not os.path.isdir(out_path):
os.makedirs(out_path)
for out_rel, (in_path, in_abspath) in file_map.items():
out_path = os.path.join(out_folder, out_rel)
if in_path in preserve or not in_path.endswith(".tpl"):
shutil.copyfile(in_abspath, out_path)
else:
# jinja needs to have unix path separators regardless of the platform and a relative path
# from the templates base directory
in_template_path = os.path.join(template_folder, in_path).replace(os.path.sep, '/')
render_template(in_template_path, info, out_path=out_path)
return file_map, create_dirs | python | def render_recursive_template(template_folder, info, out_folder, preserve=None, dry_run=False):
if isinstance(preserve, str):
raise ArgumentError("You must pass a list of strings to preserve, not a string", preserve=preserve)
if preserve is None:
preserve = []
preserve = set(preserve)
template_dir = resource_path('templates', expect='folder')
indir = os.path.join(template_dir, template_folder)
if not os.path.exists(indir):
raise ArgumentError("Input template folder for recursive template not found",
template_folder=template_folder, absolute_path=indir)
elif not os.path.isdir(indir):
raise ArgumentError("Input template folder is not a directory",
template_folder=template_folder, absolute_path=indir)
create_dirs = []
file_map = {}
# Walk over all input files
for dirpath, dirs, files in os.walk(indir):
for file in files:
in_abspath = os.path.abspath(os.path.join(dirpath, file))
in_path = os.path.relpath(os.path.join(dirpath, file), start=indir)
if file.endswith(".tpl") and not in_path in preserve:
out_path = in_path[:-4]
else:
out_path = in_path
file_map[out_path] = (in_path, in_abspath)
for folder in dirs:
dir_path = os.path.relpath(os.path.join(dirpath, folder), start=indir)
create_dirs.append(dir_path)
# Actually render / copy all files if we are not doing a dry run
if not dry_run:
for folder in create_dirs:
out_path = os.path.join(out_folder, folder)
if not os.path.isdir(out_path):
os.makedirs(out_path)
for out_rel, (in_path, in_abspath) in file_map.items():
out_path = os.path.join(out_folder, out_rel)
if in_path in preserve or not in_path.endswith(".tpl"):
shutil.copyfile(in_abspath, out_path)
else:
# jinja needs to have unix path separators regardless of the platform and a relative path
# from the templates base directory
in_template_path = os.path.join(template_folder, in_path).replace(os.path.sep, '/')
render_template(in_template_path, info, out_path=out_path)
return file_map, create_dirs | [
"def",
"render_recursive_template",
"(",
"template_folder",
",",
"info",
",",
"out_folder",
",",
"preserve",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"preserve",
",",
"str",
")",
":",
"raise",
"ArgumentError",
"(",
"\"You... | Copy a directory tree rendering all templates found within.
This function inspects all of the files in template_folder recursively. If
any file ends .tpl, it is rendered using render_template and the .tpl
suffix is removed. All other files are copied without modification.
out_folder is not cleaned before rendering so you must delete its contents
yourself if you want that behavior.
If you just want to see all of the file paths that would be generated,
call with dry_run=True. This will not render anything but just inspect
what would be generated.
Args:
template_folder (str): A relative path from config/templates with the
folder that should be rendered recursively.
info (dict): A dictionary of variables to be substituted into any
templates found in template_folder.
out_folder (str): The path to the output folder where the template will
be generated.
dry_run (bool): Whether to actually render output files or just return
the files that would be generated.
preserve (list of str): A list of file names relative to the start of the
template folder that we are rendering that end in .tpl but should not
be rendered and should not have their .tpl suffix removed. This allows
you to partially render a template so that you can render a specific
file later.
Returns:
dict, list: The dict is map of output file path (relative to
out_folder) to the absolute path of the input file that it depends
on. This result is suitable for using in a dependency graph like
SCons. The list is a list of all of the directories that would need
to be created to hold these files (not including out_folder). | [
"Copy",
"a",
"directory",
"tree",
"rendering",
"all",
"templates",
"found",
"within",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/utilities/template.py#L109-L201 |
23,304 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | _find_monitor | def _find_monitor(monitors, handle):
"""Find all devices and events with a given monitor installed."""
found_devs = set()
found_events = set()
for conn_string, device in monitors.items():
for event, handles in device.items():
if handle in handles:
found_events.add(event)
found_devs.add(conn_string)
return found_devs, found_events | python | def _find_monitor(monitors, handle):
found_devs = set()
found_events = set()
for conn_string, device in monitors.items():
for event, handles in device.items():
if handle in handles:
found_events.add(event)
found_devs.add(conn_string)
return found_devs, found_events | [
"def",
"_find_monitor",
"(",
"monitors",
",",
"handle",
")",
":",
"found_devs",
"=",
"set",
"(",
")",
"found_events",
"=",
"set",
"(",
")",
"for",
"conn_string",
",",
"device",
"in",
"monitors",
".",
"items",
"(",
")",
":",
"for",
"event",
",",
"handle... | Find all devices and events with a given monitor installed. | [
"Find",
"all",
"devices",
"and",
"events",
"with",
"a",
"given",
"monitor",
"installed",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L289-L301 |
23,305 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | _add_monitor | def _add_monitor(monitors, handle, callback, devices, events):
"""Add the given monitor to the listed devices and events."""
for conn_string in devices:
data = monitors.get(conn_string)
if data is None:
data = dict()
monitors[conn_string] = data
for event in events:
event_dict = data.get(event)
if event_dict is None:
event_dict = dict()
data[event] = event_dict
event_dict[handle] = callback | python | def _add_monitor(monitors, handle, callback, devices, events):
for conn_string in devices:
data = monitors.get(conn_string)
if data is None:
data = dict()
monitors[conn_string] = data
for event in events:
event_dict = data.get(event)
if event_dict is None:
event_dict = dict()
data[event] = event_dict
event_dict[handle] = callback | [
"def",
"_add_monitor",
"(",
"monitors",
",",
"handle",
",",
"callback",
",",
"devices",
",",
"events",
")",
":",
"for",
"conn_string",
"in",
"devices",
":",
"data",
"=",
"monitors",
".",
"get",
"(",
"conn_string",
")",
"if",
"data",
"is",
"None",
":",
... | Add the given monitor to the listed devices and events. | [
"Add",
"the",
"given",
"monitor",
"to",
"the",
"listed",
"devices",
"and",
"events",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L304-L319 |
23,306 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | _remove_monitor | def _remove_monitor(monitors, handle, devices, events):
"""Remove the given monitor from the listed devices and events."""
empty_devices = []
for conn_string in devices:
data = monitors.get(conn_string)
if data is None:
continue
for event in events:
event_dict = data.get(event)
if event_dict is None:
continue
if handle in event_dict:
del event_dict[handle]
if len(event_dict) == 0:
del data[event]
if len(data) == 0:
empty_devices.append(conn_string)
return empty_devices | python | def _remove_monitor(monitors, handle, devices, events):
empty_devices = []
for conn_string in devices:
data = monitors.get(conn_string)
if data is None:
continue
for event in events:
event_dict = data.get(event)
if event_dict is None:
continue
if handle in event_dict:
del event_dict[handle]
if len(event_dict) == 0:
del data[event]
if len(data) == 0:
empty_devices.append(conn_string)
return empty_devices | [
"def",
"_remove_monitor",
"(",
"monitors",
",",
"handle",
",",
"devices",
",",
"events",
")",
":",
"empty_devices",
"=",
"[",
"]",
"for",
"conn_string",
"in",
"devices",
":",
"data",
"=",
"monitors",
".",
"get",
"(",
"conn_string",
")",
"if",
"data",
"is... | Remove the given monitor from the listed devices and events. | [
"Remove",
"the",
"given",
"monitor",
"from",
"the",
"listed",
"devices",
"and",
"events",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L322-L346 |
23,307 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | BasicNotificationMixin.register_monitor | def register_monitor(self, devices, events, callback):
"""Register a callback when events happen.
If this method is called, it is guaranteed to take effect before the
next call to ``_notify_event`` after this method returns. This method
is safe to call from within a callback that is itself called by
``notify_event``.
See :meth:`AbstractDeviceAdapter.register_monitor`.
"""
# Ensure we don't exhaust any iterables
events = list(events)
devices = list(devices)
for event in events:
if event not in self.SUPPORTED_EVENTS:
raise ArgumentError("Unknown event type {} specified".format(event), events=events)
monitor_id = str(uuid.uuid4())
action = (monitor_id, "add", devices, events)
self._callbacks[monitor_id] = callback
if self._currently_notifying:
self._deferred_adjustments.append(action)
else:
self._adjust_monitor_internal(*action)
return monitor_id | python | def register_monitor(self, devices, events, callback):
# Ensure we don't exhaust any iterables
events = list(events)
devices = list(devices)
for event in events:
if event not in self.SUPPORTED_EVENTS:
raise ArgumentError("Unknown event type {} specified".format(event), events=events)
monitor_id = str(uuid.uuid4())
action = (monitor_id, "add", devices, events)
self._callbacks[monitor_id] = callback
if self._currently_notifying:
self._deferred_adjustments.append(action)
else:
self._adjust_monitor_internal(*action)
return monitor_id | [
"def",
"register_monitor",
"(",
"self",
",",
"devices",
",",
"events",
",",
"callback",
")",
":",
"# Ensure we don't exhaust any iterables",
"events",
"=",
"list",
"(",
"events",
")",
"devices",
"=",
"list",
"(",
"devices",
")",
"for",
"event",
"in",
"events",... | Register a callback when events happen.
If this method is called, it is guaranteed to take effect before the
next call to ``_notify_event`` after this method returns. This method
is safe to call from within a callback that is itself called by
``notify_event``.
See :meth:`AbstractDeviceAdapter.register_monitor`. | [
"Register",
"a",
"callback",
"when",
"events",
"happen",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L58-L87 |
23,308 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | BasicNotificationMixin.adjust_monitor | def adjust_monitor(self, handle, action, devices, events):
"""Adjust a previously registered callback.
See :meth:`AbstractDeviceAdapter.adjust_monitor`.
"""
events = list(events)
devices = list(devices)
for event in events:
if event not in self.SUPPORTED_EVENTS:
raise ArgumentError("Unknown event type {} specified".format(event), events=events)
if action not in self.SUPPORTED_ADJUSTMENTS:
raise ArgumentError("Unknown adjustment {} specified".format(action))
action = (handle, action, devices, events)
if self._currently_notifying:
self._deferred_adjustments.append(action)
else:
self._adjust_monitor_internal(*action) | python | def adjust_monitor(self, handle, action, devices, events):
events = list(events)
devices = list(devices)
for event in events:
if event not in self.SUPPORTED_EVENTS:
raise ArgumentError("Unknown event type {} specified".format(event), events=events)
if action not in self.SUPPORTED_ADJUSTMENTS:
raise ArgumentError("Unknown adjustment {} specified".format(action))
action = (handle, action, devices, events)
if self._currently_notifying:
self._deferred_adjustments.append(action)
else:
self._adjust_monitor_internal(*action) | [
"def",
"adjust_monitor",
"(",
"self",
",",
"handle",
",",
"action",
",",
"devices",
",",
"events",
")",
":",
"events",
"=",
"list",
"(",
"events",
")",
"devices",
"=",
"list",
"(",
"devices",
")",
"for",
"event",
"in",
"events",
":",
"if",
"event",
"... | Adjust a previously registered callback.
See :meth:`AbstractDeviceAdapter.adjust_monitor`. | [
"Adjust",
"a",
"previously",
"registered",
"callback",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L118-L138 |
23,309 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | BasicNotificationMixin.remove_monitor | def remove_monitor(self, handle):
"""Remove a previously registered monitor.
See :meth:`AbstractDeviceAdapter.adjust_monitor`.
"""
action = (handle, "delete", None, None)
if self._currently_notifying:
self._deferred_adjustments.append(action)
else:
self._adjust_monitor_internal(*action) | python | def remove_monitor(self, handle):
action = (handle, "delete", None, None)
if self._currently_notifying:
self._deferred_adjustments.append(action)
else:
self._adjust_monitor_internal(*action) | [
"def",
"remove_monitor",
"(",
"self",
",",
"handle",
")",
":",
"action",
"=",
"(",
"handle",
",",
"\"delete\"",
",",
"None",
",",
"None",
")",
"if",
"self",
".",
"_currently_notifying",
":",
"self",
".",
"_deferred_adjustments",
".",
"append",
"(",
"action... | Remove a previously registered monitor.
See :meth:`AbstractDeviceAdapter.adjust_monitor`. | [
"Remove",
"a",
"previously",
"registered",
"monitor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L140-L150 |
23,310 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | BasicNotificationMixin._notify_event_internal | async def _notify_event_internal(self, conn_string, name, event):
"""Notify that an event has occured.
This method will send a notification and ensure that all callbacks
registered for it have completed by the time it returns. In
particular, if the callbacks are awaitable, this method will await
them before returning. The order in which the callbacks are called
is undefined.
This is a low level method that is not intended to be called directly.
You should use the high level public notify_* methods for each of the
types of events to ensure consistency in how the event objects are
created.
Args:
conn_string (str): The connection string for the device that the
event is associated with.
name (str): The name of the event. Must be in SUPPORTED_EVENTS.
event (object): The event object. The type of this object will
depend on what is being notified.
"""
try:
self._currently_notifying = True
conn_id = self._get_conn_id(conn_string)
event_maps = self._monitors.get(conn_string, {})
wildcard_maps = self._monitors.get(None, {})
wildcard_handlers = wildcard_maps.get(name, {})
event_handlers = event_maps.get(name, {})
for handler, func in itertools.chain(event_handlers.items(), wildcard_handlers.items()):
try:
result = func(conn_string, conn_id, name, event)
if inspect.isawaitable(result):
await result
except: #pylint:disable=bare-except;This is a background function and we are logging exceptions
self._logger.warning("Error calling notification callback id=%s, func=%s", handler, func, exc_info=True)
finally:
for action in self._deferred_adjustments:
self._adjust_monitor_internal(*action)
self._deferred_adjustments = []
self._currently_notifying = False | python | async def _notify_event_internal(self, conn_string, name, event):
try:
self._currently_notifying = True
conn_id = self._get_conn_id(conn_string)
event_maps = self._monitors.get(conn_string, {})
wildcard_maps = self._monitors.get(None, {})
wildcard_handlers = wildcard_maps.get(name, {})
event_handlers = event_maps.get(name, {})
for handler, func in itertools.chain(event_handlers.items(), wildcard_handlers.items()):
try:
result = func(conn_string, conn_id, name, event)
if inspect.isawaitable(result):
await result
except: #pylint:disable=bare-except;This is a background function and we are logging exceptions
self._logger.warning("Error calling notification callback id=%s, func=%s", handler, func, exc_info=True)
finally:
for action in self._deferred_adjustments:
self._adjust_monitor_internal(*action)
self._deferred_adjustments = []
self._currently_notifying = False | [
"async",
"def",
"_notify_event_internal",
"(",
"self",
",",
"conn_string",
",",
"name",
",",
"event",
")",
":",
"try",
":",
"self",
".",
"_currently_notifying",
"=",
"True",
"conn_id",
"=",
"self",
".",
"_get_conn_id",
"(",
"conn_string",
")",
"event_maps",
... | Notify that an event has occured.
This method will send a notification and ensure that all callbacks
registered for it have completed by the time it returns. In
particular, if the callbacks are awaitable, this method will await
them before returning. The order in which the callbacks are called
is undefined.
This is a low level method that is not intended to be called directly.
You should use the high level public notify_* methods for each of the
types of events to ensure consistency in how the event objects are
created.
Args:
conn_string (str): The connection string for the device that the
event is associated with.
name (str): The name of the event. Must be in SUPPORTED_EVENTS.
event (object): The event object. The type of this object will
depend on what is being notified. | [
"Notify",
"that",
"an",
"event",
"has",
"occured",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L152-L196 |
23,311 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | BasicNotificationMixin.notify_progress | def notify_progress(self, conn_string, operation, finished, total, wait=True):
"""Send a progress event.
Progress events can be sent for ``debug`` and ``script`` operations and
notify the caller about the progress of these potentially long-running
operations. They have two integer properties that specify what fraction
of the operation has been completed.
Args:
conn_string (str): The device that is sending the event.
operations (str): The operation that is in progress: debug or script
finished (int): The number of "steps" that have finished.
total (int): The total number of steps to perform.
wait (bool): Whether to return an awaitable that we can use to
block until the notification has made it to all callbacks.
Returns:
awaitable or None: An awaitable if wait=True.
If wait is False, the notification is run in the background with
no way to check its progress and None is returned.
"""
if operation not in self.PROGRESS_OPERATIONS:
raise ArgumentError("Invalid operation for progress event: {}".format(operation))
event = dict(operation=operation, finished=finished, total=total)
if wait:
return self.notify_event(conn_string, 'progress', event)
self.notify_event_nowait(conn_string, 'progress', event)
return None | python | def notify_progress(self, conn_string, operation, finished, total, wait=True):
if operation not in self.PROGRESS_OPERATIONS:
raise ArgumentError("Invalid operation for progress event: {}".format(operation))
event = dict(operation=operation, finished=finished, total=total)
if wait:
return self.notify_event(conn_string, 'progress', event)
self.notify_event_nowait(conn_string, 'progress', event)
return None | [
"def",
"notify_progress",
"(",
"self",
",",
"conn_string",
",",
"operation",
",",
"finished",
",",
"total",
",",
"wait",
"=",
"True",
")",
":",
"if",
"operation",
"not",
"in",
"self",
".",
"PROGRESS_OPERATIONS",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid... | Send a progress event.
Progress events can be sent for ``debug`` and ``script`` operations and
notify the caller about the progress of these potentially long-running
operations. They have two integer properties that specify what fraction
of the operation has been completed.
Args:
conn_string (str): The device that is sending the event.
operations (str): The operation that is in progress: debug or script
finished (int): The number of "steps" that have finished.
total (int): The total number of steps to perform.
wait (bool): Whether to return an awaitable that we can use to
block until the notification has made it to all callbacks.
Returns:
awaitable or None: An awaitable if wait=True.
If wait is False, the notification is run in the background with
no way to check its progress and None is returned. | [
"Send",
"a",
"progress",
"event",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L254-L286 |
23,312 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgicxx.py | generate | def generate(env):
"""Add Builders and construction variables for SGI MIPS C++ to an Environment."""
cplusplus.generate(env)
env['CXX'] = 'CC'
env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std')
env['SHCXX'] = '$CXX'
env['SHOBJSUFFIX'] = '.o'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 | python | def generate(env):
cplusplus.generate(env)
env['CXX'] = 'CC'
env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std')
env['SHCXX'] = '$CXX'
env['SHOBJSUFFIX'] = '.o'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 | [
"def",
"generate",
"(",
"env",
")",
":",
"cplusplus",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'CXX'",
"]",
"=",
"'CC'",
"env",
"[",
"'CXXFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'-LANG:std'",
")",
"env",
"[",
"'SHCXX'",
"... | Add Builders and construction variables for SGI MIPS C++ to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"SGI",
"MIPS",
"C",
"++",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgicxx.py#L43-L52 |
23,313 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/async_packet.py | AsyncPacketBuffer.read_packet | def read_packet(self, timeout=3.0):
"""read one packet, timeout if one packet is not available in the timeout period"""
try:
return self.queue.get(timeout=timeout)
except Empty:
raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer") | python | def read_packet(self, timeout=3.0):
try:
return self.queue.get(timeout=timeout)
except Empty:
raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer") | [
"def",
"read_packet",
"(",
"self",
",",
"timeout",
"=",
"3.0",
")",
":",
"try",
":",
"return",
"self",
".",
"queue",
".",
"get",
"(",
"timeout",
"=",
"timeout",
")",
"except",
"Empty",
":",
"raise",
"InternalTimeoutError",
"(",
"\"Timeout waiting for packet ... | read one packet, timeout if one packet is not available in the timeout period | [
"read",
"one",
"packet",
"timeout",
"if",
"one",
"packet",
"is",
"not",
"available",
"in",
"the",
"timeout",
"period"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/async_packet.py#L45-L51 |
23,314 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javac.py | generate | def generate(env):
"""Add Builders and construction variables for javac to an Environment."""
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_class = SCons.Tool.CreateJavaClassFileBuilder(env)
java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env)
java_class.add_emitter(None, emit_java_classes)
java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes)
java_class_dir.emitter = emit_java_classes
env.AddMethod(Java)
env['JAVAC'] = 'javac'
env['JAVACFLAGS'] = SCons.Util.CLVar('')
env['JAVABOOTCLASSPATH'] = []
env['JAVACLASSPATH'] = []
env['JAVASOURCEPATH'] = []
env['_javapathopt'] = pathopt
env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} '
env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} '
env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} '
env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}'
env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES'
env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM','$JAVACCOMSTR')}"
env['JAVACLASSSUFFIX'] = '.class'
env['JAVASUFFIX'] = '.java' | python | def generate(env):
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_class = SCons.Tool.CreateJavaClassFileBuilder(env)
java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env)
java_class.add_emitter(None, emit_java_classes)
java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes)
java_class_dir.emitter = emit_java_classes
env.AddMethod(Java)
env['JAVAC'] = 'javac'
env['JAVACFLAGS'] = SCons.Util.CLVar('')
env['JAVABOOTCLASSPATH'] = []
env['JAVACLASSPATH'] = []
env['JAVASOURCEPATH'] = []
env['_javapathopt'] = pathopt
env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} '
env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} '
env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} '
env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}'
env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES'
env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM','$JAVACCOMSTR')}"
env['JAVACLASSSUFFIX'] = '.class'
env['JAVASUFFIX'] = '.java' | [
"def",
"generate",
"(",
"env",
")",
":",
"java_file",
"=",
"SCons",
".",
"Tool",
".",
"CreateJavaFileBuilder",
"(",
"env",
")",
"java_class",
"=",
"SCons",
".",
"Tool",
".",
"CreateJavaClassFileBuilder",
"(",
"env",
")",
"java_class_dir",
"=",
"SCons",
".",
... | Add Builders and construction variables for javac to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"javac",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javac.py#L199-L223 |
23,315 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py | Variables.Add | def Add(self, key, help="", default=None, validator=None, converter=None, **kw):
"""
Add an option.
@param key: the name of the variable, or a list or tuple of arguments
@param help: optional help text for the options
@param default: optional default value
@param validator: optional function that is called to validate the option's value
@type validator: Called with (key, value, environment)
@param converter: optional function that is called to convert the option's value before putting it in the environment.
"""
if SCons.Util.is_List(key) or isinstance(key, tuple):
self._do_add(*key)
return
if not SCons.Util.is_String(key) or \
not SCons.Environment.is_valid_construction_var(key):
raise SCons.Errors.UserError("Illegal Variables.Add() key `%s'" % str(key))
self._do_add(key, help, default, validator, converter) | python | def Add(self, key, help="", default=None, validator=None, converter=None, **kw):
if SCons.Util.is_List(key) or isinstance(key, tuple):
self._do_add(*key)
return
if not SCons.Util.is_String(key) or \
not SCons.Environment.is_valid_construction_var(key):
raise SCons.Errors.UserError("Illegal Variables.Add() key `%s'" % str(key))
self._do_add(key, help, default, validator, converter) | [
"def",
"Add",
"(",
"self",
",",
"key",
",",
"help",
"=",
"\"\"",
",",
"default",
"=",
"None",
",",
"validator",
"=",
"None",
",",
"converter",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"key",
"... | Add an option.
@param key: the name of the variable, or a list or tuple of arguments
@param help: optional help text for the options
@param default: optional default value
@param validator: optional function that is called to validate the option's value
@type validator: Called with (key, value, environment)
@param converter: optional function that is called to convert the option's value before putting it in the environment. | [
"Add",
"an",
"option",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L115-L136 |
23,316 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py | Variables.Update | def Update(self, env, args=None):
"""
Update an environment with the option variables.
env - the environment to update.
"""
values = {}
# first set the defaults:
for option in self.options:
if not option.default is None:
values[option.key] = option.default
# next set the value specified in the options file
for filename in self.files:
if os.path.exists(filename):
dir = os.path.split(os.path.abspath(filename))[0]
if dir:
sys.path.insert(0, dir)
try:
values['__name__'] = filename
with open(filename, 'r') as f:
contents = f.read()
exec(contents, {}, values)
finally:
if dir:
del sys.path[0]
del values['__name__']
# set the values specified on the command line
if args is None:
args = self.args
for arg, value in args.items():
added = False
for option in self.options:
if arg in list(option.aliases) + [ option.key ]:
values[option.key] = value
added = True
if not added:
self.unknown[arg] = value
# put the variables in the environment:
# (don't copy over variables that are not declared as options)
for option in self.options:
try:
env[option.key] = values[option.key]
except KeyError:
pass
# Call the convert functions:
for option in self.options:
if option.converter and option.key in values:
value = env.subst('${%s}'%option.key)
try:
try:
env[option.key] = option.converter(value)
except TypeError:
env[option.key] = option.converter(value, env)
except ValueError as x:
raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x))
# Finally validate the values:
for option in self.options:
if option.validator and option.key in values:
option.validator(option.key, env.subst('${%s}'%option.key), env) | python | def Update(self, env, args=None):
values = {}
# first set the defaults:
for option in self.options:
if not option.default is None:
values[option.key] = option.default
# next set the value specified in the options file
for filename in self.files:
if os.path.exists(filename):
dir = os.path.split(os.path.abspath(filename))[0]
if dir:
sys.path.insert(0, dir)
try:
values['__name__'] = filename
with open(filename, 'r') as f:
contents = f.read()
exec(contents, {}, values)
finally:
if dir:
del sys.path[0]
del values['__name__']
# set the values specified on the command line
if args is None:
args = self.args
for arg, value in args.items():
added = False
for option in self.options:
if arg in list(option.aliases) + [ option.key ]:
values[option.key] = value
added = True
if not added:
self.unknown[arg] = value
# put the variables in the environment:
# (don't copy over variables that are not declared as options)
for option in self.options:
try:
env[option.key] = values[option.key]
except KeyError:
pass
# Call the convert functions:
for option in self.options:
if option.converter and option.key in values:
value = env.subst('${%s}'%option.key)
try:
try:
env[option.key] = option.converter(value)
except TypeError:
env[option.key] = option.converter(value, env)
except ValueError as x:
raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x))
# Finally validate the values:
for option in self.options:
if option.validator and option.key in values:
option.validator(option.key, env.subst('${%s}'%option.key), env) | [
"def",
"Update",
"(",
"self",
",",
"env",
",",
"args",
"=",
"None",
")",
":",
"values",
"=",
"{",
"}",
"# first set the defaults:",
"for",
"option",
"in",
"self",
".",
"options",
":",
"if",
"not",
"option",
".",
"default",
"is",
"None",
":",
"values",
... | Update an environment with the option variables.
env - the environment to update. | [
"Update",
"an",
"environment",
"with",
"the",
"option",
"variables",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L160-L227 |
23,317 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py | Variables.Save | def Save(self, filename, env):
"""
Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file.
filename - Name of the file to save into
env - the environment get the option values from
"""
# Create the file and write out the header
try:
fh = open(filename, 'w')
try:
# Make an assignment in the file for each option
# within the environment that was assigned a value
# other than the default.
for option in self.options:
try:
value = env[option.key]
try:
prepare = value.prepare_to_store
except AttributeError:
try:
eval(repr(value))
except KeyboardInterrupt:
raise
except:
# Convert stuff that has a repr() that
# cannot be evaluated into a string
value = SCons.Util.to_String(value)
else:
value = prepare()
defaultVal = env.subst(SCons.Util.to_String(option.default))
if option.converter:
defaultVal = option.converter(defaultVal)
if str(env.subst('${%s}' % option.key)) != str(defaultVal):
fh.write('%s = %s\n' % (option.key, repr(value)))
except KeyError:
pass
finally:
fh.close()
except IOError as x:
raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x)) | python | def Save(self, filename, env):
# Create the file and write out the header
try:
fh = open(filename, 'w')
try:
# Make an assignment in the file for each option
# within the environment that was assigned a value
# other than the default.
for option in self.options:
try:
value = env[option.key]
try:
prepare = value.prepare_to_store
except AttributeError:
try:
eval(repr(value))
except KeyboardInterrupt:
raise
except:
# Convert stuff that has a repr() that
# cannot be evaluated into a string
value = SCons.Util.to_String(value)
else:
value = prepare()
defaultVal = env.subst(SCons.Util.to_String(option.default))
if option.converter:
defaultVal = option.converter(defaultVal)
if str(env.subst('${%s}' % option.key)) != str(defaultVal):
fh.write('%s = %s\n' % (option.key, repr(value)))
except KeyError:
pass
finally:
fh.close()
except IOError as x:
raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x)) | [
"def",
"Save",
"(",
"self",
",",
"filename",
",",
"env",
")",
":",
"# Create the file and write out the header",
"try",
":",
"fh",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"try",
":",
"# Make an assignment in the file for each option",
"# within the environment ... | Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file.
filename - Name of the file to save into
env - the environment get the option values from | [
"Saves",
"all",
"the",
"options",
"in",
"the",
"given",
"file",
".",
"This",
"file",
"can",
"then",
"be",
"used",
"to",
"load",
"the",
"options",
"next",
"run",
".",
"This",
"can",
"be",
"used",
"to",
"create",
"an",
"option",
"cache",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L236-L283 |
23,318 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py | Variables.GenerateHelpText | def GenerateHelpText(self, env, sort=None):
"""
Generate the help text for the options.
env - an environment that is used to get the current values
of the options.
cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1
or a boolean to indicate if it should be sorted.
"""
if callable(sort):
options = sorted(self.options, key=cmp_to_key(lambda x,y: sort(x.key,y.key)))
elif sort is True:
options = sorted(self.options, key=lambda x: x.key)
else:
options = self.options
def format(opt, self=self, env=env):
if opt.key in env:
actual = env.subst('${%s}' % opt.key)
else:
actual = None
return self.FormatVariableHelpText(env, opt.key, opt.help, opt.default, actual, opt.aliases)
lines = [_f for _f in map(format, options) if _f]
return ''.join(lines) | python | def GenerateHelpText(self, env, sort=None):
if callable(sort):
options = sorted(self.options, key=cmp_to_key(lambda x,y: sort(x.key,y.key)))
elif sort is True:
options = sorted(self.options, key=lambda x: x.key)
else:
options = self.options
def format(opt, self=self, env=env):
if opt.key in env:
actual = env.subst('${%s}' % opt.key)
else:
actual = None
return self.FormatVariableHelpText(env, opt.key, opt.help, opt.default, actual, opt.aliases)
lines = [_f for _f in map(format, options) if _f]
return ''.join(lines) | [
"def",
"GenerateHelpText",
"(",
"self",
",",
"env",
",",
"sort",
"=",
"None",
")",
":",
"if",
"callable",
"(",
"sort",
")",
":",
"options",
"=",
"sorted",
"(",
"self",
".",
"options",
",",
"key",
"=",
"cmp_to_key",
"(",
"lambda",
"x",
",",
"y",
":"... | Generate the help text for the options.
env - an environment that is used to get the current values
of the options.
cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1
or a boolean to indicate if it should be sorted. | [
"Generate",
"the",
"help",
"text",
"for",
"the",
"options",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L285-L310 |
23,319 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py | render_tree | def render_tree(root, child_func, prune=0, margin=[0], visited=None):
"""
Render a tree of nodes into an ASCII tree view.
:Parameters:
- `root`: the root node of the tree
- `child_func`: the function called to get the children of a node
- `prune`: don't visit the same node twice
- `margin`: the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
- `visited`: a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
"""
rname = str(root)
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
children = child_func(root)
retval = ""
for pipe in margin[:-1]:
if pipe:
retval = retval + "| "
else:
retval = retval + " "
if rname in visited:
return retval + "+-[" + rname + "]\n"
retval = retval + "+-" + rname + "\n"
if not prune:
visited = copy.copy(visited)
visited[rname] = 1
for i in range(len(children)):
margin.append(i < len(children)-1)
retval = retval + render_tree(children[i], child_func, prune, margin, visited)
margin.pop()
return retval | python | def render_tree(root, child_func, prune=0, margin=[0], visited=None):
rname = str(root)
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
children = child_func(root)
retval = ""
for pipe in margin[:-1]:
if pipe:
retval = retval + "| "
else:
retval = retval + " "
if rname in visited:
return retval + "+-[" + rname + "]\n"
retval = retval + "+-" + rname + "\n"
if not prune:
visited = copy.copy(visited)
visited[rname] = 1
for i in range(len(children)):
margin.append(i < len(children)-1)
retval = retval + render_tree(children[i], child_func, prune, margin, visited)
margin.pop()
return retval | [
"def",
"render_tree",
"(",
"root",
",",
"child_func",
",",
"prune",
"=",
"0",
",",
"margin",
"=",
"[",
"0",
"]",
",",
"visited",
"=",
"None",
")",
":",
"rname",
"=",
"str",
"(",
"root",
")",
"# Initialize 'visited' dict, if required",
"if",
"visited",
"i... | Render a tree of nodes into an ASCII tree view.
:Parameters:
- `root`: the root node of the tree
- `child_func`: the function called to get the children of a node
- `prune`: don't visit the same node twice
- `margin`: the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
- `visited`: a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. | [
"Render",
"a",
"tree",
"of",
"nodes",
"into",
"an",
"ASCII",
"tree",
"view",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L235-L274 |
23,320 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py | print_tree | def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
"""
Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
:Parameters:
- `root` - the root node of the tree
- `child_func` - the function called to get the children of a node
- `prune` - don't visit the same node twice
- `showtags` - print status information to the left of each node line
- `margin` - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
- `visited` - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
"""
rname = str(root)
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
if showtags:
if showtags == 2:
legend = (' E = exists\n' +
' R = exists in repository only\n' +
' b = implicit builder\n' +
' B = explicit builder\n' +
' S = side effect\n' +
' P = precious\n' +
' A = always build\n' +
' C = current\n' +
' N = no clean\n' +
' H = no cache\n' +
'\n')
sys.stdout.write(legend)
tags = ['[']
tags.append(' E'[IDX(root.exists())])
tags.append(' R'[IDX(root.rexists() and not root.exists())])
tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] +
[0,2][IDX(root.has_builder())]])
tags.append(' S'[IDX(root.side_effect)])
tags.append(' P'[IDX(root.precious)])
tags.append(' A'[IDX(root.always_build)])
tags.append(' C'[IDX(root.is_up_to_date())])
tags.append(' N'[IDX(root.noclean)])
tags.append(' H'[IDX(root.nocache)])
tags.append(']')
else:
tags = []
def MMM(m):
return [" ","| "][m]
margins = list(map(MMM, margin[:-1]))
children = child_func(root)
if prune and rname in visited and children:
sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n')
return
sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n')
visited[rname] = 1
if children:
margin.append(1)
idx = IDX(showtags)
for C in children[:-1]:
print_tree(C, child_func, prune, idx, margin, visited)
margin[-1] = 0
print_tree(children[-1], child_func, prune, idx, margin, visited)
margin.pop() | python | def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
rname = str(root)
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
if showtags:
if showtags == 2:
legend = (' E = exists\n' +
' R = exists in repository only\n' +
' b = implicit builder\n' +
' B = explicit builder\n' +
' S = side effect\n' +
' P = precious\n' +
' A = always build\n' +
' C = current\n' +
' N = no clean\n' +
' H = no cache\n' +
'\n')
sys.stdout.write(legend)
tags = ['[']
tags.append(' E'[IDX(root.exists())])
tags.append(' R'[IDX(root.rexists() and not root.exists())])
tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] +
[0,2][IDX(root.has_builder())]])
tags.append(' S'[IDX(root.side_effect)])
tags.append(' P'[IDX(root.precious)])
tags.append(' A'[IDX(root.always_build)])
tags.append(' C'[IDX(root.is_up_to_date())])
tags.append(' N'[IDX(root.noclean)])
tags.append(' H'[IDX(root.nocache)])
tags.append(']')
else:
tags = []
def MMM(m):
return [" ","| "][m]
margins = list(map(MMM, margin[:-1]))
children = child_func(root)
if prune and rname in visited and children:
sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n')
return
sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n')
visited[rname] = 1
if children:
margin.append(1)
idx = IDX(showtags)
for C in children[:-1]:
print_tree(C, child_func, prune, idx, margin, visited)
margin[-1] = 0
print_tree(children[-1], child_func, prune, idx, margin, visited)
margin.pop() | [
"def",
"print_tree",
"(",
"root",
",",
"child_func",
",",
"prune",
"=",
"0",
",",
"showtags",
"=",
"0",
",",
"margin",
"=",
"[",
"0",
"]",
",",
"visited",
"=",
"None",
")",
":",
"rname",
"=",
"str",
"(",
"root",
")",
"# Initialize 'visited' dict, if re... | Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
:Parameters:
- `root` - the root node of the tree
- `child_func` - the function called to get the children of a node
- `prune` - don't visit the same node twice
- `showtags` - print status information to the left of each node line
- `margin` - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
- `visited` - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. | [
"Print",
"a",
"tree",
"of",
"nodes",
".",
"This",
"is",
"like",
"render_tree",
"except",
"it",
"prints",
"lines",
"directly",
"instead",
"of",
"creating",
"a",
"string",
"representation",
"in",
"memory",
"so",
"that",
"huge",
"trees",
"can",
"be",
"printed",... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L279-L354 |
23,321 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py | flatten | def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
SequenceTypes=SequenceTypes, do_flatten=do_flatten):
"""Flatten a sequence to a non-nested list.
Flatten() converts either a single scalar or a nested sequence
to a non-nested list. Note that flatten() considers strings
to be scalars instead of sequences like Python would.
"""
if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
return [obj]
result = []
for item in obj:
if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
result.append(item)
else:
do_flatten(item, result)
return result | python | def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
SequenceTypes=SequenceTypes, do_flatten=do_flatten):
if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
return [obj]
result = []
for item in obj:
if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
result.append(item)
else:
do_flatten(item, result)
return result | [
"def",
"flatten",
"(",
"obj",
",",
"isinstance",
"=",
"isinstance",
",",
"StringTypes",
"=",
"StringTypes",
",",
"SequenceTypes",
"=",
"SequenceTypes",
",",
"do_flatten",
"=",
"do_flatten",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"StringTypes",
")",
"... | Flatten a sequence to a non-nested list.
Flatten() converts either a single scalar or a nested sequence
to a non-nested list. Note that flatten() considers strings
to be scalars instead of sequences like Python would. | [
"Flatten",
"a",
"sequence",
"to",
"a",
"non",
"-",
"nested",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L423-L439 |
23,322 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py | unique | def unique(s):
"""Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed, all sequence elements should be hashable. Then
unique() will usually work in linear time.
If not possible, the sequence elements should enjoy a total
ordering, and if list(s).sort() doesn't raise TypeError it's
assumed that they do enjoy a total ordering. Then unique() will
usually work in O(N*log2(N)) time.
If that's not possible either, the sequence elements must support
equality-testing. Then unique() will usually work in quadratic
time.
"""
n = len(s)
if n == 0:
return []
# Try using a dict first, as that's the fastest and will usually
# work. If it doesn't work, it will usually fail quickly, so it
# usually doesn't cost much to *try* it. It requires that all the
# sequence elements be hashable, and support equality comparison.
u = {}
try:
for x in s:
u[x] = 1
except TypeError:
pass # move on to the next method
else:
return list(u.keys())
del u
# We can't hash all the elements. Second fastest is to sort,
# which brings the equal elements together; then duplicates are
# easy to weed out in a single pass.
# NOTE: Python's list.sort() was designed to be efficient in the
# presence of many duplicate elements. This isn't true of all
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
try:
t = sorted(s)
except TypeError:
pass # move on to the next method
else:
assert n > 0
last = t[0]
lasti = i = 1
while i < n:
if t[i] != last:
t[lasti] = last = t[i]
lasti = lasti + 1
i = i + 1
return t[:lasti]
del t
# Brute force is all that's left.
u = []
for x in s:
if x not in u:
u.append(x)
return u | python | def unique(s):
n = len(s)
if n == 0:
return []
# Try using a dict first, as that's the fastest and will usually
# work. If it doesn't work, it will usually fail quickly, so it
# usually doesn't cost much to *try* it. It requires that all the
# sequence elements be hashable, and support equality comparison.
u = {}
try:
for x in s:
u[x] = 1
except TypeError:
pass # move on to the next method
else:
return list(u.keys())
del u
# We can't hash all the elements. Second fastest is to sort,
# which brings the equal elements together; then duplicates are
# easy to weed out in a single pass.
# NOTE: Python's list.sort() was designed to be efficient in the
# presence of many duplicate elements. This isn't true of all
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
try:
t = sorted(s)
except TypeError:
pass # move on to the next method
else:
assert n > 0
last = t[0]
lasti = i = 1
while i < n:
if t[i] != last:
t[lasti] = last = t[i]
lasti = lasti + 1
i = i + 1
return t[:lasti]
del t
# Brute force is all that's left.
u = []
for x in s:
if x not in u:
u.append(x)
return u | [
"def",
"unique",
"(",
"s",
")",
":",
"n",
"=",
"len",
"(",
"s",
")",
"if",
"n",
"==",
"0",
":",
"return",
"[",
"]",
"# Try using a dict first, as that's the fastest and will usually",
"# work. If it doesn't work, it will usually fail quickly, so it",
"# usually doesn't c... | Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed, all sequence elements should be hashable. Then
unique() will usually work in linear time.
If not possible, the sequence elements should enjoy a total
ordering, and if list(s).sort() doesn't raise TypeError it's
assumed that they do enjoy a total ordering. Then unique() will
usually work in O(N*log2(N)) time.
If that's not possible either, the sequence elements must support
equality-testing. Then unique() will usually work in quadratic
time. | [
"Return",
"a",
"list",
"of",
"the",
"elements",
"in",
"s",
"but",
"without",
"duplicates",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L1155-L1222 |
23,323 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py | make_path_relative | def make_path_relative(path):
""" makes an absolute path name to a relative pathname.
"""
if os.path.isabs(path):
drive_s,path = os.path.splitdrive(path)
import re
if not drive_s:
path=re.compile("/*(.*)").findall(path)[0]
else:
path=path[1:]
assert( not os.path.isabs( path ) ), path
return path | python | def make_path_relative(path):
if os.path.isabs(path):
drive_s,path = os.path.splitdrive(path)
import re
if not drive_s:
path=re.compile("/*(.*)").findall(path)[0]
else:
path=path[1:]
assert( not os.path.isabs( path ) ), path
return path | [
"def",
"make_path_relative",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"drive_s",
",",
"path",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"import",
"re",
"if",
"not",
"drive_s",
":",
"pat... | makes an absolute path name to a relative pathname. | [
"makes",
"an",
"absolute",
"path",
"name",
"to",
"a",
"relative",
"pathname",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L1411-L1424 |
23,324 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py | RenameFunction | def RenameFunction(function, name):
"""
Returns a function identical to the specified function, but with
the specified name.
"""
return FunctionType(function.__code__,
function.__globals__,
name,
function.__defaults__) | python | def RenameFunction(function, name):
return FunctionType(function.__code__,
function.__globals__,
name,
function.__defaults__) | [
"def",
"RenameFunction",
"(",
"function",
",",
"name",
")",
":",
"return",
"FunctionType",
"(",
"function",
".",
"__code__",
",",
"function",
".",
"__globals__",
",",
"name",
",",
"function",
".",
"__defaults__",
")"
] | Returns a function identical to the specified function, but with
the specified name. | [
"Returns",
"a",
"function",
"identical",
"to",
"the",
"specified",
"function",
"but",
"with",
"the",
"specified",
"name",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L1488-L1496 |
23,325 | iotile/coretools | iotilecore/iotile/core/hw/proxy/proxy.py | _create_old_return_value | def _create_old_return_value(payload, num_ints, buff):
"""Parse the response of an RPC call into a dictionary with integer and buffer results"""
parsed = {'ints': payload[:num_ints], 'buffer': None, 'error': 'No Error',
'is_error': False, 'return_value': 0}
if buff:
parsed['buffer'] = bytearray(payload[-1])
return parsed | python | def _create_old_return_value(payload, num_ints, buff):
parsed = {'ints': payload[:num_ints], 'buffer': None, 'error': 'No Error',
'is_error': False, 'return_value': 0}
if buff:
parsed['buffer'] = bytearray(payload[-1])
return parsed | [
"def",
"_create_old_return_value",
"(",
"payload",
",",
"num_ints",
",",
"buff",
")",
":",
"parsed",
"=",
"{",
"'ints'",
":",
"payload",
"[",
":",
"num_ints",
"]",
",",
"'buffer'",
":",
"None",
",",
"'error'",
":",
"'No Error'",
",",
"'is_error'",
":",
"... | Parse the response of an RPC call into a dictionary with integer and buffer results | [
"Parse",
"the",
"response",
"of",
"an",
"RPC",
"call",
"into",
"a",
"dictionary",
"with",
"integer",
"and",
"buffer",
"results"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L382-L391 |
23,326 | iotile/coretools | iotilecore/iotile/core/hw/proxy/proxy.py | TileBusProxyObject.hardware_version | def hardware_version(self):
"""Return the embedded hardware version string for this tile.
The hardware version is an up to 10 byte user readable string that is
meant to encode any necessary information about the specific hardware
that this tile is running on. For example, if you have multiple
assembly variants of a given tile, you could encode that information
here.
Returns:
str: The hardware version read from the tile.
"""
res = self.rpc(0x00, 0x02, result_type=(0, True))
# Result is a string but with zero appended to the end to make it a fixed 10 byte size
binary_version = res['buffer']
ver = ""
for x in binary_version:
if x != 0:
ver += chr(x)
return ver | python | def hardware_version(self):
res = self.rpc(0x00, 0x02, result_type=(0, True))
# Result is a string but with zero appended to the end to make it a fixed 10 byte size
binary_version = res['buffer']
ver = ""
for x in binary_version:
if x != 0:
ver += chr(x)
return ver | [
"def",
"hardware_version",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"rpc",
"(",
"0x00",
",",
"0x02",
",",
"result_type",
"=",
"(",
"0",
",",
"True",
")",
")",
"# Result is a string but with zero appended to the end to make it a fixed 10 byte size",
"binary_ve... | Return the embedded hardware version string for this tile.
The hardware version is an up to 10 byte user readable string that is
meant to encode any necessary information about the specific hardware
that this tile is running on. For example, if you have multiple
assembly variants of a given tile, you could encode that information
here.
Returns:
str: The hardware version read from the tile. | [
"Return",
"the",
"embedded",
"hardware",
"version",
"string",
"for",
"this",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L102-L125 |
23,327 | iotile/coretools | iotilecore/iotile/core/hw/proxy/proxy.py | TileBusProxyObject.check_hardware | def check_hardware(self, expected):
"""Make sure the hardware version is what we expect.
This convenience function is meant for ensuring that we are talking to
a tile that has the correct hardware version.
Args:
expected (str): The expected hardware string that is compared
against what is reported by the hardware_version RPC.
Returns:
bool: true if the hardware is the expected version, false otherwise
"""
if len(expected) < 10:
expected += '\0'*(10 - len(expected))
err, = self.rpc(0x00, 0x03, expected, result_format="L")
if err == 0:
return True
return False | python | def check_hardware(self, expected):
if len(expected) < 10:
expected += '\0'*(10 - len(expected))
err, = self.rpc(0x00, 0x03, expected, result_format="L")
if err == 0:
return True
return False | [
"def",
"check_hardware",
"(",
"self",
",",
"expected",
")",
":",
"if",
"len",
"(",
"expected",
")",
"<",
"10",
":",
"expected",
"+=",
"'\\0'",
"*",
"(",
"10",
"-",
"len",
"(",
"expected",
")",
")",
"err",
",",
"=",
"self",
".",
"rpc",
"(",
"0x00"... | Make sure the hardware version is what we expect.
This convenience function is meant for ensuring that we are talking to
a tile that has the correct hardware version.
Args:
expected (str): The expected hardware string that is compared
against what is reported by the hardware_version RPC.
Returns:
bool: true if the hardware is the expected version, false otherwise | [
"Make",
"sure",
"the",
"hardware",
"version",
"is",
"what",
"we",
"expect",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L129-L150 |
23,328 | iotile/coretools | iotilecore/iotile/core/hw/proxy/proxy.py | TileBusProxyObject.status | def status(self):
"""Query the status of an IOTile including its name and version"""
hw_type, name, major, minor, patch, status = self.rpc(0x00, 0x04, result_format="H6sBBBB")
status = {
'hw_type': hw_type,
'name': name.decode('utf-8'),
'version': (major, minor, patch),
'status': status
}
return status | python | def status(self):
hw_type, name, major, minor, patch, status = self.rpc(0x00, 0x04, result_format="H6sBBBB")
status = {
'hw_type': hw_type,
'name': name.decode('utf-8'),
'version': (major, minor, patch),
'status': status
}
return status | [
"def",
"status",
"(",
"self",
")",
":",
"hw_type",
",",
"name",
",",
"major",
",",
"minor",
",",
"patch",
",",
"status",
"=",
"self",
".",
"rpc",
"(",
"0x00",
",",
"0x04",
",",
"result_format",
"=",
"\"H6sBBBB\"",
")",
"status",
"=",
"{",
"'hw_type'"... | Query the status of an IOTile including its name and version | [
"Query",
"the",
"status",
"of",
"an",
"IOTile",
"including",
"its",
"name",
"and",
"version"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L153-L165 |
23,329 | iotile/coretools | iotilecore/iotile/core/hw/proxy/proxy.py | TileBusProxyObject.tile_status | def tile_status(self):
"""Get the current status of this tile"""
stat = self.status()
flags = stat['status']
# FIXME: This needs to stay in sync with lib_common: cdb_status.h
status = {}
status['debug_mode'] = bool(flags & (1 << 3))
status['configured'] = bool(flags & (1 << 1))
status['app_running'] = bool(flags & (1 << 0))
status['trapped'] = bool(flags & (1 << 2))
return status | python | def tile_status(self):
stat = self.status()
flags = stat['status']
# FIXME: This needs to stay in sync with lib_common: cdb_status.h
status = {}
status['debug_mode'] = bool(flags & (1 << 3))
status['configured'] = bool(flags & (1 << 1))
status['app_running'] = bool(flags & (1 << 0))
status['trapped'] = bool(flags & (1 << 2))
return status | [
"def",
"tile_status",
"(",
"self",
")",
":",
"stat",
"=",
"self",
".",
"status",
"(",
")",
"flags",
"=",
"stat",
"[",
"'status'",
"]",
"# FIXME: This needs to stay in sync with lib_common: cdb_status.h",
"status",
"=",
"{",
"}",
"status",
"[",
"'debug_mode'",
"]... | Get the current status of this tile | [
"Get",
"the",
"current",
"status",
"of",
"this",
"tile"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L190-L203 |
23,330 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.client_event_handler | async def client_event_handler(self, client_id, event_tuple, user_data):
"""Method called to actually send an event to a client.
Users of this class should override this method to actually forward
device events to their clients. It is called with the client_id
passed to (or returned from) :meth:`setup_client` as well as the
user_data object that was included there.
The event tuple is a 3-tuple of:
- connection string
- event name
- event object
If you override this to be acoroutine, it will be awaited. The
default implementation just logs the event.
Args:
client_id (str): The client_id that this event should be forwarded
to.
event_tuple (tuple): The connection_string, event_name and event_object
that should be forwarded.
user_data (object): Any user data that was passed to setup_client.
"""
conn_string, event_name, _event = event_tuple
self._logger.debug("Ignoring event %s from device %s forwarded for client %s",
event_name, conn_string, client_id)
return None | python | async def client_event_handler(self, client_id, event_tuple, user_data):
conn_string, event_name, _event = event_tuple
self._logger.debug("Ignoring event %s from device %s forwarded for client %s",
event_name, conn_string, client_id)
return None | [
"async",
"def",
"client_event_handler",
"(",
"self",
",",
"client_id",
",",
"event_tuple",
",",
"user_data",
")",
":",
"conn_string",
",",
"event_name",
",",
"_event",
"=",
"event_tuple",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Ignoring event %s from device ... | Method called to actually send an event to a client.
Users of this class should override this method to actually forward
device events to their clients. It is called with the client_id
passed to (or returned from) :meth:`setup_client` as well as the
user_data object that was included there.
The event tuple is a 3-tuple of:
- connection string
- event name
- event object
If you override this to be acoroutine, it will be awaited. The
default implementation just logs the event.
Args:
client_id (str): The client_id that this event should be forwarded
to.
event_tuple (tuple): The connection_string, event_name and event_object
that should be forwarded.
user_data (object): Any user data that was passed to setup_client. | [
"Method",
"called",
"to",
"actually",
"send",
"an",
"event",
"to",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L91-L120 |
23,331 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.setup_client | def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False):
"""Setup a newly connected client.
``client_id`` must be unique among all connected clients. If it is
passed as None, a random client_id will be generated as a string and
returned.
This method reserves internal resources for tracking what devices this
client has connected to and installs a monitor into the adapter on
behalf of the client.
It should be called whenever a new client connects to the device server
before any other activities by that client are allowed. By default,
all clients start receiving ``device_seen`` events but if you want
your client to also receive broadcast events, you can pass broadcast=True.
Args:
client_id (str): A unique identifier for this client that will be
used to refer to it in all future interactions. If this is
None, then a random string will be generated for the client_id.
user_data (object): An arbitrary object that you would like to store
with this client and will be passed to your event handler when
events are forwarded to this client.
scan (bool): Whether to install a monitor to listen for device_found
events.
broadcast (bool): Whether to install a monitor to list for broadcast
events.
Returns:
str: The client_id.
If a client id was passed in, it will be the same as what was passed
in. If no client id was passed in then it will be a random unique
string.
"""
if client_id is None:
client_id = str(uuid.uuid4())
if client_id in self._clients:
raise ArgumentError("Duplicate client_id: {}".format(client_id))
async def _client_callback(conn_string, _, event_name, event):
event_tuple = (conn_string, event_name, event)
await self._forward_client_event(client_id, event_tuple)
client_monitor = self.adapter.register_monitor([], [], _client_callback)
self._clients[client_id] = dict(user_data=user_data, connections={},
monitor=client_monitor)
self._adjust_global_events(client_id, scan, broadcast)
return client_id | python | def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False):
if client_id is None:
client_id = str(uuid.uuid4())
if client_id in self._clients:
raise ArgumentError("Duplicate client_id: {}".format(client_id))
async def _client_callback(conn_string, _, event_name, event):
event_tuple = (conn_string, event_name, event)
await self._forward_client_event(client_id, event_tuple)
client_monitor = self.adapter.register_monitor([], [], _client_callback)
self._clients[client_id] = dict(user_data=user_data, connections={},
monitor=client_monitor)
self._adjust_global_events(client_id, scan, broadcast)
return client_id | [
"def",
"setup_client",
"(",
"self",
",",
"client_id",
"=",
"None",
",",
"user_data",
"=",
"None",
",",
"scan",
"=",
"True",
",",
"broadcast",
"=",
"False",
")",
":",
"if",
"client_id",
"is",
"None",
":",
"client_id",
"=",
"str",
"(",
"uuid",
".",
"uu... | Setup a newly connected client.
``client_id`` must be unique among all connected clients. If it is
passed as None, a random client_id will be generated as a string and
returned.
This method reserves internal resources for tracking what devices this
client has connected to and installs a monitor into the adapter on
behalf of the client.
It should be called whenever a new client connects to the device server
before any other activities by that client are allowed. By default,
all clients start receiving ``device_seen`` events but if you want
your client to also receive broadcast events, you can pass broadcast=True.
Args:
client_id (str): A unique identifier for this client that will be
used to refer to it in all future interactions. If this is
None, then a random string will be generated for the client_id.
user_data (object): An arbitrary object that you would like to store
with this client and will be passed to your event handler when
events are forwarded to this client.
scan (bool): Whether to install a monitor to listen for device_found
events.
broadcast (bool): Whether to install a monitor to list for broadcast
events.
Returns:
str: The client_id.
If a client id was passed in, it will be the same as what was passed
in. If no client id was passed in then it will be a random unique
string. | [
"Setup",
"a",
"newly",
"connected",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L122-L174 |
23,332 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.stop | async def stop(self):
"""Stop the server and teardown any remaining clients.
If your subclass overrides this method, make sure to call
super().stop() to ensure that all devices with open connections from
thie server are properly closed.
See :meth:`AbstractDeviceServer.stop`.
"""
clients = list(self._clients)
for client in clients:
self._logger.info("Tearing down client %s at server stop()", client)
await self.teardown_client(client) | python | async def stop(self):
clients = list(self._clients)
for client in clients:
self._logger.info("Tearing down client %s at server stop()", client)
await self.teardown_client(client) | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"clients",
"=",
"list",
"(",
"self",
".",
"_clients",
")",
"for",
"client",
"in",
"clients",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Tearing down client %s at server stop()\"",
",",
"client",
")",
"a... | Stop the server and teardown any remaining clients.
If your subclass overrides this method, make sure to call
super().stop() to ensure that all devices with open connections from
thie server are properly closed.
See :meth:`AbstractDeviceServer.stop`. | [
"Stop",
"the",
"server",
"and",
"teardown",
"any",
"remaining",
"clients",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L182-L196 |
23,333 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.teardown_client | async def teardown_client(self, client_id):
"""Release all resources held by a client.
This method must be called and awaited whenever a client is
disconnected. It ensures that all of the client's resources are
properly released and any devices they have connected to are
disconnected cleanly.
Args:
client_id (str): The client that we should tear down.
Raises:
ArgumentError: The client_id is unknown.
"""
client_info = self._client_info(client_id)
self.adapter.remove_monitor(client_info['monitor'])
conns = client_info['connections']
for conn_string, conn_id in conns.items():
try:
self._logger.debug("Disconnecting client %s from conn %s at teardown", client_id, conn_string)
await self.adapter.disconnect(conn_id)
except: #pylint:disable=bare-except; This is a finalization method that should not raise unexpectedly
self._logger.exception("Error disconnecting device during teardown_client: conn_string=%s", conn_string)
del self._clients[client_id] | python | async def teardown_client(self, client_id):
client_info = self._client_info(client_id)
self.adapter.remove_monitor(client_info['monitor'])
conns = client_info['connections']
for conn_string, conn_id in conns.items():
try:
self._logger.debug("Disconnecting client %s from conn %s at teardown", client_id, conn_string)
await self.adapter.disconnect(conn_id)
except: #pylint:disable=bare-except; This is a finalization method that should not raise unexpectedly
self._logger.exception("Error disconnecting device during teardown_client: conn_string=%s", conn_string)
del self._clients[client_id] | [
"async",
"def",
"teardown_client",
"(",
"self",
",",
"client_id",
")",
":",
"client_info",
"=",
"self",
".",
"_client_info",
"(",
"client_id",
")",
"self",
".",
"adapter",
".",
"remove_monitor",
"(",
"client_info",
"[",
"'monitor'",
"]",
")",
"conns",
"=",
... | Release all resources held by a client.
This method must be called and awaited whenever a client is
disconnected. It ensures that all of the client's resources are
properly released and any devices they have connected to are
disconnected cleanly.
Args:
client_id (str): The client that we should tear down.
Raises:
ArgumentError: The client_id is unknown. | [
"Release",
"all",
"resources",
"held",
"by",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L198-L225 |
23,334 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.connect | async def connect(self, client_id, conn_string):
"""Connect to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.connect`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter to connect.
Raises:
DeviceServerError: There is an issue with your client_id.
DeviceAdapterError: The adapter had an issue connecting.
"""
conn_id = self.adapter.unique_conn_id()
self._client_info(client_id)
await self.adapter.connect(conn_id, conn_string)
self._hook_connect(conn_string, conn_id, client_id) | python | async def connect(self, client_id, conn_string):
conn_id = self.adapter.unique_conn_id()
self._client_info(client_id)
await self.adapter.connect(conn_id, conn_string)
self._hook_connect(conn_string, conn_id, client_id) | [
"async",
"def",
"connect",
"(",
"self",
",",
"client_id",
",",
"conn_string",
")",
":",
"conn_id",
"=",
"self",
".",
"adapter",
".",
"unique_conn_id",
"(",
")",
"self",
".",
"_client_info",
"(",
"client_id",
")",
"await",
"self",
".",
"adapter",
".",
"co... | Connect to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.connect`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter to connect.
Raises:
DeviceServerError: There is an issue with your client_id.
DeviceAdapterError: The adapter had an issue connecting. | [
"Connect",
"to",
"a",
"device",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L244-L263 |
23,335 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.disconnect | async def disconnect(self, client_id, conn_string):
"""Disconnect from a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.disconnect`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter to connect.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had an issue disconnecting.
"""
conn_id = self._client_connection(client_id, conn_string)
try:
await self.adapter.disconnect(conn_id)
finally:
self._hook_disconnect(conn_string, client_id) | python | async def disconnect(self, client_id, conn_string):
conn_id = self._client_connection(client_id, conn_string)
try:
await self.adapter.disconnect(conn_id)
finally:
self._hook_disconnect(conn_string, client_id) | [
"async",
"def",
"disconnect",
"(",
"self",
",",
"client_id",
",",
"conn_string",
")",
":",
"conn_id",
"=",
"self",
".",
"_client_connection",
"(",
"client_id",
",",
"conn_string",
")",
"try",
":",
"await",
"self",
".",
"adapter",
".",
"disconnect",
"(",
"c... | Disconnect from a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.disconnect`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter to connect.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had an issue disconnecting. | [
"Disconnect",
"from",
"a",
"device",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L265-L286 |
23,336 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.open_interface | async def open_interface(self, client_id, conn_string, interface):
"""Open a device interface on behalf of a client.
See :meth:`AbstractDeviceAdapter.open_interface`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
interface (str): The name of the interface to open.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had an issue opening the interface.
"""
conn_id = self._client_connection(client_id, conn_string)
# Hook first so there is no race on getting the first event
self._hook_open_interface(conn_string, interface, client_id)
await self.adapter.open_interface(conn_id, interface) | python | async def open_interface(self, client_id, conn_string, interface):
conn_id = self._client_connection(client_id, conn_string)
# Hook first so there is no race on getting the first event
self._hook_open_interface(conn_string, interface, client_id)
await self.adapter.open_interface(conn_id, interface) | [
"async",
"def",
"open_interface",
"(",
"self",
",",
"client_id",
",",
"conn_string",
",",
"interface",
")",
":",
"conn_id",
"=",
"self",
".",
"_client_connection",
"(",
"client_id",
",",
"conn_string",
")",
"# Hook first so there is no race on getting the first event",
... | Open a device interface on behalf of a client.
See :meth:`AbstractDeviceAdapter.open_interface`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
interface (str): The name of the interface to open.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had an issue opening the interface. | [
"Open",
"a",
"device",
"interface",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L288-L309 |
23,337 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.close_interface | async def close_interface(self, client_id, conn_string, interface):
"""Close a device interface on behalf of a client.
See :meth:`AbstractDeviceAdapter.close_interface`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
interface (str): The name of the interface to close.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had an issue closing the interface.
"""
conn_id = self._client_connection(client_id, conn_string)
await self.adapter.close_interface(conn_id, interface)
self._hook_close_interface(conn_string, interface, client_id) | python | async def close_interface(self, client_id, conn_string, interface):
conn_id = self._client_connection(client_id, conn_string)
await self.adapter.close_interface(conn_id, interface)
self._hook_close_interface(conn_string, interface, client_id) | [
"async",
"def",
"close_interface",
"(",
"self",
",",
"client_id",
",",
"conn_string",
",",
"interface",
")",
":",
"conn_id",
"=",
"self",
".",
"_client_connection",
"(",
"client_id",
",",
"conn_string",
")",
"await",
"self",
".",
"adapter",
".",
"close_interfa... | Close a device interface on behalf of a client.
See :meth:`AbstractDeviceAdapter.close_interface`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
interface (str): The name of the interface to close.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had an issue closing the interface. | [
"Close",
"a",
"device",
"interface",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L311-L331 |
23,338 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.send_rpc | async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout):
"""Send an RPC on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_rpc`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter to connect.
address (int): The RPC address.
rpc_id (int): The ID number of the RPC
payload (bytes): The RPC argument payload
timeout (float): The RPC's expected timeout to hand to the underlying
device adapter.
Returns:
bytes: The RPC response.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
TileNotFoundError: The destination tile address does not exist
RPCNotFoundError: The rpc_id does not exist on the given tile
RPCErrorCode: The RPC was invoked successfully and wishes to fail
with a non-zero status code.
RPCInvalidIDError: The rpc_id is too large to fit in 16-bits.
TileBusSerror: The tile was busy and could not respond to the RPC.
Exception: The rpc raised an exception during processing.
DeviceAdapterError: If there is a hardware or communication issue
invoking the RPC.
"""
conn_id = self._client_connection(client_id, conn_string)
return await self.adapter.send_rpc(conn_id, address, rpc_id, payload, timeout) | python | async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout):
conn_id = self._client_connection(client_id, conn_string)
return await self.adapter.send_rpc(conn_id, address, rpc_id, payload, timeout) | [
"async",
"def",
"send_rpc",
"(",
"self",
",",
"client_id",
",",
"conn_string",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"timeout",
")",
":",
"conn_id",
"=",
"self",
".",
"_client_connection",
"(",
"client_id",
",",
"conn_string",
")",
"return",
... | Send an RPC on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_rpc`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter to connect.
address (int): The RPC address.
rpc_id (int): The ID number of the RPC
payload (bytes): The RPC argument payload
timeout (float): The RPC's expected timeout to hand to the underlying
device adapter.
Returns:
bytes: The RPC response.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
TileNotFoundError: The destination tile address does not exist
RPCNotFoundError: The rpc_id does not exist on the given tile
RPCErrorCode: The RPC was invoked successfully and wishes to fail
with a non-zero status code.
RPCInvalidIDError: The rpc_id is too large to fit in 16-bits.
TileBusSerror: The tile was busy and could not respond to the RPC.
Exception: The rpc raised an exception during processing.
DeviceAdapterError: If there is a hardware or communication issue
invoking the RPC. | [
"Send",
"an",
"RPC",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L334-L367 |
23,339 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.send_script | async def send_script(self, client_id, conn_string, script):
"""Send a script to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
script (bytes): The script that we wish to send.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had a protocol issue sending the script.
"""
conn_id = self._client_connection(client_id, conn_string)
await self.adapter.send_script(conn_id, script) | python | async def send_script(self, client_id, conn_string, script):
conn_id = self._client_connection(client_id, conn_string)
await self.adapter.send_script(conn_id, script) | [
"async",
"def",
"send_script",
"(",
"self",
",",
"client_id",
",",
"conn_string",
",",
"script",
")",
":",
"conn_id",
"=",
"self",
".",
"_client_connection",
"(",
"client_id",
",",
"conn_string",
")",
"await",
"self",
".",
"adapter",
".",
"send_script",
"(",... | Send a script to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
script (bytes): The script that we wish to send.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had a protocol issue sending the script. | [
"Send",
"a",
"script",
"to",
"a",
"device",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L369-L387 |
23,340 | iotile/coretools | iotilecore/iotile/core/hw/transport/server/standard.py | StandardDeviceServer.debug | async def debug(self, client_id, conn_string, command, args):
"""Send a debug command to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
command (str): The name of the debug command to run.
args (dict): Any command arguments.
Returns:
object: The response to the debug command.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had a protocol issue sending the debug
command.
"""
conn_id = self._client_info(client_id, 'connections')[conn_string]
return await self.adapter.debug(conn_id, command, args) | python | async def debug(self, client_id, conn_string, command, args):
conn_id = self._client_info(client_id, 'connections')[conn_string]
return await self.adapter.debug(conn_id, command, args) | [
"async",
"def",
"debug",
"(",
"self",
",",
"client_id",
",",
"conn_string",
",",
"command",
",",
"args",
")",
":",
"conn_id",
"=",
"self",
".",
"_client_info",
"(",
"client_id",
",",
"'connections'",
")",
"[",
"conn_string",
"]",
"return",
"await",
"self",... | Send a debug command to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
command (str): The name of the debug command to run.
args (dict): Any command arguments.
Returns:
object: The response to the debug command.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had a protocol issue sending the debug
command. | [
"Send",
"a",
"debug",
"command",
"to",
"a",
"device",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L389-L412 |
23,341 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py | TileInfo.registration_packet | def registration_packet(self):
"""Serialize this into a tuple suitable for returning from an RPC.
Returns:
tuple: The serialized values.
"""
return (self.hw_type, self.api_info[0], self.api_info[1], self.name, self.fw_info[0], self.fw_info[1], self.fw_info[2],
self.exec_info[0], self.exec_info[0], self.exec_info[0], self.slot, self.unique_id) | python | def registration_packet(self):
return (self.hw_type, self.api_info[0], self.api_info[1], self.name, self.fw_info[0], self.fw_info[1], self.fw_info[2],
self.exec_info[0], self.exec_info[0], self.exec_info[0], self.slot, self.unique_id) | [
"def",
"registration_packet",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"hw_type",
",",
"self",
".",
"api_info",
"[",
"0",
"]",
",",
"self",
".",
"api_info",
"[",
"1",
"]",
",",
"self",
".",
"name",
",",
"self",
".",
"fw_info",
"[",
"0",
... | Serialize this into a tuple suitable for returning from an RPC.
Returns:
tuple: The serialized values. | [
"Serialize",
"this",
"into",
"a",
"tuple",
"suitable",
"for",
"returning",
"from",
"an",
"RPC",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L33-L41 |
23,342 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py | TileManagerState.clear_to_reset | def clear_to_reset(self, config_vars):
"""Clear to the state immediately after a reset."""
super(TileManagerState, self).clear_to_reset(config_vars)
self.registered_tiles = self.registered_tiles[:1]
self.safe_mode = False
self.debug_mode = False | python | def clear_to_reset(self, config_vars):
super(TileManagerState, self).clear_to_reset(config_vars)
self.registered_tiles = self.registered_tiles[:1]
self.safe_mode = False
self.debug_mode = False | [
"def",
"clear_to_reset",
"(",
"self",
",",
"config_vars",
")",
":",
"super",
"(",
"TileManagerState",
",",
"self",
")",
".",
"clear_to_reset",
"(",
"config_vars",
")",
"self",
".",
"registered_tiles",
"=",
"self",
".",
"registered_tiles",
"[",
":",
"1",
"]",... | Clear to the state immediately after a reset. | [
"Clear",
"to",
"the",
"state",
"immediately",
"after",
"a",
"reset",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L86-L92 |
23,343 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py | TileManagerState.insert_tile | def insert_tile(self, tile_info):
"""Add or replace an entry in the tile cache.
Args:
tile_info (TileInfo): The newly registered tile.
"""
for i, tile in enumerate(self.registered_tiles):
if tile.slot == tile_info.slot:
self.registered_tiles[i] = tile_info
return
self.registered_tiles.append(tile_info) | python | def insert_tile(self, tile_info):
for i, tile in enumerate(self.registered_tiles):
if tile.slot == tile_info.slot:
self.registered_tiles[i] = tile_info
return
self.registered_tiles.append(tile_info) | [
"def",
"insert_tile",
"(",
"self",
",",
"tile_info",
")",
":",
"for",
"i",
",",
"tile",
"in",
"enumerate",
"(",
"self",
".",
"registered_tiles",
")",
":",
"if",
"tile",
".",
"slot",
"==",
"tile_info",
".",
"slot",
":",
"self",
".",
"registered_tiles",
... | Add or replace an entry in the tile cache.
Args:
tile_info (TileInfo): The newly registered tile. | [
"Add",
"or",
"replace",
"an",
"entry",
"in",
"the",
"tile",
"cache",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L108-L120 |
23,344 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py | TileManagerMixin.register_tile | def register_tile(self, hw_type, api_major, api_minor, name, fw_major, fw_minor, fw_patch, exec_major, exec_minor, exec_patch, slot, unique_id):
"""Register a tile with this controller.
This function adds the tile immediately to its internal cache of registered tiles
and queues RPCs to send all config variables and start tile rpcs back to the tile.
"""
api_info = (api_major, api_minor)
fw_info = (fw_major, fw_minor, fw_patch)
exec_info = (exec_major, exec_minor, exec_patch)
address = 10 + slot
info = TileInfo(hw_type, name, api_info, fw_info, exec_info, slot, unique_id, state=TileState.JUST_REGISTERED, address=address)
self.tile_manager.insert_tile(info)
debug = int(self.tile_manager.debug_mode)
if self.tile_manager.safe_mode:
run_level = RunLevel.SAFE_MODE
info.state = TileState.SAFE_MODE
config_rpcs = []
else:
run_level = RunLevel.START_ON_COMMAND
info.state = TileState.BEING_CONFIGURED
config_rpcs = self.config_database.stream_matching(address, name)
self.tile_manager.queue.put_nowait((info, config_rpcs))
return [address, run_level, debug] | python | def register_tile(self, hw_type, api_major, api_minor, name, fw_major, fw_minor, fw_patch, exec_major, exec_minor, exec_patch, slot, unique_id):
api_info = (api_major, api_minor)
fw_info = (fw_major, fw_minor, fw_patch)
exec_info = (exec_major, exec_minor, exec_patch)
address = 10 + slot
info = TileInfo(hw_type, name, api_info, fw_info, exec_info, slot, unique_id, state=TileState.JUST_REGISTERED, address=address)
self.tile_manager.insert_tile(info)
debug = int(self.tile_manager.debug_mode)
if self.tile_manager.safe_mode:
run_level = RunLevel.SAFE_MODE
info.state = TileState.SAFE_MODE
config_rpcs = []
else:
run_level = RunLevel.START_ON_COMMAND
info.state = TileState.BEING_CONFIGURED
config_rpcs = self.config_database.stream_matching(address, name)
self.tile_manager.queue.put_nowait((info, config_rpcs))
return [address, run_level, debug] | [
"def",
"register_tile",
"(",
"self",
",",
"hw_type",
",",
"api_major",
",",
"api_minor",
",",
"name",
",",
"fw_major",
",",
"fw_minor",
",",
"fw_patch",
",",
"exec_major",
",",
"exec_minor",
",",
"exec_patch",
",",
"slot",
",",
"unique_id",
")",
":",
"api_... | Register a tile with this controller.
This function adds the tile immediately to its internal cache of registered tiles
and queues RPCs to send all config variables and start tile rpcs back to the tile. | [
"Register",
"a",
"tile",
"with",
"this",
"controller",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L140-L169 |
23,345 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py | TileManagerMixin.describe_tile | def describe_tile(self, index):
"""Get the registration information for the tile at the given index."""
if index >= len(self.tile_manager.registered_tiles):
tile = TileInfo.CreateInvalid()
else:
tile = self.tile_manager.registered_tiles[index]
return tile.registration_packet() | python | def describe_tile(self, index):
if index >= len(self.tile_manager.registered_tiles):
tile = TileInfo.CreateInvalid()
else:
tile = self.tile_manager.registered_tiles[index]
return tile.registration_packet() | [
"def",
"describe_tile",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
">=",
"len",
"(",
"self",
".",
"tile_manager",
".",
"registered_tiles",
")",
":",
"tile",
"=",
"TileInfo",
".",
"CreateInvalid",
"(",
")",
"else",
":",
"tile",
"=",
"self",
"."... | Get the registration information for the tile at the given index. | [
"Get",
"the",
"registration",
"information",
"for",
"the",
"tile",
"at",
"the",
"given",
"index",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L178-L186 |
23,346 | iotile/coretools | iotilecore/iotile/core/hw/update/script.py | UpdateScript.ParseHeader | def ParseHeader(cls, script_data):
"""Parse a script integrity header.
This function makes sure any integrity hashes are correctly parsed and
returns a ScriptHeader structure containing the information that it
was able to parse out.
Args:
script_data (bytearray): The script that we should parse.
Raises:
ArgumentError: If the script contains malformed data that
cannot be parsed.
Returns:
ScriptHeader: The parsed script header information
"""
if len(script_data) < UpdateScript.SCRIPT_HEADER_LENGTH:
raise ArgumentError("Script is too short to contain a script header",
length=len(script_data), header_length=UpdateScript.SCRIPT_HEADER_LENGTH)
embedded_hash, magic, total_length = struct.unpack_from("<16sLL", script_data)
if magic != UpdateScript.SCRIPT_MAGIC:
raise ArgumentError("Script has invalid magic value", expected=UpdateScript.SCRIPT_MAGIC, found=magic)
if total_length != len(script_data):
raise ArgumentError("Script length does not match embedded length",
embedded_length=total_length, length=len(script_data))
hashed_data = script_data[16:]
sha = hashlib.sha256()
sha.update(hashed_data)
hash_value = sha.digest()[:16]
if not compare_digest(embedded_hash, hash_value):
raise ArgumentError("Script has invalid embedded hash", embedded_hash=hexlify(embedded_hash),
calculated_hash=hexlify(hash_value))
return ScriptHeader(UpdateScript.SCRIPT_HEADER_LENGTH, False, True, False) | python | def ParseHeader(cls, script_data):
if len(script_data) < UpdateScript.SCRIPT_HEADER_LENGTH:
raise ArgumentError("Script is too short to contain a script header",
length=len(script_data), header_length=UpdateScript.SCRIPT_HEADER_LENGTH)
embedded_hash, magic, total_length = struct.unpack_from("<16sLL", script_data)
if magic != UpdateScript.SCRIPT_MAGIC:
raise ArgumentError("Script has invalid magic value", expected=UpdateScript.SCRIPT_MAGIC, found=magic)
if total_length != len(script_data):
raise ArgumentError("Script length does not match embedded length",
embedded_length=total_length, length=len(script_data))
hashed_data = script_data[16:]
sha = hashlib.sha256()
sha.update(hashed_data)
hash_value = sha.digest()[:16]
if not compare_digest(embedded_hash, hash_value):
raise ArgumentError("Script has invalid embedded hash", embedded_hash=hexlify(embedded_hash),
calculated_hash=hexlify(hash_value))
return ScriptHeader(UpdateScript.SCRIPT_HEADER_LENGTH, False, True, False) | [
"def",
"ParseHeader",
"(",
"cls",
",",
"script_data",
")",
":",
"if",
"len",
"(",
"script_data",
")",
"<",
"UpdateScript",
".",
"SCRIPT_HEADER_LENGTH",
":",
"raise",
"ArgumentError",
"(",
"\"Script is too short to contain a script header\"",
",",
"length",
"=",
"len... | Parse a script integrity header.
This function makes sure any integrity hashes are correctly parsed and
returns a ScriptHeader structure containing the information that it
was able to parse out.
Args:
script_data (bytearray): The script that we should parse.
Raises:
ArgumentError: If the script contains malformed data that
cannot be parsed.
Returns:
ScriptHeader: The parsed script header information | [
"Parse",
"a",
"script",
"integrity",
"header",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/script.py#L32-L72 |
23,347 | iotile/coretools | iotilecore/iotile/core/hw/update/script.py | UpdateScript.FromBinary | def FromBinary(cls, script_data, allow_unknown=True, show_rpcs=False):
"""Parse a binary update script.
Args:
script_data (bytearray): The binary data containing the script.
allow_unknown (bool): Allow the script to contain unknown records
so long as they have correct headers to allow us to skip them.
show_rpcs (bool): Show SendRPCRecord matches for each record rather than
the more specific operation
Raises:
ArgumentError: If the script contains malformed data that cannot
be parsed.
DataError: If the script contains unknown records and allow_unknown=False
Returns:
UpdateScript: The parsed update script.
"""
curr = 0
records = []
header = cls.ParseHeader(script_data)
curr = header.header_length
cls.logger.debug("Parsed script header: %s, skipping %d bytes", header, curr)
record_count = 0
record_data = bytearray()
partial_match = None
match_offset = 0
while curr < len(script_data):
if len(script_data) - curr < UpdateRecord.HEADER_LENGTH:
raise ArgumentError("Script ended with a partial record", remaining_length=len(script_data) - curr)
# Add another record to our current list of records that we're parsing
total_length, record_type = struct.unpack_from("<LB", script_data[curr:])
cls.logger.debug("Found record of type %d, length %d", record_type, total_length)
record_data += script_data[curr:curr+total_length]
record_count += 1
curr += total_length
try:
if show_rpcs and record_type == SendRPCRecord.MatchType():
cls.logger.debug(" {0}".format(hexlify(record_data)))
record = SendRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:], record_count)
elif show_rpcs and record_type == SendErrorCheckingRPCRecord.MatchType():
cls.logger.debug(" {0}".format(hexlify(record_data)))
record = SendErrorCheckingRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:],
record_count)
else:
record = UpdateRecord.FromBinary(record_data, record_count)
except DeferMatching as defer:
# If we're told to defer matching, continue accumulating record_data
# until we get a complete match. If a partial match is available, keep track of
# that partial match so that we can use it once the record no longer matches.
if defer.partial_match is not None:
partial_match = defer.partial_match
match_offset = curr
continue
except DataError:
if record_count > 1 and partial_match:
record = partial_match
curr = match_offset
elif not allow_unknown:
raise
elif allow_unknown and record_count > 1:
raise ArgumentError("A record matched an initial record subset but failed"
" matching a subsequent addition without leaving a partial_match")
else:
record = UnknownRecord(record_type, record_data[UpdateRecord.HEADER_LENGTH:])
# Reset our record accumulator since we successfully matched one or more records
record_count = 0
record_data = bytearray()
partial_match = None
match_offset = 0
records.append(record)
return UpdateScript(records) | python | def FromBinary(cls, script_data, allow_unknown=True, show_rpcs=False):
curr = 0
records = []
header = cls.ParseHeader(script_data)
curr = header.header_length
cls.logger.debug("Parsed script header: %s, skipping %d bytes", header, curr)
record_count = 0
record_data = bytearray()
partial_match = None
match_offset = 0
while curr < len(script_data):
if len(script_data) - curr < UpdateRecord.HEADER_LENGTH:
raise ArgumentError("Script ended with a partial record", remaining_length=len(script_data) - curr)
# Add another record to our current list of records that we're parsing
total_length, record_type = struct.unpack_from("<LB", script_data[curr:])
cls.logger.debug("Found record of type %d, length %d", record_type, total_length)
record_data += script_data[curr:curr+total_length]
record_count += 1
curr += total_length
try:
if show_rpcs and record_type == SendRPCRecord.MatchType():
cls.logger.debug(" {0}".format(hexlify(record_data)))
record = SendRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:], record_count)
elif show_rpcs and record_type == SendErrorCheckingRPCRecord.MatchType():
cls.logger.debug(" {0}".format(hexlify(record_data)))
record = SendErrorCheckingRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:],
record_count)
else:
record = UpdateRecord.FromBinary(record_data, record_count)
except DeferMatching as defer:
# If we're told to defer matching, continue accumulating record_data
# until we get a complete match. If a partial match is available, keep track of
# that partial match so that we can use it once the record no longer matches.
if defer.partial_match is not None:
partial_match = defer.partial_match
match_offset = curr
continue
except DataError:
if record_count > 1 and partial_match:
record = partial_match
curr = match_offset
elif not allow_unknown:
raise
elif allow_unknown and record_count > 1:
raise ArgumentError("A record matched an initial record subset but failed"
" matching a subsequent addition without leaving a partial_match")
else:
record = UnknownRecord(record_type, record_data[UpdateRecord.HEADER_LENGTH:])
# Reset our record accumulator since we successfully matched one or more records
record_count = 0
record_data = bytearray()
partial_match = None
match_offset = 0
records.append(record)
return UpdateScript(records) | [
"def",
"FromBinary",
"(",
"cls",
",",
"script_data",
",",
"allow_unknown",
"=",
"True",
",",
"show_rpcs",
"=",
"False",
")",
":",
"curr",
"=",
"0",
"records",
"=",
"[",
"]",
"header",
"=",
"cls",
".",
"ParseHeader",
"(",
"script_data",
")",
"curr",
"="... | Parse a binary update script.
Args:
script_data (bytearray): The binary data containing the script.
allow_unknown (bool): Allow the script to contain unknown records
so long as they have correct headers to allow us to skip them.
show_rpcs (bool): Show SendRPCRecord matches for each record rather than
the more specific operation
Raises:
ArgumentError: If the script contains malformed data that cannot
be parsed.
DataError: If the script contains unknown records and allow_unknown=False
Returns:
UpdateScript: The parsed update script. | [
"Parse",
"a",
"binary",
"update",
"script",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/script.py#L75-L161 |
23,348 | iotile/coretools | iotilecore/iotile/core/hw/update/script.py | UpdateScript.encode | def encode(self):
"""Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script.
"""
blob = bytearray()
for record in self.records:
blob += record.encode()
header = struct.pack("<LL", self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH)
blob = header + blob
sha = hashlib.sha256()
sha.update(blob)
hash_value = sha.digest()[:16]
return bytearray(hash_value) + blob | python | def encode(self):
blob = bytearray()
for record in self.records:
blob += record.encode()
header = struct.pack("<LL", self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH)
blob = header + blob
sha = hashlib.sha256()
sha.update(blob)
hash_value = sha.digest()[:16]
return bytearray(hash_value) + blob | [
"def",
"encode",
"(",
"self",
")",
":",
"blob",
"=",
"bytearray",
"(",
")",
"for",
"record",
"in",
"self",
".",
"records",
":",
"blob",
"+=",
"record",
".",
"encode",
"(",
")",
"header",
"=",
"struct",
".",
"pack",
"(",
"\"<LL\"",
",",
"self",
".",... | Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script. | [
"Encode",
"this",
"record",
"into",
"a",
"binary",
"blob",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/script.py#L163-L184 |
23,349 | iotile/coretools | iotilecore/iotile/core/hw/virtual/base_runnable.py | BaseRunnable.create_worker | def create_worker(self, func, interval, *args, **kwargs):
"""Spawn a worker thread running func.
The worker will be automatically be started when start() is called
and terminated when stop() is called on this object.
This must be called only from the main thread, not from a worker thread.
create_worker must not be called after stop() has been called. If it
is called before start() is called, the thread is started when start()
is called, otherwise it is started immediately.
Args:
func (callable): Either a function that will be called in a loop
with a sleep of interval seconds with *args and **kwargs or
a generator function that will be called once and expected to
yield periodically so that the worker can check if it should
be killed.
interval (float): The time interval between invocations of func.
This should not be 0 so that the thread doesn't peg the CPU
and should be short enough so that the worker checks if it
should be killed in a timely fashion.
*args: Arguments that are passed to func as positional args
**kwargs: Arguments that are passed to func as keyword args
"""
thread = StoppableWorkerThread(func, interval, args, kwargs)
self._workers.append(thread)
if self._started:
thread.start() | python | def create_worker(self, func, interval, *args, **kwargs):
thread = StoppableWorkerThread(func, interval, args, kwargs)
self._workers.append(thread)
if self._started:
thread.start() | [
"def",
"create_worker",
"(",
"self",
",",
"func",
",",
"interval",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"StoppableWorkerThread",
"(",
"func",
",",
"interval",
",",
"args",
",",
"kwargs",
")",
"self",
".",
"_workers",
".",... | Spawn a worker thread running func.
The worker will be automatically be started when start() is called
and terminated when stop() is called on this object.
This must be called only from the main thread, not from a worker thread.
create_worker must not be called after stop() has been called. If it
is called before start() is called, the thread is started when start()
is called, otherwise it is started immediately.
Args:
func (callable): Either a function that will be called in a loop
with a sleep of interval seconds with *args and **kwargs or
a generator function that will be called once and expected to
yield periodically so that the worker can check if it should
be killed.
interval (float): The time interval between invocations of func.
This should not be 0 so that the thread doesn't peg the CPU
and should be short enough so that the worker checks if it
should be killed in a timely fashion.
*args: Arguments that are passed to func as positional args
**kwargs: Arguments that are passed to func as keyword args | [
"Spawn",
"a",
"worker",
"thread",
"running",
"func",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/base_runnable.py#L16-L45 |
23,350 | iotile/coretools | iotilecore/iotile/core/hw/virtual/base_runnable.py | BaseRunnable.stop_workers | def stop_workers(self):
"""Synchronously stop any potential workers."""
self._started = False
for worker in self._workers:
worker.stop() | python | def stop_workers(self):
self._started = False
for worker in self._workers:
worker.stop() | [
"def",
"stop_workers",
"(",
"self",
")",
":",
"self",
".",
"_started",
"=",
"False",
"for",
"worker",
"in",
"self",
".",
"_workers",
":",
"worker",
".",
"stop",
"(",
")"
] | Synchronously stop any potential workers. | [
"Synchronously",
"stop",
"any",
"potential",
"workers",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/base_runnable.py#L58-L64 |
23,351 | iotile/coretools | iotilecore/iotile/core/hw/virtual/base_runnable.py | BaseRunnable.stop_workers_async | def stop_workers_async(self):
"""Signal that all workers should stop without waiting."""
self._started = False
for worker in self._workers:
worker.signal_stop() | python | def stop_workers_async(self):
self._started = False
for worker in self._workers:
worker.signal_stop() | [
"def",
"stop_workers_async",
"(",
"self",
")",
":",
"self",
".",
"_started",
"=",
"False",
"for",
"worker",
"in",
"self",
".",
"_workers",
":",
"worker",
".",
"signal_stop",
"(",
")"
] | Signal that all workers should stop without waiting. | [
"Signal",
"that",
"all",
"workers",
"should",
"stop",
"without",
"waiting",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/base_runnable.py#L66-L71 |
23,352 | iotile/coretools | iotile_ext_cloud/iotile/cloud/apps/ota_updater.py | _download_ota_script | def _download_ota_script(script_url):
"""Download the script from the cloud service and store to temporary file location"""
try:
blob = requests.get(script_url, stream=True)
return blob.content
except Exception as e:
iprint("Failed to download OTA script")
iprint(e)
return False | python | def _download_ota_script(script_url):
try:
blob = requests.get(script_url, stream=True)
return blob.content
except Exception as e:
iprint("Failed to download OTA script")
iprint(e)
return False | [
"def",
"_download_ota_script",
"(",
"script_url",
")",
":",
"try",
":",
"blob",
"=",
"requests",
".",
"get",
"(",
"script_url",
",",
"stream",
"=",
"True",
")",
"return",
"blob",
".",
"content",
"except",
"Exception",
"as",
"e",
":",
"iprint",
"(",
"\"Fa... | Download the script from the cloud service and store to temporary file location | [
"Download",
"the",
"script",
"from",
"the",
"cloud",
"service",
"and",
"store",
"to",
"temporary",
"file",
"location"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotile_ext_cloud/iotile/cloud/apps/ota_updater.py#L27-L36 |
23,353 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/compat/__init__.py | rename_module | def rename_module(new, old):
"""
Attempts to import the old module and load it under the new name.
Used for purely cosmetic name changes in Python 3.x.
"""
try:
sys.modules[new] = imp.load_module(old, *imp.find_module(old))
return True
except ImportError:
return False | python | def rename_module(new, old):
try:
sys.modules[new] = imp.load_module(old, *imp.find_module(old))
return True
except ImportError:
return False | [
"def",
"rename_module",
"(",
"new",
",",
"old",
")",
":",
"try",
":",
"sys",
".",
"modules",
"[",
"new",
"]",
"=",
"imp",
".",
"load_module",
"(",
"old",
",",
"*",
"imp",
".",
"find_module",
"(",
"old",
")",
")",
"return",
"True",
"except",
"Import... | Attempts to import the old module and load it under the new name.
Used for purely cosmetic name changes in Python 3.x. | [
"Attempts",
"to",
"import",
"the",
"old",
"module",
"and",
"load",
"it",
"under",
"the",
"new",
"name",
".",
"Used",
"for",
"purely",
"cosmetic",
"name",
"changes",
"in",
"Python",
"3",
".",
"x",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/compat/__init__.py#L78-L87 |
23,354 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink.py | JLinkAdapter._parse_conn_string | def _parse_conn_string(self, conn_string):
"""Parse a connection string passed from 'debug -c' or 'connect_direct'
Returns True if any settings changed in the debug port, which
would require a jlink disconnection """
disconnection_required = False
"""If device not in conn_string, set to default info"""
if conn_string is None or 'device' not in conn_string:
if self._default_device_info is not None and self._device_info != self._default_device_info:
disconnection_required = True
self._device_info = self._default_device_info
if conn_string is None or len(conn_string) == 0:
return disconnection_required
if '@' in conn_string:
raise ArgumentError("Configuration files are not yet supported as part of a connection string argument",
conn_string=conn_string)
pairs = conn_string.split(';')
for pair in pairs:
name, _, value = pair.partition('=')
if len(name) == 0 or len(value) == 0:
continue
name = name.strip()
value = value.strip()
if name == 'device':
if value in DEVICE_ALIASES:
device_name = DEVICE_ALIASES[value]
if device_name in KNOWN_DEVICES:
device_info = KNOWN_DEVICES.get(device_name)
if self._device_info != device_info:
self._device_info = device_info
disconnection_required = True
else:
raise ArgumentError("Unknown device name or alias, please select from known_devices",
device_name=value, known_devices=[x for x in DEVICE_ALIASES.keys()])
elif name == 'channel':
if self._mux_func is not None:
if self._channel != int(value):
self._channel = int(value)
disconnection_required = True
else:
print("Warning: multiplexing architecture not selected, channel will not be set")
return disconnection_required | python | def _parse_conn_string(self, conn_string):
disconnection_required = False
"""If device not in conn_string, set to default info"""
if conn_string is None or 'device' not in conn_string:
if self._default_device_info is not None and self._device_info != self._default_device_info:
disconnection_required = True
self._device_info = self._default_device_info
if conn_string is None or len(conn_string) == 0:
return disconnection_required
if '@' in conn_string:
raise ArgumentError("Configuration files are not yet supported as part of a connection string argument",
conn_string=conn_string)
pairs = conn_string.split(';')
for pair in pairs:
name, _, value = pair.partition('=')
if len(name) == 0 or len(value) == 0:
continue
name = name.strip()
value = value.strip()
if name == 'device':
if value in DEVICE_ALIASES:
device_name = DEVICE_ALIASES[value]
if device_name in KNOWN_DEVICES:
device_info = KNOWN_DEVICES.get(device_name)
if self._device_info != device_info:
self._device_info = device_info
disconnection_required = True
else:
raise ArgumentError("Unknown device name or alias, please select from known_devices",
device_name=value, known_devices=[x for x in DEVICE_ALIASES.keys()])
elif name == 'channel':
if self._mux_func is not None:
if self._channel != int(value):
self._channel = int(value)
disconnection_required = True
else:
print("Warning: multiplexing architecture not selected, channel will not be set")
return disconnection_required | [
"def",
"_parse_conn_string",
"(",
"self",
",",
"conn_string",
")",
":",
"disconnection_required",
"=",
"False",
"\"\"\"If device not in conn_string, set to default info\"\"\"",
"if",
"conn_string",
"is",
"None",
"or",
"'device'",
"not",
"in",
"conn_string",
":",
"if",
"... | Parse a connection string passed from 'debug -c' or 'connect_direct'
Returns True if any settings changed in the debug port, which
would require a jlink disconnection | [
"Parse",
"a",
"connection",
"string",
"passed",
"from",
"debug",
"-",
"c",
"or",
"connect_direct",
"Returns",
"True",
"if",
"any",
"settings",
"changed",
"in",
"the",
"debug",
"port",
"which",
"would",
"require",
"a",
"jlink",
"disconnection"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L85-L131 |
23,355 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink.py | JLinkAdapter._try_connect | def _try_connect(self, connection_string):
"""If the connecton string settings are different, try and connect to an attached device"""
if self._parse_conn_string(connection_string):
self._trigger_callback('on_disconnect', self.id, self._connection_id)
self.stop_sync()
if self._mux_func is not None:
self._mux_func(self._channel)
if self._device_info is None:
raise ArgumentError("Missing device name or alias, specify using device=name in port string "
"or -c device=name in connect_direct or debug command",
known_devices=[x for x in DEVICE_ALIASES.keys()])
try:
self.jlink = pylink.JLink()
self.jlink.open(serial_no=self._jlink_serial)
self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
self.jlink.connect(self._device_info.jlink_name)
self.jlink.set_little_endian()
except pylink.errors.JLinkException as exc:
if exc.code == exc.VCC_FAILURE:
raise HardwareError("No target power detected", code=exc.code,
suggestion="Check jlink connection and power wiring")
raise
except:
raise
self._control_thread = JLinkControlThread(self.jlink)
self._control_thread.start()
self.set_config('probe_required', True)
self.set_config('probe_supported', True) | python | def _try_connect(self, connection_string):
if self._parse_conn_string(connection_string):
self._trigger_callback('on_disconnect', self.id, self._connection_id)
self.stop_sync()
if self._mux_func is not None:
self._mux_func(self._channel)
if self._device_info is None:
raise ArgumentError("Missing device name or alias, specify using device=name in port string "
"or -c device=name in connect_direct or debug command",
known_devices=[x for x in DEVICE_ALIASES.keys()])
try:
self.jlink = pylink.JLink()
self.jlink.open(serial_no=self._jlink_serial)
self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
self.jlink.connect(self._device_info.jlink_name)
self.jlink.set_little_endian()
except pylink.errors.JLinkException as exc:
if exc.code == exc.VCC_FAILURE:
raise HardwareError("No target power detected", code=exc.code,
suggestion="Check jlink connection and power wiring")
raise
except:
raise
self._control_thread = JLinkControlThread(self.jlink)
self._control_thread.start()
self.set_config('probe_required', True)
self.set_config('probe_supported', True) | [
"def",
"_try_connect",
"(",
"self",
",",
"connection_string",
")",
":",
"if",
"self",
".",
"_parse_conn_string",
"(",
"connection_string",
")",
":",
"self",
".",
"_trigger_callback",
"(",
"'on_disconnect'",
",",
"self",
".",
"id",
",",
"self",
".",
"_connectio... | If the connecton string settings are different, try and connect to an attached device | [
"If",
"the",
"connecton",
"string",
"settings",
"are",
"different",
"try",
"and",
"connect",
"to",
"an",
"attached",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L133-L167 |
23,356 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink.py | JLinkAdapter.stop_sync | def stop_sync(self):
"""Synchronously stop this adapter and release all resources."""
if self._control_thread is not None and self._control_thread.is_alive():
self._control_thread.stop()
self._control_thread.join()
if self.jlink is not None:
self.jlink.close() | python | def stop_sync(self):
if self._control_thread is not None and self._control_thread.is_alive():
self._control_thread.stop()
self._control_thread.join()
if self.jlink is not None:
self.jlink.close() | [
"def",
"stop_sync",
"(",
"self",
")",
":",
"if",
"self",
".",
"_control_thread",
"is",
"not",
"None",
"and",
"self",
".",
"_control_thread",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"_control_thread",
".",
"stop",
"(",
")",
"self",
".",
"_control_thr... | Synchronously stop this adapter and release all resources. | [
"Synchronously",
"stop",
"this",
"adapter",
"and",
"release",
"all",
"resources",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L169-L177 |
23,357 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink.py | JLinkAdapter.probe_async | def probe_async(self, callback):
"""Send advertisements for all connected devices.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
success: bool
failure_reason: None if success is True, otherwise a reason for why we could not probe
"""
def _on_finished(_name, control_info, exception):
if exception is not None:
callback(self.id, False, str(exception))
return
self._control_info = control_info
try:
info = {
'connection_string': "direct",
'uuid': control_info.uuid,
'signal_strength': 100
}
self._trigger_callback('on_scan', self.id, info, self.ExpirationTime)
finally:
callback(self.id, True, None)
self._control_thread.command(JLinkControlThread.FIND_CONTROL, _on_finished, self._device_info.ram_start, self._device_info.ram_size) | python | def probe_async(self, callback):
def _on_finished(_name, control_info, exception):
if exception is not None:
callback(self.id, False, str(exception))
return
self._control_info = control_info
try:
info = {
'connection_string': "direct",
'uuid': control_info.uuid,
'signal_strength': 100
}
self._trigger_callback('on_scan', self.id, info, self.ExpirationTime)
finally:
callback(self.id, True, None)
self._control_thread.command(JLinkControlThread.FIND_CONTROL, _on_finished, self._device_info.ram_start, self._device_info.ram_size) | [
"def",
"probe_async",
"(",
"self",
",",
"callback",
")",
":",
"def",
"_on_finished",
"(",
"_name",
",",
"control_info",
",",
"exception",
")",
":",
"if",
"exception",
"is",
"not",
"None",
":",
"callback",
"(",
"self",
".",
"id",
",",
"False",
",",
"str... | Send advertisements for all connected devices.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
success: bool
failure_reason: None if success is True, otherwise a reason for why we could not probe | [
"Send",
"advertisements",
"for",
"all",
"connected",
"devices",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L179-L207 |
23,358 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink.py | JLinkAdapter._open_debug_interface | def _open_debug_interface(self, conn_id, callback, connection_string=None):
"""Enable debug interface for this IOTile device
Args:
conn_id (int): the unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
self._try_connect(connection_string)
callback(conn_id, self.id, True, None) | python | def _open_debug_interface(self, conn_id, callback, connection_string=None):
self._try_connect(connection_string)
callback(conn_id, self.id, True, None) | [
"def",
"_open_debug_interface",
"(",
"self",
",",
"conn_id",
",",
"callback",
",",
"connection_string",
"=",
"None",
")",
":",
"self",
".",
"_try_connect",
"(",
"connection_string",
")",
"callback",
"(",
"conn_id",
",",
"self",
".",
"id",
",",
"True",
",",
... | Enable debug interface for this IOTile device
Args:
conn_id (int): the unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason) | [
"Enable",
"debug",
"interface",
"for",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L305-L314 |
23,359 | iotile/coretools | iotileemulate/iotile/emulate/virtual/peripheral_tile.py | EmulatedPeripheralTile._reset_vector | async def _reset_vector(self):
"""Main background task for the tile executive.
The tile executive is in charge registering the tile with the
controller and then handing control over to the tile's application
firmware after proper configuration values have been received.
"""
self._logger.info("Tile %s at address %d is starting from reset", self.name, self.address)
try:
address, run_level, debug = await self._device.emulator.await_rpc(8, rpcs.REGISTER_TILE, *self._registration_tuple())
except:
self._logger.exception("Error registering tile: address=%d, name=%s", self.address, self.name)
raise
self.debug_mode = bool(debug)
self.run_level = run_level
self._logger.info("Tile at address %d registered itself, received address=%d, runlevel=%d and debug=%d", self.address, address, run_level, debug)
self._registered.set()
# If we are in safe mode we do not run the main application
# loop.
if run_level == RunLevel.SAFE_MODE:
self.initialized.set()
return
if run_level == RunLevel.START_ON_COMMAND:
await self._start_received.wait()
self._hosted_app_running.set()
await self._application_main() | python | async def _reset_vector(self):
self._logger.info("Tile %s at address %d is starting from reset", self.name, self.address)
try:
address, run_level, debug = await self._device.emulator.await_rpc(8, rpcs.REGISTER_TILE, *self._registration_tuple())
except:
self._logger.exception("Error registering tile: address=%d, name=%s", self.address, self.name)
raise
self.debug_mode = bool(debug)
self.run_level = run_level
self._logger.info("Tile at address %d registered itself, received address=%d, runlevel=%d and debug=%d", self.address, address, run_level, debug)
self._registered.set()
# If we are in safe mode we do not run the main application
# loop.
if run_level == RunLevel.SAFE_MODE:
self.initialized.set()
return
if run_level == RunLevel.START_ON_COMMAND:
await self._start_received.wait()
self._hosted_app_running.set()
await self._application_main() | [
"async",
"def",
"_reset_vector",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Tile %s at address %d is starting from reset\"",
",",
"self",
".",
"name",
",",
"self",
".",
"address",
")",
"try",
":",
"address",
",",
"run_level",
",",
"d... | Main background task for the tile executive.
The tile executive is in charge registering the tile with the
controller and then handing control over to the tile's application
firmware after proper configuration values have been received. | [
"Main",
"background",
"task",
"for",
"the",
"tile",
"executive",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/peripheral_tile.py#L55-L87 |
23,360 | iotile/coretools | iotileemulate/iotile/emulate/virtual/peripheral_tile.py | EmulatedPeripheralTile._handle_reset | def _handle_reset(self):
"""Reset this tile.
This process needs to trigger the peripheral tile to reregister itself
with the controller and get new configuration variables. It also
needs to clear app_running.
"""
self._registered.clear()
self._start_received.clear()
self._hosted_app_running.clear()
super(EmulatedPeripheralTile, self)._handle_reset() | python | def _handle_reset(self):
self._registered.clear()
self._start_received.clear()
self._hosted_app_running.clear()
super(EmulatedPeripheralTile, self)._handle_reset() | [
"def",
"_handle_reset",
"(",
"self",
")",
":",
"self",
".",
"_registered",
".",
"clear",
"(",
")",
"self",
".",
"_start_received",
".",
"clear",
"(",
")",
"self",
".",
"_hosted_app_running",
".",
"clear",
"(",
")",
"super",
"(",
"EmulatedPeripheralTile",
"... | Reset this tile.
This process needs to trigger the peripheral tile to reregister itself
with the controller and get new configuration variables. It also
needs to clear app_running. | [
"Reset",
"this",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/peripheral_tile.py#L95-L107 |
23,361 | iotile/coretools | iotilegateway/iotilegateway/gateway.py | IOTileGateway.start | async def start(self):
"""Start the gateway."""
self._logger.info("Starting all device adapters")
await self.device_manager.start()
self._logger.info("Starting all servers")
for server in self.servers:
await server.start() | python | async def start(self):
self._logger.info("Starting all device adapters")
await self.device_manager.start()
self._logger.info("Starting all servers")
for server in self.servers:
await server.start() | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Starting all device adapters\"",
")",
"await",
"self",
".",
"device_manager",
".",
"start",
"(",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Starting all serve... | Start the gateway. | [
"Start",
"the",
"gateway",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/gateway.py#L49-L57 |
23,362 | iotile/coretools | iotilegateway/iotilegateway/gateway.py | IOTileGateway.stop | async def stop(self):
"""Stop the gateway manager and synchronously wait for it to stop."""
self._logger.info("Stopping all servers")
for server in self.servers:
await server.stop()
self._logger.info("Stopping all device adapters")
await self.device_manager.stop() | python | async def stop(self):
self._logger.info("Stopping all servers")
for server in self.servers:
await server.stop()
self._logger.info("Stopping all device adapters")
await self.device_manager.stop() | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Stopping all servers\"",
")",
"for",
"server",
"in",
"self",
".",
"servers",
":",
"await",
"server",
".",
"stop",
"(",
")",
"self",
".",
"_logger",
".",
"info",... | Stop the gateway manager and synchronously wait for it to stop. | [
"Stop",
"the",
"gateway",
"manager",
"and",
"synchronously",
"wait",
"for",
"it",
"to",
"stop",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/gateway.py#L59-L67 |
23,363 | iotile/coretools | iotileship/iotile/ship/scripts/iotile_ship.py | main | def main(argv=None):
"""Main entry point for iotile-ship recipe runner.
This is the iotile-ship command line program.
Args:
argv (list of str): An optional set of command line
parameters. If not passed, these are taken from
sys.argv.
"""
if argv is None:
argv = sys.argv[1:]
parser = build_args()
args = parser.parse_args(args=argv)
recipe_name, _ext = os.path.splitext(os.path.basename(args.recipe))
rm = RecipeManager()
rm.add_recipe_folder(os.path.dirname(args.recipe), whitelist=[os.path.basename(args.recipe)])
recipe = rm.get_recipe(recipe_name)
if args.archive is not None:
print("Archiving recipe into %s" % args.archive)
recipe.archive(args.archive)
return 0
if args.info:
print(recipe)
return 0
variables = load_variables(args.define, args.config)
success = 0
start_time = time.time()
if args.loop is None:
try:
recipe.run(variables)
success += 1
except IOTileException as exc:
print("Error running recipe: %s" % str(exc))
return 1
else:
while True:
value = input("Enter value for loop variable %s (return to stop): " % args.loop)
if value == '':
break
local_vars = dict(**variables)
local_vars[args.loop] = value
try:
recipe.run(local_vars)
success += 1
except IOTileException as exc:
print("--> ERROR processing loop variable %s: %s" % (value, str(exc)))
end_time = time.time()
total_time = end_time - start_time
if success == 0:
per_time = 0.0
else:
per_time = total_time / success
print("Performed %d runs in %.1f seconds (%.1f seconds / run)" % (success, total_time, per_time))
return 0 | python | def main(argv=None):
if argv is None:
argv = sys.argv[1:]
parser = build_args()
args = parser.parse_args(args=argv)
recipe_name, _ext = os.path.splitext(os.path.basename(args.recipe))
rm = RecipeManager()
rm.add_recipe_folder(os.path.dirname(args.recipe), whitelist=[os.path.basename(args.recipe)])
recipe = rm.get_recipe(recipe_name)
if args.archive is not None:
print("Archiving recipe into %s" % args.archive)
recipe.archive(args.archive)
return 0
if args.info:
print(recipe)
return 0
variables = load_variables(args.define, args.config)
success = 0
start_time = time.time()
if args.loop is None:
try:
recipe.run(variables)
success += 1
except IOTileException as exc:
print("Error running recipe: %s" % str(exc))
return 1
else:
while True:
value = input("Enter value for loop variable %s (return to stop): " % args.loop)
if value == '':
break
local_vars = dict(**variables)
local_vars[args.loop] = value
try:
recipe.run(local_vars)
success += 1
except IOTileException as exc:
print("--> ERROR processing loop variable %s: %s" % (value, str(exc)))
end_time = time.time()
total_time = end_time - start_time
if success == 0:
per_time = 0.0
else:
per_time = total_time / success
print("Performed %d runs in %.1f seconds (%.1f seconds / run)" % (success, total_time, per_time))
return 0 | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"build_args",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
"=",
"argv",
... | Main entry point for iotile-ship recipe runner.
This is the iotile-ship command line program.
Args:
argv (list of str): An optional set of command line
parameters. If not passed, these are taken from
sys.argv. | [
"Main",
"entry",
"point",
"for",
"iotile",
"-",
"ship",
"recipe",
"runner",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/scripts/iotile_ship.py#L59-L129 |
23,364 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Subst.py | subst_dict | def subst_dict(target, source):
"""Create a dictionary for substitution of special
construction variables.
This translates the following special arguments:
target - the target (object or array of objects),
used to generate the TARGET and TARGETS
construction variables
source - the source (object or array of objects),
used to generate the SOURCES and SOURCE
construction variables
"""
dict = {}
if target:
def get_tgt_subst_proxy(thing):
try:
subst_proxy = thing.get_subst_proxy()
except AttributeError:
subst_proxy = thing # probably a string, just return it
return subst_proxy
tnl = NLWrapper(target, get_tgt_subst_proxy)
dict['TARGETS'] = Targets_or_Sources(tnl)
dict['TARGET'] = Target_or_Source(tnl)
# This is a total cheat, but hopefully this dictionary goes
# away soon anyway. We just let these expand to $TARGETS
# because that's "good enough" for the use of ToolSurrogates
# (see test/ToolSurrogate.py) to generate documentation.
dict['CHANGED_TARGETS'] = '$TARGETS'
dict['UNCHANGED_TARGETS'] = '$TARGETS'
else:
dict['TARGETS'] = NullNodesList
dict['TARGET'] = NullNodesList
if source:
def get_src_subst_proxy(node):
try:
rfile = node.rfile
except AttributeError:
pass
else:
node = rfile()
try:
return node.get_subst_proxy()
except AttributeError:
return node # probably a String, just return it
snl = NLWrapper(source, get_src_subst_proxy)
dict['SOURCES'] = Targets_or_Sources(snl)
dict['SOURCE'] = Target_or_Source(snl)
# This is a total cheat, but hopefully this dictionary goes
# away soon anyway. We just let these expand to $TARGETS
# because that's "good enough" for the use of ToolSurrogates
# (see test/ToolSurrogate.py) to generate documentation.
dict['CHANGED_SOURCES'] = '$SOURCES'
dict['UNCHANGED_SOURCES'] = '$SOURCES'
else:
dict['SOURCES'] = NullNodesList
dict['SOURCE'] = NullNodesList
return dict | python | def subst_dict(target, source):
dict = {}
if target:
def get_tgt_subst_proxy(thing):
try:
subst_proxy = thing.get_subst_proxy()
except AttributeError:
subst_proxy = thing # probably a string, just return it
return subst_proxy
tnl = NLWrapper(target, get_tgt_subst_proxy)
dict['TARGETS'] = Targets_or_Sources(tnl)
dict['TARGET'] = Target_or_Source(tnl)
# This is a total cheat, but hopefully this dictionary goes
# away soon anyway. We just let these expand to $TARGETS
# because that's "good enough" for the use of ToolSurrogates
# (see test/ToolSurrogate.py) to generate documentation.
dict['CHANGED_TARGETS'] = '$TARGETS'
dict['UNCHANGED_TARGETS'] = '$TARGETS'
else:
dict['TARGETS'] = NullNodesList
dict['TARGET'] = NullNodesList
if source:
def get_src_subst_proxy(node):
try:
rfile = node.rfile
except AttributeError:
pass
else:
node = rfile()
try:
return node.get_subst_proxy()
except AttributeError:
return node # probably a String, just return it
snl = NLWrapper(source, get_src_subst_proxy)
dict['SOURCES'] = Targets_or_Sources(snl)
dict['SOURCE'] = Target_or_Source(snl)
# This is a total cheat, but hopefully this dictionary goes
# away soon anyway. We just let these expand to $TARGETS
# because that's "good enough" for the use of ToolSurrogates
# (see test/ToolSurrogate.py) to generate documentation.
dict['CHANGED_SOURCES'] = '$SOURCES'
dict['UNCHANGED_SOURCES'] = '$SOURCES'
else:
dict['SOURCES'] = NullNodesList
dict['SOURCE'] = NullNodesList
return dict | [
"def",
"subst_dict",
"(",
"target",
",",
"source",
")",
":",
"dict",
"=",
"{",
"}",
"if",
"target",
":",
"def",
"get_tgt_subst_proxy",
"(",
"thing",
")",
":",
"try",
":",
"subst_proxy",
"=",
"thing",
".",
"get_subst_proxy",
"(",
")",
"except",
"Attribute... | Create a dictionary for substitution of special
construction variables.
This translates the following special arguments:
target - the target (object or array of objects),
used to generate the TARGET and TARGETS
construction variables
source - the source (object or array of objects),
used to generate the SOURCES and SOURCE
construction variables | [
"Create",
"a",
"dictionary",
"for",
"substitution",
"of",
"special",
"construction",
"variables",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Subst.py#L266-L329 |
23,365 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Subst.py | CmdStringHolder.escape | def escape(self, escape_func, quote_func=quote_spaces):
"""Escape the string with the supplied function. The
function is expected to take an arbitrary string, then
return it with all special characters escaped and ready
for passing to the command interpreter.
After calling this function, the next call to str() will
return the escaped string.
"""
if self.is_literal():
return escape_func(self.data)
elif ' ' in self.data or '\t' in self.data:
return quote_func(self.data)
else:
return self.data | python | def escape(self, escape_func, quote_func=quote_spaces):
if self.is_literal():
return escape_func(self.data)
elif ' ' in self.data or '\t' in self.data:
return quote_func(self.data)
else:
return self.data | [
"def",
"escape",
"(",
"self",
",",
"escape_func",
",",
"quote_func",
"=",
"quote_spaces",
")",
":",
"if",
"self",
".",
"is_literal",
"(",
")",
":",
"return",
"escape_func",
"(",
"self",
".",
"data",
")",
"elif",
"' '",
"in",
"self",
".",
"data",
"or",
... | Escape the string with the supplied function. The
function is expected to take an arbitrary string, then
return it with all special characters escaped and ready
for passing to the command interpreter.
After calling this function, the next call to str() will
return the escaped string. | [
"Escape",
"the",
"string",
"with",
"the",
"supplied",
"function",
".",
"The",
"function",
"is",
"expected",
"to",
"take",
"an",
"arbitrary",
"string",
"then",
"return",
"it",
"with",
"all",
"special",
"characters",
"escaped",
"and",
"ready",
"for",
"passing",
... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Subst.py#L142-L157 |
23,366 | iotile/coretools | iotilecore/iotile/core/utilities/formatting.py | indent_list | def indent_list(inlist, level):
"""Join a list of strings, one per line with 'level' spaces before each one"""
indent = ' '*level
joinstr = '\n' + indent
retval = joinstr.join(inlist)
return indent + retval | python | def indent_list(inlist, level):
indent = ' '*level
joinstr = '\n' + indent
retval = joinstr.join(inlist)
return indent + retval | [
"def",
"indent_list",
"(",
"inlist",
",",
"level",
")",
":",
"indent",
"=",
"' '",
"*",
"level",
"joinstr",
"=",
"'\\n'",
"+",
"indent",
"retval",
"=",
"joinstr",
".",
"join",
"(",
"inlist",
")",
"return",
"indent",
"+",
"retval"
] | Join a list of strings, one per line with 'level' spaces before each one | [
"Join",
"a",
"list",
"of",
"strings",
"one",
"per",
"line",
"with",
"level",
"spaces",
"before",
"each",
"one"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/formatting.py#L20-L27 |
23,367 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/gfortran.py | generate | def generate(env):
"""Add Builders and construction variables for gfortran to an
Environment."""
fortran.generate(env)
for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03', 'F08']:
env['%s' % dialect] = 'gfortran'
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)
else:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect)
env['INC%sPREFIX' % dialect] = "-I"
env['INC%sSUFFIX' % dialect] = "" | python | def generate(env):
fortran.generate(env)
for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03', 'F08']:
env['%s' % dialect] = 'gfortran'
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)
else:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect)
env['INC%sPREFIX' % dialect] = "-I"
env['INC%sSUFFIX' % dialect] = "" | [
"def",
"generate",
"(",
"env",
")",
":",
"fortran",
".",
"generate",
"(",
"env",
")",
"for",
"dialect",
"in",
"[",
"'F77'",
",",
"'F90'",
",",
"'FORTRAN'",
",",
"'F95'",
",",
"'F03'",
",",
"'F08'",
"]",
":",
"env",
"[",
"'%s'",
"%",
"dialect",
"]",... | Add Builders and construction variables for gfortran to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"gfortran",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/gfortran.py#L41-L55 |
23,368 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._extract_device_uuid | def _extract_device_uuid(cls, slug):
"""Turn a string slug into a UUID
"""
if len(slug) != 22:
raise ArgumentError("Invalid device slug", slug=slug)
hexdigits = slug[3:]
hexdigits = hexdigits.replace('-', '')
try:
rawbytes = binascii.unhexlify(hexdigits)
words = struct.unpack(">LL", rawbytes)
return (words[0] << 32) | (words[1])
except ValueError as exc:
raise ArgumentError("Could not convert device slug to hex integer", slug=slug, error=str(exc)) | python | def _extract_device_uuid(cls, slug):
if len(slug) != 22:
raise ArgumentError("Invalid device slug", slug=slug)
hexdigits = slug[3:]
hexdigits = hexdigits.replace('-', '')
try:
rawbytes = binascii.unhexlify(hexdigits)
words = struct.unpack(">LL", rawbytes)
return (words[0] << 32) | (words[1])
except ValueError as exc:
raise ArgumentError("Could not convert device slug to hex integer", slug=slug, error=str(exc)) | [
"def",
"_extract_device_uuid",
"(",
"cls",
",",
"slug",
")",
":",
"if",
"len",
"(",
"slug",
")",
"!=",
"22",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid device slug\"",
",",
"slug",
"=",
"slug",
")",
"hexdigits",
"=",
"slug",
"[",
"3",
":",
"]",
"he... | Turn a string slug into a UUID | [
"Turn",
"a",
"string",
"slug",
"into",
"a",
"UUID"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L69-L84 |
23,369 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent.start | def start(self):
"""Start this gateway agent."""
self._prepare()
self._disconnector = tornado.ioloop.PeriodicCallback(self._disconnect_hanging_devices, 1000, self._loop)
self._disconnector.start() | python | def start(self):
self._prepare()
self._disconnector = tornado.ioloop.PeriodicCallback(self._disconnect_hanging_devices, 1000, self._loop)
self._disconnector.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_prepare",
"(",
")",
"self",
".",
"_disconnector",
"=",
"tornado",
".",
"ioloop",
".",
"PeriodicCallback",
"(",
"self",
".",
"_disconnect_hanging_devices",
",",
"1000",
",",
"self",
".",
"_loop",
")",
... | Start this gateway agent. | [
"Start",
"this",
"gateway",
"agent",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L86-L92 |
23,370 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent.stop | def stop(self):
"""Stop this gateway agent."""
if self._disconnector:
self._disconnector.stop()
self.client.disconnect() | python | def stop(self):
if self._disconnector:
self._disconnector.stop()
self.client.disconnect() | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_disconnector",
":",
"self",
".",
"_disconnector",
".",
"stop",
"(",
")",
"self",
".",
"client",
".",
"disconnect",
"(",
")"
] | Stop this gateway agent. | [
"Stop",
"this",
"gateway",
"agent",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L94-L100 |
23,371 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._validate_connection | def _validate_connection(self, action, uuid, key):
"""Validate that a message received for a device has the right key
If this action is valid the corresponding internal connection id to
be used with the DeviceManager is returned, otherwise None is returned
and an invalid message status is published.
Args:
slug (string): The slug for the device we're trying to connect to
uuid (int): The uuid corresponding to the slug
key (string): The key passed in when this device was first connected
to
Returns:
int: if the action is allowed, otherwise None
"""
if uuid not in self._connections:
self._logger.warn("Received message for device with no connection 0x%X", uuid)
return None
data = self._connections[uuid]
if key != data['key']:
self._logger.warn("Received message for device with incorrect key, uuid=0x%X", uuid)
return None
return data['connection_id'] | python | def _validate_connection(self, action, uuid, key):
if uuid not in self._connections:
self._logger.warn("Received message for device with no connection 0x%X", uuid)
return None
data = self._connections[uuid]
if key != data['key']:
self._logger.warn("Received message for device with incorrect key, uuid=0x%X", uuid)
return None
return data['connection_id'] | [
"def",
"_validate_connection",
"(",
"self",
",",
"action",
",",
"uuid",
",",
"key",
")",
":",
"if",
"uuid",
"not",
"in",
"self",
".",
"_connections",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Received message for device with no connection 0x%X\"",
",",
... | Validate that a message received for a device has the right key
If this action is valid the corresponding internal connection id to
be used with the DeviceManager is returned, otherwise None is returned
and an invalid message status is published.
Args:
slug (string): The slug for the device we're trying to connect to
uuid (int): The uuid corresponding to the slug
key (string): The key passed in when this device was first connected
to
Returns:
int: if the action is allowed, otherwise None | [
"Validate",
"that",
"a",
"message",
"received",
"for",
"a",
"device",
"has",
"the",
"right",
"key"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L118-L144 |
23,372 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._publish_status | def _publish_status(self, slug, data):
"""Publish a status message for a device
Args:
slug (string): The device slug that we are publishing on behalf of
data (dict): The status message data to be sent back to the caller
"""
status_topic = self.topics.prefix + 'devices/{}/data/status'.format(slug)
self._logger.debug("Publishing status message: (topic=%s) (message=%s)", status_topic, str(data))
self.client.publish(status_topic, data) | python | def _publish_status(self, slug, data):
status_topic = self.topics.prefix + 'devices/{}/data/status'.format(slug)
self._logger.debug("Publishing status message: (topic=%s) (message=%s)", status_topic, str(data))
self.client.publish(status_topic, data) | [
"def",
"_publish_status",
"(",
"self",
",",
"slug",
",",
"data",
")",
":",
"status_topic",
"=",
"self",
".",
"topics",
".",
"prefix",
"+",
"'devices/{}/data/status'",
".",
"format",
"(",
"slug",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Publishing... | Publish a status message for a device
Args:
slug (string): The device slug that we are publishing on behalf of
data (dict): The status message data to be sent back to the caller | [
"Publish",
"a",
"status",
"message",
"for",
"a",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L146-L157 |
23,373 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._publish_response | def _publish_response(self, slug, message):
"""Publish a response message for a device
Args:
slug (string): The device slug that we are publishing on behalf of
message (dict): A set of key value pairs that are used to create the message
that is sent.
"""
resp_topic = self.topics.gateway_topic(slug, 'data/response')
self._logger.debug("Publishing response message: (topic=%s) (message=%s)", resp_topic, message)
self.client.publish(resp_topic, message) | python | def _publish_response(self, slug, message):
resp_topic = self.topics.gateway_topic(slug, 'data/response')
self._logger.debug("Publishing response message: (topic=%s) (message=%s)", resp_topic, message)
self.client.publish(resp_topic, message) | [
"def",
"_publish_response",
"(",
"self",
",",
"slug",
",",
"message",
")",
":",
"resp_topic",
"=",
"self",
".",
"topics",
".",
"gateway_topic",
"(",
"slug",
",",
"'data/response'",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Publishing response message:... | Publish a response message for a device
Args:
slug (string): The device slug that we are publishing on behalf of
message (dict): A set of key value pairs that are used to create the message
that is sent. | [
"Publish",
"a",
"response",
"message",
"for",
"a",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L159-L170 |
23,374 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._on_action | def _on_action(self, sequence, topic, message):
"""Process a command action that we received on behalf of a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
try:
slug = None
parts = topic.split('/')
slug = parts[-3]
uuid = self._extract_device_uuid(slug)
except Exception as exc:
self._logger.warn("Error parsing slug in action handler (slug=%s, topic=%s)", slug, topic)
return
if messages.DisconnectCommand.matches(message):
self._logger.debug("Received disconnect command for device 0x%X", uuid)
key = message['key']
client = message['client']
self._loop.add_callback(self._disconnect_from_device, uuid, key, client)
elif messages.OpenInterfaceCommand.matches(message) or messages.CloseInterfaceCommand.matches(message):
self._logger.debug("Received %s command for device 0x%X", message['operation'], uuid)
key = message['key']
client = message['client']
oper = message['operation']
if oper == 'open_interface':
self._loop.add_callback(self._open_interface, client, uuid, message['interface'], key)
else:
self._loop.add_callback(self._close_interface, client, uuid, message['interface'], key)
elif messages.RPCCommand.matches(message):
rpc_msg = messages.RPCCommand.verify(message)
client = rpc_msg['client']
address = rpc_msg['address']
rpc = rpc_msg['rpc_id']
payload = rpc_msg['payload']
key = rpc_msg['key']
timeout = rpc_msg['timeout']
self._loop.add_callback(self._send_rpc, client, uuid, address, rpc, payload, timeout, key)
elif messages.ScriptCommand.matches(message):
script_msg = messages.ScriptCommand.verify(message)
key = script_msg['key']
client = script_msg['client']
script = script_msg['script']
self._loop.add_callback(self._send_script, client, uuid, script, key, (script_msg['fragment_index'], script_msg['fragment_count']))
else:
self._logger.error("Unsupported message received (topic=%s) (message=%s)", topic, str(message)) | python | def _on_action(self, sequence, topic, message):
try:
slug = None
parts = topic.split('/')
slug = parts[-3]
uuid = self._extract_device_uuid(slug)
except Exception as exc:
self._logger.warn("Error parsing slug in action handler (slug=%s, topic=%s)", slug, topic)
return
if messages.DisconnectCommand.matches(message):
self._logger.debug("Received disconnect command for device 0x%X", uuid)
key = message['key']
client = message['client']
self._loop.add_callback(self._disconnect_from_device, uuid, key, client)
elif messages.OpenInterfaceCommand.matches(message) or messages.CloseInterfaceCommand.matches(message):
self._logger.debug("Received %s command for device 0x%X", message['operation'], uuid)
key = message['key']
client = message['client']
oper = message['operation']
if oper == 'open_interface':
self._loop.add_callback(self._open_interface, client, uuid, message['interface'], key)
else:
self._loop.add_callback(self._close_interface, client, uuid, message['interface'], key)
elif messages.RPCCommand.matches(message):
rpc_msg = messages.RPCCommand.verify(message)
client = rpc_msg['client']
address = rpc_msg['address']
rpc = rpc_msg['rpc_id']
payload = rpc_msg['payload']
key = rpc_msg['key']
timeout = rpc_msg['timeout']
self._loop.add_callback(self._send_rpc, client, uuid, address, rpc, payload, timeout, key)
elif messages.ScriptCommand.matches(message):
script_msg = messages.ScriptCommand.verify(message)
key = script_msg['key']
client = script_msg['client']
script = script_msg['script']
self._loop.add_callback(self._send_script, client, uuid, script, key, (script_msg['fragment_index'], script_msg['fragment_count']))
else:
self._logger.error("Unsupported message received (topic=%s) (message=%s)", topic, str(message)) | [
"def",
"_on_action",
"(",
"self",
",",
"sequence",
",",
"topic",
",",
"message",
")",
":",
"try",
":",
"slug",
"=",
"None",
"parts",
"=",
"topic",
".",
"split",
"(",
"'/'",
")",
"slug",
"=",
"parts",
"[",
"-",
"3",
"]",
"uuid",
"=",
"self",
".",
... | Process a command action that we received on behalf of a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself | [
"Process",
"a",
"command",
"action",
"that",
"we",
"received",
"on",
"behalf",
"of",
"a",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L172-L225 |
23,375 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._on_connect | def _on_connect(self, sequence, topic, message):
"""Process a request to connect to an IOTile device
A connection message triggers an attempt to connect to a device,
any error checking is done by the DeviceManager that is actually
managing the devices.
A disconnection message is checked to make sure its key matches
what we except for this device and is either discarded or
forwarded on to the DeviceManager.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message_type (string): The type of the packet received
message (dict): The message itself
"""
try:
slug = None
parts = topic.split('/')
slug = parts[-3]
uuid = self._extract_device_uuid(slug)
except Exception:
self._logger.exception("Error parsing slug from connection request (slug=%s, topic=%s)", slug, topic)
return
if messages.ConnectCommand.matches(message):
key = message['key']
client = message['client']
self._loop.add_callback(self._connect_to_device, uuid, key, client)
else:
self._logger.warn("Unknown message received on connect topic=%s, message=%s", topic, message) | python | def _on_connect(self, sequence, topic, message):
try:
slug = None
parts = topic.split('/')
slug = parts[-3]
uuid = self._extract_device_uuid(slug)
except Exception:
self._logger.exception("Error parsing slug from connection request (slug=%s, topic=%s)", slug, topic)
return
if messages.ConnectCommand.matches(message):
key = message['key']
client = message['client']
self._loop.add_callback(self._connect_to_device, uuid, key, client)
else:
self._logger.warn("Unknown message received on connect topic=%s, message=%s", topic, message) | [
"def",
"_on_connect",
"(",
"self",
",",
"sequence",
",",
"topic",
",",
"message",
")",
":",
"try",
":",
"slug",
"=",
"None",
"parts",
"=",
"topic",
".",
"split",
"(",
"'/'",
")",
"slug",
"=",
"parts",
"[",
"-",
"3",
"]",
"uuid",
"=",
"self",
".",... | Process a request to connect to an IOTile device
A connection message triggers an attempt to connect to a device,
any error checking is done by the DeviceManager that is actually
managing the devices.
A disconnection message is checked to make sure its key matches
what we except for this device and is either discarded or
forwarded on to the DeviceManager.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message_type (string): The type of the packet received
message (dict): The message itself | [
"Process",
"a",
"request",
"to",
"connect",
"to",
"an",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L227-L259 |
23,376 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._send_rpc | def _send_rpc(self, client, uuid, address, rpc, payload, timeout, key):
"""Send an RPC to a connected device
Args:
client (string): The client that sent the rpc request
uuid (int): The id of the device we're opening the interface on
address (int): The address of the tile that we want to send the RPC to
rpc (int): The id of the rpc that we want to send.
payload (bytearray): The payload of arguments that we want to send
timeout (float): The number of seconds to wait for the response
key (string): The key to authenticate the caller
"""
conn_id = self._validate_connection('send_rpc', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = monotonic()
slug = self._build_device_slug(uuid)
try:
resp = yield self._manager.send_rpc(conn_id, address, rpc >> 8, rpc & 0xFF, bytes(payload), timeout)
except Exception as exc:
self._logger.error("Error in manager send rpc: %s" % str(exc))
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
payload = {'client': client, 'type': 'response', 'operation': 'rpc'}
payload['success'] = resp['success']
if resp['success'] is False:
payload['failure_reason'] = resp['reason']
else:
payload['status'] = resp['status']
payload['payload'] = binascii.hexlify(resp['payload'])
self._publish_response(slug, payload) | python | def _send_rpc(self, client, uuid, address, rpc, payload, timeout, key):
conn_id = self._validate_connection('send_rpc', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = monotonic()
slug = self._build_device_slug(uuid)
try:
resp = yield self._manager.send_rpc(conn_id, address, rpc >> 8, rpc & 0xFF, bytes(payload), timeout)
except Exception as exc:
self._logger.error("Error in manager send rpc: %s" % str(exc))
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
payload = {'client': client, 'type': 'response', 'operation': 'rpc'}
payload['success'] = resp['success']
if resp['success'] is False:
payload['failure_reason'] = resp['reason']
else:
payload['status'] = resp['status']
payload['payload'] = binascii.hexlify(resp['payload'])
self._publish_response(slug, payload) | [
"def",
"_send_rpc",
"(",
"self",
",",
"client",
",",
"uuid",
",",
"address",
",",
"rpc",
",",
"payload",
",",
"timeout",
",",
"key",
")",
":",
"conn_id",
"=",
"self",
".",
"_validate_connection",
"(",
"'send_rpc'",
",",
"uuid",
",",
"key",
")",
"if",
... | Send an RPC to a connected device
Args:
client (string): The client that sent the rpc request
uuid (int): The id of the device we're opening the interface on
address (int): The address of the tile that we want to send the RPC to
rpc (int): The id of the rpc that we want to send.
payload (bytearray): The payload of arguments that we want to send
timeout (float): The number of seconds to wait for the response
key (string): The key to authenticate the caller | [
"Send",
"an",
"RPC",
"to",
"a",
"connected",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L262-L299 |
23,377 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._send_script | def _send_script(self, client, uuid, chunk, key, chunk_status):
"""Send a script to the connected device.
Args:
client (string): The client that sent the rpc request
uuid (int): The id of the device we're opening the interface on
chunk (bytes): The binary script to send to the device
key (string): The key to authenticate the caller
last_chunk (tuple): the chunk index and count of chunks of this script
so that we know to either accumulate it or send it on to the device
immediately.
"""
conn_id = self._validate_connection('send_script', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = monotonic()
slug = self._build_device_slug(uuid)
# Check and see if we have the entire script or if we need to accumulate it
index, count = chunk_status
if index == 0:
conn_data['script'] = bytes()
conn_data['script'] += chunk
# If there is more than one chunk and we aren't on the last one, wait until we receive them
# all before sending them on to the device as a unit
if index != count - 1:
return
# Initialize our progress throttling system in case we need to throttle progress reports
conn_data['last_progress'] = None
try:
resp = yield self._manager.send_script(conn_id, conn_data['script'], lambda x, y: self._notify_progress_async(uuid, client, x, y))
yield None # Make sure we give time for any progress notifications that may have been queued to flush out
conn_data['script'] = bytes()
except Exception as exc:
self._logger.exception("Error in manager send_script")
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
payload = {'client': client, 'type': 'response', 'operation': 'send_script', 'success': resp['success']}
if resp['success'] is False:
payload['failure_reason'] = resp['reason']
self._publish_response(slug, payload) | python | def _send_script(self, client, uuid, chunk, key, chunk_status):
conn_id = self._validate_connection('send_script', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = monotonic()
slug = self._build_device_slug(uuid)
# Check and see if we have the entire script or if we need to accumulate it
index, count = chunk_status
if index == 0:
conn_data['script'] = bytes()
conn_data['script'] += chunk
# If there is more than one chunk and we aren't on the last one, wait until we receive them
# all before sending them on to the device as a unit
if index != count - 1:
return
# Initialize our progress throttling system in case we need to throttle progress reports
conn_data['last_progress'] = None
try:
resp = yield self._manager.send_script(conn_id, conn_data['script'], lambda x, y: self._notify_progress_async(uuid, client, x, y))
yield None # Make sure we give time for any progress notifications that may have been queued to flush out
conn_data['script'] = bytes()
except Exception as exc:
self._logger.exception("Error in manager send_script")
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
payload = {'client': client, 'type': 'response', 'operation': 'send_script', 'success': resp['success']}
if resp['success'] is False:
payload['failure_reason'] = resp['reason']
self._publish_response(slug, payload) | [
"def",
"_send_script",
"(",
"self",
",",
"client",
",",
"uuid",
",",
"chunk",
",",
"key",
",",
"chunk_status",
")",
":",
"conn_id",
"=",
"self",
".",
"_validate_connection",
"(",
"'send_script'",
",",
"uuid",
",",
"key",
")",
"if",
"conn_id",
"is",
"None... | Send a script to the connected device.
Args:
client (string): The client that sent the rpc request
uuid (int): The id of the device we're opening the interface on
chunk (bytes): The binary script to send to the device
key (string): The key to authenticate the caller
last_chunk (tuple): the chunk index and count of chunks of this script
so that we know to either accumulate it or send it on to the device
immediately. | [
"Send",
"a",
"script",
"to",
"the",
"connected",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L302-L351 |
23,378 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._open_interface | def _open_interface(self, client, uuid, iface, key):
"""Open an interface on a connected device.
Args:
client (string): The client id who is requesting this operation
uuid (int): The id of the device we're opening the interface on
iface (string): The name of the interface that we're opening
key (string): The key to authenticate the caller
"""
conn_id = self._validate_connection('open_interface', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = monotonic()
slug = self._build_device_slug(uuid)
try:
resp = yield self._manager.open_interface(conn_id, iface)
except Exception as exc:
self._logger.exception("Error in manager open interface")
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
message = {'type': 'response', 'operation': 'open_interface', 'client': client}
message['success'] = resp['success']
if not message['success']:
message['failure_reason'] = resp['reason']
self._publish_response(slug, message) | python | def _open_interface(self, client, uuid, iface, key):
conn_id = self._validate_connection('open_interface', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = monotonic()
slug = self._build_device_slug(uuid)
try:
resp = yield self._manager.open_interface(conn_id, iface)
except Exception as exc:
self._logger.exception("Error in manager open interface")
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
message = {'type': 'response', 'operation': 'open_interface', 'client': client}
message['success'] = resp['success']
if not message['success']:
message['failure_reason'] = resp['reason']
self._publish_response(slug, message) | [
"def",
"_open_interface",
"(",
"self",
",",
"client",
",",
"uuid",
",",
"iface",
",",
"key",
")",
":",
"conn_id",
"=",
"self",
".",
"_validate_connection",
"(",
"'open_interface'",
",",
"uuid",
",",
"key",
")",
"if",
"conn_id",
"is",
"None",
":",
"return... | Open an interface on a connected device.
Args:
client (string): The client id who is requesting this operation
uuid (int): The id of the device we're opening the interface on
iface (string): The name of the interface that we're opening
key (string): The key to authenticate the caller | [
"Open",
"an",
"interface",
"on",
"a",
"connected",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L409-L440 |
23,379 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._disconnect_hanging_devices | def _disconnect_hanging_devices(self):
"""Periodic callback that checks for devices that haven't been used and disconnects them."""
now = monotonic()
for uuid, data in self._connections.items():
if (now - data['last_touch']) > self.client_timeout:
self._logger.info("Disconnect inactive client %s from device 0x%X", data['client'], uuid)
self._loop.add_callback(self._disconnect_from_device, uuid, data['key'], data['client'], unsolicited=True) | python | def _disconnect_hanging_devices(self):
now = monotonic()
for uuid, data in self._connections.items():
if (now - data['last_touch']) > self.client_timeout:
self._logger.info("Disconnect inactive client %s from device 0x%X", data['client'], uuid)
self._loop.add_callback(self._disconnect_from_device, uuid, data['key'], data['client'], unsolicited=True) | [
"def",
"_disconnect_hanging_devices",
"(",
"self",
")",
":",
"now",
"=",
"monotonic",
"(",
")",
"for",
"uuid",
",",
"data",
"in",
"self",
".",
"_connections",
".",
"items",
"(",
")",
":",
"if",
"(",
"now",
"-",
"data",
"[",
"'last_touch'",
"]",
")",
... | Periodic callback that checks for devices that haven't been used and disconnects them. | [
"Periodic",
"callback",
"that",
"checks",
"for",
"devices",
"that",
"haven",
"t",
"been",
"used",
"and",
"disconnects",
"them",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L476-L483 |
23,380 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._disconnect_from_device | def _disconnect_from_device(self, uuid, key, client, unsolicited=False):
"""Disconnect from a device that we have previously connected to.
Args:
uuid (int): The unique id of the device
key (string): A 64 byte string used to secure this connection
client (string): The client id for who is trying to connect
to the device.
unsolicited (bool): Whether the client asked us to disconnect or we
are forcibly doing it. Forcible disconnections are sent as notifications
instead of responses.
"""
conn_id = self._validate_connection('disconnect', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
slug = self._build_device_slug(uuid)
message = {'client': client, 'type': 'response', 'operation': 'disconnect'}
self.client.reset_sequence(self.topics.gateway_topic(slug, 'control/connect'))
self.client.reset_sequence(self.topics.gateway_topic(slug, 'control/action'))
try:
resp = yield self._manager.disconnect(conn_id)
except Exception as exc:
self._logger.exception("Error in manager disconnect")
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
# Remove any monitors that we registered for this device
self._manager.remove_monitor(conn_data['report_monitor'])
self._manager.remove_monitor(conn_data['trace_monitor'])
if resp['success']:
del self._connections[uuid]
message['success'] = True
else:
message['success'] = False
message['failure_reason'] = resp['reason']
self._logger.info("Client %s disconnected from device 0x%X", client, uuid)
# Send a response for all requested disconnects and if we tried to disconnect the client
# on our own and succeeded, send an unsolicited notification to that effect
if unsolicited and resp['success']:
self._publish_response(slug, {'client': client, 'type': 'notification', 'operation': 'disconnect'})
elif not unsolicited:
self._publish_response(slug, message) | python | def _disconnect_from_device(self, uuid, key, client, unsolicited=False):
conn_id = self._validate_connection('disconnect', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
slug = self._build_device_slug(uuid)
message = {'client': client, 'type': 'response', 'operation': 'disconnect'}
self.client.reset_sequence(self.topics.gateway_topic(slug, 'control/connect'))
self.client.reset_sequence(self.topics.gateway_topic(slug, 'control/action'))
try:
resp = yield self._manager.disconnect(conn_id)
except Exception as exc:
self._logger.exception("Error in manager disconnect")
resp = {'success': False, 'reason': "Internal error: %s" % str(exc)}
# Remove any monitors that we registered for this device
self._manager.remove_monitor(conn_data['report_monitor'])
self._manager.remove_monitor(conn_data['trace_monitor'])
if resp['success']:
del self._connections[uuid]
message['success'] = True
else:
message['success'] = False
message['failure_reason'] = resp['reason']
self._logger.info("Client %s disconnected from device 0x%X", client, uuid)
# Send a response for all requested disconnects and if we tried to disconnect the client
# on our own and succeeded, send an unsolicited notification to that effect
if unsolicited and resp['success']:
self._publish_response(slug, {'client': client, 'type': 'notification', 'operation': 'disconnect'})
elif not unsolicited:
self._publish_response(slug, message) | [
"def",
"_disconnect_from_device",
"(",
"self",
",",
"uuid",
",",
"key",
",",
"client",
",",
"unsolicited",
"=",
"False",
")",
":",
"conn_id",
"=",
"self",
".",
"_validate_connection",
"(",
"'disconnect'",
",",
"uuid",
",",
"key",
")",
"if",
"conn_id",
"is"... | Disconnect from a device that we have previously connected to.
Args:
uuid (int): The unique id of the device
key (string): A 64 byte string used to secure this connection
client (string): The client id for who is trying to connect
to the device.
unsolicited (bool): Whether the client asked us to disconnect or we
are forcibly doing it. Forcible disconnections are sent as notifications
instead of responses. | [
"Disconnect",
"from",
"a",
"device",
"that",
"we",
"have",
"previously",
"connected",
"to",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L486-L536 |
23,381 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._notify_report | def _notify_report(self, device_uuid, event_name, report):
"""Notify that a report has been received from a device.
This routine is called synchronously in the event loop by the DeviceManager
"""
if device_uuid not in self._connections:
self._logger.debug("Dropping report for device without an active connection, uuid=0x%X", device_uuid)
return
slug = self._build_device_slug(device_uuid)
streaming_topic = self.topics.prefix + 'devices/{}/data/streaming'.format(slug)
data = {'type': 'notification', 'operation': 'report'}
ser = report.serialize()
data['received_time'] = ser['received_time'].strftime("%Y%m%dT%H:%M:%S.%fZ").encode()
data['report_origin'] = ser['origin']
data['report_format'] = ser['report_format']
data['report'] = binascii.hexlify(ser['encoded_report'])
data['fragment_count'] = 1
data['fragment_index'] = 0
self._logger.debug("Publishing report: (topic=%s)", streaming_topic)
self.client.publish(streaming_topic, data) | python | def _notify_report(self, device_uuid, event_name, report):
if device_uuid not in self._connections:
self._logger.debug("Dropping report for device without an active connection, uuid=0x%X", device_uuid)
return
slug = self._build_device_slug(device_uuid)
streaming_topic = self.topics.prefix + 'devices/{}/data/streaming'.format(slug)
data = {'type': 'notification', 'operation': 'report'}
ser = report.serialize()
data['received_time'] = ser['received_time'].strftime("%Y%m%dT%H:%M:%S.%fZ").encode()
data['report_origin'] = ser['origin']
data['report_format'] = ser['report_format']
data['report'] = binascii.hexlify(ser['encoded_report'])
data['fragment_count'] = 1
data['fragment_index'] = 0
self._logger.debug("Publishing report: (topic=%s)", streaming_topic)
self.client.publish(streaming_topic, data) | [
"def",
"_notify_report",
"(",
"self",
",",
"device_uuid",
",",
"event_name",
",",
"report",
")",
":",
"if",
"device_uuid",
"not",
"in",
"self",
".",
"_connections",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Dropping report for device without an active con... | Notify that a report has been received from a device.
This routine is called synchronously in the event loop by the DeviceManager | [
"Notify",
"that",
"a",
"report",
"has",
"been",
"received",
"from",
"a",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L580-L603 |
23,382 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._notify_trace | def _notify_trace(self, device_uuid, event_name, trace):
"""Notify that we have received tracing data from a device.
This routine is called synchronously in the event loop by the DeviceManager
"""
if device_uuid not in self._connections:
self._logger.debug("Dropping trace data for device without an active connection, uuid=0x%X", device_uuid)
return
conn_data = self._connections[device_uuid]
last_trace = conn_data['last_trace']
now = monotonic()
conn_data['trace_accum'] += bytes(trace)
# If we're throttling tracing data, we need to see if we should accumulate this trace or
# send it now. We acculumate if we've last sent tracing data less than self.throttle_trace seconds ago
if last_trace is not None and (now - last_trace) < self.throttle_trace:
if not conn_data['trace_scheduled']:
self._loop.call_later(self.throttle_trace - (now - last_trace), self._send_accum_trace, device_uuid)
conn_data['trace_scheduled'] = True
self._logger.debug("Deferring trace data due to throttling uuid=0x%X", device_uuid)
else:
self._send_accum_trace(device_uuid) | python | def _notify_trace(self, device_uuid, event_name, trace):
if device_uuid not in self._connections:
self._logger.debug("Dropping trace data for device without an active connection, uuid=0x%X", device_uuid)
return
conn_data = self._connections[device_uuid]
last_trace = conn_data['last_trace']
now = monotonic()
conn_data['trace_accum'] += bytes(trace)
# If we're throttling tracing data, we need to see if we should accumulate this trace or
# send it now. We acculumate if we've last sent tracing data less than self.throttle_trace seconds ago
if last_trace is not None and (now - last_trace) < self.throttle_trace:
if not conn_data['trace_scheduled']:
self._loop.call_later(self.throttle_trace - (now - last_trace), self._send_accum_trace, device_uuid)
conn_data['trace_scheduled'] = True
self._logger.debug("Deferring trace data due to throttling uuid=0x%X", device_uuid)
else:
self._send_accum_trace(device_uuid) | [
"def",
"_notify_trace",
"(",
"self",
",",
"device_uuid",
",",
"event_name",
",",
"trace",
")",
":",
"if",
"device_uuid",
"not",
"in",
"self",
".",
"_connections",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Dropping trace data for device without an active c... | Notify that we have received tracing data from a device.
This routine is called synchronously in the event loop by the DeviceManager | [
"Notify",
"that",
"we",
"have",
"received",
"tracing",
"data",
"from",
"a",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L605-L629 |
23,383 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._send_accum_trace | def _send_accum_trace(self, device_uuid):
"""Send whatever accumulated tracing data we have for the device."""
if device_uuid not in self._connections:
self._logger.debug("Dropping trace data for device without an active connection, uuid=0x%X", device_uuid)
return
conn_data = self._connections[device_uuid]
trace = conn_data['trace_accum']
if len(trace) > 0:
slug = self._build_device_slug(device_uuid)
tracing_topic = self.topics.prefix + 'devices/{}/data/tracing'.format(slug)
data = {'type': 'notification', 'operation': 'trace'}
data['trace'] = binascii.hexlify(trace)
data['trace_origin'] = device_uuid
self._logger.debug('Publishing trace: (topic=%s)', tracing_topic)
self.client.publish(tracing_topic, data)
conn_data['trace_scheduled'] = False
conn_data['last_trace'] = monotonic()
conn_data['trace_accum'] = bytes() | python | def _send_accum_trace(self, device_uuid):
if device_uuid not in self._connections:
self._logger.debug("Dropping trace data for device without an active connection, uuid=0x%X", device_uuid)
return
conn_data = self._connections[device_uuid]
trace = conn_data['trace_accum']
if len(trace) > 0:
slug = self._build_device_slug(device_uuid)
tracing_topic = self.topics.prefix + 'devices/{}/data/tracing'.format(slug)
data = {'type': 'notification', 'operation': 'trace'}
data['trace'] = binascii.hexlify(trace)
data['trace_origin'] = device_uuid
self._logger.debug('Publishing trace: (topic=%s)', tracing_topic)
self.client.publish(tracing_topic, data)
conn_data['trace_scheduled'] = False
conn_data['last_trace'] = monotonic()
conn_data['trace_accum'] = bytes() | [
"def",
"_send_accum_trace",
"(",
"self",
",",
"device_uuid",
")",
":",
"if",
"device_uuid",
"not",
"in",
"self",
".",
"_connections",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Dropping trace data for device without an active connection, uuid=0x%X\"",
",",
"de... | Send whatever accumulated tracing data we have for the device. | [
"Send",
"whatever",
"accumulated",
"tracing",
"data",
"we",
"have",
"for",
"the",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L631-L655 |
23,384 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._on_scan_request | def _on_scan_request(self, sequence, topic, message):
"""Process a request for scanning information
Args:
sequence (int:) The sequence number of the packet received
topic (string): The topic this message was received on
message_type (string): The type of the packet received
message (dict): The message itself
"""
if messages.ProbeCommand.matches(message):
self._logger.debug("Received probe message on topic %s, message=%s", topic, message)
self._loop.add_callback(self._publish_scan_response, message['client'])
else:
self._logger.warn("Invalid message received on topic %s, message=%s", topic, message) | python | def _on_scan_request(self, sequence, topic, message):
if messages.ProbeCommand.matches(message):
self._logger.debug("Received probe message on topic %s, message=%s", topic, message)
self._loop.add_callback(self._publish_scan_response, message['client'])
else:
self._logger.warn("Invalid message received on topic %s, message=%s", topic, message) | [
"def",
"_on_scan_request",
"(",
"self",
",",
"sequence",
",",
"topic",
",",
"message",
")",
":",
"if",
"messages",
".",
"ProbeCommand",
".",
"matches",
"(",
"message",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Received probe message on topic %s, ... | Process a request for scanning information
Args:
sequence (int:) The sequence number of the packet received
topic (string): The topic this message was received on
message_type (string): The type of the packet received
message (dict): The message itself | [
"Process",
"a",
"request",
"for",
"scanning",
"information"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L657-L671 |
23,385 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py | AWSIOTGatewayAgent._publish_scan_response | def _publish_scan_response(self, client):
"""Publish a scan response message
The message contains all of the devices that are currently known
to this agent. Connection strings for direct connections are
translated to what is appropriate for this agent.
Args:
client (string): A unique id for the client that made this request
"""
devices = self._manager.scanned_devices
converted_devs = []
for uuid, info in devices.items():
slug = self._build_device_slug(uuid)
message = {}
message['uuid'] = uuid
if uuid in self._connections:
message['user_connected'] = True
elif 'user_connected' in info:
message['user_connected'] = info['user_connected']
else:
message['user_connected'] = False
message['connection_string'] = slug
message['signal_strength'] = info['signal_strength']
converted_devs.append({x: y for x, y in message.items()})
message['type'] = 'notification'
message['operation'] = 'advertisement'
self.client.publish(self.topics.gateway_topic(slug, 'data/advertisement'), message)
probe_message = {}
probe_message['type'] = 'response'
probe_message['client'] = client
probe_message['success'] = True
probe_message['devices'] = converted_devs
self.client.publish(self.topics.status, probe_message) | python | def _publish_scan_response(self, client):
devices = self._manager.scanned_devices
converted_devs = []
for uuid, info in devices.items():
slug = self._build_device_slug(uuid)
message = {}
message['uuid'] = uuid
if uuid in self._connections:
message['user_connected'] = True
elif 'user_connected' in info:
message['user_connected'] = info['user_connected']
else:
message['user_connected'] = False
message['connection_string'] = slug
message['signal_strength'] = info['signal_strength']
converted_devs.append({x: y for x, y in message.items()})
message['type'] = 'notification'
message['operation'] = 'advertisement'
self.client.publish(self.topics.gateway_topic(slug, 'data/advertisement'), message)
probe_message = {}
probe_message['type'] = 'response'
probe_message['client'] = client
probe_message['success'] = True
probe_message['devices'] = converted_devs
self.client.publish(self.topics.status, probe_message) | [
"def",
"_publish_scan_response",
"(",
"self",
",",
"client",
")",
":",
"devices",
"=",
"self",
".",
"_manager",
".",
"scanned_devices",
"converted_devs",
"=",
"[",
"]",
"for",
"uuid",
",",
"info",
"in",
"devices",
".",
"items",
"(",
")",
":",
"slug",
"="... | Publish a scan response message
The message contains all of the devices that are currently known
to this agent. Connection strings for direct connections are
translated to what is appropriate for this agent.
Args:
client (string): A unique id for the client that made this request | [
"Publish",
"a",
"scan",
"response",
"message"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/gateway_agent.py#L673-L714 |
23,386 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/link.py | _versioned_lib_suffix | def _versioned_lib_suffix(env, suffix, version):
"""For suffix='.so' and version='0.1.2' it returns '.so.0.1.2'"""
Verbose = False
if Verbose:
print("_versioned_lib_suffix: suffix={:r}".format(suffix))
print("_versioned_lib_suffix: version={:r}".format(version))
if not suffix.endswith(version):
suffix = suffix + '.' + version
if Verbose:
print("_versioned_lib_suffix: return suffix={:r}".format(suffix))
return suffix | python | def _versioned_lib_suffix(env, suffix, version):
"""For suffix='.so' and version='0.1.2' it returns '.so.0.1.2'"""
Verbose = False
if Verbose:
print("_versioned_lib_suffix: suffix={:r}".format(suffix))
print("_versioned_lib_suffix: version={:r}".format(version))
if not suffix.endswith(version):
suffix = suffix + '.' + version
if Verbose:
print("_versioned_lib_suffix: return suffix={:r}".format(suffix))
return suffix | [
"def",
"_versioned_lib_suffix",
"(",
"env",
",",
"suffix",
",",
"version",
")",
":",
"Verbose",
"=",
"False",
"if",
"Verbose",
":",
"print",
"(",
"\"_versioned_lib_suffix: suffix={:r}\"",
".",
"format",
"(",
"suffix",
")",
")",
"print",
"(",
"\"_versioned_lib_su... | For suffix='.so' and version='0.1.2' it returns '.so.0.1.2 | [
"For",
"suffix",
"=",
".",
"so",
"and",
"version",
"=",
"0",
".",
"1",
".",
"2",
"it",
"returns",
".",
"so",
".",
"0",
".",
"1",
".",
"2"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/link.py#L148-L158 |
23,387 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/link.py | _setup_versioned_lib_variables | def _setup_versioned_lib_variables(env, **kw):
"""
Setup all variables required by the versioning machinery
"""
tool = None
try: tool = kw['tool']
except KeyError: pass
use_soname = False
try: use_soname = kw['use_soname']
except KeyError: pass
# The $_SHLIBVERSIONFLAGS define extra commandline flags used when
# building VERSIONED shared libraries. It's always set, but used only
# when VERSIONED library is built (see __SHLIBVERSIONFLAGS in SCons/Defaults.py).
if use_soname:
# If the linker uses SONAME, then we need this little automata
if tool == 'sunlink':
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS -h $_SHLIBSONAME'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS -h $_LDMODULESONAME'
else:
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS -Wl,-soname=$_SHLIBSONAME'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS -Wl,-soname=$_LDMODULESONAME'
env['_SHLIBSONAME'] = '${ShLibSonameGenerator(__env__,TARGET)}'
env['_LDMODULESONAME'] = '${LdModSonameGenerator(__env__,TARGET)}'
env['ShLibSonameGenerator'] = SCons.Tool.ShLibSonameGenerator
env['LdModSonameGenerator'] = SCons.Tool.LdModSonameGenerator
else:
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS'
# LDOMDULVERSIONFLAGS should always default to $SHLIBVERSIONFLAGS
env['LDMODULEVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS' | python | def _setup_versioned_lib_variables(env, **kw):
tool = None
try: tool = kw['tool']
except KeyError: pass
use_soname = False
try: use_soname = kw['use_soname']
except KeyError: pass
# The $_SHLIBVERSIONFLAGS define extra commandline flags used when
# building VERSIONED shared libraries. It's always set, but used only
# when VERSIONED library is built (see __SHLIBVERSIONFLAGS in SCons/Defaults.py).
if use_soname:
# If the linker uses SONAME, then we need this little automata
if tool == 'sunlink':
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS -h $_SHLIBSONAME'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS -h $_LDMODULESONAME'
else:
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS -Wl,-soname=$_SHLIBSONAME'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS -Wl,-soname=$_LDMODULESONAME'
env['_SHLIBSONAME'] = '${ShLibSonameGenerator(__env__,TARGET)}'
env['_LDMODULESONAME'] = '${LdModSonameGenerator(__env__,TARGET)}'
env['ShLibSonameGenerator'] = SCons.Tool.ShLibSonameGenerator
env['LdModSonameGenerator'] = SCons.Tool.LdModSonameGenerator
else:
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS'
# LDOMDULVERSIONFLAGS should always default to $SHLIBVERSIONFLAGS
env['LDMODULEVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS' | [
"def",
"_setup_versioned_lib_variables",
"(",
"env",
",",
"*",
"*",
"kw",
")",
":",
"tool",
"=",
"None",
"try",
":",
"tool",
"=",
"kw",
"[",
"'tool'",
"]",
"except",
"KeyError",
":",
"pass",
"use_soname",
"=",
"False",
"try",
":",
"use_soname",
"=",
"k... | Setup all variables required by the versioning machinery | [
"Setup",
"all",
"variables",
"required",
"by",
"the",
"versioning",
"machinery"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/link.py#L245-L278 |
23,388 | iotile/coretools | iotilegateway/iotilegateway/main.py | main | def main(argv=None, loop=SharedLoop, max_time=None):
"""Main entry point for iotile-gateway."""
should_raise = argv is not None
if argv is None:
argv = sys.argv[1:]
parser = build_parser()
cmd_args = parser.parse_args(argv)
configure_logging(cmd_args.verbose)
logger = logging.getLogger(__name__)
try:
args = {}
if cmd_args.config is not None:
try:
with open(cmd_args.config, "r") as conf:
args = json.load(conf)
except IOError as exc:
raise ScriptError("Could not open config file %s due to %s"
% (cmd_args.config, str(exc)), 2)
except ValueError as exc:
raise ScriptError("Could not parse JSON from config file %s due to %s"
% (cmd_args.config, str(exc)), 3)
except TypeError as exc:
raise ScriptError("You must pass the path to a json config file", 4)
logger.critical("Starting gateway")
gateway = IOTileGateway(args, loop=loop)
loop.run_coroutine(gateway.start())
logger.critical("Gateway running")
# Run forever until we receive a ctrl-c
# (allow quitting early after max_time seconds for testing)
loop.wait_for_interrupt(max_time=max_time)
loop.run_coroutine(gateway.stop())
except ScriptError as exc:
if should_raise:
raise exc
logger.fatal("Quitting due to error: %s", exc.msg)
return exc.code
except Exception as exc: # pylint: disable=W0703
if should_raise:
raise exc
logger.exception("Fatal error running gateway")
return 1
return 0 | python | def main(argv=None, loop=SharedLoop, max_time=None):
should_raise = argv is not None
if argv is None:
argv = sys.argv[1:]
parser = build_parser()
cmd_args = parser.parse_args(argv)
configure_logging(cmd_args.verbose)
logger = logging.getLogger(__name__)
try:
args = {}
if cmd_args.config is not None:
try:
with open(cmd_args.config, "r") as conf:
args = json.load(conf)
except IOError as exc:
raise ScriptError("Could not open config file %s due to %s"
% (cmd_args.config, str(exc)), 2)
except ValueError as exc:
raise ScriptError("Could not parse JSON from config file %s due to %s"
% (cmd_args.config, str(exc)), 3)
except TypeError as exc:
raise ScriptError("You must pass the path to a json config file", 4)
logger.critical("Starting gateway")
gateway = IOTileGateway(args, loop=loop)
loop.run_coroutine(gateway.start())
logger.critical("Gateway running")
# Run forever until we receive a ctrl-c
# (allow quitting early after max_time seconds for testing)
loop.wait_for_interrupt(max_time=max_time)
loop.run_coroutine(gateway.stop())
except ScriptError as exc:
if should_raise:
raise exc
logger.fatal("Quitting due to error: %s", exc.msg)
return exc.code
except Exception as exc: # pylint: disable=W0703
if should_raise:
raise exc
logger.exception("Fatal error running gateway")
return 1
return 0 | [
"def",
"main",
"(",
"argv",
"=",
"None",
",",
"loop",
"=",
"SharedLoop",
",",
"max_time",
"=",
"None",
")",
":",
"should_raise",
"=",
"argv",
"is",
"not",
"None",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]... | Main entry point for iotile-gateway. | [
"Main",
"entry",
"point",
"for",
"iotile",
"-",
"gateway",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/main.py#L54-L107 |
23,389 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | _TimeAnchor.copy | def copy(self):
"""Return a copy of this _TimeAnchor."""
return _TimeAnchor(self.reading_id, self.uptime, self.utc, self.is_break, self.exact) | python | def copy(self):
return _TimeAnchor(self.reading_id, self.uptime, self.utc, self.is_break, self.exact) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"_TimeAnchor",
"(",
"self",
".",
"reading_id",
",",
"self",
".",
"uptime",
",",
"self",
".",
"utc",
",",
"self",
".",
"is_break",
",",
"self",
".",
"exact",
")"
] | Return a copy of this _TimeAnchor. | [
"Return",
"a",
"copy",
"of",
"this",
"_TimeAnchor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L43-L45 |
23,390 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.anchor_stream | def anchor_stream(self, stream_id, converter="rtc"):
"""Mark a stream as containing anchor points."""
if isinstance(converter, str):
converter = self._known_converters.get(converter)
if converter is None:
raise ArgumentError("Unknown anchor converter string: %s" % converter,
known_converters=list(self._known_converters))
self._anchor_streams[stream_id] = converter | python | def anchor_stream(self, stream_id, converter="rtc"):
if isinstance(converter, str):
converter = self._known_converters.get(converter)
if converter is None:
raise ArgumentError("Unknown anchor converter string: %s" % converter,
known_converters=list(self._known_converters))
self._anchor_streams[stream_id] = converter | [
"def",
"anchor_stream",
"(",
"self",
",",
"stream_id",
",",
"converter",
"=",
"\"rtc\"",
")",
":",
"if",
"isinstance",
"(",
"converter",
",",
"str",
")",
":",
"converter",
"=",
"self",
".",
"_known_converters",
".",
"get",
"(",
"converter",
")",
"if",
"c... | Mark a stream as containing anchor points. | [
"Mark",
"a",
"stream",
"as",
"containing",
"anchor",
"points",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L125-L135 |
23,391 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.id_range | def id_range(self):
"""Get the range of archor reading_ids.
Returns:
(int, int): The lowest and highest reading ids.
If no reading ids have been loaded, (0, 0) is returned.
"""
if len(self._anchor_points) == 0:
return (0, 0)
return (self._anchor_points[0].reading_id, self._anchor_points[-1].reading_id) | python | def id_range(self):
if len(self._anchor_points) == 0:
return (0, 0)
return (self._anchor_points[0].reading_id, self._anchor_points[-1].reading_id) | [
"def",
"id_range",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_anchor_points",
")",
"==",
"0",
":",
"return",
"(",
"0",
",",
"0",
")",
"return",
"(",
"self",
".",
"_anchor_points",
"[",
"0",
"]",
".",
"reading_id",
",",
"self",
".",
"... | Get the range of archor reading_ids.
Returns:
(int, int): The lowest and highest reading ids.
If no reading ids have been loaded, (0, 0) is returned. | [
"Get",
"the",
"range",
"of",
"archor",
"reading_ids",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L137-L149 |
23,392 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner._convert_epoch_anchor | def _convert_epoch_anchor(cls, reading):
"""Convert a reading containing an epoch timestamp to datetime."""
delta = datetime.timedelta(seconds=reading.value)
return cls._EpochReference + delta | python | def _convert_epoch_anchor(cls, reading):
delta = datetime.timedelta(seconds=reading.value)
return cls._EpochReference + delta | [
"def",
"_convert_epoch_anchor",
"(",
"cls",
",",
"reading",
")",
":",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"reading",
".",
"value",
")",
"return",
"cls",
".",
"_EpochReference",
"+",
"delta"
] | Convert a reading containing an epoch timestamp to datetime. | [
"Convert",
"a",
"reading",
"containing",
"an",
"epoch",
"timestamp",
"to",
"datetime",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L168-L172 |
23,393 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.add_point | def add_point(self, reading_id, uptime=None, utc=None, is_break=False):
"""Add a time point that could be used as a UTC reference."""
if reading_id == 0:
return
if uptime is None and utc is None:
return
if uptime is not None and uptime & (1 << 31):
if utc is not None:
return
uptime &= ~(1 << 31)
utc = self.convert_rtc(uptime)
uptime = None
anchor = _TimeAnchor(reading_id, uptime, utc, is_break, exact=utc is not None)
if anchor in self._anchor_points:
return
self._anchor_points.add(anchor)
self._prepared = False | python | def add_point(self, reading_id, uptime=None, utc=None, is_break=False):
if reading_id == 0:
return
if uptime is None and utc is None:
return
if uptime is not None and uptime & (1 << 31):
if utc is not None:
return
uptime &= ~(1 << 31)
utc = self.convert_rtc(uptime)
uptime = None
anchor = _TimeAnchor(reading_id, uptime, utc, is_break, exact=utc is not None)
if anchor in self._anchor_points:
return
self._anchor_points.add(anchor)
self._prepared = False | [
"def",
"add_point",
"(",
"self",
",",
"reading_id",
",",
"uptime",
"=",
"None",
",",
"utc",
"=",
"None",
",",
"is_break",
"=",
"False",
")",
":",
"if",
"reading_id",
"==",
"0",
":",
"return",
"if",
"uptime",
"is",
"None",
"and",
"utc",
"is",
"None",
... | Add a time point that could be used as a UTC reference. | [
"Add",
"a",
"time",
"point",
"that",
"could",
"be",
"used",
"as",
"a",
"UTC",
"reference",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L174-L198 |
23,394 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.add_reading | def add_reading(self, reading):
"""Add an IOTileReading."""
is_break = False
utc = None
if reading.stream in self._break_streams:
is_break = True
if reading.stream in self._anchor_streams:
utc = self._anchor_streams[reading.stream](reading)
self.add_point(reading.reading_id, reading.raw_time, utc, is_break=is_break) | python | def add_reading(self, reading):
is_break = False
utc = None
if reading.stream in self._break_streams:
is_break = True
if reading.stream in self._anchor_streams:
utc = self._anchor_streams[reading.stream](reading)
self.add_point(reading.reading_id, reading.raw_time, utc, is_break=is_break) | [
"def",
"add_reading",
"(",
"self",
",",
"reading",
")",
":",
"is_break",
"=",
"False",
"utc",
"=",
"None",
"if",
"reading",
".",
"stream",
"in",
"self",
".",
"_break_streams",
":",
"is_break",
"=",
"True",
"if",
"reading",
".",
"stream",
"in",
"self",
... | Add an IOTileReading. | [
"Add",
"an",
"IOTileReading",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L200-L212 |
23,395 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.add_report | def add_report(self, report, ignore_errors=False):
"""Add all anchors from a report."""
if not isinstance(report, SignedListReport):
if ignore_errors:
return
raise ArgumentError("You can only add SignedListReports to a UTCAssigner", report=report)
for reading in report.visible_readings:
self.add_reading(reading)
self.add_point(report.report_id, report.sent_timestamp, report.received_time) | python | def add_report(self, report, ignore_errors=False):
if not isinstance(report, SignedListReport):
if ignore_errors:
return
raise ArgumentError("You can only add SignedListReports to a UTCAssigner", report=report)
for reading in report.visible_readings:
self.add_reading(reading)
self.add_point(report.report_id, report.sent_timestamp, report.received_time) | [
"def",
"add_report",
"(",
"self",
",",
"report",
",",
"ignore_errors",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"report",
",",
"SignedListReport",
")",
":",
"if",
"ignore_errors",
":",
"return",
"raise",
"ArgumentError",
"(",
"\"You can only add... | Add all anchors from a report. | [
"Add",
"all",
"anchors",
"from",
"a",
"report",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L214-L226 |
23,396 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.assign_utc | def assign_utc(self, reading_id, uptime=None, prefer="before"):
"""Assign a utc datetime to a reading id.
This method will return an object with assignment information or None
if a utc value cannot be assigned. The assignment object returned
contains a utc property that has the asssigned UTC as well as other
properties describing how reliable the assignment is.
Args:
reading_id (int): The monotonic reading id that we wish to assign
a utc timestamp to.
uptime (int): Optional uptime that should be associated with the
reading id. If this is not specified and the reading_id is
found in the anchor points passed to this class then the
uptime from the corresponding anchor point will be used.
prefer (str): There are two possible directions that can be used
to assign a UTC timestamp (the nearest anchor before or after the
reading). If both directions are of similar quality, the choice
is arbitrary. Passing prefer="before" will use the anchor point
before the reading. Passing prefer="after" will use the anchor
point after the reading. Default: before.
Returns:
UTCAssignment: The assigned UTC time or None if assignment is impossible.
"""
if prefer not in ("before", "after"):
raise ArgumentError("Invalid prefer parameter: {}, must be 'before' or 'after'".format(prefer))
if len(self._anchor_points) == 0:
return None
if reading_id > self._anchor_points[-1].reading_id:
return None
i = self._anchor_points.bisect_key_left(reading_id)
found_id = False
crossed_break = False
exact = True
last = self._anchor_points[i].copy()
if uptime is not None:
last.uptime = uptime
if last.reading_id == reading_id:
found_id = True
if last.utc is not None:
return UTCAssignment(reading_id, last.utc, found_id, exact, crossed_break)
left_assign = self._fix_left(reading_id, last, i, found_id)
if left_assign is not None and left_assign.exact:
return left_assign
right_assign = self._fix_right(reading_id, last, i, found_id)
if right_assign is not None and right_assign.exact:
return right_assign
return self._pick_best_fix(left_assign, right_assign, prefer) | python | def assign_utc(self, reading_id, uptime=None, prefer="before"):
if prefer not in ("before", "after"):
raise ArgumentError("Invalid prefer parameter: {}, must be 'before' or 'after'".format(prefer))
if len(self._anchor_points) == 0:
return None
if reading_id > self._anchor_points[-1].reading_id:
return None
i = self._anchor_points.bisect_key_left(reading_id)
found_id = False
crossed_break = False
exact = True
last = self._anchor_points[i].copy()
if uptime is not None:
last.uptime = uptime
if last.reading_id == reading_id:
found_id = True
if last.utc is not None:
return UTCAssignment(reading_id, last.utc, found_id, exact, crossed_break)
left_assign = self._fix_left(reading_id, last, i, found_id)
if left_assign is not None and left_assign.exact:
return left_assign
right_assign = self._fix_right(reading_id, last, i, found_id)
if right_assign is not None and right_assign.exact:
return right_assign
return self._pick_best_fix(left_assign, right_assign, prefer) | [
"def",
"assign_utc",
"(",
"self",
",",
"reading_id",
",",
"uptime",
"=",
"None",
",",
"prefer",
"=",
"\"before\"",
")",
":",
"if",
"prefer",
"not",
"in",
"(",
"\"before\"",
",",
"\"after\"",
")",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid prefer paramete... | Assign a utc datetime to a reading id.
This method will return an object with assignment information or None
if a utc value cannot be assigned. The assignment object returned
contains a utc property that has the asssigned UTC as well as other
properties describing how reliable the assignment is.
Args:
reading_id (int): The monotonic reading id that we wish to assign
a utc timestamp to.
uptime (int): Optional uptime that should be associated with the
reading id. If this is not specified and the reading_id is
found in the anchor points passed to this class then the
uptime from the corresponding anchor point will be used.
prefer (str): There are two possible directions that can be used
to assign a UTC timestamp (the nearest anchor before or after the
reading). If both directions are of similar quality, the choice
is arbitrary. Passing prefer="before" will use the anchor point
before the reading. Passing prefer="after" will use the anchor
point after the reading. Default: before.
Returns:
UTCAssignment: The assigned UTC time or None if assignment is impossible. | [
"Assign",
"a",
"utc",
"datetime",
"to",
"a",
"reading",
"id",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L228-L286 |
23,397 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.ensure_prepared | def ensure_prepared(self):
"""Calculate and cache UTC values for all exactly known anchor points."""
if self._prepared:
return
exact_count = 0
fixed_count = 0
inexact_count = 0
self._logger.debug("Preparing UTCAssigner (%d total anchors)", len(self._anchor_points))
for curr in self._anchor_points:
if not curr.exact:
assignment = self.assign_utc(curr.reading_id, curr.uptime)
if assignment is not None and assignment.exact:
curr.utc = assignment.utc
curr.exact = True
fixed_count += 1
else:
inexact_count += 1
else:
exact_count += 1
self._logger.debug("Prepared UTCAssigner with %d reference points, "
"%d exact anchors and %d inexact anchors",
exact_count, fixed_count, inexact_count)
self._prepared = True | python | def ensure_prepared(self):
if self._prepared:
return
exact_count = 0
fixed_count = 0
inexact_count = 0
self._logger.debug("Preparing UTCAssigner (%d total anchors)", len(self._anchor_points))
for curr in self._anchor_points:
if not curr.exact:
assignment = self.assign_utc(curr.reading_id, curr.uptime)
if assignment is not None and assignment.exact:
curr.utc = assignment.utc
curr.exact = True
fixed_count += 1
else:
inexact_count += 1
else:
exact_count += 1
self._logger.debug("Prepared UTCAssigner with %d reference points, "
"%d exact anchors and %d inexact anchors",
exact_count, fixed_count, inexact_count)
self._prepared = True | [
"def",
"ensure_prepared",
"(",
"self",
")",
":",
"if",
"self",
".",
"_prepared",
":",
"return",
"exact_count",
"=",
"0",
"fixed_count",
"=",
"0",
"inexact_count",
"=",
"0",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Preparing UTCAssigner (%d total anchors)\""... | Calculate and cache UTC values for all exactly known anchor points. | [
"Calculate",
"and",
"cache",
"UTC",
"values",
"for",
"all",
"exactly",
"known",
"anchor",
"points",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L288-L316 |
23,398 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner.fix_report | def fix_report(self, report, errors="drop", prefer="before"):
"""Perform utc assignment on all readings in a report.
The returned report will have all reading timestamps in UTC. This only
works on SignedListReport objects. Note that the report should
typically have previously been added to the UTC assigner using
add_report or no reference points from the report will be used.
Args:
report (SignedListReport): The report that we should fix.
errors (str): The behavior that we should have when we can't
fix a given reading. The only currently support behavior is
drop, which means that the reading will be dropped and not
included in the new report.
prefer (str): Whether to prefer fixing readings by looking for
reference points after the reading or before, all other things
being equal. See the description of ``assign_utc``.
Returns:
SignedListReport: The report with UTC timestamps.
"""
if not isinstance(report, SignedListReport):
raise ArgumentError("Report must be a SignedListReport", report=report)
if errors not in ('drop',):
raise ArgumentError("Unknown errors handler: {}, supported=['drop']".format(errors))
self.ensure_prepared()
fixed_readings = []
dropped_readings = 0
for reading in report.visible_readings:
assignment = self.assign_utc(reading.reading_id, reading.raw_time, prefer=prefer)
if assignment is None:
dropped_readings += 1
continue
fixed_reading = IOTileReading(assignment.rtc_value, reading.stream, reading.value,
reading_time=assignment.utc, reading_id=reading.reading_id)
fixed_readings.append(fixed_reading)
fixed_report = SignedListReport.FromReadings(report.origin, fixed_readings, report_id=report.report_id,
selector=report.streamer_selector, streamer=report.origin_streamer,
sent_timestamp=report.sent_timestamp)
fixed_report.received_time = report.received_time
if dropped_readings > 0:
self._logger.warning("Dropped %d readings of %d when fixing UTC timestamps in report 0x%08X for device 0x%08X",
dropped_readings, len(report.visible_readings), report.report_id, report.origin)
return fixed_report | python | def fix_report(self, report, errors="drop", prefer="before"):
if not isinstance(report, SignedListReport):
raise ArgumentError("Report must be a SignedListReport", report=report)
if errors not in ('drop',):
raise ArgumentError("Unknown errors handler: {}, supported=['drop']".format(errors))
self.ensure_prepared()
fixed_readings = []
dropped_readings = 0
for reading in report.visible_readings:
assignment = self.assign_utc(reading.reading_id, reading.raw_time, prefer=prefer)
if assignment is None:
dropped_readings += 1
continue
fixed_reading = IOTileReading(assignment.rtc_value, reading.stream, reading.value,
reading_time=assignment.utc, reading_id=reading.reading_id)
fixed_readings.append(fixed_reading)
fixed_report = SignedListReport.FromReadings(report.origin, fixed_readings, report_id=report.report_id,
selector=report.streamer_selector, streamer=report.origin_streamer,
sent_timestamp=report.sent_timestamp)
fixed_report.received_time = report.received_time
if dropped_readings > 0:
self._logger.warning("Dropped %d readings of %d when fixing UTC timestamps in report 0x%08X for device 0x%08X",
dropped_readings, len(report.visible_readings), report.report_id, report.origin)
return fixed_report | [
"def",
"fix_report",
"(",
"self",
",",
"report",
",",
"errors",
"=",
"\"drop\"",
",",
"prefer",
"=",
"\"before\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"report",
",",
"SignedListReport",
")",
":",
"raise",
"ArgumentError",
"(",
"\"Report must be a SignedL... | Perform utc assignment on all readings in a report.
The returned report will have all reading timestamps in UTC. This only
works on SignedListReport objects. Note that the report should
typically have previously been added to the UTC assigner using
add_report or no reference points from the report will be used.
Args:
report (SignedListReport): The report that we should fix.
errors (str): The behavior that we should have when we can't
fix a given reading. The only currently support behavior is
drop, which means that the reading will be dropped and not
included in the new report.
prefer (str): Whether to prefer fixing readings by looking for
reference points after the reading or before, all other things
being equal. See the description of ``assign_utc``.
Returns:
SignedListReport: The report with UTC timestamps. | [
"Perform",
"utc",
"assignment",
"on",
"all",
"readings",
"in",
"a",
"report",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L318-L371 |
23,399 | iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | UTCAssigner._fix_left | def _fix_left(self, reading_id, last, start, found_id):
"""Fix a reading by looking for the nearest anchor point before it."""
accum_delta = 0
exact = True
crossed_break = False
if start == 0:
return None
for curr in self._anchor_points.islice(None, start - 1, reverse=True):
if curr.uptime is None or last.uptime is None:
exact = False
elif curr.is_break or last.uptime < curr.uptime:
exact = False
crossed_break = True
else:
accum_delta += last.uptime - curr.uptime
if curr.utc is not None:
time_delta = datetime.timedelta(seconds=accum_delta)
return UTCAssignment(reading_id, curr.utc + time_delta, found_id, exact, crossed_break)
last = curr
return None | python | def _fix_left(self, reading_id, last, start, found_id):
accum_delta = 0
exact = True
crossed_break = False
if start == 0:
return None
for curr in self._anchor_points.islice(None, start - 1, reverse=True):
if curr.uptime is None or last.uptime is None:
exact = False
elif curr.is_break or last.uptime < curr.uptime:
exact = False
crossed_break = True
else:
accum_delta += last.uptime - curr.uptime
if curr.utc is not None:
time_delta = datetime.timedelta(seconds=accum_delta)
return UTCAssignment(reading_id, curr.utc + time_delta, found_id, exact, crossed_break)
last = curr
return None | [
"def",
"_fix_left",
"(",
"self",
",",
"reading_id",
",",
"last",
",",
"start",
",",
"found_id",
")",
":",
"accum_delta",
"=",
"0",
"exact",
"=",
"True",
"crossed_break",
"=",
"False",
"if",
"start",
"==",
"0",
":",
"return",
"None",
"for",
"curr",
"in"... | Fix a reading by looking for the nearest anchor point before it. | [
"Fix",
"a",
"reading",
"by",
"looking",
"for",
"the",
"nearest",
"anchor",
"point",
"before",
"it",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L427-L452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.