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,900 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py | DirScanner | def DirScanner(**kw):
"""Return a prototype Scanner instance for scanning
directories for on-disk files"""
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = only_dirs
return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) | python | def DirScanner(**kw):
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = only_dirs
return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) | [
"def",
"DirScanner",
"(",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'node_factory'",
"]",
"=",
"SCons",
".",
"Node",
".",
"FS",
".",
"Entry",
"kw",
"[",
"'recursive'",
"]",
"=",
"only_dirs",
"return",
"SCons",
".",
"Scanner",
".",
"Base",
"(",
"scan_on_d... | Return a prototype Scanner instance for scanning
directories for on-disk files | [
"Return",
"a",
"prototype",
"Scanner",
"instance",
"for",
"scanning",
"directories",
"for",
"on",
"-",
"disk",
"files"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L32-L37 |
23,901 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py | DirEntryScanner | def DirEntryScanner(**kw):
"""Return a prototype Scanner instance for "scanning"
directory Nodes for their in-memory entries"""
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = None
return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) | python | def DirEntryScanner(**kw):
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = None
return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) | [
"def",
"DirEntryScanner",
"(",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'node_factory'",
"]",
"=",
"SCons",
".",
"Node",
".",
"FS",
".",
"Entry",
"kw",
"[",
"'recursive'",
"]",
"=",
"None",
"return",
"SCons",
".",
"Scanner",
".",
"Base",
"(",
"scan_in_m... | Return a prototype Scanner instance for "scanning"
directory Nodes for their in-memory entries | [
"Return",
"a",
"prototype",
"Scanner",
"instance",
"for",
"scanning",
"directory",
"Nodes",
"for",
"their",
"in",
"-",
"memory",
"entries"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L39-L44 |
23,902 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py | scan_on_disk | def scan_on_disk(node, env, path=()):
"""
Scans a directory for on-disk files and directories therein.
Looking up the entries will add these to the in-memory Node tree
representation of the file system, so all we have to do is just
that and then call the in-memory scanning function.
"""
try:
flist = node.fs.listdir(node.get_abspath())
except (IOError, OSError):
return []
e = node.Entry
for f in filter(do_not_scan, flist):
# Add ./ to the beginning of the file name so if it begins with a
# '#' we don't look it up relative to the top-level directory.
e('./' + f)
return scan_in_memory(node, env, path) | python | def scan_on_disk(node, env, path=()):
try:
flist = node.fs.listdir(node.get_abspath())
except (IOError, OSError):
return []
e = node.Entry
for f in filter(do_not_scan, flist):
# Add ./ to the beginning of the file name so if it begins with a
# '#' we don't look it up relative to the top-level directory.
e('./' + f)
return scan_in_memory(node, env, path) | [
"def",
"scan_on_disk",
"(",
"node",
",",
"env",
",",
"path",
"=",
"(",
")",
")",
":",
"try",
":",
"flist",
"=",
"node",
".",
"fs",
".",
"listdir",
"(",
"node",
".",
"get_abspath",
"(",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",... | Scans a directory for on-disk files and directories therein.
Looking up the entries will add these to the in-memory Node tree
representation of the file system, so all we have to do is just
that and then call the in-memory scanning function. | [
"Scans",
"a",
"directory",
"for",
"on",
"-",
"disk",
"files",
"and",
"directories",
"therein",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L71-L88 |
23,903 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py | scan_in_memory | def scan_in_memory(node, env, path=()):
"""
"Scans" a Node.FS.Dir for its in-memory entries.
"""
try:
entries = node.entries
except AttributeError:
# It's not a Node.FS.Dir (or doesn't look enough like one for
# our purposes), which can happen if a target list containing
# mixed Node types (Dirs and Files, for example) has a Dir as
# the first entry.
return []
entry_list = sorted(filter(do_not_scan, list(entries.keys())))
return [entries[n] for n in entry_list] | python | def scan_in_memory(node, env, path=()):
try:
entries = node.entries
except AttributeError:
# It's not a Node.FS.Dir (or doesn't look enough like one for
# our purposes), which can happen if a target list containing
# mixed Node types (Dirs and Files, for example) has a Dir as
# the first entry.
return []
entry_list = sorted(filter(do_not_scan, list(entries.keys())))
return [entries[n] for n in entry_list] | [
"def",
"scan_in_memory",
"(",
"node",
",",
"env",
",",
"path",
"=",
"(",
")",
")",
":",
"try",
":",
"entries",
"=",
"node",
".",
"entries",
"except",
"AttributeError",
":",
"# It's not a Node.FS.Dir (or doesn't look enough like one for",
"# our purposes), which can ha... | "Scans" a Node.FS.Dir for its in-memory entries. | [
"Scans",
"a",
"Node",
".",
"FS",
".",
"Dir",
"for",
"its",
"in",
"-",
"memory",
"entries",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L90-L103 |
23,904 | iotile/coretools | iotileemulate/iotile/emulate/internal/response.py | GenericResponse.set_result | def set_result(self, result):
"""Finish this response and set the result."""
if self.is_finished():
raise InternalError("set_result called on finished AsynchronousResponse",
result=self._result, exception=self._exception)
self._result = result
self.finish() | python | def set_result(self, result):
if self.is_finished():
raise InternalError("set_result called on finished AsynchronousResponse",
result=self._result, exception=self._exception)
self._result = result
self.finish() | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"if",
"self",
".",
"is_finished",
"(",
")",
":",
"raise",
"InternalError",
"(",
"\"set_result called on finished AsynchronousResponse\"",
",",
"result",
"=",
"self",
".",
"_result",
",",
"exception",
"="... | Finish this response and set the result. | [
"Finish",
"this",
"response",
"and",
"set",
"the",
"result",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/response.py#L23-L31 |
23,905 | iotile/coretools | iotileemulate/iotile/emulate/internal/response.py | GenericResponse.set_exception | def set_exception(self, exc_class, exc_info, exc_stack):
"""Set an exception as the result of this operation.
Args:
exc_class (object): The exception type """
if self.is_finished():
raise InternalError("set_exception called on finished AsynchronousResponse",
result=self._result, exception=self._exception)
self._exception = (exc_class, exc_info, exc_stack)
self.finish() | python | def set_exception(self, exc_class, exc_info, exc_stack):
if self.is_finished():
raise InternalError("set_exception called on finished AsynchronousResponse",
result=self._result, exception=self._exception)
self._exception = (exc_class, exc_info, exc_stack)
self.finish() | [
"def",
"set_exception",
"(",
"self",
",",
"exc_class",
",",
"exc_info",
",",
"exc_stack",
")",
":",
"if",
"self",
".",
"is_finished",
"(",
")",
":",
"raise",
"InternalError",
"(",
"\"set_exception called on finished AsynchronousResponse\"",
",",
"result",
"=",
"se... | Set an exception as the result of this operation.
Args:
exc_class (object): The exception type | [
"Set",
"an",
"exception",
"as",
"the",
"result",
"of",
"this",
"operation",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/response.py#L33-L44 |
23,906 | iotile/coretools | scripts/status.py | get_released_versions | def get_released_versions(component):
"""Get all released versions of the given component ordered newest to oldest
"""
releases = get_tags()
releases = sorted([(x[0], [int(y) for y in x[1].split('.')]) for x in releases], key=lambda x: x[1])[::-1]
return [(x[0], ".".join(map(str, x[1]))) for x in releases if x[0] == component] | python | def get_released_versions(component):
releases = get_tags()
releases = sorted([(x[0], [int(y) for y in x[1].split('.')]) for x in releases], key=lambda x: x[1])[::-1]
return [(x[0], ".".join(map(str, x[1]))) for x in releases if x[0] == component] | [
"def",
"get_released_versions",
"(",
"component",
")",
":",
"releases",
"=",
"get_tags",
"(",
")",
"releases",
"=",
"sorted",
"(",
"[",
"(",
"x",
"[",
"0",
"]",
",",
"[",
"int",
"(",
"y",
")",
"for",
"y",
"in",
"x",
"[",
"1",
"]",
".",
"split",
... | Get all released versions of the given component ordered newest to oldest | [
"Get",
"all",
"released",
"versions",
"of",
"the",
"given",
"component",
"ordered",
"newest",
"to",
"oldest"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/scripts/status.py#L22-L29 |
23,907 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/dependencies.py | load_dependencies | def load_dependencies(orig_tile, build_env):
"""Load all tile dependencies and filter only the products from each that we use
build_env must define the architecture that we are targeting so that we get the
correct dependency list and products per dependency since that may change
when building for different architectures
"""
if 'DEPENDENCIES' not in build_env:
build_env['DEPENDENCIES'] = []
dep_targets = []
chip = build_env['ARCH']
raw_arch_deps = chip.property('depends')
# Properly separate out the version information from the name of the dependency
# The raw keys come back as name,version
arch_deps = {}
for key, value in raw_arch_deps.items():
name, _, _ = key.partition(',')
arch_deps[name] = value
for dep in orig_tile.dependencies:
try:
tile = IOTile(os.path.join('build', 'deps', dep['unique_id']))
# Make sure we filter products using the view of module dependency products
# as seen in the target we are targeting.
if dep['name'] not in arch_deps:
tile.filter_products([])
else:
tile.filter_products(arch_deps[dep['name']])
except (ArgumentError, EnvironmentError):
raise BuildError("Could not find required dependency", name=dep['name'])
build_env['DEPENDENCIES'].append(tile)
target = os.path.join(tile.folder, 'module_settings.json')
dep_targets.append(target)
return dep_targets | python | def load_dependencies(orig_tile, build_env):
if 'DEPENDENCIES' not in build_env:
build_env['DEPENDENCIES'] = []
dep_targets = []
chip = build_env['ARCH']
raw_arch_deps = chip.property('depends')
# Properly separate out the version information from the name of the dependency
# The raw keys come back as name,version
arch_deps = {}
for key, value in raw_arch_deps.items():
name, _, _ = key.partition(',')
arch_deps[name] = value
for dep in orig_tile.dependencies:
try:
tile = IOTile(os.path.join('build', 'deps', dep['unique_id']))
# Make sure we filter products using the view of module dependency products
# as seen in the target we are targeting.
if dep['name'] not in arch_deps:
tile.filter_products([])
else:
tile.filter_products(arch_deps[dep['name']])
except (ArgumentError, EnvironmentError):
raise BuildError("Could not find required dependency", name=dep['name'])
build_env['DEPENDENCIES'].append(tile)
target = os.path.join(tile.folder, 'module_settings.json')
dep_targets.append(target)
return dep_targets | [
"def",
"load_dependencies",
"(",
"orig_tile",
",",
"build_env",
")",
":",
"if",
"'DEPENDENCIES'",
"not",
"in",
"build_env",
":",
"build_env",
"[",
"'DEPENDENCIES'",
"]",
"=",
"[",
"]",
"dep_targets",
"=",
"[",
"]",
"chip",
"=",
"build_env",
"[",
"'ARCH'",
... | Load all tile dependencies and filter only the products from each that we use
build_env must define the architecture that we are targeting so that we get the
correct dependency list and products per dependency since that may change
when building for different architectures | [
"Load",
"all",
"tile",
"dependencies",
"and",
"filter",
"only",
"the",
"products",
"from",
"each",
"that",
"we",
"use"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/dependencies.py#L9-L49 |
23,908 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/dependencies.py | find_dependency_wheels | def find_dependency_wheels(tile):
"""Return a list of all python wheel objects created by dependencies of this tile
Args:
tile (IOTile): Tile that we should scan for dependencies
Returns:
list: A list of paths to dependency wheels
"""
return [os.path.join(x.folder, 'python', x.support_wheel) for x in _iter_dependencies(tile) if x.has_wheel] | python | def find_dependency_wheels(tile):
return [os.path.join(x.folder, 'python', x.support_wheel) for x in _iter_dependencies(tile) if x.has_wheel] | [
"def",
"find_dependency_wheels",
"(",
"tile",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"x",
".",
"folder",
",",
"'python'",
",",
"x",
".",
"support_wheel",
")",
"for",
"x",
"in",
"_iter_dependencies",
"(",
"tile",
")",
"if",
"x",
... | Return a list of all python wheel objects created by dependencies of this tile
Args:
tile (IOTile): Tile that we should scan for dependencies
Returns:
list: A list of paths to dependency wheels | [
"Return",
"a",
"list",
"of",
"all",
"python",
"wheel",
"objects",
"created",
"by",
"dependencies",
"of",
"this",
"tile"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/dependencies.py#L60-L70 |
23,909 | iotile/coretools | iotilecore/iotile/core/dev/semver.py | SemanticVersionRange._check_ver_range | def _check_ver_range(self, version, ver_range):
"""Check if version is included in ver_range
"""
lower, upper, lower_inc, upper_inc = ver_range
#If the range extends over everything, we automatically match
if lower is None and upper is None:
return True
if lower is not None:
if lower_inc and version < lower:
return False
elif not lower_inc and version <= lower:
return False
if upper is not None:
if upper_inc and version > upper:
return False
elif not upper_inc and version >= upper:
return False
# Prereleases have special matching requirements
if version.is_prerelease:
# Prereleases cannot match ranges that are not defined as prereleases
if (lower is None or not lower.is_prerelease) and (upper is None or not upper.is_prerelease):
return False
# Prereleases without the same major.minor.patch as a range end point cannot match
if (lower is not None and version.release_tuple != lower.release_tuple) and \
(upper is not None and version.release_tuple != upper.release_tuple):
return False
return True | python | def _check_ver_range(self, version, ver_range):
lower, upper, lower_inc, upper_inc = ver_range
#If the range extends over everything, we automatically match
if lower is None and upper is None:
return True
if lower is not None:
if lower_inc and version < lower:
return False
elif not lower_inc and version <= lower:
return False
if upper is not None:
if upper_inc and version > upper:
return False
elif not upper_inc and version >= upper:
return False
# Prereleases have special matching requirements
if version.is_prerelease:
# Prereleases cannot match ranges that are not defined as prereleases
if (lower is None or not lower.is_prerelease) and (upper is None or not upper.is_prerelease):
return False
# Prereleases without the same major.minor.patch as a range end point cannot match
if (lower is not None and version.release_tuple != lower.release_tuple) and \
(upper is not None and version.release_tuple != upper.release_tuple):
return False
return True | [
"def",
"_check_ver_range",
"(",
"self",
",",
"version",
",",
"ver_range",
")",
":",
"lower",
",",
"upper",
",",
"lower_inc",
",",
"upper_inc",
"=",
"ver_range",
"#If the range extends over everything, we automatically match",
"if",
"lower",
"is",
"None",
"and",
"upp... | Check if version is included in ver_range | [
"Check",
"if",
"version",
"is",
"included",
"in",
"ver_range"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L298-L331 |
23,910 | iotile/coretools | iotilecore/iotile/core/dev/semver.py | SemanticVersionRange._check_insersection | def _check_insersection(self, version, ranges):
"""Check that a version is inside all of a list of ranges"""
for ver_range in ranges:
if not self._check_ver_range(version, ver_range):
return False
return True | python | def _check_insersection(self, version, ranges):
for ver_range in ranges:
if not self._check_ver_range(version, ver_range):
return False
return True | [
"def",
"_check_insersection",
"(",
"self",
",",
"version",
",",
"ranges",
")",
":",
"for",
"ver_range",
"in",
"ranges",
":",
"if",
"not",
"self",
".",
"_check_ver_range",
"(",
"version",
",",
"ver_range",
")",
":",
"return",
"False",
"return",
"True"
] | Check that a version is inside all of a list of ranges | [
"Check",
"that",
"a",
"version",
"is",
"inside",
"all",
"of",
"a",
"list",
"of",
"ranges"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L333-L340 |
23,911 | iotile/coretools | iotilecore/iotile/core/dev/semver.py | SemanticVersionRange.check | def check(self, version):
"""Check that a version is inside this SemanticVersionRange
Args:
version (SemanticVersion): The version to check
Returns:
bool: True if the version is included in the range, False if not
"""
for disjunct in self._disjuncts:
if self._check_insersection(version, disjunct):
return True
return False | python | def check(self, version):
for disjunct in self._disjuncts:
if self._check_insersection(version, disjunct):
return True
return False | [
"def",
"check",
"(",
"self",
",",
"version",
")",
":",
"for",
"disjunct",
"in",
"self",
".",
"_disjuncts",
":",
"if",
"self",
".",
"_check_insersection",
"(",
"version",
",",
"disjunct",
")",
":",
"return",
"True",
"return",
"False"
] | Check that a version is inside this SemanticVersionRange
Args:
version (SemanticVersion): The version to check
Returns:
bool: True if the version is included in the range, False if not | [
"Check",
"that",
"a",
"version",
"is",
"inside",
"this",
"SemanticVersionRange"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L342-L356 |
23,912 | iotile/coretools | iotilecore/iotile/core/dev/semver.py | SemanticVersionRange.filter | def filter(self, versions, key=lambda x: x):
"""Filter all of the versions in an iterable that match this version range
Args:
versions (iterable): An iterable of SemanticVersion objects
Returns:
list: A list of the SemanticVersion objects that matched this range
"""
return [x for x in versions if self.check(key(x))] | python | def filter(self, versions, key=lambda x: x):
return [x for x in versions if self.check(key(x))] | [
"def",
"filter",
"(",
"self",
",",
"versions",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"versions",
"if",
"self",
".",
"check",
"(",
"key",
"(",
"x",
")",
")",
"]"
] | Filter all of the versions in an iterable that match this version range
Args:
versions (iterable): An iterable of SemanticVersion objects
Returns:
list: A list of the SemanticVersion objects that matched this range | [
"Filter",
"all",
"of",
"the",
"versions",
"in",
"an",
"iterable",
"that",
"match",
"this",
"version",
"range"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L358-L368 |
23,913 | iotile/coretools | iotilecore/iotile/core/dev/semver.py | SemanticVersionRange.FromString | def FromString(cls, range_string):
"""Parse a version range string into a SemanticVersionRange
Currently, the only possible range strings are:
^X.Y.Z - matches all versions with the same leading nonzero digit
greater than or equal the given range.
* - matches everything
=X.Y.Z - matches only the exact version given
Args:
range_string (string): A string specifying the version range
Returns:
SemanticVersionRange: The resulting version range object
Raises:
ArgumentError: if the range string does not define a valid range.
"""
disjuncts = None
range_string = range_string.strip()
if len(range_string) == 0:
raise ArgumentError("You must pass a finite string to SemanticVersionRange.FromString",
range_string=range_string)
# Check for *
if len(range_string) == 1 and range_string[0] == '*':
conj = (None, None, True, True)
disjuncts = [[conj]]
# Check for ^X.Y.Z
elif range_string[0] == '^':
ver = range_string[1:]
try:
ver = SemanticVersion.FromString(ver)
except DataError as err:
raise ArgumentError("Could not parse ^X.Y.Z version", parse_error=str(err), range_string=range_string)
lower = ver
upper = ver.inc_first_nonzero()
conj = (lower, upper, True, False)
disjuncts = [[conj]]
elif range_string[0] == '=':
ver = range_string[1:]
try:
ver = SemanticVersion.FromString(ver)
except DataError as err:
raise ArgumentError("Could not parse =X.Y.Z version", parse_error=str(err), range_string=range_string)
conj = (ver, ver, True, True)
disjuncts = [[conj]]
if disjuncts is None:
raise ArgumentError("Invalid range specification that could not be parsed", range_string=range_string)
return SemanticVersionRange(disjuncts) | python | def FromString(cls, range_string):
disjuncts = None
range_string = range_string.strip()
if len(range_string) == 0:
raise ArgumentError("You must pass a finite string to SemanticVersionRange.FromString",
range_string=range_string)
# Check for *
if len(range_string) == 1 and range_string[0] == '*':
conj = (None, None, True, True)
disjuncts = [[conj]]
# Check for ^X.Y.Z
elif range_string[0] == '^':
ver = range_string[1:]
try:
ver = SemanticVersion.FromString(ver)
except DataError as err:
raise ArgumentError("Could not parse ^X.Y.Z version", parse_error=str(err), range_string=range_string)
lower = ver
upper = ver.inc_first_nonzero()
conj = (lower, upper, True, False)
disjuncts = [[conj]]
elif range_string[0] == '=':
ver = range_string[1:]
try:
ver = SemanticVersion.FromString(ver)
except DataError as err:
raise ArgumentError("Could not parse =X.Y.Z version", parse_error=str(err), range_string=range_string)
conj = (ver, ver, True, True)
disjuncts = [[conj]]
if disjuncts is None:
raise ArgumentError("Invalid range specification that could not be parsed", range_string=range_string)
return SemanticVersionRange(disjuncts) | [
"def",
"FromString",
"(",
"cls",
",",
"range_string",
")",
":",
"disjuncts",
"=",
"None",
"range_string",
"=",
"range_string",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"range_string",
")",
"==",
"0",
":",
"raise",
"ArgumentError",
"(",
"\"You must pass a fi... | Parse a version range string into a SemanticVersionRange
Currently, the only possible range strings are:
^X.Y.Z - matches all versions with the same leading nonzero digit
greater than or equal the given range.
* - matches everything
=X.Y.Z - matches only the exact version given
Args:
range_string (string): A string specifying the version range
Returns:
SemanticVersionRange: The resulting version range object
Raises:
ArgumentError: if the range string does not define a valid range. | [
"Parse",
"a",
"version",
"range",
"string",
"into",
"a",
"SemanticVersionRange"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L371-L433 |
23,914 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/hosted_executor.py | SemihostedRPCExecutor._call_rpc | def _call_rpc(self, address, rpc_id, payload):
"""Call an RPC with the given information and return its response.
Must raise a hardware error of the appropriate kind if the RPC
can not be executed correctly. Otherwise it should return the binary
response payload received from the RPC.
Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
payload (bytes, bytearray): The data that we want to send as the payload
"""
# FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but
# this should be long enough to accommodate any actual RPCs we need to send.
status, response = self.hw.stream.send_rpc(address, rpc_id, payload, timeout=1.1)
return response | python | def _call_rpc(self, address, rpc_id, payload):
# FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but
# this should be long enough to accommodate any actual RPCs we need to send.
status, response = self.hw.stream.send_rpc(address, rpc_id, payload, timeout=1.1)
return response | [
"def",
"_call_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"payload",
")",
":",
"# FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but",
"# this should be long enough to accommodate any actual RPCs we need to send.",
"status",
",",
"respo... | Call an RPC with the given information and return its response.
Must raise a hardware error of the appropriate kind if the RPC
can not be executed correctly. Otherwise it should return the binary
response payload received from the RPC.
Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
payload (bytes, bytearray): The data that we want to send as the payload | [
"Call",
"an",
"RPC",
"with",
"the",
"given",
"information",
"and",
"return",
"its",
"response",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/hosted_executor.py#L38-L56 |
23,915 | iotile/coretools | iotilecore/iotile/core/hw/reports/individual_format.py | IndividualReadingReport.FromReadings | def FromReadings(cls, uuid, readings):
"""Generate an instance of the report format from a list of readings and a uuid
"""
if len(readings) != 1:
raise ArgumentError("IndividualReading reports must be created with exactly one reading",
num_readings=len(readings))
reading = readings[0]
data = struct.pack("<BBHLLLL", 0, 0, reading.stream, uuid, 0, reading.raw_time, reading.value)
return IndividualReadingReport(data) | python | def FromReadings(cls, uuid, readings):
if len(readings) != 1:
raise ArgumentError("IndividualReading reports must be created with exactly one reading",
num_readings=len(readings))
reading = readings[0]
data = struct.pack("<BBHLLLL", 0, 0, reading.stream, uuid, 0, reading.raw_time, reading.value)
return IndividualReadingReport(data) | [
"def",
"FromReadings",
"(",
"cls",
",",
"uuid",
",",
"readings",
")",
":",
"if",
"len",
"(",
"readings",
")",
"!=",
"1",
":",
"raise",
"ArgumentError",
"(",
"\"IndividualReading reports must be created with exactly one reading\"",
",",
"num_readings",
"=",
"len",
... | Generate an instance of the report format from a list of readings and a uuid | [
"Generate",
"an",
"instance",
"of",
"the",
"report",
"format",
"from",
"a",
"list",
"of",
"readings",
"and",
"a",
"uuid"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/individual_format.py#L39-L49 |
23,916 | iotile/coretools | iotilecore/iotile/core/hw/reports/individual_format.py | IndividualReadingReport.decode | def decode(self):
"""Decode this report into a single reading
"""
fmt, _, stream, uuid, sent_timestamp, reading_timestamp, reading_value = unpack("<BBHLLLL", self.raw_report)
assert fmt == 0
# Estimate the UTC time when this device was turned on
time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp)
reading = IOTileReading(reading_timestamp, stream, reading_value, time_base=time_base)
self.origin = uuid
self.sent_timestamp = sent_timestamp
return [reading], [] | python | def decode(self):
fmt, _, stream, uuid, sent_timestamp, reading_timestamp, reading_value = unpack("<BBHLLLL", self.raw_report)
assert fmt == 0
# Estimate the UTC time when this device was turned on
time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp)
reading = IOTileReading(reading_timestamp, stream, reading_value, time_base=time_base)
self.origin = uuid
self.sent_timestamp = sent_timestamp
return [reading], [] | [
"def",
"decode",
"(",
"self",
")",
":",
"fmt",
",",
"_",
",",
"stream",
",",
"uuid",
",",
"sent_timestamp",
",",
"reading_timestamp",
",",
"reading_value",
"=",
"unpack",
"(",
"\"<BBHLLLL\"",
",",
"self",
".",
"raw_report",
")",
"assert",
"fmt",
"==",
"0... | Decode this report into a single reading | [
"Decode",
"this",
"report",
"into",
"a",
"single",
"reading"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/individual_format.py#L51-L65 |
23,917 | iotile/coretools | iotilecore/iotile/core/hw/reports/individual_format.py | IndividualReadingReport.encode | def encode(self):
"""Turn this report into a serialized bytearray that could be decoded with a call to decode"""
reading = self.visible_readings[0]
data = struct.pack("<BBHLLLL", 0, 0, reading.stream, self.origin,
self.sent_timestamp, reading.raw_time, reading.value)
return bytearray(data) | python | def encode(self):
reading = self.visible_readings[0]
data = struct.pack("<BBHLLLL", 0, 0, reading.stream, self.origin,
self.sent_timestamp, reading.raw_time, reading.value)
return bytearray(data) | [
"def",
"encode",
"(",
"self",
")",
":",
"reading",
"=",
"self",
".",
"visible_readings",
"[",
"0",
"]",
"data",
"=",
"struct",
".",
"pack",
"(",
"\"<BBHLLLL\"",
",",
"0",
",",
"0",
",",
"reading",
".",
"stream",
",",
"self",
".",
"origin",
",",
"se... | Turn this report into a serialized bytearray that could be decoded with a call to decode | [
"Turn",
"this",
"report",
"into",
"a",
"serialized",
"bytearray",
"that",
"could",
"be",
"decoded",
"with",
"a",
"call",
"to",
"decode"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/individual_format.py#L67-L74 |
23,918 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py | is_LaTeX | def is_LaTeX(flist,env,abspath):
"""Scan a file list to decide if it's TeX- or LaTeX-flavored."""
# We need to scan files that are included in case the
# \documentclass command is in them.
# get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS']
savedpath = modify_env_var(env, 'TEXINPUTS', abspath)
paths = env['ENV']['TEXINPUTS']
if SCons.Util.is_List(paths):
pass
else:
# Split at os.pathsep to convert into absolute path
paths = paths.split(os.pathsep)
# now that we have the path list restore the env
if savedpath is _null:
try:
del env['ENV']['TEXINPUTS']
except KeyError:
pass # was never set
else:
env['ENV']['TEXINPUTS'] = savedpath
if Verbose:
print("is_LaTeX search path ",paths)
print("files to search :",flist)
# Now that we have the search path and file list, check each one
for f in flist:
if Verbose:
print(" checking for Latex source ",str(f))
content = f.get_text_contents()
if LaTeX_re.search(content):
if Verbose:
print("file %s is a LaTeX file" % str(f))
return 1
if Verbose:
print("file %s is not a LaTeX file" % str(f))
# now find included files
inc_files = [ ]
inc_files.extend( include_re.findall(content) )
if Verbose:
print("files included by '%s': "%str(f),inc_files)
# inc_files is list of file names as given. need to find them
# using TEXINPUTS paths.
# search the included files
for src in inc_files:
srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False)
# make this a list since is_LaTeX takes a list.
fileList = [srcNode,]
if Verbose:
print("FindFile found ",srcNode)
if srcNode is not None:
file_test = is_LaTeX(fileList, env, abspath)
# return on first file that finds latex is needed.
if file_test:
return file_test
if Verbose:
print(" done scanning ",str(f))
return 0 | python | def is_LaTeX(flist,env,abspath):
# We need to scan files that are included in case the
# \documentclass command is in them.
# get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS']
savedpath = modify_env_var(env, 'TEXINPUTS', abspath)
paths = env['ENV']['TEXINPUTS']
if SCons.Util.is_List(paths):
pass
else:
# Split at os.pathsep to convert into absolute path
paths = paths.split(os.pathsep)
# now that we have the path list restore the env
if savedpath is _null:
try:
del env['ENV']['TEXINPUTS']
except KeyError:
pass # was never set
else:
env['ENV']['TEXINPUTS'] = savedpath
if Verbose:
print("is_LaTeX search path ",paths)
print("files to search :",flist)
# Now that we have the search path and file list, check each one
for f in flist:
if Verbose:
print(" checking for Latex source ",str(f))
content = f.get_text_contents()
if LaTeX_re.search(content):
if Verbose:
print("file %s is a LaTeX file" % str(f))
return 1
if Verbose:
print("file %s is not a LaTeX file" % str(f))
# now find included files
inc_files = [ ]
inc_files.extend( include_re.findall(content) )
if Verbose:
print("files included by '%s': "%str(f),inc_files)
# inc_files is list of file names as given. need to find them
# using TEXINPUTS paths.
# search the included files
for src in inc_files:
srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False)
# make this a list since is_LaTeX takes a list.
fileList = [srcNode,]
if Verbose:
print("FindFile found ",srcNode)
if srcNode is not None:
file_test = is_LaTeX(fileList, env, abspath)
# return on first file that finds latex is needed.
if file_test:
return file_test
if Verbose:
print(" done scanning ",str(f))
return 0 | [
"def",
"is_LaTeX",
"(",
"flist",
",",
"env",
",",
"abspath",
")",
":",
"# We need to scan files that are included in case the",
"# \\documentclass command is in them.",
"# get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS']",
"savedpath",
"=",
"modify_env_var",
"(",
... | Scan a file list to decide if it's TeX- or LaTeX-flavored. | [
"Scan",
"a",
"file",
"list",
"to",
"decide",
"if",
"it",
"s",
"TeX",
"-",
"or",
"LaTeX",
"-",
"flavored",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L495-L560 |
23,919 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py | TeXLaTeXStrFunction | def TeXLaTeXStrFunction(target = None, source= None, env=None):
"""A strfunction for TeX and LaTeX that scans the source file to
decide the "flavor" of the source and then returns the appropriate
command string."""
if env.GetOption("no_exec"):
# find these paths for use in is_LaTeX to search for included files
basedir = os.path.split(str(source[0]))[0]
abspath = os.path.abspath(basedir)
if is_LaTeX(source,env,abspath):
result = env.subst('$LATEXCOM',0,target,source)+" ..."
else:
result = env.subst("$TEXCOM",0,target,source)+" ..."
else:
result = ''
return result | python | def TeXLaTeXStrFunction(target = None, source= None, env=None):
if env.GetOption("no_exec"):
# find these paths for use in is_LaTeX to search for included files
basedir = os.path.split(str(source[0]))[0]
abspath = os.path.abspath(basedir)
if is_LaTeX(source,env,abspath):
result = env.subst('$LATEXCOM',0,target,source)+" ..."
else:
result = env.subst("$TEXCOM",0,target,source)+" ..."
else:
result = ''
return result | [
"def",
"TeXLaTeXStrFunction",
"(",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
".",
"GetOption",
"(",
"\"no_exec\"",
")",
":",
"# find these paths for use in is_LaTeX to search for included files",
"basedir",
... | A strfunction for TeX and LaTeX that scans the source file to
decide the "flavor" of the source and then returns the appropriate
command string. | [
"A",
"strfunction",
"for",
"TeX",
"and",
"LaTeX",
"that",
"scans",
"the",
"source",
"file",
"to",
"decide",
"the",
"flavor",
"of",
"the",
"source",
"and",
"then",
"returns",
"the",
"appropriate",
"command",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L581-L597 |
23,920 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py | tex_eps_emitter | def tex_eps_emitter(target, source, env):
"""An emitter for TeX and LaTeX sources when
executing tex or latex. It will accept .ps and .eps
graphics files
"""
(target, source) = tex_emitter_core(target, source, env, TexGraphics)
return (target, source) | python | def tex_eps_emitter(target, source, env):
(target, source) = tex_emitter_core(target, source, env, TexGraphics)
return (target, source) | [
"def",
"tex_eps_emitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"(",
"target",
",",
"source",
")",
"=",
"tex_emitter_core",
"(",
"target",
",",
"source",
",",
"env",
",",
"TexGraphics",
")",
"return",
"(",
"target",
",",
"source",
")"
] | An emitter for TeX and LaTeX sources when
executing tex or latex. It will accept .ps and .eps
graphics files | [
"An",
"emitter",
"for",
"TeX",
"and",
"LaTeX",
"sources",
"when",
"executing",
"tex",
"or",
"latex",
".",
"It",
"will",
"accept",
".",
"ps",
"and",
".",
"eps",
"graphics",
"files"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L599-L606 |
23,921 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py | tex_pdf_emitter | def tex_pdf_emitter(target, source, env):
"""An emitter for TeX and LaTeX sources when
executing pdftex or pdflatex. It will accept graphics
files of types .pdf, .jpg, .png, .gif, and .tif
"""
(target, source) = tex_emitter_core(target, source, env, LatexGraphics)
return (target, source) | python | def tex_pdf_emitter(target, source, env):
(target, source) = tex_emitter_core(target, source, env, LatexGraphics)
return (target, source) | [
"def",
"tex_pdf_emitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"(",
"target",
",",
"source",
")",
"=",
"tex_emitter_core",
"(",
"target",
",",
"source",
",",
"env",
",",
"LatexGraphics",
")",
"return",
"(",
"target",
",",
"source",
")"
] | An emitter for TeX and LaTeX sources when
executing pdftex or pdflatex. It will accept graphics
files of types .pdf, .jpg, .png, .gif, and .tif | [
"An",
"emitter",
"for",
"TeX",
"and",
"LaTeX",
"sources",
"when",
"executing",
"pdftex",
"or",
"pdflatex",
".",
"It",
"will",
"accept",
"graphics",
"files",
"of",
"types",
".",
"pdf",
".",
"jpg",
".",
"png",
".",
"gif",
"and",
".",
"tif"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L608-L615 |
23,922 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py | generate | def generate(env):
"""Add Builders and construction variables for TeX to an Environment."""
global TeXLaTeXAction
if TeXLaTeXAction is None:
TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction,
strfunction=TeXLaTeXStrFunction)
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
generate_common(env)
from . import dvi
dvi.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.tex', TeXLaTeXAction)
bld.add_emitter('.tex', tex_eps_emitter) | python | def generate(env):
global TeXLaTeXAction
if TeXLaTeXAction is None:
TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction,
strfunction=TeXLaTeXStrFunction)
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
generate_common(env)
from . import dvi
dvi.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.tex', TeXLaTeXAction)
bld.add_emitter('.tex', tex_eps_emitter) | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"TeXLaTeXAction",
"if",
"TeXLaTeXAction",
"is",
"None",
":",
"TeXLaTeXAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"TeXLaTeXFunction",
",",
"strfunction",
"=",
"TeXLaTeXStrFunction",
")",
"env",
"... | Add Builders and construction variables for TeX to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"TeX",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L831-L848 |
23,923 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py | is_win64 | def is_win64():
"""Return true if running on windows 64 bits.
Works whether python itself runs in 64 bits or 32 bits."""
# Unfortunately, python does not provide a useful way to determine
# if the underlying Windows OS is 32-bit or 64-bit. Worse, whether
# the Python itself is 32-bit or 64-bit affects what it returns,
# so nothing in sys.* or os.* help.
# Apparently the best solution is to use env vars that Windows
# sets. If PROCESSOR_ARCHITECTURE is not x86, then the python
# process is running in 64 bit mode (on a 64-bit OS, 64-bit
# hardware, obviously).
# If this python is 32-bit but the OS is 64, Windows will set
# ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null.
# (Checking for HKLM\Software\Wow6432Node in the registry doesn't
# work, because some 32-bit installers create it.)
global _is_win64
if _is_win64 is None:
# I structured these tests to make it easy to add new ones or
# add exceptions in the future, because this is a bit fragile.
_is_win64 = False
if os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') != 'x86':
_is_win64 = True
if os.environ.get('PROCESSOR_ARCHITEW6432'):
_is_win64 = True
if os.environ.get('ProgramW6432'):
_is_win64 = True
return _is_win64 | python | def is_win64():
# Unfortunately, python does not provide a useful way to determine
# if the underlying Windows OS is 32-bit or 64-bit. Worse, whether
# the Python itself is 32-bit or 64-bit affects what it returns,
# so nothing in sys.* or os.* help.
# Apparently the best solution is to use env vars that Windows
# sets. If PROCESSOR_ARCHITECTURE is not x86, then the python
# process is running in 64 bit mode (on a 64-bit OS, 64-bit
# hardware, obviously).
# If this python is 32-bit but the OS is 64, Windows will set
# ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null.
# (Checking for HKLM\Software\Wow6432Node in the registry doesn't
# work, because some 32-bit installers create it.)
global _is_win64
if _is_win64 is None:
# I structured these tests to make it easy to add new ones or
# add exceptions in the future, because this is a bit fragile.
_is_win64 = False
if os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') != 'x86':
_is_win64 = True
if os.environ.get('PROCESSOR_ARCHITEW6432'):
_is_win64 = True
if os.environ.get('ProgramW6432'):
_is_win64 = True
return _is_win64 | [
"def",
"is_win64",
"(",
")",
":",
"# Unfortunately, python does not provide a useful way to determine",
"# if the underlying Windows OS is 32-bit or 64-bit. Worse, whether",
"# the Python itself is 32-bit or 64-bit affects what it returns,",
"# so nothing in sys.* or os.* help.",
"# Apparently th... | Return true if running on windows 64 bits.
Works whether python itself runs in 64 bits or 32 bits. | [
"Return",
"true",
"if",
"running",
"on",
"windows",
"64",
"bits",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L55-L83 |
23,924 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py | has_reg | def has_reg(value):
"""Return True if the given key exists in HKEY_LOCAL_MACHINE, False
otherwise."""
try:
SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value)
ret = True
except SCons.Util.WinError:
ret = False
return ret | python | def has_reg(value):
try:
SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value)
ret = True
except SCons.Util.WinError:
ret = False
return ret | [
"def",
"has_reg",
"(",
"value",
")",
":",
"try",
":",
"SCons",
".",
"Util",
".",
"RegOpenKeyEx",
"(",
"SCons",
".",
"Util",
".",
"HKEY_LOCAL_MACHINE",
",",
"value",
")",
"ret",
"=",
"True",
"except",
"SCons",
".",
"Util",
".",
"WinError",
":",
"ret",
... | Return True if the given key exists in HKEY_LOCAL_MACHINE, False
otherwise. | [
"Return",
"True",
"if",
"the",
"given",
"key",
"exists",
"in",
"HKEY_LOCAL_MACHINE",
"False",
"otherwise",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L89-L97 |
23,925 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py | normalize_env | def normalize_env(env, keys, force=False):
"""Given a dictionary representing a shell environment, add the variables
from os.environ needed for the processing of .bat files; the keys are
controlled by the keys argument.
It also makes sure the environment values are correctly encoded.
If force=True, then all of the key values that exist are copied
into the returned dictionary. If force=false, values are only
copied if the key does not already exist in the copied dictionary.
Note: the environment is copied."""
normenv = {}
if env:
for k in list(env.keys()):
normenv[k] = copy.deepcopy(env[k])
for k in keys:
if k in os.environ and (force or not k in normenv):
normenv[k] = os.environ[k]
# This shouldn't be necessary, since the default environment should include system32,
# but keep this here to be safe, since it's needed to find reg.exe which the MSVC
# bat scripts use.
sys32_dir = os.path.join(os.environ.get("SystemRoot",
os.environ.get("windir", r"C:\Windows\system32")),
"System32")
if sys32_dir not in normenv['PATH']:
normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_dir
# Without Wbem in PATH, vcvarsall.bat has a "'wmic' is not recognized"
# error starting with Visual Studio 2017, although the script still
# seems to work anyway.
sys32_wbem_dir = os.path.join(sys32_dir, 'Wbem')
if sys32_wbem_dir not in normenv['PATH']:
normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_wbem_dir
debug("PATH: %s"%normenv['PATH'])
return normenv | python | def normalize_env(env, keys, force=False):
normenv = {}
if env:
for k in list(env.keys()):
normenv[k] = copy.deepcopy(env[k])
for k in keys:
if k in os.environ and (force or not k in normenv):
normenv[k] = os.environ[k]
# This shouldn't be necessary, since the default environment should include system32,
# but keep this here to be safe, since it's needed to find reg.exe which the MSVC
# bat scripts use.
sys32_dir = os.path.join(os.environ.get("SystemRoot",
os.environ.get("windir", r"C:\Windows\system32")),
"System32")
if sys32_dir not in normenv['PATH']:
normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_dir
# Without Wbem in PATH, vcvarsall.bat has a "'wmic' is not recognized"
# error starting with Visual Studio 2017, although the script still
# seems to work anyway.
sys32_wbem_dir = os.path.join(sys32_dir, 'Wbem')
if sys32_wbem_dir not in normenv['PATH']:
normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_wbem_dir
debug("PATH: %s"%normenv['PATH'])
return normenv | [
"def",
"normalize_env",
"(",
"env",
",",
"keys",
",",
"force",
"=",
"False",
")",
":",
"normenv",
"=",
"{",
"}",
"if",
"env",
":",
"for",
"k",
"in",
"list",
"(",
"env",
".",
"keys",
"(",
")",
")",
":",
"normenv",
"[",
"k",
"]",
"=",
"copy",
"... | Given a dictionary representing a shell environment, add the variables
from os.environ needed for the processing of .bat files; the keys are
controlled by the keys argument.
It also makes sure the environment values are correctly encoded.
If force=True, then all of the key values that exist are copied
into the returned dictionary. If force=false, values are only
copied if the key does not already exist in the copied dictionary.
Note: the environment is copied. | [
"Given",
"a",
"dictionary",
"representing",
"a",
"shell",
"environment",
"add",
"the",
"variables",
"from",
"os",
".",
"environ",
"needed",
"for",
"the",
"processing",
"of",
".",
"bat",
"files",
";",
"the",
"keys",
"are",
"controlled",
"by",
"the",
"keys",
... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L101-L141 |
23,926 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py | get_output | def get_output(vcbat, args = None, env = None):
"""Parse the output of given bat file, with given args."""
if env is None:
# Create a blank environment, for use in launching the tools
env = SCons.Environment.Environment(tools=[])
# TODO: This is a hard-coded list of the variables that (may) need
# to be imported from os.environ[] for v[sc]*vars*.bat file
# execution to work. This list should really be either directly
# controlled by vc.py, or else derived from the common_tools_var
# settings in vs.py.
vs_vc_vars = [
'COMSPEC',
# VS100 and VS110: Still set, but modern MSVC setup scripts will
# discard these if registry has values. However Intel compiler setup
# script still requires these as of 2013/2014.
'VS140COMNTOOLS',
'VS120COMNTOOLS',
'VS110COMNTOOLS',
'VS100COMNTOOLS',
'VS90COMNTOOLS',
'VS80COMNTOOLS',
'VS71COMNTOOLS',
'VS70COMNTOOLS',
'VS60COMNTOOLS',
]
env['ENV'] = normalize_env(env['ENV'], vs_vc_vars, force=False)
if args:
debug("Calling '%s %s'" % (vcbat, args))
popen = SCons.Action._subproc(env,
'"%s" %s & set' % (vcbat, args),
stdin='devnull',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
else:
debug("Calling '%s'" % vcbat)
popen = SCons.Action._subproc(env,
'"%s" & set' % vcbat,
stdin='devnull',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Use the .stdout and .stderr attributes directly because the
# .communicate() method uses the threading module on Windows
# and won't work under Pythons not built with threading.
stdout = popen.stdout.read()
stderr = popen.stderr.read()
# Extra debug logic, uncomment if necessary
# debug('get_output():stdout:%s'%stdout)
# debug('get_output():stderr:%s'%stderr)
if stderr:
# TODO: find something better to do with stderr;
# this at least prevents errors from getting swallowed.
import sys
sys.stderr.write(stderr)
if popen.wait() != 0:
raise IOError(stderr.decode("mbcs"))
output = stdout.decode("mbcs")
return output | python | def get_output(vcbat, args = None, env = None):
if env is None:
# Create a blank environment, for use in launching the tools
env = SCons.Environment.Environment(tools=[])
# TODO: This is a hard-coded list of the variables that (may) need
# to be imported from os.environ[] for v[sc]*vars*.bat file
# execution to work. This list should really be either directly
# controlled by vc.py, or else derived from the common_tools_var
# settings in vs.py.
vs_vc_vars = [
'COMSPEC',
# VS100 and VS110: Still set, but modern MSVC setup scripts will
# discard these if registry has values. However Intel compiler setup
# script still requires these as of 2013/2014.
'VS140COMNTOOLS',
'VS120COMNTOOLS',
'VS110COMNTOOLS',
'VS100COMNTOOLS',
'VS90COMNTOOLS',
'VS80COMNTOOLS',
'VS71COMNTOOLS',
'VS70COMNTOOLS',
'VS60COMNTOOLS',
]
env['ENV'] = normalize_env(env['ENV'], vs_vc_vars, force=False)
if args:
debug("Calling '%s %s'" % (vcbat, args))
popen = SCons.Action._subproc(env,
'"%s" %s & set' % (vcbat, args),
stdin='devnull',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
else:
debug("Calling '%s'" % vcbat)
popen = SCons.Action._subproc(env,
'"%s" & set' % vcbat,
stdin='devnull',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Use the .stdout and .stderr attributes directly because the
# .communicate() method uses the threading module on Windows
# and won't work under Pythons not built with threading.
stdout = popen.stdout.read()
stderr = popen.stderr.read()
# Extra debug logic, uncomment if necessary
# debug('get_output():stdout:%s'%stdout)
# debug('get_output():stderr:%s'%stderr)
if stderr:
# TODO: find something better to do with stderr;
# this at least prevents errors from getting swallowed.
import sys
sys.stderr.write(stderr)
if popen.wait() != 0:
raise IOError(stderr.decode("mbcs"))
output = stdout.decode("mbcs")
return output | [
"def",
"get_output",
"(",
"vcbat",
",",
"args",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
"is",
"None",
":",
"# Create a blank environment, for use in launching the tools",
"env",
"=",
"SCons",
".",
"Environment",
".",
"Environment",
"(",
"t... | Parse the output of given bat file, with given args. | [
"Parse",
"the",
"output",
"of",
"given",
"bat",
"file",
"with",
"given",
"args",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L143-L206 |
23,927 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/default.py | generate | def generate(env):
"""Add default tools."""
for t in SCons.Tool.tool_list(env['PLATFORM'], env):
SCons.Tool.Tool(t)(env) | python | def generate(env):
for t in SCons.Tool.tool_list(env['PLATFORM'], env):
SCons.Tool.Tool(t)(env) | [
"def",
"generate",
"(",
"env",
")",
":",
"for",
"t",
"in",
"SCons",
".",
"Tool",
".",
"tool_list",
"(",
"env",
"[",
"'PLATFORM'",
"]",
",",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"Tool",
"(",
"t",
")",
"(",
"env",
")"
] | Add default tools. | [
"Add",
"default",
"tools",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/default.py#L38-L41 |
23,928 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py | _PathList.subst_path | def subst_path(self, env, target, source):
"""
Performs construction variable substitution on a pre-digested
PathList for a specific target and source.
"""
result = []
for type, value in self.pathlist:
if type == TYPE_STRING_SUBST:
value = env.subst(value, target=target, source=source,
conv=node_conv)
if SCons.Util.is_Sequence(value):
result.extend(SCons.Util.flatten(value))
elif value:
result.append(value)
elif type == TYPE_OBJECT:
value = node_conv(value)
if value:
result.append(value)
elif value:
result.append(value)
return tuple(result) | python | def subst_path(self, env, target, source):
result = []
for type, value in self.pathlist:
if type == TYPE_STRING_SUBST:
value = env.subst(value, target=target, source=source,
conv=node_conv)
if SCons.Util.is_Sequence(value):
result.extend(SCons.Util.flatten(value))
elif value:
result.append(value)
elif type == TYPE_OBJECT:
value = node_conv(value)
if value:
result.append(value)
elif value:
result.append(value)
return tuple(result) | [
"def",
"subst_path",
"(",
"self",
",",
"env",
",",
"target",
",",
"source",
")",
":",
"result",
"=",
"[",
"]",
"for",
"type",
",",
"value",
"in",
"self",
".",
"pathlist",
":",
"if",
"type",
"==",
"TYPE_STRING_SUBST",
":",
"value",
"=",
"env",
".",
... | Performs construction variable substitution on a pre-digested
PathList for a specific target and source. | [
"Performs",
"construction",
"variable",
"substitution",
"on",
"a",
"pre",
"-",
"digested",
"PathList",
"for",
"a",
"specific",
"target",
"and",
"source",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py#L123-L143 |
23,929 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py | PathListCache._PathList_key | def _PathList_key(self, pathlist):
"""
Returns the key for memoization of PathLists.
Note that we want this to be pretty quick, so we don't completely
canonicalize all forms of the same list. For example,
'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically
represent the same list if you're executing from $ROOT, but
we're not going to bother splitting strings into path elements,
or massaging strings into Nodes, to identify that equivalence.
We just want to eliminate obvious redundancy from the normal
case of re-using exactly the same cloned value for a path.
"""
if SCons.Util.is_Sequence(pathlist):
pathlist = tuple(SCons.Util.flatten(pathlist))
return pathlist | python | def _PathList_key(self, pathlist):
if SCons.Util.is_Sequence(pathlist):
pathlist = tuple(SCons.Util.flatten(pathlist))
return pathlist | [
"def",
"_PathList_key",
"(",
"self",
",",
"pathlist",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_Sequence",
"(",
"pathlist",
")",
":",
"pathlist",
"=",
"tuple",
"(",
"SCons",
".",
"Util",
".",
"flatten",
"(",
"pathlist",
")",
")",
"return",
"pathli... | Returns the key for memoization of PathLists.
Note that we want this to be pretty quick, so we don't completely
canonicalize all forms of the same list. For example,
'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically
represent the same list if you're executing from $ROOT, but
we're not going to bother splitting strings into path elements,
or massaging strings into Nodes, to identify that equivalence.
We just want to eliminate obvious redundancy from the normal
case of re-using exactly the same cloned value for a path. | [
"Returns",
"the",
"key",
"for",
"memoization",
"of",
"PathLists",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py#L177-L192 |
23,930 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py | PathListCache.PathList | def PathList(self, pathlist):
"""
Returns the cached _PathList object for the specified pathlist,
creating and caching a new object as necessary.
"""
pathlist = self._PathList_key(pathlist)
try:
memo_dict = self._memo['PathList']
except KeyError:
memo_dict = {}
self._memo['PathList'] = memo_dict
else:
try:
return memo_dict[pathlist]
except KeyError:
pass
result = _PathList(pathlist)
memo_dict[pathlist] = result
return result | python | def PathList(self, pathlist):
pathlist = self._PathList_key(pathlist)
try:
memo_dict = self._memo['PathList']
except KeyError:
memo_dict = {}
self._memo['PathList'] = memo_dict
else:
try:
return memo_dict[pathlist]
except KeyError:
pass
result = _PathList(pathlist)
memo_dict[pathlist] = result
return result | [
"def",
"PathList",
"(",
"self",
",",
"pathlist",
")",
":",
"pathlist",
"=",
"self",
".",
"_PathList_key",
"(",
"pathlist",
")",
"try",
":",
"memo_dict",
"=",
"self",
".",
"_memo",
"[",
"'PathList'",
"]",
"except",
"KeyError",
":",
"memo_dict",
"=",
"{",
... | Returns the cached _PathList object for the specified pathlist,
creating and caching a new object as necessary. | [
"Returns",
"the",
"cached",
"_PathList",
"object",
"for",
"the",
"specified",
"pathlist",
"creating",
"and",
"caching",
"a",
"new",
"object",
"as",
"necessary",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py#L195-L216 |
23,931 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py | DefaultEnvironment | def DefaultEnvironment(*args, **kw):
"""
Initial public entry point for creating the default construction
Environment.
After creating the environment, we overwrite our name
(DefaultEnvironment) with the _fetch_DefaultEnvironment() function,
which more efficiently returns the initialized default construction
environment without checking for its existence.
(This function still exists with its _default_check because someone
else (*cough* Script/__init__.py *cough*) may keep a reference
to this function. So we can't use the fully functional idiom of
having the name originally be a something that *only* creates the
construction environment and then overwrites the name.)
"""
global _default_env
if not _default_env:
import SCons.Util
_default_env = SCons.Environment.Environment(*args, **kw)
if SCons.Util.md5:
_default_env.Decider('MD5')
else:
_default_env.Decider('timestamp-match')
global DefaultEnvironment
DefaultEnvironment = _fetch_DefaultEnvironment
_default_env._CacheDir_path = None
return _default_env | python | def DefaultEnvironment(*args, **kw):
global _default_env
if not _default_env:
import SCons.Util
_default_env = SCons.Environment.Environment(*args, **kw)
if SCons.Util.md5:
_default_env.Decider('MD5')
else:
_default_env.Decider('timestamp-match')
global DefaultEnvironment
DefaultEnvironment = _fetch_DefaultEnvironment
_default_env._CacheDir_path = None
return _default_env | [
"def",
"DefaultEnvironment",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"global",
"_default_env",
"if",
"not",
"_default_env",
":",
"import",
"SCons",
".",
"Util",
"_default_env",
"=",
"SCons",
".",
"Environment",
".",
"Environment",
"(",
"*",
"args"... | Initial public entry point for creating the default construction
Environment.
After creating the environment, we overwrite our name
(DefaultEnvironment) with the _fetch_DefaultEnvironment() function,
which more efficiently returns the initialized default construction
environment without checking for its existence.
(This function still exists with its _default_check because someone
else (*cough* Script/__init__.py *cough*) may keep a reference
to this function. So we can't use the fully functional idiom of
having the name originally be a something that *only* creates the
construction environment and then overwrites the name.) | [
"Initial",
"public",
"entry",
"point",
"for",
"creating",
"the",
"default",
"construction",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L68-L95 |
23,932 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py | _concat | def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None):
"""
Creates a new list from 'list' by first interpolating each element
in the list using the 'env' dictionary and then calling f on the
list, and finally calling _concat_ixes to concatenate 'prefix' and
'suffix' onto each element of the list.
"""
if not list:
return list
l = f(SCons.PathList.PathList(list).subst_path(env, target, source))
if l is not None:
list = l
return _concat_ixes(prefix, list, suffix, env) | python | def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None):
if not list:
return list
l = f(SCons.PathList.PathList(list).subst_path(env, target, source))
if l is not None:
list = l
return _concat_ixes(prefix, list, suffix, env) | [
"def",
"_concat",
"(",
"prefix",
",",
"list",
",",
"suffix",
",",
"env",
",",
"f",
"=",
"lambda",
"x",
":",
"x",
",",
"target",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"if",
"not",
"list",
":",
"return",
"list",
"l",
"=",
"f",
"(",
... | Creates a new list from 'list' by first interpolating each element
in the list using the 'env' dictionary and then calling f on the
list, and finally calling _concat_ixes to concatenate 'prefix' and
'suffix' onto each element of the list. | [
"Creates",
"a",
"new",
"list",
"from",
"list",
"by",
"first",
"interpolating",
"each",
"element",
"in",
"the",
"list",
"using",
"the",
"env",
"dictionary",
"and",
"then",
"calling",
"f",
"on",
"the",
"list",
"and",
"finally",
"calling",
"_concat_ixes",
"to",... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L344-L358 |
23,933 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py | _concat_ixes | def _concat_ixes(prefix, list, suffix, env):
"""
Creates a new list from 'list' by concatenating the 'prefix' and
'suffix' arguments onto each element of the list. A trailing space
on 'prefix' or leading space on 'suffix' will cause them to be put
into separate list elements rather than being concatenated.
"""
result = []
# ensure that prefix and suffix are strings
prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW))
suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW))
for x in list:
if isinstance(x, SCons.Node.FS.File):
result.append(x)
continue
x = str(x)
if x:
if prefix:
if prefix[-1] == ' ':
result.append(prefix[:-1])
elif x[:len(prefix)] != prefix:
x = prefix + x
result.append(x)
if suffix:
if suffix[0] == ' ':
result.append(suffix[1:])
elif x[-len(suffix):] != suffix:
result[-1] = result[-1]+suffix
return result | python | def _concat_ixes(prefix, list, suffix, env):
result = []
# ensure that prefix and suffix are strings
prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW))
suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW))
for x in list:
if isinstance(x, SCons.Node.FS.File):
result.append(x)
continue
x = str(x)
if x:
if prefix:
if prefix[-1] == ' ':
result.append(prefix[:-1])
elif x[:len(prefix)] != prefix:
x = prefix + x
result.append(x)
if suffix:
if suffix[0] == ' ':
result.append(suffix[1:])
elif x[-len(suffix):] != suffix:
result[-1] = result[-1]+suffix
return result | [
"def",
"_concat_ixes",
"(",
"prefix",
",",
"list",
",",
"suffix",
",",
"env",
")",
":",
"result",
"=",
"[",
"]",
"# ensure that prefix and suffix are strings",
"prefix",
"=",
"str",
"(",
"env",
".",
"subst",
"(",
"prefix",
",",
"SCons",
".",
"Subst",
".",
... | Creates a new list from 'list' by concatenating the 'prefix' and
'suffix' arguments onto each element of the list. A trailing space
on 'prefix' or leading space on 'suffix' will cause them to be put
into separate list elements rather than being concatenated. | [
"Creates",
"a",
"new",
"list",
"from",
"list",
"by",
"concatenating",
"the",
"prefix",
"and",
"suffix",
"arguments",
"onto",
"each",
"element",
"of",
"the",
"list",
".",
"A",
"trailing",
"space",
"on",
"prefix",
"or",
"leading",
"space",
"on",
"suffix",
"w... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L360-L395 |
23,934 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py | processDefines | def processDefines(defs):
"""process defines, resolving strings, lists, dictionaries, into a list of
strings
"""
if SCons.Util.is_List(defs):
l = []
for d in defs:
if d is None:
continue
elif SCons.Util.is_List(d) or isinstance(d, tuple):
if len(d) >= 2:
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d[0]))
elif SCons.Util.is_Dict(d):
for macro,value in d.items():
if value is not None:
l.append(str(macro) + '=' + str(value))
else:
l.append(str(macro))
elif SCons.Util.is_String(d):
l.append(str(d))
else:
raise SCons.Errors.UserError("DEFINE %s is not a list, dict, string or None."%repr(d))
elif SCons.Util.is_Dict(defs):
# The items in a dictionary are stored in random order, but
# if the order of the command-line options changes from
# invocation to invocation, then the signature of the command
# line will change and we'll get random unnecessary rebuilds.
# Consequently, we have to sort the keys to ensure a
# consistent order...
l = []
for k,v in sorted(defs.items()):
if v is None:
l.append(str(k))
else:
l.append(str(k) + '=' + str(v))
else:
l = [str(defs)]
return l | python | def processDefines(defs):
if SCons.Util.is_List(defs):
l = []
for d in defs:
if d is None:
continue
elif SCons.Util.is_List(d) or isinstance(d, tuple):
if len(d) >= 2:
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d[0]))
elif SCons.Util.is_Dict(d):
for macro,value in d.items():
if value is not None:
l.append(str(macro) + '=' + str(value))
else:
l.append(str(macro))
elif SCons.Util.is_String(d):
l.append(str(d))
else:
raise SCons.Errors.UserError("DEFINE %s is not a list, dict, string or None."%repr(d))
elif SCons.Util.is_Dict(defs):
# The items in a dictionary are stored in random order, but
# if the order of the command-line options changes from
# invocation to invocation, then the signature of the command
# line will change and we'll get random unnecessary rebuilds.
# Consequently, we have to sort the keys to ensure a
# consistent order...
l = []
for k,v in sorted(defs.items()):
if v is None:
l.append(str(k))
else:
l.append(str(k) + '=' + str(v))
else:
l = [str(defs)]
return l | [
"def",
"processDefines",
"(",
"defs",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"defs",
")",
":",
"l",
"=",
"[",
"]",
"for",
"d",
"in",
"defs",
":",
"if",
"d",
"is",
"None",
":",
"continue",
"elif",
"SCons",
".",
"Util",
".",
"... | process defines, resolving strings, lists, dictionaries, into a list of
strings | [
"process",
"defines",
"resolving",
"strings",
"lists",
"dictionaries",
"into",
"a",
"list",
"of",
"strings"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L449-L488 |
23,935 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py | _defines | def _defines(prefix, defs, suffix, env, c=_concat_ixes):
"""A wrapper around _concat_ixes that turns a list or string
into a list of C preprocessor command-line definitions.
"""
return c(prefix, env.subst_path(processDefines(defs)), suffix, env) | python | def _defines(prefix, defs, suffix, env, c=_concat_ixes):
return c(prefix, env.subst_path(processDefines(defs)), suffix, env) | [
"def",
"_defines",
"(",
"prefix",
",",
"defs",
",",
"suffix",
",",
"env",
",",
"c",
"=",
"_concat_ixes",
")",
":",
"return",
"c",
"(",
"prefix",
",",
"env",
".",
"subst_path",
"(",
"processDefines",
"(",
"defs",
")",
")",
",",
"suffix",
",",
"env",
... | A wrapper around _concat_ixes that turns a list or string
into a list of C preprocessor command-line definitions. | [
"A",
"wrapper",
"around",
"_concat_ixes",
"that",
"turns",
"a",
"list",
"or",
"string",
"into",
"a",
"list",
"of",
"C",
"preprocessor",
"command",
"-",
"line",
"definitions",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L491-L496 |
23,936 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/__init__.py | Scanner | def Scanner(function, *args, **kw):
"""
Public interface factory function for creating different types
of Scanners based on the different types of "functions" that may
be supplied.
TODO: Deprecate this some day. We've moved the functionality
inside the Base class and really don't need this factory function
any more. It was, however, used by some of our Tool modules, so
the call probably ended up in various people's custom modules
patterned on SCons code.
"""
if SCons.Util.is_Dict(function):
return Selector(function, *args, **kw)
else:
return Base(function, *args, **kw) | python | def Scanner(function, *args, **kw):
if SCons.Util.is_Dict(function):
return Selector(function, *args, **kw)
else:
return Base(function, *args, **kw) | [
"def",
"Scanner",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_Dict",
"(",
"function",
")",
":",
"return",
"Selector",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"else",
... | Public interface factory function for creating different types
of Scanners based on the different types of "functions" that may
be supplied.
TODO: Deprecate this some day. We've moved the functionality
inside the Base class and really don't need this factory function
any more. It was, however, used by some of our Tool modules, so
the call probably ended up in various people's custom modules
patterned on SCons code. | [
"Public",
"interface",
"factory",
"function",
"for",
"creating",
"different",
"types",
"of",
"Scanners",
"based",
"on",
"the",
"different",
"types",
"of",
"functions",
"that",
"may",
"be",
"supplied",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/__init__.py#L45-L60 |
23,937 | iotile/coretools | iotilecore/iotile/core/hw/reports/broadcast.py | BroadcastReport.ReportLength | def ReportLength(cls, header):
"""Given a header of HeaderLength bytes, calculate the size of this report.
Returns:
int: The total length of the report including the header that we are passed.
"""
parsed_header = cls._parse_header(header)
auth_size = cls._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type)
if auth_size is None:
raise DataError("Unknown auth block size in BroadcastReport")
return cls._HEADER_LENGTH + parsed_header.reading_length + auth_size | python | def ReportLength(cls, header):
parsed_header = cls._parse_header(header)
auth_size = cls._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type)
if auth_size is None:
raise DataError("Unknown auth block size in BroadcastReport")
return cls._HEADER_LENGTH + parsed_header.reading_length + auth_size | [
"def",
"ReportLength",
"(",
"cls",
",",
"header",
")",
":",
"parsed_header",
"=",
"cls",
".",
"_parse_header",
"(",
"header",
")",
"auth_size",
"=",
"cls",
".",
"_AUTH_BLOCK_LENGTHS",
".",
"get",
"(",
"parsed_header",
".",
"auth_type",
")",
"if",
"auth_size"... | Given a header of HeaderLength bytes, calculate the size of this report.
Returns:
int: The total length of the report including the header that we are passed. | [
"Given",
"a",
"header",
"of",
"HeaderLength",
"bytes",
"calculate",
"the",
"size",
"of",
"this",
"report",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/broadcast.py#L68-L81 |
23,938 | iotile/coretools | iotilecore/iotile/core/hw/reports/broadcast.py | BroadcastReport.FromReadings | def FromReadings(cls, uuid, readings, sent_timestamp=0):
"""Generate a broadcast report from a list of readings and a uuid."""
header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0)
packed_readings = bytearray()
for reading in readings:
packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id,
reading.raw_time, reading.value)
packed_readings += bytearray(packed_reading)
return BroadcastReport(bytearray(header) + packed_readings) | python | def FromReadings(cls, uuid, readings, sent_timestamp=0):
header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0)
packed_readings = bytearray()
for reading in readings:
packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id,
reading.raw_time, reading.value)
packed_readings += bytearray(packed_reading)
return BroadcastReport(bytearray(header) + packed_readings) | [
"def",
"FromReadings",
"(",
"cls",
",",
"uuid",
",",
"readings",
",",
"sent_timestamp",
"=",
"0",
")",
":",
"header",
"=",
"struct",
".",
"pack",
"(",
"\"<BBHLLL\"",
",",
"cls",
".",
"ReportType",
",",
"0",
",",
"len",
"(",
"readings",
")",
"*",
"16"... | Generate a broadcast report from a list of readings and a uuid. | [
"Generate",
"a",
"broadcast",
"report",
"from",
"a",
"list",
"of",
"readings",
"and",
"a",
"uuid",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/broadcast.py#L84-L96 |
23,939 | iotile/coretools | iotilecore/iotile/core/hw/reports/broadcast.py | BroadcastReport.decode | def decode(self):
"""Decode this report into a list of visible readings."""
parsed_header = self._parse_header(self.raw_report[:self._HEADER_LENGTH])
auth_size = self._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type)
assert auth_size is not None
assert parsed_header.reading_length % 16 == 0
time_base = self.received_time - datetime.timedelta(seconds=parsed_header.sent_timestamp)
readings = self.raw_report[self._HEADER_LENGTH:self._HEADER_LENGTH + parsed_header.reading_length]
parsed_readings = []
for i in range(0, len(readings), 16):
reading = readings[i:i+16]
stream, _, reading_id, timestamp, value = struct.unpack("<HHLLL", reading)
parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id)
parsed_readings.append(parsed)
self.sent_timestamp = parsed_header.sent_timestamp
self.origin = parsed_header.uuid
return parsed_readings, [] | python | def decode(self):
parsed_header = self._parse_header(self.raw_report[:self._HEADER_LENGTH])
auth_size = self._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type)
assert auth_size is not None
assert parsed_header.reading_length % 16 == 0
time_base = self.received_time - datetime.timedelta(seconds=parsed_header.sent_timestamp)
readings = self.raw_report[self._HEADER_LENGTH:self._HEADER_LENGTH + parsed_header.reading_length]
parsed_readings = []
for i in range(0, len(readings), 16):
reading = readings[i:i+16]
stream, _, reading_id, timestamp, value = struct.unpack("<HHLLL", reading)
parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id)
parsed_readings.append(parsed)
self.sent_timestamp = parsed_header.sent_timestamp
self.origin = parsed_header.uuid
return parsed_readings, [] | [
"def",
"decode",
"(",
"self",
")",
":",
"parsed_header",
"=",
"self",
".",
"_parse_header",
"(",
"self",
".",
"raw_report",
"[",
":",
"self",
".",
"_HEADER_LENGTH",
"]",
")",
"auth_size",
"=",
"self",
".",
"_AUTH_BLOCK_LENGTHS",
".",
"get",
"(",
"parsed_he... | Decode this report into a list of visible readings. | [
"Decode",
"this",
"report",
"into",
"a",
"list",
"of",
"visible",
"readings",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/broadcast.py#L98-L122 |
23,940 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface.start | def start(self, device):
"""Start serving access to this VirtualIOTileDevice
Args:
device (VirtualIOTileDevice): The device we will be providing access to
"""
super(NativeBLEVirtualInterface, self).start(device)
self.set_advertising(True) | python | def start(self, device):
super(NativeBLEVirtualInterface, self).start(device)
self.set_advertising(True) | [
"def",
"start",
"(",
"self",
",",
"device",
")",
":",
"super",
"(",
"NativeBLEVirtualInterface",
",",
"self",
")",
".",
"start",
"(",
"device",
")",
"self",
".",
"set_advertising",
"(",
"True",
")"
] | Start serving access to this VirtualIOTileDevice
Args:
device (VirtualIOTileDevice): The device we will be providing access to | [
"Start",
"serving",
"access",
"to",
"this",
"VirtualIOTileDevice"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L116-L124 |
23,941 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface.register_gatt_table | def register_gatt_table(self):
"""Register the GATT table into baBLE."""
services = [BLEService, TileBusService]
characteristics = [
NameChar,
AppearanceChar,
ReceiveHeaderChar,
ReceivePayloadChar,
SendHeaderChar,
SendPayloadChar,
StreamingChar,
HighSpeedChar,
TracingChar
]
self.bable.set_gatt_table(services, characteristics) | python | def register_gatt_table(self):
services = [BLEService, TileBusService]
characteristics = [
NameChar,
AppearanceChar,
ReceiveHeaderChar,
ReceivePayloadChar,
SendHeaderChar,
SendPayloadChar,
StreamingChar,
HighSpeedChar,
TracingChar
]
self.bable.set_gatt_table(services, characteristics) | [
"def",
"register_gatt_table",
"(",
"self",
")",
":",
"services",
"=",
"[",
"BLEService",
",",
"TileBusService",
"]",
"characteristics",
"=",
"[",
"NameChar",
",",
"AppearanceChar",
",",
"ReceiveHeaderChar",
",",
"ReceivePayloadChar",
",",
"SendHeaderChar",
",",
"S... | Register the GATT table into baBLE. | [
"Register",
"the",
"GATT",
"table",
"into",
"baBLE",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L134-L150 |
23,942 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface.set_advertising | def set_advertising(self, enabled):
"""Toggle advertising."""
if enabled:
self.bable.set_advertising(
enabled=True,
uuids=[TileBusService.uuid],
name="V_IOTile ",
company_id=ArchManuID,
advertising_data=self._advertisement(),
scan_response=self._scan_response(),
sync=True
)
else:
try:
self.bable.set_advertising(enabled=False, sync=True)
except bable_interface.BaBLEException:
# If advertising is already disabled
pass | python | def set_advertising(self, enabled):
if enabled:
self.bable.set_advertising(
enabled=True,
uuids=[TileBusService.uuid],
name="V_IOTile ",
company_id=ArchManuID,
advertising_data=self._advertisement(),
scan_response=self._scan_response(),
sync=True
)
else:
try:
self.bable.set_advertising(enabled=False, sync=True)
except bable_interface.BaBLEException:
# If advertising is already disabled
pass | [
"def",
"set_advertising",
"(",
"self",
",",
"enabled",
")",
":",
"if",
"enabled",
":",
"self",
".",
"bable",
".",
"set_advertising",
"(",
"enabled",
"=",
"True",
",",
"uuids",
"=",
"[",
"TileBusService",
".",
"uuid",
"]",
",",
"name",
"=",
"\"V_IOTile \"... | Toggle advertising. | [
"Toggle",
"advertising",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L160-L177 |
23,943 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface._advertisement | def _advertisement(self):
"""Create advertisement data."""
# Flags are
# bit 0: whether we have pending data
# bit 1: whether we are in a low voltage state
# bit 2: whether another user is connected
# bit 3: whether we support robust reports
# bit 4: whether we allow fast writes
flags = int(self.device.pending_data) | (0 << 1) | (0 << 2) | (1 << 3) | (1 << 4)
return struct.pack("<LH", self.device.iotile_id, flags) | python | def _advertisement(self):
# Flags are
# bit 0: whether we have pending data
# bit 1: whether we are in a low voltage state
# bit 2: whether another user is connected
# bit 3: whether we support robust reports
# bit 4: whether we allow fast writes
flags = int(self.device.pending_data) | (0 << 1) | (0 << 2) | (1 << 3) | (1 << 4)
return struct.pack("<LH", self.device.iotile_id, flags) | [
"def",
"_advertisement",
"(",
"self",
")",
":",
"# Flags are",
"# bit 0: whether we have pending data",
"# bit 1: whether we are in a low voltage state",
"# bit 2: whether another user is connected",
"# bit 3: whether we support robust reports",
"# bit 4: whether we allow fast writes",
"flag... | Create advertisement data. | [
"Create",
"advertisement",
"data",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L179-L189 |
23,944 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface._scan_response | def _scan_response(self):
"""Create scan response data."""
voltage = struct.pack("<H", int(self.voltage*256))
reading = struct.pack("<HLLL", 0xFFFF, 0, 0, 0)
response = voltage + reading
return response | python | def _scan_response(self):
voltage = struct.pack("<H", int(self.voltage*256))
reading = struct.pack("<HLLL", 0xFFFF, 0, 0, 0)
response = voltage + reading
return response | [
"def",
"_scan_response",
"(",
"self",
")",
":",
"voltage",
"=",
"struct",
".",
"pack",
"(",
"\"<H\"",
",",
"int",
"(",
"self",
".",
"voltage",
"*",
"256",
")",
")",
"reading",
"=",
"struct",
".",
"pack",
"(",
"\"<HLLL\"",
",",
"0xFFFF",
",",
"0",
"... | Create scan response data. | [
"Create",
"scan",
"response",
"data",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L191-L198 |
23,945 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface.stop_sync | def stop_sync(self):
"""Safely stop this BLED112 instance without leaving it in a weird state."""
# Disconnect connected device
if self.connected:
self.disconnect_sync(self._connection_handle)
# Disable advertising
self.set_advertising(False)
# Stop the baBLE interface
self.bable.stop()
self.actions.queue.clear() | python | def stop_sync(self):
# Disconnect connected device
if self.connected:
self.disconnect_sync(self._connection_handle)
# Disable advertising
self.set_advertising(False)
# Stop the baBLE interface
self.bable.stop()
self.actions.queue.clear() | [
"def",
"stop_sync",
"(",
"self",
")",
":",
"# Disconnect connected device",
"if",
"self",
".",
"connected",
":",
"self",
".",
"disconnect_sync",
"(",
"self",
".",
"_connection_handle",
")",
"# Disable advertising",
"self",
".",
"set_advertising",
"(",
"False",
")"... | Safely stop this BLED112 instance without leaving it in a weird state. | [
"Safely",
"stop",
"this",
"BLED112",
"instance",
"without",
"leaving",
"it",
"in",
"a",
"weird",
"state",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L200-L212 |
23,946 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface.disconnect_sync | def disconnect_sync(self, connection_handle):
"""Synchronously disconnect from whoever has connected to us
Args:
connection_handle (int): The handle of the connection we wish to disconnect.
"""
self.bable.disconnect(connection_handle=connection_handle, sync=True) | python | def disconnect_sync(self, connection_handle):
self.bable.disconnect(connection_handle=connection_handle, sync=True) | [
"def",
"disconnect_sync",
"(",
"self",
",",
"connection_handle",
")",
":",
"self",
".",
"bable",
".",
"disconnect",
"(",
"connection_handle",
"=",
"connection_handle",
",",
"sync",
"=",
"True",
")"
] | Synchronously disconnect from whoever has connected to us
Args:
connection_handle (int): The handle of the connection we wish to disconnect. | [
"Synchronously",
"disconnect",
"from",
"whoever",
"has",
"connected",
"to",
"us"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L214-L221 |
23,947 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface._stream_data | def _stream_data(self, chunk=None):
"""Stream reports to the ble client in 20 byte chunks
Args:
chunk (bytearray): A chunk that should be sent instead of requesting a
new chunk from the pending reports.
"""
# If we failed to transmit a chunk, we will be requeued with an argument
self._stream_sm_running = True
if chunk is None:
chunk = self._next_streaming_chunk(20)
if chunk is None or len(chunk) == 0:
self._stream_sm_running = False
return
try:
self._send_notification(StreamingChar.value_handle, chunk)
self._defer(self._stream_data)
except bable_interface.BaBLEException as err:
if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again
time.sleep(0.05)
self._defer(self._stream_data, [chunk])
else:
self._audit('ErrorStreamingReport') # If there was an error, stop streaming but don't choke
self._logger.exception("Error while streaming data") | python | def _stream_data(self, chunk=None):
# If we failed to transmit a chunk, we will be requeued with an argument
self._stream_sm_running = True
if chunk is None:
chunk = self._next_streaming_chunk(20)
if chunk is None or len(chunk) == 0:
self._stream_sm_running = False
return
try:
self._send_notification(StreamingChar.value_handle, chunk)
self._defer(self._stream_data)
except bable_interface.BaBLEException as err:
if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again
time.sleep(0.05)
self._defer(self._stream_data, [chunk])
else:
self._audit('ErrorStreamingReport') # If there was an error, stop streaming but don't choke
self._logger.exception("Error while streaming data") | [
"def",
"_stream_data",
"(",
"self",
",",
"chunk",
"=",
"None",
")",
":",
"# If we failed to transmit a chunk, we will be requeued with an argument",
"self",
".",
"_stream_sm_running",
"=",
"True",
"if",
"chunk",
"is",
"None",
":",
"chunk",
"=",
"self",
".",
"_next_s... | Stream reports to the ble client in 20 byte chunks
Args:
chunk (bytearray): A chunk that should be sent instead of requesting a
new chunk from the pending reports. | [
"Stream",
"reports",
"to",
"the",
"ble",
"client",
"in",
"20",
"byte",
"chunks"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L446-L473 |
23,948 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface._send_trace | def _send_trace(self, chunk=None):
"""Stream tracing data to the ble client in 20 byte chunks
Args:
chunk (bytearray): A chunk that should be sent instead of requesting a
new chunk from the pending reports.
"""
self._trace_sm_running = True
# If we failed to transmit a chunk, we will be requeued with an argument
if chunk is None:
chunk = self._next_tracing_chunk(20)
if chunk is None or len(chunk) == 0:
self._trace_sm_running = False
return
try:
self._send_notification(TracingChar.value_handle, chunk)
self._defer(self._send_trace)
except bable_interface.BaBLEException as err:
if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again
time.sleep(0.05)
self._defer(self._send_trace, [chunk])
else:
self._audit('ErrorStreamingTrace') # If there was an error, stop streaming but don't choke
self._logger.exception("Error while tracing data") | python | def _send_trace(self, chunk=None):
self._trace_sm_running = True
# If we failed to transmit a chunk, we will be requeued with an argument
if chunk is None:
chunk = self._next_tracing_chunk(20)
if chunk is None or len(chunk) == 0:
self._trace_sm_running = False
return
try:
self._send_notification(TracingChar.value_handle, chunk)
self._defer(self._send_trace)
except bable_interface.BaBLEException as err:
if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again
time.sleep(0.05)
self._defer(self._send_trace, [chunk])
else:
self._audit('ErrorStreamingTrace') # If there was an error, stop streaming but don't choke
self._logger.exception("Error while tracing data") | [
"def",
"_send_trace",
"(",
"self",
",",
"chunk",
"=",
"None",
")",
":",
"self",
".",
"_trace_sm_running",
"=",
"True",
"# If we failed to transmit a chunk, we will be requeued with an argument",
"if",
"chunk",
"is",
"None",
":",
"chunk",
"=",
"self",
".",
"_next_tra... | Stream tracing data to the ble client in 20 byte chunks
Args:
chunk (bytearray): A chunk that should be sent instead of requesting a
new chunk from the pending reports. | [
"Stream",
"tracing",
"data",
"to",
"the",
"ble",
"client",
"in",
"20",
"byte",
"chunks"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L475-L501 |
23,949 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py | NativeBLEVirtualInterface.process | def process(self):
"""Periodic nonblocking processes"""
super(NativeBLEVirtualInterface, self).process()
if (not self._stream_sm_running) and (not self.reports.empty()):
self._stream_data()
if (not self._trace_sm_running) and (not self.traces.empty()):
self._send_trace() | python | def process(self):
super(NativeBLEVirtualInterface, self).process()
if (not self._stream_sm_running) and (not self.reports.empty()):
self._stream_data()
if (not self._trace_sm_running) and (not self.traces.empty()):
self._send_trace() | [
"def",
"process",
"(",
"self",
")",
":",
"super",
"(",
"NativeBLEVirtualInterface",
",",
"self",
")",
".",
"process",
"(",
")",
"if",
"(",
"not",
"self",
".",
"_stream_sm_running",
")",
"and",
"(",
"not",
"self",
".",
"reports",
".",
"empty",
"(",
")",... | Periodic nonblocking processes | [
"Periodic",
"nonblocking",
"processes"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L503-L512 |
23,950 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient._populate_name_map | async def _populate_name_map(self):
"""Populate the name map of services as reported by the supervisor"""
services = await self.sync_services()
with self._state_lock:
self.services = services
for i, name in enumerate(self.services.keys()):
self._name_map[i] = name | python | async def _populate_name_map(self):
services = await self.sync_services()
with self._state_lock:
self.services = services
for i, name in enumerate(self.services.keys()):
self._name_map[i] = name | [
"async",
"def",
"_populate_name_map",
"(",
"self",
")",
":",
"services",
"=",
"await",
"self",
".",
"sync_services",
"(",
")",
"with",
"self",
".",
"_state_lock",
":",
"self",
".",
"services",
"=",
"services",
"for",
"i",
",",
"name",
"in",
"enumerate",
... | Populate the name map of services as reported by the supervisor | [
"Populate",
"the",
"name",
"map",
"of",
"services",
"as",
"reported",
"by",
"the",
"supervisor"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L87-L96 |
23,951 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient.local_service | def local_service(self, name_or_id):
"""Get the locally synced information for a service.
This method is safe to call outside of the background event loop
without any race condition. Internally it uses a thread-safe mutex to
protect the local copies of supervisor data and ensure that it cannot
change while this method is iterating over it.
Args:
name_or_id (string or int): Either a short name for the service or
a numeric id.
Returns:
ServiceState: the current state of the service synced locally
at the time of the call.
"""
if not self._loop.inside_loop():
self._state_lock.acquire()
try:
if isinstance(name_or_id, int):
if name_or_id not in self._name_map:
raise ArgumentError("Unknown ID used to look up service", id=name_or_id)
name = self._name_map[name_or_id]
else:
name = name_or_id
if name not in self.services:
raise ArgumentError("Unknown service name", name=name)
return copy(self.services[name])
finally:
if not self._loop.inside_loop():
self._state_lock.release() | python | def local_service(self, name_or_id):
if not self._loop.inside_loop():
self._state_lock.acquire()
try:
if isinstance(name_or_id, int):
if name_or_id not in self._name_map:
raise ArgumentError("Unknown ID used to look up service", id=name_or_id)
name = self._name_map[name_or_id]
else:
name = name_or_id
if name not in self.services:
raise ArgumentError("Unknown service name", name=name)
return copy(self.services[name])
finally:
if not self._loop.inside_loop():
self._state_lock.release() | [
"def",
"local_service",
"(",
"self",
",",
"name_or_id",
")",
":",
"if",
"not",
"self",
".",
"_loop",
".",
"inside_loop",
"(",
")",
":",
"self",
".",
"_state_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"isinstance",
"(",
"name_or_id",
",",
"int",... | Get the locally synced information for a service.
This method is safe to call outside of the background event loop
without any race condition. Internally it uses a thread-safe mutex to
protect the local copies of supervisor data and ensure that it cannot
change while this method is iterating over it.
Args:
name_or_id (string or int): Either a short name for the service or
a numeric id.
Returns:
ServiceState: the current state of the service synced locally
at the time of the call. | [
"Get",
"the",
"locally",
"synced",
"information",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L108-L141 |
23,952 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient.local_services | def local_services(self):
"""Get a list of id, name pairs for all of the known synced services.
This method is safe to call outside of the background event loop
without any race condition. Internally it uses a thread-safe mutex to
protect the local copies of supervisor data and ensure that it cannot
change while this method is iterating over it.
Returns:
list (id, name): A list of tuples with id and service name sorted by id
from low to high
"""
if not self._loop.inside_loop():
self._state_lock.acquire()
try:
return sorted([(index, name) for index, name in self._name_map.items()], key=lambda element: element[0])
finally:
if not self._loop.inside_loop():
self._state_lock.release() | python | def local_services(self):
if not self._loop.inside_loop():
self._state_lock.acquire()
try:
return sorted([(index, name) for index, name in self._name_map.items()], key=lambda element: element[0])
finally:
if not self._loop.inside_loop():
self._state_lock.release() | [
"def",
"local_services",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_loop",
".",
"inside_loop",
"(",
")",
":",
"self",
".",
"_state_lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"sorted",
"(",
"[",
"(",
"index",
",",
"name",
")",
"f... | Get a list of id, name pairs for all of the known synced services.
This method is safe to call outside of the background event loop
without any race condition. Internally it uses a thread-safe mutex to
protect the local copies of supervisor data and ensure that it cannot
change while this method is iterating over it.
Returns:
list (id, name): A list of tuples with id and service name sorted by id
from low to high | [
"Get",
"a",
"list",
"of",
"id",
"name",
"pairs",
"for",
"all",
"of",
"the",
"known",
"synced",
"services",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L143-L163 |
23,953 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient.sync_services | async def sync_services(self):
"""Poll the current state of all services.
Returns:
dict: A dictionary mapping service name to service status
"""
services = {}
servs = await self.list_services()
for i, serv in enumerate(servs):
info = await self.service_info(serv)
status = await self.service_status(serv)
messages = await self.get_messages(serv)
headline = await self.get_headline(serv)
services[serv] = states.ServiceState(info['short_name'], info['long_name'], info['preregistered'], i)
services[serv].state = status['numeric_status']
for message in messages:
services[serv].post_message(message.level, message.message, message.count, message.created)
if headline is not None:
services[serv].set_headline(headline.level, headline.message, headline.created)
return services | python | async def sync_services(self):
services = {}
servs = await self.list_services()
for i, serv in enumerate(servs):
info = await self.service_info(serv)
status = await self.service_status(serv)
messages = await self.get_messages(serv)
headline = await self.get_headline(serv)
services[serv] = states.ServiceState(info['short_name'], info['long_name'], info['preregistered'], i)
services[serv].state = status['numeric_status']
for message in messages:
services[serv].post_message(message.level, message.message, message.count, message.created)
if headline is not None:
services[serv].set_headline(headline.level, headline.message, headline.created)
return services | [
"async",
"def",
"sync_services",
"(",
"self",
")",
":",
"services",
"=",
"{",
"}",
"servs",
"=",
"await",
"self",
".",
"list_services",
"(",
")",
"for",
"i",
",",
"serv",
"in",
"enumerate",
"(",
"servs",
")",
":",
"info",
"=",
"await",
"self",
".",
... | Poll the current state of all services.
Returns:
dict: A dictionary mapping service name to service status | [
"Poll",
"the",
"current",
"state",
"of",
"all",
"services",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L165-L189 |
23,954 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient.post_state | def post_state(self, name, state):
"""Asynchronously try to update the state for a service.
If the update fails, nothing is reported because we don't wait for a
response from the server. This function will return immmediately and
not block.
Args:
name (string): The name of the service
state (int): The new state of the service
"""
self.post_command(OPERATIONS.CMD_UPDATE_STATE,
{'name': name, 'new_status': state}) | python | def post_state(self, name, state):
self.post_command(OPERATIONS.CMD_UPDATE_STATE,
{'name': name, 'new_status': state}) | [
"def",
"post_state",
"(",
"self",
",",
"name",
",",
"state",
")",
":",
"self",
".",
"post_command",
"(",
"OPERATIONS",
".",
"CMD_UPDATE_STATE",
",",
"{",
"'name'",
":",
"name",
",",
"'new_status'",
":",
"state",
"}",
")"
] | Asynchronously try to update the state for a service.
If the update fails, nothing is reported because we don't wait for a
response from the server. This function will return immmediately and
not block.
Args:
name (string): The name of the service
state (int): The new state of the service | [
"Asynchronously",
"try",
"to",
"update",
"the",
"state",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L287-L300 |
23,955 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient.post_error | def post_error(self, name, message):
"""Asynchronously post a user facing error message about a service.
Args:
name (string): The name of the service
message (string): The user facing error message that will be stored
for the service and can be queried later.
"""
self.post_command(OPERATIONS.CMD_POST_MESSAGE,
_create_message(name, states.ERROR_LEVEL, message)) | python | def post_error(self, name, message):
self.post_command(OPERATIONS.CMD_POST_MESSAGE,
_create_message(name, states.ERROR_LEVEL, message)) | [
"def",
"post_error",
"(",
"self",
",",
"name",
",",
"message",
")",
":",
"self",
".",
"post_command",
"(",
"OPERATIONS",
".",
"CMD_POST_MESSAGE",
",",
"_create_message",
"(",
"name",
",",
"states",
".",
"ERROR_LEVEL",
",",
"message",
")",
")"
] | Asynchronously post a user facing error message about a service.
Args:
name (string): The name of the service
message (string): The user facing error message that will be stored
for the service and can be queried later. | [
"Asynchronously",
"post",
"a",
"user",
"facing",
"error",
"message",
"about",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L302-L312 |
23,956 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient.post_warning | def post_warning(self, name, message):
"""Asynchronously post a user facing warning message about a service.
Args:
name (string): The name of the service
message (string): The user facing warning message that will be stored
for the service and can be queried later.
"""
self.post_command(OPERATIONS.CMD_POST_MESSAGE,
_create_message(name, states.WARNING_LEVEL, message)) | python | def post_warning(self, name, message):
self.post_command(OPERATIONS.CMD_POST_MESSAGE,
_create_message(name, states.WARNING_LEVEL, message)) | [
"def",
"post_warning",
"(",
"self",
",",
"name",
",",
"message",
")",
":",
"self",
".",
"post_command",
"(",
"OPERATIONS",
".",
"CMD_POST_MESSAGE",
",",
"_create_message",
"(",
"name",
",",
"states",
".",
"WARNING_LEVEL",
",",
"message",
")",
")"
] | Asynchronously post a user facing warning message about a service.
Args:
name (string): The name of the service
message (string): The user facing warning message that will be stored
for the service and can be queried later. | [
"Asynchronously",
"post",
"a",
"user",
"facing",
"warning",
"message",
"about",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L314-L324 |
23,957 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient.post_info | def post_info(self, name, message):
"""Asynchronously post a user facing info message about a service.
Args:
name (string): The name of the service
message (string): The user facing info message that will be stored
for the service and can be queried later.
"""
self.post_command(OPERATIONS.CMD_POST_MESSAGE,
_create_message(name, states.INFO_LEVEL, message)) | python | def post_info(self, name, message):
self.post_command(OPERATIONS.CMD_POST_MESSAGE,
_create_message(name, states.INFO_LEVEL, message)) | [
"def",
"post_info",
"(",
"self",
",",
"name",
",",
"message",
")",
":",
"self",
".",
"post_command",
"(",
"OPERATIONS",
".",
"CMD_POST_MESSAGE",
",",
"_create_message",
"(",
"name",
",",
"states",
".",
"INFO_LEVEL",
",",
"message",
")",
")"
] | Asynchronously post a user facing info message about a service.
Args:
name (string): The name of the service
message (string): The user facing info message that will be stored
for the service and can be queried later. | [
"Asynchronously",
"post",
"a",
"user",
"facing",
"info",
"message",
"about",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L326-L335 |
23,958 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient._on_status_change | async def _on_status_change(self, update):
"""Update a service that has its status updated."""
info = update['payload']
new_number = info['new_status']
name = update['service']
if name not in self.services:
return
with self._state_lock:
is_changed = self.services[name].state != new_number
self.services[name].state = new_number
# Notify about this service state change if anyone is listening
if self._on_change_callback and is_changed:
self._on_change_callback(name, self.services[name].id, new_number, False, False) | python | async def _on_status_change(self, update):
info = update['payload']
new_number = info['new_status']
name = update['service']
if name not in self.services:
return
with self._state_lock:
is_changed = self.services[name].state != new_number
self.services[name].state = new_number
# Notify about this service state change if anyone is listening
if self._on_change_callback and is_changed:
self._on_change_callback(name, self.services[name].id, new_number, False, False) | [
"async",
"def",
"_on_status_change",
"(",
"self",
",",
"update",
")",
":",
"info",
"=",
"update",
"[",
"'payload'",
"]",
"new_number",
"=",
"info",
"[",
"'new_status'",
"]",
"name",
"=",
"update",
"[",
"'service'",
"]",
"if",
"name",
"not",
"in",
"self",... | Update a service that has its status updated. | [
"Update",
"a",
"service",
"that",
"has",
"its",
"status",
"updated",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L408-L424 |
23,959 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient._on_heartbeat | async def _on_heartbeat(self, update):
"""Receive a new heartbeat for a service."""
name = update['service']
if name not in self.services:
return
with self._state_lock:
self.services[name].heartbeat() | python | async def _on_heartbeat(self, update):
name = update['service']
if name not in self.services:
return
with self._state_lock:
self.services[name].heartbeat() | [
"async",
"def",
"_on_heartbeat",
"(",
"self",
",",
"update",
")",
":",
"name",
"=",
"update",
"[",
"'service'",
"]",
"if",
"name",
"not",
"in",
"self",
".",
"services",
":",
"return",
"with",
"self",
".",
"_state_lock",
":",
"self",
".",
"services",
"[... | Receive a new heartbeat for a service. | [
"Receive",
"a",
"new",
"heartbeat",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L446-L455 |
23,960 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient._on_message | async def _on_message(self, update):
"""Receive a message from a service."""
name = update['service']
message_obj = update['payload']
if name not in self.services:
return
with self._state_lock:
self.services[name].post_message(message_obj['level'], message_obj['message']) | python | async def _on_message(self, update):
name = update['service']
message_obj = update['payload']
if name not in self.services:
return
with self._state_lock:
self.services[name].post_message(message_obj['level'], message_obj['message']) | [
"async",
"def",
"_on_message",
"(",
"self",
",",
"update",
")",
":",
"name",
"=",
"update",
"[",
"'service'",
"]",
"message_obj",
"=",
"update",
"[",
"'payload'",
"]",
"if",
"name",
"not",
"in",
"self",
".",
"services",
":",
"return",
"with",
"self",
"... | Receive a message from a service. | [
"Receive",
"a",
"message",
"from",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L457-L467 |
23,961 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient._on_headline | async def _on_headline(self, update):
"""Receive a headline from a service."""
name = update['service']
message_obj = update['payload']
new_headline = False
if name not in self.services:
return
with self._state_lock:
self.services[name].set_headline(message_obj['level'], message_obj['message'])
if self.services[name].headline.count == 1:
new_headline = True
# Notify about this service state change if anyone is listening
# headline changes are only reported if they are not duplicates
if self._on_change_callback and new_headline:
self._on_change_callback(name, self.services[name].id, self.services[name].state, False, True) | python | async def _on_headline(self, update):
name = update['service']
message_obj = update['payload']
new_headline = False
if name not in self.services:
return
with self._state_lock:
self.services[name].set_headline(message_obj['level'], message_obj['message'])
if self.services[name].headline.count == 1:
new_headline = True
# Notify about this service state change if anyone is listening
# headline changes are only reported if they are not duplicates
if self._on_change_callback and new_headline:
self._on_change_callback(name, self.services[name].id, self.services[name].state, False, True) | [
"async",
"def",
"_on_headline",
"(",
"self",
",",
"update",
")",
":",
"name",
"=",
"update",
"[",
"'service'",
"]",
"message_obj",
"=",
"update",
"[",
"'payload'",
"]",
"new_headline",
"=",
"False",
"if",
"name",
"not",
"in",
"self",
".",
"services",
":"... | Receive a headline from a service. | [
"Receive",
"a",
"headline",
"from",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L469-L488 |
23,962 | iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | AsyncSupervisorClient._on_rpc_command | async def _on_rpc_command(self, event):
"""Received an RPC command that we should execute."""
payload = event['payload']
rpc_id = payload['rpc_id']
tag = payload['response_uuid']
args = payload['payload']
result = 'success'
response = b''
if self._rpc_dispatcher is None or not self._rpc_dispatcher.has_rpc(rpc_id):
result = 'rpc_not_found'
else:
try:
response = self._rpc_dispatcher.call_rpc(rpc_id, args)
if inspect.iscoroutine(response):
response = await response
except RPCInvalidArgumentsError:
result = 'invalid_arguments'
except RPCInvalidReturnValueError:
result = 'invalid_response'
except Exception: #pylint:disable=broad-except;We are being called in a background task
self._logger.exception("Exception handling RPC 0x%04X", rpc_id)
result = 'execution_exception'
message = dict(response_uuid=tag, result=result, response=response)
try:
await self.send_command(OPERATIONS.CMD_RESPOND_RPC, message,
MESSAGES.RespondRPCResponse)
except: #pylint:disable=bare-except;We are being called in a background worker
self._logger.exception("Error sending response to RPC 0x%04X", rpc_id) | python | async def _on_rpc_command(self, event):
payload = event['payload']
rpc_id = payload['rpc_id']
tag = payload['response_uuid']
args = payload['payload']
result = 'success'
response = b''
if self._rpc_dispatcher is None or not self._rpc_dispatcher.has_rpc(rpc_id):
result = 'rpc_not_found'
else:
try:
response = self._rpc_dispatcher.call_rpc(rpc_id, args)
if inspect.iscoroutine(response):
response = await response
except RPCInvalidArgumentsError:
result = 'invalid_arguments'
except RPCInvalidReturnValueError:
result = 'invalid_response'
except Exception: #pylint:disable=broad-except;We are being called in a background task
self._logger.exception("Exception handling RPC 0x%04X", rpc_id)
result = 'execution_exception'
message = dict(response_uuid=tag, result=result, response=response)
try:
await self.send_command(OPERATIONS.CMD_RESPOND_RPC, message,
MESSAGES.RespondRPCResponse)
except: #pylint:disable=bare-except;We are being called in a background worker
self._logger.exception("Error sending response to RPC 0x%04X", rpc_id) | [
"async",
"def",
"_on_rpc_command",
"(",
"self",
",",
"event",
")",
":",
"payload",
"=",
"event",
"[",
"'payload'",
"]",
"rpc_id",
"=",
"payload",
"[",
"'rpc_id'",
"]",
"tag",
"=",
"payload",
"[",
"'response_uuid'",
"]",
"args",
"=",
"payload",
"[",
"'pay... | Received an RPC command that we should execute. | [
"Received",
"an",
"RPC",
"command",
"that",
"we",
"should",
"execute",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L490-L522 |
23,963 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/packing.py | _decode_datetime | def _decode_datetime(obj):
"""Decode a msgpack'ed datetime."""
if '__datetime__' in obj:
obj = datetime.datetime.strptime(obj['as_str'].decode(), "%Y%m%dT%H:%M:%S.%f")
return obj | python | def _decode_datetime(obj):
if '__datetime__' in obj:
obj = datetime.datetime.strptime(obj['as_str'].decode(), "%Y%m%dT%H:%M:%S.%f")
return obj | [
"def",
"_decode_datetime",
"(",
"obj",
")",
":",
"if",
"'__datetime__'",
"in",
"obj",
":",
"obj",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"obj",
"[",
"'as_str'",
"]",
".",
"decode",
"(",
")",
",",
"\"%Y%m%dT%H:%M:%S.%f\"",
")",
"return",
... | Decode a msgpack'ed datetime. | [
"Decode",
"a",
"msgpack",
"ed",
"datetime",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/packing.py#L19-L24 |
23,964 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/packing.py | _encode_datetime | def _encode_datetime(obj):
"""Encode a msgpck'ed datetime."""
if isinstance(obj, datetime.datetime):
obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
return obj | python | def _encode_datetime(obj):
if isinstance(obj, datetime.datetime):
obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
return obj | [
"def",
"_encode_datetime",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"obj",
"=",
"{",
"'__datetime__'",
":",
"True",
",",
"'as_str'",
":",
"obj",
".",
"strftime",
"(",
"\"%Y%m%dT%H:%M:%S.%f\"",
")",
... | Encode a msgpck'ed datetime. | [
"Encode",
"a",
"msgpck",
"ed",
"datetime",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/packing.py#L27-L32 |
23,965 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cyglink.py | _versioned_lib_suffix | def _versioned_lib_suffix(env, suffix, version):
"""Generate versioned shared library suffix from a unversioned one.
If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'"""
Verbose = False
if Verbose:
print("_versioned_lib_suffix: suffix= ", suffix)
print("_versioned_lib_suffix: version= ", version)
cygversion = re.sub('\.', '-', version)
if not suffix.startswith('-' + cygversion):
suffix = '-' + cygversion + suffix
if Verbose:
print("_versioned_lib_suffix: return suffix= ", suffix)
return suffix | python | def _versioned_lib_suffix(env, suffix, version):
"""Generate versioned shared library suffix from a unversioned one.
If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'"""
Verbose = False
if Verbose:
print("_versioned_lib_suffix: suffix= ", suffix)
print("_versioned_lib_suffix: version= ", version)
cygversion = re.sub('\.', '-', version)
if not suffix.startswith('-' + cygversion):
suffix = '-' + cygversion + suffix
if Verbose:
print("_versioned_lib_suffix: return suffix= ", suffix)
return suffix | [
"def",
"_versioned_lib_suffix",
"(",
"env",
",",
"suffix",
",",
"version",
")",
":",
"Verbose",
"=",
"False",
"if",
"Verbose",
":",
"print",
"(",
"\"_versioned_lib_suffix: suffix= \"",
",",
"suffix",
")",
"print",
"(",
"\"_versioned_lib_suffix: version= \"",
",",
... | Generate versioned shared library suffix from a unversioned one.
If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll | [
"Generate",
"versioned",
"shared",
"library",
"suffix",
"from",
"a",
"unversioned",
"one",
".",
"If",
"suffix",
"=",
".",
"dll",
"and",
"version",
"=",
"0",
".",
"1",
".",
"2",
"then",
"it",
"returns",
"-",
"0",
"-",
"1",
"-",
"2",
".",
"dll"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cyglink.py#L128-L140 |
23,966 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cyglink.py | generate | def generate(env):
"""Add Builders and construction variables for cyglink to an Environment."""
gnulink.generate(env)
env['LINKFLAGS'] = SCons.Util.CLVar('-Wl,-no-undefined')
env['SHLINKCOM'] = shlib_action
env['LDMODULECOM'] = ldmod_action
env.Append(SHLIBEMITTER = [shlib_emitter])
env.Append(LDMODULEEMITTER = [ldmod_emitter])
env['SHLIBPREFIX'] = 'cyg'
env['SHLIBSUFFIX'] = '.dll'
env['IMPLIBPREFIX'] = 'lib'
env['IMPLIBSUFFIX'] = '.dll.a'
# Variables used by versioned shared libraries
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS'
# SHLIBVERSIONFLAGS and LDMODULEVERSIONFLAGS are same as in gnulink...
# LINKCALLBACKS are NOT inherited from gnulink
env['LINKCALLBACKS'] = {
'VersionedShLibSuffix' : _versioned_lib_suffix,
'VersionedLdModSuffix' : _versioned_lib_suffix,
'VersionedImpLibSuffix' : _versioned_lib_suffix,
'VersionedShLibName' : link._versioned_shlib_name,
'VersionedLdModName' : link._versioned_ldmod_name,
'VersionedShLibImpLibName' : lambda *args: _versioned_implib_name(*args, libtype='ShLib'),
'VersionedLdModImpLibName' : lambda *args: _versioned_implib_name(*args, libtype='LdMod'),
'VersionedShLibImpLibSymlinks' : lambda *args: _versioned_implib_symlinks(*args, libtype='ShLib'),
'VersionedLdModImpLibSymlinks' : lambda *args: _versioned_implib_symlinks(*args, libtype='LdMod'),
}
# these variables were set by gnulink but are not used in cyglink
try: del env['_SHLIBSONAME']
except KeyError: pass
try: del env['_LDMODULESONAME']
except KeyError: pass | python | def generate(env):
gnulink.generate(env)
env['LINKFLAGS'] = SCons.Util.CLVar('-Wl,-no-undefined')
env['SHLINKCOM'] = shlib_action
env['LDMODULECOM'] = ldmod_action
env.Append(SHLIBEMITTER = [shlib_emitter])
env.Append(LDMODULEEMITTER = [ldmod_emitter])
env['SHLIBPREFIX'] = 'cyg'
env['SHLIBSUFFIX'] = '.dll'
env['IMPLIBPREFIX'] = 'lib'
env['IMPLIBSUFFIX'] = '.dll.a'
# Variables used by versioned shared libraries
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS'
# SHLIBVERSIONFLAGS and LDMODULEVERSIONFLAGS are same as in gnulink...
# LINKCALLBACKS are NOT inherited from gnulink
env['LINKCALLBACKS'] = {
'VersionedShLibSuffix' : _versioned_lib_suffix,
'VersionedLdModSuffix' : _versioned_lib_suffix,
'VersionedImpLibSuffix' : _versioned_lib_suffix,
'VersionedShLibName' : link._versioned_shlib_name,
'VersionedLdModName' : link._versioned_ldmod_name,
'VersionedShLibImpLibName' : lambda *args: _versioned_implib_name(*args, libtype='ShLib'),
'VersionedLdModImpLibName' : lambda *args: _versioned_implib_name(*args, libtype='LdMod'),
'VersionedShLibImpLibSymlinks' : lambda *args: _versioned_implib_symlinks(*args, libtype='ShLib'),
'VersionedLdModImpLibSymlinks' : lambda *args: _versioned_implib_symlinks(*args, libtype='LdMod'),
}
# these variables were set by gnulink but are not used in cyglink
try: del env['_SHLIBSONAME']
except KeyError: pass
try: del env['_LDMODULESONAME']
except KeyError: pass | [
"def",
"generate",
"(",
"env",
")",
":",
"gnulink",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'LINKFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'-Wl,-no-undefined'",
")",
"env",
"[",
"'SHLINKCOM'",
"]",
"=",
"shlib_action",
"env",
... | Add Builders and construction variables for cyglink to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"cyglink",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cyglink.py#L185-L225 |
23,967 | iotile/coretools | iotilecore/iotile/core/utilities/validating_dispatcher.py | ValidatingDispatcher.dispatch | def dispatch(self, message):
"""Dispatch a message to a callback based on its schema.
Args:
message (dict): The message to dispatch
"""
for validator, callback in self.validators:
if not validator.matches(message):
continue
callback(message)
return
raise ArgumentError("No handler was registered for message", message=message) | python | def dispatch(self, message):
for validator, callback in self.validators:
if not validator.matches(message):
continue
callback(message)
return
raise ArgumentError("No handler was registered for message", message=message) | [
"def",
"dispatch",
"(",
"self",
",",
"message",
")",
":",
"for",
"validator",
",",
"callback",
"in",
"self",
".",
"validators",
":",
"if",
"not",
"validator",
".",
"matches",
"(",
"message",
")",
":",
"continue",
"callback",
"(",
"message",
")",
"return"... | Dispatch a message to a callback based on its schema.
Args:
message (dict): The message to dispatch | [
"Dispatch",
"a",
"message",
"to",
"a",
"callback",
"based",
"on",
"its",
"schema",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/validating_dispatcher.py#L27-L41 |
23,968 | iotile/coretools | iotilebuild/iotile/build/scripts/iotile_emulate.py | main | def main(raw_args=None):
"""Run the iotile-emulate script.
Args:
raw_args (list): Optional list of commmand line arguments. If not
passed these are pulled from sys.argv.
"""
if raw_args is None:
raw_args = sys.argv[1:]
parser = build_parser()
args = parser.parse_args(raw_args)
if args.firmware_image is None and args.gdb is None:
print("You must specify either a firmware image or attach a debugger with --gdb <PORT>")
return 1
test_args = ['qemu-system-gnuarmeclipse', '-verbose', '-verbose', '-board', 'STM32F0-Discovery',
'-nographic', '-monitor', 'null', '-serial', 'null', '--semihosting-config',
'enable=on,target=native', '-d', 'unimp,guest_errors']
if args.firmware_image:
test_args += ['-image', args.firmware_image]
if args.gdb:
test_args += ['--gdb', 'tcp::%d' % args.gdb]
proc = subprocess.Popen(test_args, stdout=sys.stdout, stderr=sys.stderr)
try:
proc.communicate()
except KeyboardInterrupt:
proc.terminate()
return 0 | python | def main(raw_args=None):
if raw_args is None:
raw_args = sys.argv[1:]
parser = build_parser()
args = parser.parse_args(raw_args)
if args.firmware_image is None and args.gdb is None:
print("You must specify either a firmware image or attach a debugger with --gdb <PORT>")
return 1
test_args = ['qemu-system-gnuarmeclipse', '-verbose', '-verbose', '-board', 'STM32F0-Discovery',
'-nographic', '-monitor', 'null', '-serial', 'null', '--semihosting-config',
'enable=on,target=native', '-d', 'unimp,guest_errors']
if args.firmware_image:
test_args += ['-image', args.firmware_image]
if args.gdb:
test_args += ['--gdb', 'tcp::%d' % args.gdb]
proc = subprocess.Popen(test_args, stdout=sys.stdout, stderr=sys.stderr)
try:
proc.communicate()
except KeyboardInterrupt:
proc.terminate()
return 0 | [
"def",
"main",
"(",
"raw_args",
"=",
"None",
")",
":",
"if",
"raw_args",
"is",
"None",
":",
"raw_args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"build_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"raw_args",
... | Run the iotile-emulate script.
Args:
raw_args (list): Optional list of commmand line arguments. If not
passed these are pulled from sys.argv. | [
"Run",
"the",
"iotile",
"-",
"emulate",
"script",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/scripts/iotile_emulate.py#L30-L65 |
23,969 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/qt.py | _detect | def _detect(env):
"""Not really safe, but fast method to detect the QT library"""
QTDIR = None
if not QTDIR:
QTDIR = env.get('QTDIR',None)
if not QTDIR:
QTDIR = os.environ.get('QTDIR',None)
if not QTDIR:
moc = env.WhereIs('moc')
if moc:
QTDIR = os.path.dirname(os.path.dirname(moc))
SCons.Warnings.warn(
QtdirNotFound,
"Could not detect qt, using moc executable as a hint (QTDIR=%s)" % QTDIR)
else:
QTDIR = None
SCons.Warnings.warn(
QtdirNotFound,
"Could not detect qt, using empty QTDIR")
return QTDIR | python | def _detect(env):
QTDIR = None
if not QTDIR:
QTDIR = env.get('QTDIR',None)
if not QTDIR:
QTDIR = os.environ.get('QTDIR',None)
if not QTDIR:
moc = env.WhereIs('moc')
if moc:
QTDIR = os.path.dirname(os.path.dirname(moc))
SCons.Warnings.warn(
QtdirNotFound,
"Could not detect qt, using moc executable as a hint (QTDIR=%s)" % QTDIR)
else:
QTDIR = None
SCons.Warnings.warn(
QtdirNotFound,
"Could not detect qt, using empty QTDIR")
return QTDIR | [
"def",
"_detect",
"(",
"env",
")",
":",
"QTDIR",
"=",
"None",
"if",
"not",
"QTDIR",
":",
"QTDIR",
"=",
"env",
".",
"get",
"(",
"'QTDIR'",
",",
"None",
")",
"if",
"not",
"QTDIR",
":",
"QTDIR",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'QTDIR'",... | Not really safe, but fast method to detect the QT library | [
"Not",
"really",
"safe",
"but",
"fast",
"method",
"to",
"detect",
"the",
"QT",
"library"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/qt.py#L188-L207 |
23,970 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/qt.py | generate | def generate(env):
"""Add Builders and construction variables for qt to an Environment."""
CLVar = SCons.Util.CLVar
Action = SCons.Action.Action
Builder = SCons.Builder.Builder
env.SetDefault(QTDIR = _detect(env),
QT_BINPATH = os.path.join('$QTDIR', 'bin'),
QT_CPPPATH = os.path.join('$QTDIR', 'include'),
QT_LIBPATH = os.path.join('$QTDIR', 'lib'),
QT_MOC = os.path.join('$QT_BINPATH','moc'),
QT_UIC = os.path.join('$QT_BINPATH','uic'),
QT_LIB = 'qt', # may be set to qt-mt
QT_AUTOSCAN = 1, # scan for moc'able sources
# Some QT specific flags. I don't expect someone wants to
# manipulate those ...
QT_UICIMPLFLAGS = CLVar(''),
QT_UICDECLFLAGS = CLVar(''),
QT_MOCFROMHFLAGS = CLVar(''),
QT_MOCFROMCXXFLAGS = CLVar('-i'),
# suffixes/prefixes for the headers / sources to generate
QT_UICDECLPREFIX = '',
QT_UICDECLSUFFIX = '.h',
QT_UICIMPLPREFIX = 'uic_',
QT_UICIMPLSUFFIX = '$CXXFILESUFFIX',
QT_MOCHPREFIX = 'moc_',
QT_MOCHSUFFIX = '$CXXFILESUFFIX',
QT_MOCCXXPREFIX = '',
QT_MOCCXXSUFFIX = '.moc',
QT_UISUFFIX = '.ui',
# Commands for the qt support ...
# command to generate header, implementation and moc-file
# from a .ui file
QT_UICCOM = [
CLVar('$QT_UIC $QT_UICDECLFLAGS -o ${TARGETS[0]} $SOURCE'),
CLVar('$QT_UIC $QT_UICIMPLFLAGS -impl ${TARGETS[0].file} '
'-o ${TARGETS[1]} $SOURCE'),
CLVar('$QT_MOC $QT_MOCFROMHFLAGS -o ${TARGETS[2]} ${TARGETS[0]}')],
# command to generate meta object information for a class
# declarated in a header
QT_MOCFROMHCOM = (
'$QT_MOC $QT_MOCFROMHFLAGS -o ${TARGETS[0]} $SOURCE'),
# command to generate meta object information for a class
# declarated in a cpp file
QT_MOCFROMCXXCOM = [
CLVar('$QT_MOC $QT_MOCFROMCXXFLAGS -o ${TARGETS[0]} $SOURCE'),
Action(checkMocIncluded,None)])
# ... and the corresponding builders
uicBld = Builder(action=SCons.Action.Action('$QT_UICCOM', '$QT_UICCOMSTR'),
emitter=uicEmitter,
src_suffix='$QT_UISUFFIX',
suffix='$QT_UICDECLSUFFIX',
prefix='$QT_UICDECLPREFIX',
source_scanner=uicScanner)
mocBld = Builder(action={}, prefix={}, suffix={})
for h in header_extensions:
act = SCons.Action.Action('$QT_MOCFROMHCOM', '$QT_MOCFROMHCOMSTR')
mocBld.add_action(h, act)
mocBld.prefix[h] = '$QT_MOCHPREFIX'
mocBld.suffix[h] = '$QT_MOCHSUFFIX'
for cxx in cxx_suffixes:
act = SCons.Action.Action('$QT_MOCFROMCXXCOM', '$QT_MOCFROMCXXCOMSTR')
mocBld.add_action(cxx, act)
mocBld.prefix[cxx] = '$QT_MOCCXXPREFIX'
mocBld.suffix[cxx] = '$QT_MOCCXXSUFFIX'
# register the builders
env['BUILDERS']['Uic'] = uicBld
env['BUILDERS']['Moc'] = mocBld
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
static_obj.add_src_builder('Uic')
shared_obj.add_src_builder('Uic')
# We use the emitters of Program / StaticLibrary / SharedLibrary
# to scan for moc'able files
# We can't refer to the builders directly, we have to fetch them
# as Environment attributes because that sets them up to be called
# correctly later by our emitter.
env.AppendUnique(PROGEMITTER =[AutomocStatic],
SHLIBEMITTER=[AutomocShared],
LDMODULEEMITTER=[AutomocShared],
LIBEMITTER =[AutomocStatic],
# Of course, we need to link against the qt libraries
CPPPATH=["$QT_CPPPATH"],
LIBPATH=["$QT_LIBPATH"],
LIBS=['$QT_LIB']) | python | def generate(env):
CLVar = SCons.Util.CLVar
Action = SCons.Action.Action
Builder = SCons.Builder.Builder
env.SetDefault(QTDIR = _detect(env),
QT_BINPATH = os.path.join('$QTDIR', 'bin'),
QT_CPPPATH = os.path.join('$QTDIR', 'include'),
QT_LIBPATH = os.path.join('$QTDIR', 'lib'),
QT_MOC = os.path.join('$QT_BINPATH','moc'),
QT_UIC = os.path.join('$QT_BINPATH','uic'),
QT_LIB = 'qt', # may be set to qt-mt
QT_AUTOSCAN = 1, # scan for moc'able sources
# Some QT specific flags. I don't expect someone wants to
# manipulate those ...
QT_UICIMPLFLAGS = CLVar(''),
QT_UICDECLFLAGS = CLVar(''),
QT_MOCFROMHFLAGS = CLVar(''),
QT_MOCFROMCXXFLAGS = CLVar('-i'),
# suffixes/prefixes for the headers / sources to generate
QT_UICDECLPREFIX = '',
QT_UICDECLSUFFIX = '.h',
QT_UICIMPLPREFIX = 'uic_',
QT_UICIMPLSUFFIX = '$CXXFILESUFFIX',
QT_MOCHPREFIX = 'moc_',
QT_MOCHSUFFIX = '$CXXFILESUFFIX',
QT_MOCCXXPREFIX = '',
QT_MOCCXXSUFFIX = '.moc',
QT_UISUFFIX = '.ui',
# Commands for the qt support ...
# command to generate header, implementation and moc-file
# from a .ui file
QT_UICCOM = [
CLVar('$QT_UIC $QT_UICDECLFLAGS -o ${TARGETS[0]} $SOURCE'),
CLVar('$QT_UIC $QT_UICIMPLFLAGS -impl ${TARGETS[0].file} '
'-o ${TARGETS[1]} $SOURCE'),
CLVar('$QT_MOC $QT_MOCFROMHFLAGS -o ${TARGETS[2]} ${TARGETS[0]}')],
# command to generate meta object information for a class
# declarated in a header
QT_MOCFROMHCOM = (
'$QT_MOC $QT_MOCFROMHFLAGS -o ${TARGETS[0]} $SOURCE'),
# command to generate meta object information for a class
# declarated in a cpp file
QT_MOCFROMCXXCOM = [
CLVar('$QT_MOC $QT_MOCFROMCXXFLAGS -o ${TARGETS[0]} $SOURCE'),
Action(checkMocIncluded,None)])
# ... and the corresponding builders
uicBld = Builder(action=SCons.Action.Action('$QT_UICCOM', '$QT_UICCOMSTR'),
emitter=uicEmitter,
src_suffix='$QT_UISUFFIX',
suffix='$QT_UICDECLSUFFIX',
prefix='$QT_UICDECLPREFIX',
source_scanner=uicScanner)
mocBld = Builder(action={}, prefix={}, suffix={})
for h in header_extensions:
act = SCons.Action.Action('$QT_MOCFROMHCOM', '$QT_MOCFROMHCOMSTR')
mocBld.add_action(h, act)
mocBld.prefix[h] = '$QT_MOCHPREFIX'
mocBld.suffix[h] = '$QT_MOCHSUFFIX'
for cxx in cxx_suffixes:
act = SCons.Action.Action('$QT_MOCFROMCXXCOM', '$QT_MOCFROMCXXCOMSTR')
mocBld.add_action(cxx, act)
mocBld.prefix[cxx] = '$QT_MOCCXXPREFIX'
mocBld.suffix[cxx] = '$QT_MOCCXXSUFFIX'
# register the builders
env['BUILDERS']['Uic'] = uicBld
env['BUILDERS']['Moc'] = mocBld
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
static_obj.add_src_builder('Uic')
shared_obj.add_src_builder('Uic')
# We use the emitters of Program / StaticLibrary / SharedLibrary
# to scan for moc'able files
# We can't refer to the builders directly, we have to fetch them
# as Environment attributes because that sets them up to be called
# correctly later by our emitter.
env.AppendUnique(PROGEMITTER =[AutomocStatic],
SHLIBEMITTER=[AutomocShared],
LDMODULEEMITTER=[AutomocShared],
LIBEMITTER =[AutomocStatic],
# Of course, we need to link against the qt libraries
CPPPATH=["$QT_CPPPATH"],
LIBPATH=["$QT_LIBPATH"],
LIBS=['$QT_LIB']) | [
"def",
"generate",
"(",
"env",
")",
":",
"CLVar",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"Action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"Builder",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"env",
".",
"SetDefault",
"(",
"QTDIR",
"=",
"_d... | Add Builders and construction variables for qt to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"qt",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/qt.py#L244-L334 |
23,971 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py | CPP_to_Python | def CPP_to_Python(s):
"""
Converts a C pre-processor expression into an equivalent
Python expression that can be evaluated.
"""
s = CPP_to_Python_Ops_Expression.sub(CPP_to_Python_Ops_Sub, s)
for expr, repl in CPP_to_Python_Eval_List:
s = expr.sub(repl, s)
return s | python | def CPP_to_Python(s):
s = CPP_to_Python_Ops_Expression.sub(CPP_to_Python_Ops_Sub, s)
for expr, repl in CPP_to_Python_Eval_List:
s = expr.sub(repl, s)
return s | [
"def",
"CPP_to_Python",
"(",
"s",
")",
":",
"s",
"=",
"CPP_to_Python_Ops_Expression",
".",
"sub",
"(",
"CPP_to_Python_Ops_Sub",
",",
"s",
")",
"for",
"expr",
",",
"repl",
"in",
"CPP_to_Python_Eval_List",
":",
"s",
"=",
"expr",
".",
"sub",
"(",
"repl",
",",... | Converts a C pre-processor expression into an equivalent
Python expression that can be evaluated. | [
"Converts",
"a",
"C",
"pre",
"-",
"processor",
"expression",
"into",
"an",
"equivalent",
"Python",
"expression",
"that",
"can",
"be",
"evaluated",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py#L158-L166 |
23,972 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py | PreProcessor.tupleize | def tupleize(self, contents):
"""
Turns the contents of a file into a list of easily-processed
tuples describing the CPP lines in the file.
The first element of each tuple is the line's preprocessor
directive (#if, #include, #define, etc., minus the initial '#').
The remaining elements are specific to the type of directive, as
pulled apart by the regular expression.
"""
global CPP_Expression, Table
contents = line_continuations.sub('', contents)
cpp_tuples = CPP_Expression.findall(contents)
return [(m[0],) + Table[m[0]].match(m[1]).groups() for m in cpp_tuples] | python | def tupleize(self, contents):
global CPP_Expression, Table
contents = line_continuations.sub('', contents)
cpp_tuples = CPP_Expression.findall(contents)
return [(m[0],) + Table[m[0]].match(m[1]).groups() for m in cpp_tuples] | [
"def",
"tupleize",
"(",
"self",
",",
"contents",
")",
":",
"global",
"CPP_Expression",
",",
"Table",
"contents",
"=",
"line_continuations",
".",
"sub",
"(",
"''",
",",
"contents",
")",
"cpp_tuples",
"=",
"CPP_Expression",
".",
"findall",
"(",
"contents",
")"... | Turns the contents of a file into a list of easily-processed
tuples describing the CPP lines in the file.
The first element of each tuple is the line's preprocessor
directive (#if, #include, #define, etc., minus the initial '#').
The remaining elements are specific to the type of directive, as
pulled apart by the regular expression. | [
"Turns",
"the",
"contents",
"of",
"a",
"file",
"into",
"a",
"list",
"of",
"easily",
"-",
"processed",
"tuples",
"describing",
"the",
"CPP",
"lines",
"in",
"the",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py#L274-L287 |
23,973 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py | PreProcessor.process_contents | def process_contents(self, contents, fname=None):
"""
Pre-processes a file contents.
This is the main internal entry point.
"""
self.stack = []
self.dispatch_table = self.default_table.copy()
self.current_file = fname
self.tuples = self.tupleize(contents)
self.initialize_result(fname)
while self.tuples:
t = self.tuples.pop(0)
# Uncomment to see the list of tuples being processed (e.g.,
# to validate the CPP lines are being translated correctly).
#print(t)
self.dispatch_table[t[0]](t)
return self.finalize_result(fname) | python | def process_contents(self, contents, fname=None):
self.stack = []
self.dispatch_table = self.default_table.copy()
self.current_file = fname
self.tuples = self.tupleize(contents)
self.initialize_result(fname)
while self.tuples:
t = self.tuples.pop(0)
# Uncomment to see the list of tuples being processed (e.g.,
# to validate the CPP lines are being translated correctly).
#print(t)
self.dispatch_table[t[0]](t)
return self.finalize_result(fname) | [
"def",
"process_contents",
"(",
"self",
",",
"contents",
",",
"fname",
"=",
"None",
")",
":",
"self",
".",
"stack",
"=",
"[",
"]",
"self",
".",
"dispatch_table",
"=",
"self",
".",
"default_table",
".",
"copy",
"(",
")",
"self",
".",
"current_file",
"="... | Pre-processes a file contents.
This is the main internal entry point. | [
"Pre",
"-",
"processes",
"a",
"file",
"contents",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py#L298-L316 |
23,974 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py | PreProcessor.save | def save(self):
"""
Pushes the current dispatch table on the stack and re-initializes
the current dispatch table to the default.
"""
self.stack.append(self.dispatch_table)
self.dispatch_table = self.default_table.copy() | python | def save(self):
self.stack.append(self.dispatch_table)
self.dispatch_table = self.default_table.copy() | [
"def",
"save",
"(",
"self",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"self",
".",
"dispatch_table",
")",
"self",
".",
"dispatch_table",
"=",
"self",
".",
"default_table",
".",
"copy",
"(",
")"
] | Pushes the current dispatch table on the stack and re-initializes
the current dispatch table to the default. | [
"Pushes",
"the",
"current",
"dispatch",
"table",
"on",
"the",
"stack",
"and",
"re",
"-",
"initializes",
"the",
"current",
"dispatch",
"table",
"to",
"the",
"default",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py#L320-L326 |
23,975 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py | PreProcessor.eval_expression | def eval_expression(self, t):
"""
Evaluates a C preprocessor expression.
This is done by converting it to a Python equivalent and
eval()ing it in the C preprocessor namespace we use to
track #define values.
"""
t = CPP_to_Python(' '.join(t[1:]))
try: return eval(t, self.cpp_namespace)
except (NameError, TypeError): return 0 | python | def eval_expression(self, t):
t = CPP_to_Python(' '.join(t[1:]))
try: return eval(t, self.cpp_namespace)
except (NameError, TypeError): return 0 | [
"def",
"eval_expression",
"(",
"self",
",",
"t",
")",
":",
"t",
"=",
"CPP_to_Python",
"(",
"' '",
".",
"join",
"(",
"t",
"[",
"1",
":",
"]",
")",
")",
"try",
":",
"return",
"eval",
"(",
"t",
",",
"self",
".",
"cpp_namespace",
")",
"except",
"(",
... | Evaluates a C preprocessor expression.
This is done by converting it to a Python equivalent and
eval()ing it in the C preprocessor namespace we use to
track #define values. | [
"Evaluates",
"a",
"C",
"preprocessor",
"expression",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/cpp.py#L348-L358 |
23,976 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rmic.py | emit_rmic_classes | def emit_rmic_classes(target, source, env):
"""Create and return lists of Java RMI stub and skeleton
class files to be created from a set of class files.
"""
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
classdir = env.get('JAVACLASSDIR')
if not classdir:
try:
s = source[0]
except IndexError:
classdir = '.'
else:
try:
classdir = s.attributes.java_classdir
except AttributeError:
classdir = '.'
classdir = env.Dir(classdir).rdir()
if str(classdir) == '.':
c_ = None
else:
c_ = str(classdir) + os.sep
slist = []
for src in source:
try:
classname = src.attributes.java_classname
except AttributeError:
classname = str(src)
if c_ and classname[:len(c_)] == c_:
classname = classname[len(c_):]
if class_suffix and classname[:-len(class_suffix)] == class_suffix:
classname = classname[-len(class_suffix):]
s = src.rfile()
s.attributes.java_classdir = classdir
s.attributes.java_classname = classname
slist.append(s)
stub_suffixes = ['_Stub']
if env.get('JAVAVERSION') == '1.4':
stub_suffixes.append('_Skel')
tlist = []
for s in source:
for suff in stub_suffixes:
fname = s.attributes.java_classname.replace('.', os.sep) + \
suff + class_suffix
t = target[0].File(fname)
t.attributes.java_lookupdir = target[0]
tlist.append(t)
return tlist, source | python | def emit_rmic_classes(target, source, env):
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
classdir = env.get('JAVACLASSDIR')
if not classdir:
try:
s = source[0]
except IndexError:
classdir = '.'
else:
try:
classdir = s.attributes.java_classdir
except AttributeError:
classdir = '.'
classdir = env.Dir(classdir).rdir()
if str(classdir) == '.':
c_ = None
else:
c_ = str(classdir) + os.sep
slist = []
for src in source:
try:
classname = src.attributes.java_classname
except AttributeError:
classname = str(src)
if c_ and classname[:len(c_)] == c_:
classname = classname[len(c_):]
if class_suffix and classname[:-len(class_suffix)] == class_suffix:
classname = classname[-len(class_suffix):]
s = src.rfile()
s.attributes.java_classdir = classdir
s.attributes.java_classname = classname
slist.append(s)
stub_suffixes = ['_Stub']
if env.get('JAVAVERSION') == '1.4':
stub_suffixes.append('_Skel')
tlist = []
for s in source:
for suff in stub_suffixes:
fname = s.attributes.java_classname.replace('.', os.sep) + \
suff + class_suffix
t = target[0].File(fname)
t.attributes.java_lookupdir = target[0]
tlist.append(t)
return tlist, source | [
"def",
"emit_rmic_classes",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"class_suffix",
"=",
"env",
".",
"get",
"(",
"'JAVACLASSSUFFIX'",
",",
"'.class'",
")",
"classdir",
"=",
"env",
".",
"get",
"(",
"'JAVACLASSDIR'",
")",
"if",
"not",
"classdir",... | Create and return lists of Java RMI stub and skeleton
class files to be created from a set of class files. | [
"Create",
"and",
"return",
"lists",
"of",
"Java",
"RMI",
"stub",
"and",
"skeleton",
"class",
"files",
"to",
"be",
"created",
"from",
"a",
"set",
"of",
"class",
"files",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rmic.py#L43-L94 |
23,977 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rmic.py | generate | def generate(env):
"""Add Builders and construction variables for rmic to an Environment."""
env['BUILDERS']['RMIC'] = RMICBuilder
env['RMIC'] = 'rmic'
env['RMICFLAGS'] = SCons.Util.CLVar('')
env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}'
env['JAVACLASSSUFFIX'] = '.class' | python | def generate(env):
env['BUILDERS']['RMIC'] = RMICBuilder
env['RMIC'] = 'rmic'
env['RMICFLAGS'] = SCons.Util.CLVar('')
env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}'
env['JAVACLASSSUFFIX'] = '.class' | [
"def",
"generate",
"(",
"env",
")",
":",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'RMIC'",
"]",
"=",
"RMICBuilder",
"env",
"[",
"'RMIC'",
"]",
"=",
"'rmic'",
"env",
"[",
"'RMICFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
"env"... | Add Builders and construction variables for rmic to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"rmic",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rmic.py#L104-L111 |
23,978 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._set_scan_parameters | def _set_scan_parameters(self, interval=2100, window=2100, active=False):
"""
Set the scan interval and window in units of ms and set whether active scanning is performed
"""
active_num = 0
if bool(active):
active_num = 1
interval_num = int(interval*1000/625)
window_num = int(window*1000/625)
payload = struct.pack("<HHB", interval_num, window_num, active_num)
try:
response = self._send_command(6, 7, payload)
if response.payload[0] != 0:
return False, {'reason': "Could not set scanning parameters", 'error': response.payload[0]}
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for response'}
return True, None | python | def _set_scan_parameters(self, interval=2100, window=2100, active=False):
active_num = 0
if bool(active):
active_num = 1
interval_num = int(interval*1000/625)
window_num = int(window*1000/625)
payload = struct.pack("<HHB", interval_num, window_num, active_num)
try:
response = self._send_command(6, 7, payload)
if response.payload[0] != 0:
return False, {'reason': "Could not set scanning parameters", 'error': response.payload[0]}
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for response'}
return True, None | [
"def",
"_set_scan_parameters",
"(",
"self",
",",
"interval",
"=",
"2100",
",",
"window",
"=",
"2100",
",",
"active",
"=",
"False",
")",
":",
"active_num",
"=",
"0",
"if",
"bool",
"(",
"active",
")",
":",
"active_num",
"=",
"1",
"interval_num",
"=",
"in... | Set the scan interval and window in units of ms and set whether active scanning is performed | [
"Set",
"the",
"scan",
"interval",
"and",
"window",
"in",
"units",
"of",
"ms",
"and",
"set",
"whether",
"active",
"scanning",
"is",
"performed"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L76-L97 |
23,979 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._query_systemstate | def _query_systemstate(self):
"""Query the maximum number of connections supported by this adapter
"""
def status_filter_func(event):
if event.command_class == 3 and event.command == 0:
return True
return False
try:
response = self._send_command(0, 6, [])
maxconn, = unpack("<B", response.payload)
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for command response'}
events = self._wait_process_events(0.5, status_filter_func, lambda x: False)
conns = []
for event in events:
handle, flags, addr, addr_type, interval, timeout, lat, bond = unpack("<BB6sBHHHB", event.payload)
if flags != 0:
conns.append(handle)
return True, {'max_connections': maxconn, 'active_connections': conns} | python | def _query_systemstate(self):
def status_filter_func(event):
if event.command_class == 3 and event.command == 0:
return True
return False
try:
response = self._send_command(0, 6, [])
maxconn, = unpack("<B", response.payload)
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for command response'}
events = self._wait_process_events(0.5, status_filter_func, lambda x: False)
conns = []
for event in events:
handle, flags, addr, addr_type, interval, timeout, lat, bond = unpack("<BB6sBHHHB", event.payload)
if flags != 0:
conns.append(handle)
return True, {'max_connections': maxconn, 'active_connections': conns} | [
"def",
"_query_systemstate",
"(",
"self",
")",
":",
"def",
"status_filter_func",
"(",
"event",
")",
":",
"if",
"event",
".",
"command_class",
"==",
"3",
"and",
"event",
".",
"command",
"==",
"0",
":",
"return",
"True",
"return",
"False",
"try",
":",
"res... | Query the maximum number of connections supported by this adapter | [
"Query",
"the",
"maximum",
"number",
"of",
"connections",
"supported",
"by",
"this",
"adapter"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L99-L124 |
23,980 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._start_scan | def _start_scan(self, active):
"""Begin scanning forever
"""
success, retval = self._set_scan_parameters(active=active)
if not success:
return success, retval
try:
response = self._send_command(6, 2, [2])
if response.payload[0] != 0:
self._logger.error('Error starting scan for devices, error=%d', response.payload[0])
return False, {'reason': "Could not initiate scan for ble devices, error_code=%d, response=%s" % (response.payload[0], response)}
except InternalTimeoutError:
return False, {'reason': "Timeout waiting for response"}
return True, None | python | def _start_scan(self, active):
success, retval = self._set_scan_parameters(active=active)
if not success:
return success, retval
try:
response = self._send_command(6, 2, [2])
if response.payload[0] != 0:
self._logger.error('Error starting scan for devices, error=%d', response.payload[0])
return False, {'reason': "Could not initiate scan for ble devices, error_code=%d, response=%s" % (response.payload[0], response)}
except InternalTimeoutError:
return False, {'reason': "Timeout waiting for response"}
return True, None | [
"def",
"_start_scan",
"(",
"self",
",",
"active",
")",
":",
"success",
",",
"retval",
"=",
"self",
".",
"_set_scan_parameters",
"(",
"active",
"=",
"active",
")",
"if",
"not",
"success",
":",
"return",
"success",
",",
"retval",
"try",
":",
"response",
"=... | Begin scanning forever | [
"Begin",
"scanning",
"forever"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L126-L142 |
23,981 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._stop_scan | def _stop_scan(self):
"""Stop scanning for BLE devices
"""
try:
response = self._send_command(6, 4, [])
if response.payload[0] != 0:
# Error code 129 means we just were not currently scanning
if response.payload[0] != 129:
self._logger.error('Error stopping scan for devices, error=%d', response.payload[0])
return False, {'reason': "Could not stop scan for ble devices"}
except InternalTimeoutError:
return False, {'reason': "Timeout waiting for response"}
except DeviceNotConfiguredError:
return True, {'reason': "Device not connected (did you disconnect the dongle?"}
return True, None | python | def _stop_scan(self):
try:
response = self._send_command(6, 4, [])
if response.payload[0] != 0:
# Error code 129 means we just were not currently scanning
if response.payload[0] != 129:
self._logger.error('Error stopping scan for devices, error=%d', response.payload[0])
return False, {'reason': "Could not stop scan for ble devices"}
except InternalTimeoutError:
return False, {'reason': "Timeout waiting for response"}
except DeviceNotConfiguredError:
return True, {'reason': "Device not connected (did you disconnect the dongle?"}
return True, None | [
"def",
"_stop_scan",
"(",
"self",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"_send_command",
"(",
"6",
",",
"4",
",",
"[",
"]",
")",
"if",
"response",
".",
"payload",
"[",
"0",
"]",
"!=",
"0",
":",
"# Error code 129 means we just were not curre... | Stop scanning for BLE devices | [
"Stop",
"scanning",
"for",
"BLE",
"devices"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L144-L161 |
23,982 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._probe_services | def _probe_services(self, handle):
"""Probe for all primary services and characteristics in those services
Args:
handle (int): the connection handle to probe
"""
code = 0x2800
def event_filter_func(event):
if (event.command_class == 4 and event.command == 2):
event_handle, = unpack("B", event.payload[0:1])
return event_handle == handle
return False
def end_filter_func(event):
if (event.command_class == 4 and event.command == 1):
event_handle, = unpack("B", event.payload[0:1])
return event_handle == handle
return False
payload = struct.pack('<BHHBH', handle, 1, 0xFFFF, 2, code)
try:
response = self._send_command(4, 1, payload)
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for command response'}
handle, result = unpack("<BH", response.payload)
if result != 0:
return False, None
events = self._wait_process_events(0.5, event_filter_func, end_filter_func)
gatt_events = [x for x in events if event_filter_func(x)]
end_events = [x for x in events if end_filter_func(x)]
if len(end_events) == 0:
return False, None
#Make sure we successfully probed the gatt table
end_event = end_events[0]
_, result, _ = unpack("<BHH", end_event.payload)
if result != 0:
self._logger.warn("Error enumerating GATT table, protocol error code = %d (0x%X)" % (result, result))
return False, None
services = {}
for event in gatt_events:
process_gatt_service(services, event)
return True, {'services': services} | python | def _probe_services(self, handle):
code = 0x2800
def event_filter_func(event):
if (event.command_class == 4 and event.command == 2):
event_handle, = unpack("B", event.payload[0:1])
return event_handle == handle
return False
def end_filter_func(event):
if (event.command_class == 4 and event.command == 1):
event_handle, = unpack("B", event.payload[0:1])
return event_handle == handle
return False
payload = struct.pack('<BHHBH', handle, 1, 0xFFFF, 2, code)
try:
response = self._send_command(4, 1, payload)
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for command response'}
handle, result = unpack("<BH", response.payload)
if result != 0:
return False, None
events = self._wait_process_events(0.5, event_filter_func, end_filter_func)
gatt_events = [x for x in events if event_filter_func(x)]
end_events = [x for x in events if end_filter_func(x)]
if len(end_events) == 0:
return False, None
#Make sure we successfully probed the gatt table
end_event = end_events[0]
_, result, _ = unpack("<BHH", end_event.payload)
if result != 0:
self._logger.warn("Error enumerating GATT table, protocol error code = %d (0x%X)" % (result, result))
return False, None
services = {}
for event in gatt_events:
process_gatt_service(services, event)
return True, {'services': services} | [
"def",
"_probe_services",
"(",
"self",
",",
"handle",
")",
":",
"code",
"=",
"0x2800",
"def",
"event_filter_func",
"(",
"event",
")",
":",
"if",
"(",
"event",
".",
"command_class",
"==",
"4",
"and",
"event",
".",
"command",
"==",
"2",
")",
":",
"event_... | Probe for all primary services and characteristics in those services
Args:
handle (int): the connection handle to probe | [
"Probe",
"for",
"all",
"primary",
"services",
"and",
"characteristics",
"in",
"those",
"services"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L163-L215 |
23,983 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._probe_characteristics | def _probe_characteristics(self, conn, services, timeout=5.0):
"""Probe gatt services for all associated characteristics in a BLE device
Args:
conn (int): the connection handle to probe
services (dict): a dictionary of services produced by probe_services()
timeout (float): the maximum number of seconds to spend in any single task
"""
for service in services.values():
success, result = self._enumerate_handles(conn, service['start_handle'],
service['end_handle'])
if not success:
return False, None
attributes = result['attributes']
service['characteristics'] = {}
last_char = None
for handle, attribute in attributes.items():
if attribute['uuid'].hex[-4:] == '0328':
success, result = self._read_handle(conn, handle, timeout)
if not success:
return False, None
value = result['data']
char = parse_characteristic_declaration(value)
service['characteristics'][char['uuid']] = char
last_char = char
elif attribute['uuid'].hex[-4:] == '0229':
if last_char is None:
return False, None
success, result = self._read_handle(conn, handle, timeout)
if not success:
return False, None
value = result['data']
assert len(value) == 2
value, = unpack("<H", value)
last_char['client_configuration'] = {'handle': handle, 'value': value}
return True, {'services': services} | python | def _probe_characteristics(self, conn, services, timeout=5.0):
for service in services.values():
success, result = self._enumerate_handles(conn, service['start_handle'],
service['end_handle'])
if not success:
return False, None
attributes = result['attributes']
service['characteristics'] = {}
last_char = None
for handle, attribute in attributes.items():
if attribute['uuid'].hex[-4:] == '0328':
success, result = self._read_handle(conn, handle, timeout)
if not success:
return False, None
value = result['data']
char = parse_characteristic_declaration(value)
service['characteristics'][char['uuid']] = char
last_char = char
elif attribute['uuid'].hex[-4:] == '0229':
if last_char is None:
return False, None
success, result = self._read_handle(conn, handle, timeout)
if not success:
return False, None
value = result['data']
assert len(value) == 2
value, = unpack("<H", value)
last_char['client_configuration'] = {'handle': handle, 'value': value}
return True, {'services': services} | [
"def",
"_probe_characteristics",
"(",
"self",
",",
"conn",
",",
"services",
",",
"timeout",
"=",
"5.0",
")",
":",
"for",
"service",
"in",
"services",
".",
"values",
"(",
")",
":",
"success",
",",
"result",
"=",
"self",
".",
"_enumerate_handles",
"(",
"co... | Probe gatt services for all associated characteristics in a BLE device
Args:
conn (int): the connection handle to probe
services (dict): a dictionary of services produced by probe_services()
timeout (float): the maximum number of seconds to spend in any single task | [
"Probe",
"gatt",
"services",
"for",
"all",
"associated",
"characteristics",
"in",
"a",
"BLE",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L217-L262 |
23,984 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._enable_rpcs | def _enable_rpcs(self, conn, services, timeout=1.0):
"""Prepare this device to receive RPCs
"""
#FIXME: Check for characteristic existence in a try/catch and return failure if not found
success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceiveHeaderCharacteristic], True, timeout)
if not success:
return success, result
return self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceivePayloadCharacteristic], True, timeout) | python | def _enable_rpcs(self, conn, services, timeout=1.0):
#FIXME: Check for characteristic existence in a try/catch and return failure if not found
success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceiveHeaderCharacteristic], True, timeout)
if not success:
return success, result
return self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceivePayloadCharacteristic], True, timeout) | [
"def",
"_enable_rpcs",
"(",
"self",
",",
"conn",
",",
"services",
",",
"timeout",
"=",
"1.0",
")",
":",
"#FIXME: Check for characteristic existence in a try/catch and return failure if not found",
"success",
",",
"result",
"=",
"self",
".",
"_set_notification",
"(",
"co... | Prepare this device to receive RPCs | [
"Prepare",
"this",
"device",
"to",
"receive",
"RPCs"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L264-L274 |
23,985 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._disable_rpcs | def _disable_rpcs(self, conn, services, timeout=1.0):
"""Prevent this device from receiving more RPCs
"""
success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceiveHeaderCharacteristic], False, timeout)
if not success:
return success, result
return self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceivePayloadCharacteristic], False, timeout) | python | def _disable_rpcs(self, conn, services, timeout=1.0):
success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceiveHeaderCharacteristic], False, timeout)
if not success:
return success, result
return self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceivePayloadCharacteristic], False, timeout) | [
"def",
"_disable_rpcs",
"(",
"self",
",",
"conn",
",",
"services",
",",
"timeout",
"=",
"1.0",
")",
":",
"success",
",",
"result",
"=",
"self",
".",
"_set_notification",
"(",
"conn",
",",
"services",
"[",
"TileBusService",
"]",
"[",
"'characteristics'",
"]... | Prevent this device from receiving more RPCs | [
"Prevent",
"this",
"device",
"from",
"receiving",
"more",
"RPCs"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L290-L298 |
23,986 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._write_handle | def _write_handle(self, conn, handle, ack, value, timeout=1.0):
"""Write to a BLE device characteristic by its handle
Args:
conn (int): The connection handle for the device we should read from
handle (int): The characteristics handle we should read
ack (bool): Should this be an acknowledges write or unacknowledged
timeout (float): How long to wait before failing
value (bytearray): The value that we should write
"""
conn_handle = conn
char_handle = handle
def write_handle_acked(event):
if event.command_class == 4 and event.command == 1:
conn, _, char = unpack("<BHH", event.payload)
return conn_handle == conn and char_handle == char
data_len = len(value)
if data_len > 20:
return False, {'reason': 'Data too long to write'}
payload = struct.pack("<BHB%ds" % data_len, conn_handle, char_handle, data_len, value)
try:
if ack:
response = self._send_command(4, 5, payload)
else:
response = self._send_command(4, 6, payload)
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for response to command in _write_handle'}
_, result = unpack("<BH", response.payload)
if result != 0:
return False, {'reason': 'Error writing to handle', 'error_code': result}
if ack:
events = self._wait_process_events(timeout, lambda x: False, write_handle_acked)
if len(events) == 0:
return False, {'reason': 'Timeout waiting for acknowledge on write'}
_, result, _ = unpack("<BHH", events[0].payload)
if result != 0:
return False, {'reason': 'Error received during write to handle', 'error_code': result}
return True, None | python | def _write_handle(self, conn, handle, ack, value, timeout=1.0):
conn_handle = conn
char_handle = handle
def write_handle_acked(event):
if event.command_class == 4 and event.command == 1:
conn, _, char = unpack("<BHH", event.payload)
return conn_handle == conn and char_handle == char
data_len = len(value)
if data_len > 20:
return False, {'reason': 'Data too long to write'}
payload = struct.pack("<BHB%ds" % data_len, conn_handle, char_handle, data_len, value)
try:
if ack:
response = self._send_command(4, 5, payload)
else:
response = self._send_command(4, 6, payload)
except InternalTimeoutError:
return False, {'reason': 'Timeout waiting for response to command in _write_handle'}
_, result = unpack("<BH", response.payload)
if result != 0:
return False, {'reason': 'Error writing to handle', 'error_code': result}
if ack:
events = self._wait_process_events(timeout, lambda x: False, write_handle_acked)
if len(events) == 0:
return False, {'reason': 'Timeout waiting for acknowledge on write'}
_, result, _ = unpack("<BHH", events[0].payload)
if result != 0:
return False, {'reason': 'Error received during write to handle', 'error_code': result}
return True, None | [
"def",
"_write_handle",
"(",
"self",
",",
"conn",
",",
"handle",
",",
"ack",
",",
"value",
",",
"timeout",
"=",
"1.0",
")",
":",
"conn_handle",
"=",
"conn",
"char_handle",
"=",
"handle",
"def",
"write_handle_acked",
"(",
"event",
")",
":",
"if",
"event",... | Write to a BLE device characteristic by its handle
Args:
conn (int): The connection handle for the device we should read from
handle (int): The characteristics handle we should read
ack (bool): Should this be an acknowledges write or unacknowledged
timeout (float): How long to wait before failing
value (bytearray): The value that we should write | [
"Write",
"to",
"a",
"BLE",
"device",
"characteristic",
"by",
"its",
"handle"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L373-L420 |
23,987 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._set_advertising_data | def _set_advertising_data(self, packet_type, data):
"""Set the advertising data for advertisements sent out by this bled112
Args:
packet_type (int): 0 for advertisement, 1 for scan response
data (bytearray): the data to set
"""
payload = struct.pack("<BB%ss" % (len(data)), packet_type, len(data), bytes(data))
response = self._send_command(6, 9, payload)
result, = unpack("<H", response.payload)
if result != 0:
return False, {'reason': 'Error code from BLED112 setting advertising data', 'code': result}
return True, None | python | def _set_advertising_data(self, packet_type, data):
payload = struct.pack("<BB%ss" % (len(data)), packet_type, len(data), bytes(data))
response = self._send_command(6, 9, payload)
result, = unpack("<H", response.payload)
if result != 0:
return False, {'reason': 'Error code from BLED112 setting advertising data', 'code': result}
return True, None | [
"def",
"_set_advertising_data",
"(",
"self",
",",
"packet_type",
",",
"data",
")",
":",
"payload",
"=",
"struct",
".",
"pack",
"(",
"\"<BB%ss\"",
"%",
"(",
"len",
"(",
"data",
")",
")",
",",
"packet_type",
",",
"len",
"(",
"data",
")",
",",
"bytes",
... | Set the advertising data for advertisements sent out by this bled112
Args:
packet_type (int): 0 for advertisement, 1 for scan response
data (bytearray): the data to set | [
"Set",
"the",
"advertising",
"data",
"for",
"advertisements",
"sent",
"out",
"by",
"this",
"bled112"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L513-L528 |
23,988 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._set_mode | def _set_mode(self, discover_mode, connect_mode):
"""Set the mode of the BLED112, used to enable and disable advertising
To enable advertising, use 4, 2.
To disable advertising use 0, 0.
Args:
discover_mode (int): The discoverability mode, 0 for off, 4 for on (user data)
connect_mode (int): The connectability mode, 0 for of, 2 for undirected connectable
"""
payload = struct.pack("<BB", discover_mode, connect_mode)
response = self._send_command(6, 1, payload)
result, = unpack("<H", response.payload)
if result != 0:
return False, {'reason': 'Error code from BLED112 setting mode', 'code': result}
return True, None | python | def _set_mode(self, discover_mode, connect_mode):
payload = struct.pack("<BB", discover_mode, connect_mode)
response = self._send_command(6, 1, payload)
result, = unpack("<H", response.payload)
if result != 0:
return False, {'reason': 'Error code from BLED112 setting mode', 'code': result}
return True, None | [
"def",
"_set_mode",
"(",
"self",
",",
"discover_mode",
",",
"connect_mode",
")",
":",
"payload",
"=",
"struct",
".",
"pack",
"(",
"\"<BB\"",
",",
"discover_mode",
",",
"connect_mode",
")",
"response",
"=",
"self",
".",
"_send_command",
"(",
"6",
",",
"1",
... | Set the mode of the BLED112, used to enable and disable advertising
To enable advertising, use 4, 2.
To disable advertising use 0, 0.
Args:
discover_mode (int): The discoverability mode, 0 for off, 4 for on (user data)
connect_mode (int): The connectability mode, 0 for of, 2 for undirected connectable | [
"Set",
"the",
"mode",
"of",
"the",
"BLED112",
"used",
"to",
"enable",
"and",
"disable",
"advertising"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L530-L548 |
23,989 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._send_notification | def _send_notification(self, handle, value):
"""Send a notification to all connected clients on a characteristic
Args:
handle (int): The handle we wish to notify on
value (bytearray): The value we wish to send
"""
value_len = len(value)
value = bytes(value)
payload = struct.pack("<BHB%ds" % value_len, 0xFF, handle, value_len, value)
response = self._send_command(2, 5, payload)
result, = unpack("<H", response.payload)
if result != 0:
return False, {'reason': 'Error code from BLED112 notifying a value', 'code': result, 'handle': handle, 'value': value}
return True, None | python | def _send_notification(self, handle, value):
value_len = len(value)
value = bytes(value)
payload = struct.pack("<BHB%ds" % value_len, 0xFF, handle, value_len, value)
response = self._send_command(2, 5, payload)
result, = unpack("<H", response.payload)
if result != 0:
return False, {'reason': 'Error code from BLED112 notifying a value', 'code': result, 'handle': handle, 'value': value}
return True, None | [
"def",
"_send_notification",
"(",
"self",
",",
"handle",
",",
"value",
")",
":",
"value_len",
"=",
"len",
"(",
"value",
")",
"value",
"=",
"bytes",
"(",
"value",
")",
"payload",
"=",
"struct",
".",
"pack",
"(",
"\"<BHB%ds\"",
"%",
"value_len",
",",
"0x... | Send a notification to all connected clients on a characteristic
Args:
handle (int): The handle we wish to notify on
value (bytearray): The value we wish to send | [
"Send",
"a",
"notification",
"to",
"all",
"connected",
"clients",
"on",
"a",
"characteristic"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L550-L568 |
23,990 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._disconnect | def _disconnect(self, handle):
"""Disconnect from a device that we have previously connected to
"""
payload = struct.pack('<B', handle)
response = self._send_command(3, 0, payload)
conn_handle, result = unpack("<BH", response.payload)
if result != 0:
self._logger.info("Disconnection failed result=%d", result)
return False, None
assert conn_handle == handle
def disconnect_succeeded(event):
if event.command_class == 3 and event.command == 4:
event_handle, = unpack("B", event.payload[0:1])
return event_handle == handle
return False
#FIXME Hardcoded timeout
events = self._wait_process_events(3.0, lambda x: False, disconnect_succeeded)
if len(events) != 1:
return False, None
return True, {'handle': handle} | python | def _disconnect(self, handle):
payload = struct.pack('<B', handle)
response = self._send_command(3, 0, payload)
conn_handle, result = unpack("<BH", response.payload)
if result != 0:
self._logger.info("Disconnection failed result=%d", result)
return False, None
assert conn_handle == handle
def disconnect_succeeded(event):
if event.command_class == 3 and event.command == 4:
event_handle, = unpack("B", event.payload[0:1])
return event_handle == handle
return False
#FIXME Hardcoded timeout
events = self._wait_process_events(3.0, lambda x: False, disconnect_succeeded)
if len(events) != 1:
return False, None
return True, {'handle': handle} | [
"def",
"_disconnect",
"(",
"self",
",",
"handle",
")",
":",
"payload",
"=",
"struct",
".",
"pack",
"(",
"'<B'",
",",
"handle",
")",
"response",
"=",
"self",
".",
"_send_command",
"(",
"3",
",",
"0",
",",
"payload",
")",
"conn_handle",
",",
"result",
... | Disconnect from a device that we have previously connected to | [
"Disconnect",
"from",
"a",
"device",
"that",
"we",
"have",
"previously",
"connected",
"to"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L657-L683 |
23,991 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._send_command | def _send_command(self, cmd_class, command, payload, timeout=3.0):
"""
Send a BGAPI packet to the dongle and return the response
"""
if len(payload) > 60:
return ValueError("Attempting to send a BGAPI packet with length > 60 is not allowed", actual_length=len(payload), command=command, command_class=cmd_class)
header = bytearray(4)
header[0] = 0
header[1] = len(payload)
header[2] = cmd_class
header[3] = command
packet = header + bytearray(payload)
self._stream.write(bytes(packet))
#Every command has a response so wait for the response here
response = self._receive_packet(timeout)
return response | python | def _send_command(self, cmd_class, command, payload, timeout=3.0):
if len(payload) > 60:
return ValueError("Attempting to send a BGAPI packet with length > 60 is not allowed", actual_length=len(payload), command=command, command_class=cmd_class)
header = bytearray(4)
header[0] = 0
header[1] = len(payload)
header[2] = cmd_class
header[3] = command
packet = header + bytearray(payload)
self._stream.write(bytes(packet))
#Every command has a response so wait for the response here
response = self._receive_packet(timeout)
return response | [
"def",
"_send_command",
"(",
"self",
",",
"cmd_class",
",",
"command",
",",
"payload",
",",
"timeout",
"=",
"3.0",
")",
":",
"if",
"len",
"(",
"payload",
")",
">",
"60",
":",
"return",
"ValueError",
"(",
"\"Attempting to send a BGAPI packet with length > 60 is n... | Send a BGAPI packet to the dongle and return the response | [
"Send",
"a",
"BGAPI",
"packet",
"to",
"the",
"dongle",
"and",
"return",
"the",
"response"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L685-L704 |
23,992 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._receive_packet | def _receive_packet(self, timeout=3.0):
"""
Receive a response packet to a command
"""
while True:
response_data = self._stream.read_packet(timeout=timeout)
response = BGAPIPacket(is_event=(response_data[0] == 0x80), command_class=response_data[2], command=response_data[3], payload=response_data[4:])
if response.is_event:
if self.event_handler is not None:
self.event_handler(response)
continue
return response | python | def _receive_packet(self, timeout=3.0):
while True:
response_data = self._stream.read_packet(timeout=timeout)
response = BGAPIPacket(is_event=(response_data[0] == 0x80), command_class=response_data[2], command=response_data[3], payload=response_data[4:])
if response.is_event:
if self.event_handler is not None:
self.event_handler(response)
continue
return response | [
"def",
"_receive_packet",
"(",
"self",
",",
"timeout",
"=",
"3.0",
")",
":",
"while",
"True",
":",
"response_data",
"=",
"self",
".",
"_stream",
".",
"read_packet",
"(",
"timeout",
"=",
"timeout",
")",
"response",
"=",
"BGAPIPacket",
"(",
"is_event",
"=",
... | Receive a response packet to a command | [
"Receive",
"a",
"response",
"packet",
"to",
"a",
"command"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L706-L721 |
23,993 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | BLED112CommandProcessor._wait_process_events | def _wait_process_events(self, total_time, return_filter, end_filter):
"""Synchronously process events until a specific event is found or we timeout
Args:
total_time (float): The aproximate maximum number of seconds we should wait for the end event
return_filter (callable): A function that returns True for events we should return and not process
normally via callbacks to the IOLoop
end_filter (callable): A function that returns True for the end event that we are looking for to
stop processing.
Returns:
list: A list of events that matched return_filter or end_filter
"""
acc = []
delta = 0.01
start_time = time.time()
end_time = start_time + total_time
while time.time() < end_time:
events = self._process_events(lambda x: return_filter(x) or end_filter(x), max_events=1)
acc += events
for event in events:
if end_filter(event):
return acc
if len(events) == 0:
time.sleep(delta)
return acc | python | def _wait_process_events(self, total_time, return_filter, end_filter):
acc = []
delta = 0.01
start_time = time.time()
end_time = start_time + total_time
while time.time() < end_time:
events = self._process_events(lambda x: return_filter(x) or end_filter(x), max_events=1)
acc += events
for event in events:
if end_filter(event):
return acc
if len(events) == 0:
time.sleep(delta)
return acc | [
"def",
"_wait_process_events",
"(",
"self",
",",
"total_time",
",",
"return_filter",
",",
"end_filter",
")",
":",
"acc",
"=",
"[",
"]",
"delta",
"=",
"0.01",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"end_time",
"=",
"start_time",
"+",
"total_time"... | Synchronously process events until a specific event is found or we timeout
Args:
total_time (float): The aproximate maximum number of seconds we should wait for the end event
return_filter (callable): A function that returns True for events we should return and not process
normally via callbacks to the IOLoop
end_filter (callable): A function that returns True for the end event that we are looking for to
stop processing.
Returns:
list: A list of events that matched return_filter or end_filter | [
"Synchronously",
"process",
"events",
"until",
"a",
"specific",
"event",
"is",
"found",
"or",
"we",
"timeout"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L774-L805 |
23,994 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py | OrderedAWSIOTClient.connect | def connect(self, client_id):
"""Connect to AWS IOT with the given client_id
Args:
client_id (string): The client ID passed to the MQTT message broker
"""
if self.client is not None:
raise InternalError("Connect called on an alreaded connected MQTT client")
client = AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient(client_id, useWebsocket=self.websockets)
if self.websockets:
client.configureEndpoint(self.endpoint, 443)
client.configureCredentials(self.root)
if self.iam_session is None:
client.configureIAMCredentials(self.iam_key, self.iam_secret)
else:
client.configureIAMCredentials(self.iam_key, self.iam_secret, self.iam_session)
else:
client.configureEndpoint(self.endpoint, 8883)
client.configureCredentials(self.root, self.key, self.cert)
client.configureOfflinePublishQueueing(0)
try:
client.connect()
self.client = client
except operationError as exc:
raise InternalError("Could not connect to AWS IOT", message=exc.message)
self.sequencer.reset() | python | def connect(self, client_id):
if self.client is not None:
raise InternalError("Connect called on an alreaded connected MQTT client")
client = AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient(client_id, useWebsocket=self.websockets)
if self.websockets:
client.configureEndpoint(self.endpoint, 443)
client.configureCredentials(self.root)
if self.iam_session is None:
client.configureIAMCredentials(self.iam_key, self.iam_secret)
else:
client.configureIAMCredentials(self.iam_key, self.iam_secret, self.iam_session)
else:
client.configureEndpoint(self.endpoint, 8883)
client.configureCredentials(self.root, self.key, self.cert)
client.configureOfflinePublishQueueing(0)
try:
client.connect()
self.client = client
except operationError as exc:
raise InternalError("Could not connect to AWS IOT", message=exc.message)
self.sequencer.reset() | [
"def",
"connect",
"(",
"self",
",",
"client_id",
")",
":",
"if",
"self",
".",
"client",
"is",
"not",
"None",
":",
"raise",
"InternalError",
"(",
"\"Connect called on an alreaded connected MQTT client\"",
")",
"client",
"=",
"AWSIoTPythonSDK",
".",
"MQTTLib",
".",
... | Connect to AWS IOT with the given client_id
Args:
client_id (string): The client ID passed to the MQTT message broker | [
"Connect",
"to",
"AWS",
"IOT",
"with",
"the",
"given",
"client_id"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py#L78-L110 |
23,995 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py | OrderedAWSIOTClient.disconnect | def disconnect(self):
"""Disconnect from AWS IOT message broker
"""
if self.client is None:
return
try:
self.client.disconnect()
except operationError as exc:
raise InternalError("Could not disconnect from AWS IOT", message=exc.message) | python | def disconnect(self):
if self.client is None:
return
try:
self.client.disconnect()
except operationError as exc:
raise InternalError("Could not disconnect from AWS IOT", message=exc.message) | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"client",
"is",
"None",
":",
"return",
"try",
":",
"self",
".",
"client",
".",
"disconnect",
"(",
")",
"except",
"operationError",
"as",
"exc",
":",
"raise",
"InternalError",
"(",
"\"Could no... | Disconnect from AWS IOT message broker | [
"Disconnect",
"from",
"AWS",
"IOT",
"message",
"broker"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py#L112-L122 |
23,996 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py | OrderedAWSIOTClient.publish | def publish(self, topic, message):
"""Publish a json message to a topic with a type and a sequence number
The actual message will be published as a JSON object:
{
"sequence": <incrementing id>,
"message": message
}
Args:
topic (string): The MQTT topic to publish in
message (string, dict): The message to publish
"""
seq = self.sequencer.next_id(topic)
packet = {
'sequence': seq,
'message': message
}
# Need to encode bytes types for json.dumps
if 'key' in packet['message']:
packet['message']['key'] = packet['message']['key'].decode('utf8')
if 'payload' in packet['message']:
packet['message']['payload'] = packet['message']['payload'].decode('utf8')
if 'script' in packet['message']:
packet['message']['script'] = packet['message']['script'].decode('utf8')
if 'trace' in packet['message']:
packet['message']['trace'] = packet['message']['trace'].decode('utf8')
if 'report' in packet['message']:
packet['message']['report'] = packet['message']['report'].decode('utf8')
if 'received_time' in packet['message']:
packet['message']['received_time'] = packet['message']['received_time'].decode('utf8')
serialized_packet = json.dumps(packet)
try:
# Limit how much we log in case the message is very long
self._logger.debug("Publishing %s on topic %s", serialized_packet[:256], topic)
self.client.publish(topic, serialized_packet, 1)
except operationError as exc:
raise InternalError("Could not publish message", topic=topic, message=exc.message) | python | def publish(self, topic, message):
seq = self.sequencer.next_id(topic)
packet = {
'sequence': seq,
'message': message
}
# Need to encode bytes types for json.dumps
if 'key' in packet['message']:
packet['message']['key'] = packet['message']['key'].decode('utf8')
if 'payload' in packet['message']:
packet['message']['payload'] = packet['message']['payload'].decode('utf8')
if 'script' in packet['message']:
packet['message']['script'] = packet['message']['script'].decode('utf8')
if 'trace' in packet['message']:
packet['message']['trace'] = packet['message']['trace'].decode('utf8')
if 'report' in packet['message']:
packet['message']['report'] = packet['message']['report'].decode('utf8')
if 'received_time' in packet['message']:
packet['message']['received_time'] = packet['message']['received_time'].decode('utf8')
serialized_packet = json.dumps(packet)
try:
# Limit how much we log in case the message is very long
self._logger.debug("Publishing %s on topic %s", serialized_packet[:256], topic)
self.client.publish(topic, serialized_packet, 1)
except operationError as exc:
raise InternalError("Could not publish message", topic=topic, message=exc.message) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"message",
")",
":",
"seq",
"=",
"self",
".",
"sequencer",
".",
"next_id",
"(",
"topic",
")",
"packet",
"=",
"{",
"'sequence'",
":",
"seq",
",",
"'message'",
":",
"message",
"}",
"# Need to encode bytes t... | Publish a json message to a topic with a type and a sequence number
The actual message will be published as a JSON object:
{
"sequence": <incrementing id>,
"message": message
}
Args:
topic (string): The MQTT topic to publish in
message (string, dict): The message to publish | [
"Publish",
"a",
"json",
"message",
"to",
"a",
"topic",
"with",
"a",
"type",
"and",
"a",
"sequence",
"number"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py#L124-L165 |
23,997 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py | OrderedAWSIOTClient.subscribe | def subscribe(self, topic, callback, ordered=True):
"""Subscribe to future messages in the given topic
The contents of topic should be in the format created by self.publish with a
sequence number of message type encoded as a json string.
Wildcard topics containing + and # are allowed and
Args:
topic (string): The MQTT topic to subscribe to
callback (callable): The callback to call when a new mesage is received
The signature of callback should be callback(sequence, topic, type, message)
ordered (bool): Whether messages on this topic have a sequence number that must
be checked and queued to ensure that packets are received in order
"""
if '+' in topic or '#' in topic:
regex = re.compile(topic.replace('+', '[^/]+').replace('#', '.*'))
self.wildcard_queues.append((topic, regex, callback, ordered))
else:
self.queues[topic] = PacketQueue(0, callback, ordered)
try:
self.client.subscribe(topic, 1, self._on_receive)
except operationError as exc:
raise InternalError("Could not subscribe to topic", topic=topic, message=exc.message) | python | def subscribe(self, topic, callback, ordered=True):
if '+' in topic or '#' in topic:
regex = re.compile(topic.replace('+', '[^/]+').replace('#', '.*'))
self.wildcard_queues.append((topic, regex, callback, ordered))
else:
self.queues[topic] = PacketQueue(0, callback, ordered)
try:
self.client.subscribe(topic, 1, self._on_receive)
except operationError as exc:
raise InternalError("Could not subscribe to topic", topic=topic, message=exc.message) | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"callback",
",",
"ordered",
"=",
"True",
")",
":",
"if",
"'+'",
"in",
"topic",
"or",
"'#'",
"in",
"topic",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"topic",
".",
"replace",
"(",
"'+'",
",",
... | Subscribe to future messages in the given topic
The contents of topic should be in the format created by self.publish with a
sequence number of message type encoded as a json string.
Wildcard topics containing + and # are allowed and
Args:
topic (string): The MQTT topic to subscribe to
callback (callable): The callback to call when a new mesage is received
The signature of callback should be callback(sequence, topic, type, message)
ordered (bool): Whether messages on this topic have a sequence number that must
be checked and queued to ensure that packets are received in order | [
"Subscribe",
"to",
"future",
"messages",
"in",
"the",
"given",
"topic"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py#L167-L192 |
23,998 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py | OrderedAWSIOTClient.reset_sequence | def reset_sequence(self, topic):
"""Reset the expected sequence number for a topic
If the topic is unknown, this does nothing. This behaviour is
useful when you have wildcard topics that only create queues
once they receive the first message matching the topic.
Args:
topic (string): The topic to reset the packet queue on
"""
if topic in self.queues:
self.queues[topic].reset() | python | def reset_sequence(self, topic):
if topic in self.queues:
self.queues[topic].reset() | [
"def",
"reset_sequence",
"(",
"self",
",",
"topic",
")",
":",
"if",
"topic",
"in",
"self",
".",
"queues",
":",
"self",
".",
"queues",
"[",
"topic",
"]",
".",
"reset",
"(",
")"
] | Reset the expected sequence number for a topic
If the topic is unknown, this does nothing. This behaviour is
useful when you have wildcard topics that only create queues
once they receive the first message matching the topic.
Args:
topic (string): The topic to reset the packet queue on | [
"Reset",
"the",
"expected",
"sequence",
"number",
"for",
"a",
"topic"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py#L194-L206 |
23,999 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py | OrderedAWSIOTClient.unsubscribe | def unsubscribe(self, topic):
"""Unsubscribe from messages on a given topic
Args:
topic (string): The MQTT topic to unsubscribe from
"""
del self.queues[topic]
try:
self.client.unsubscribe(topic)
except operationError as exc:
raise InternalError("Could not unsubscribe from topic", topic=topic, message=exc.message) | python | def unsubscribe(self, topic):
del self.queues[topic]
try:
self.client.unsubscribe(topic)
except operationError as exc:
raise InternalError("Could not unsubscribe from topic", topic=topic, message=exc.message) | [
"def",
"unsubscribe",
"(",
"self",
",",
"topic",
")",
":",
"del",
"self",
".",
"queues",
"[",
"topic",
"]",
"try",
":",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topic",
")",
"except",
"operationError",
"as",
"exc",
":",
"raise",
"InternalError",
... | Unsubscribe from messages on a given topic
Args:
topic (string): The MQTT topic to unsubscribe from | [
"Unsubscribe",
"from",
"messages",
"on",
"a",
"given",
"topic"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py#L208-L220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.