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,800 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | generate | def generate(env):
"""Add Builders and construction variables for Microsoft Visual
Studio project files to an Environment."""
try:
env['BUILDERS']['MSVSProject']
except KeyError:
env['BUILDERS']['MSVSProject'] = projectBuilder
try:
env['BUILDERS']['MSVSSolution']
except KeyError:
env['BUILDERS']['MSVSSolution'] = solutionBuilder
env['MSVSPROJECTCOM'] = projectAction
env['MSVSSOLUTIONCOM'] = solutionAction
if SCons.Script.call_stack:
# XXX Need to find a way to abstract this; the build engine
# shouldn't depend on anything in SCons.Script.
env['MSVSSCONSCRIPT'] = SCons.Script.call_stack[0].sconscript
else:
global default_MSVS_SConscript
if default_MSVS_SConscript is None:
default_MSVS_SConscript = env.File('SConstruct')
env['MSVSSCONSCRIPT'] = default_MSVS_SConscript
env['MSVSSCONS'] = '"%s" -c "%s"' % (python_executable, getExecScriptMain(env))
env['MSVSSCONSFLAGS'] = '-C "${MSVSSCONSCRIPT.dir.get_abspath()}" -f ${MSVSSCONSCRIPT.name}'
env['MSVSSCONSCOM'] = '$MSVSSCONS $MSVSSCONSFLAGS'
env['MSVSBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSREBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSCLEANCOM'] = '$MSVSSCONSCOM -c "$MSVSBUILDTARGET"'
# Set-up ms tools paths for default version
msvc_setup_env_once(env)
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
else:
(version_num, suite) = (7.0, None) # guess at a default
if 'MSVS' not in env:
env['MSVS'] = {}
if (version_num < 7.0):
env['MSVS']['PROJECTSUFFIX'] = '.dsp'
env['MSVS']['SOLUTIONSUFFIX'] = '.dsw'
elif (version_num < 10.0):
env['MSVS']['PROJECTSUFFIX'] = '.vcproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
else:
env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
if (version_num >= 10.0):
env['MSVSENCODING'] = 'utf-8'
else:
env['MSVSENCODING'] = 'Windows-1252'
env['GET_MSVSPROJECTSUFFIX'] = GetMSVSProjectSuffix
env['GET_MSVSSOLUTIONSUFFIX'] = GetMSVSSolutionSuffix
env['MSVSPROJECTSUFFIX'] = '${GET_MSVSPROJECTSUFFIX}'
env['MSVSSOLUTIONSUFFIX'] = '${GET_MSVSSOLUTIONSUFFIX}'
env['SCONS_HOME'] = os.environ.get('SCONS_HOME') | python | def generate(env):
try:
env['BUILDERS']['MSVSProject']
except KeyError:
env['BUILDERS']['MSVSProject'] = projectBuilder
try:
env['BUILDERS']['MSVSSolution']
except KeyError:
env['BUILDERS']['MSVSSolution'] = solutionBuilder
env['MSVSPROJECTCOM'] = projectAction
env['MSVSSOLUTIONCOM'] = solutionAction
if SCons.Script.call_stack:
# XXX Need to find a way to abstract this; the build engine
# shouldn't depend on anything in SCons.Script.
env['MSVSSCONSCRIPT'] = SCons.Script.call_stack[0].sconscript
else:
global default_MSVS_SConscript
if default_MSVS_SConscript is None:
default_MSVS_SConscript = env.File('SConstruct')
env['MSVSSCONSCRIPT'] = default_MSVS_SConscript
env['MSVSSCONS'] = '"%s" -c "%s"' % (python_executable, getExecScriptMain(env))
env['MSVSSCONSFLAGS'] = '-C "${MSVSSCONSCRIPT.dir.get_abspath()}" -f ${MSVSSCONSCRIPT.name}'
env['MSVSSCONSCOM'] = '$MSVSSCONS $MSVSSCONSFLAGS'
env['MSVSBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSREBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSCLEANCOM'] = '$MSVSSCONSCOM -c "$MSVSBUILDTARGET"'
# Set-up ms tools paths for default version
msvc_setup_env_once(env)
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
else:
(version_num, suite) = (7.0, None) # guess at a default
if 'MSVS' not in env:
env['MSVS'] = {}
if (version_num < 7.0):
env['MSVS']['PROJECTSUFFIX'] = '.dsp'
env['MSVS']['SOLUTIONSUFFIX'] = '.dsw'
elif (version_num < 10.0):
env['MSVS']['PROJECTSUFFIX'] = '.vcproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
else:
env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
if (version_num >= 10.0):
env['MSVSENCODING'] = 'utf-8'
else:
env['MSVSENCODING'] = 'Windows-1252'
env['GET_MSVSPROJECTSUFFIX'] = GetMSVSProjectSuffix
env['GET_MSVSSOLUTIONSUFFIX'] = GetMSVSSolutionSuffix
env['MSVSPROJECTSUFFIX'] = '${GET_MSVSPROJECTSUFFIX}'
env['MSVSSOLUTIONSUFFIX'] = '${GET_MSVSSOLUTIONSUFFIX}'
env['SCONS_HOME'] = os.environ.get('SCONS_HOME') | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'MSVSProject'",
"]",
"except",
"KeyError",
":",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'MSVSProject'",
"]",
"=",
"projectBuilder",
"try",
":",
"env",
"[",
"'BUILDERS'... | Add Builders and construction variables for Microsoft Visual
Studio project files to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Microsoft",
"Visual",
"Studio",
"project",
"files",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1928-L1989 |
23,801 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | _GenerateV6DSW.PrintWorkspace | def PrintWorkspace(self):
""" writes a DSW file """
name = self.name
dspfile = os.path.relpath(self.dspfiles[0], self.dsw_folder_path)
self.file.write(V6DSWHeader % locals()) | python | def PrintWorkspace(self):
name = self.name
dspfile = os.path.relpath(self.dspfiles[0], self.dsw_folder_path)
self.file.write(V6DSWHeader % locals()) | [
"def",
"PrintWorkspace",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
"dspfile",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"dspfiles",
"[",
"0",
"]",
",",
"self",
".",
"dsw_folder_path",
")",
"self",
".",
"file",
".",
"w... | writes a DSW file | [
"writes",
"a",
"DSW",
"file"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1659-L1663 |
23,802 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.waiters | def waiters(self, path=None):
"""Iterate over all waiters.
This method will return the waiters in unspecified order
including the future or callback object that will be invoked
and a list containing the keys/value that are being matched.
Yields:
list, future or callable
"""
context = self._waiters
if path is None:
path = []
for key in path:
context = context[key]
if self._LEAF in context:
for future in context[self._LEAF]:
yield (path, future)
for key in context:
if key is self._LEAF:
continue
yield from self.waiters(path=path + [key]) | python | def waiters(self, path=None):
context = self._waiters
if path is None:
path = []
for key in path:
context = context[key]
if self._LEAF in context:
for future in context[self._LEAF]:
yield (path, future)
for key in context:
if key is self._LEAF:
continue
yield from self.waiters(path=path + [key]) | [
"def",
"waiters",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"context",
"=",
"self",
".",
"_waiters",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"path",
":",
"context",
"=",
"context",
"[",
"key",
"]",
"if",... | Iterate over all waiters.
This method will return the waiters in unspecified order
including the future or callback object that will be invoked
and a list containing the keys/value that are being matched.
Yields:
list, future or callable | [
"Iterate",
"over",
"all",
"waiters",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L138-L165 |
23,803 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.every_match | def every_match(self, callback, **kwargs):
"""Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The callback can be removed by a call to remove_waiter(), passing the
handle object returned by this call to identify it.
Args:
callback (callable): A callable function that will be called as
callback(message) whenever a matching message is received.
Returns:
object: An opaque handle that can be passed to remove_waiter().
This handle is the only way to remove this callback if you no
longer want it to be called.
"""
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
responder = self._add_waiter(spec, callback)
return (spec, responder) | python | def every_match(self, callback, **kwargs):
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
responder = self._add_waiter(spec, callback)
return (spec, responder) | [
"def",
"every_match",
"(",
"self",
",",
"callback",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"raise",
"ArgumentError",
"(",
"\"You must specify at least one message field to wait on\"",
")",
"spec",
"=",
"MessageSpec",
... | Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The callback can be removed by a call to remove_waiter(), passing the
handle object returned by this call to identify it.
Args:
callback (callable): A callable function that will be called as
callback(message) whenever a matching message is received.
Returns:
object: An opaque handle that can be passed to remove_waiter().
This handle is the only way to remove this callback if you no
longer want it to be called. | [
"Invoke",
"callback",
"every",
"time",
"a",
"matching",
"message",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L167-L194 |
23,804 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.remove_waiter | def remove_waiter(self, waiter_handle):
"""Remove a message callback.
This call will remove a callback previously registered using
every_match.
Args:
waiter_handle (object): The opaque handle returned by the
previous call to every_match().
"""
spec, waiter = waiter_handle
self._remove_waiter(spec, waiter) | python | def remove_waiter(self, waiter_handle):
spec, waiter = waiter_handle
self._remove_waiter(spec, waiter) | [
"def",
"remove_waiter",
"(",
"self",
",",
"waiter_handle",
")",
":",
"spec",
",",
"waiter",
"=",
"waiter_handle",
"self",
".",
"_remove_waiter",
"(",
"spec",
",",
"waiter",
")"
] | Remove a message callback.
This call will remove a callback previously registered using
every_match.
Args:
waiter_handle (object): The opaque handle returned by the
previous call to every_match(). | [
"Remove",
"a",
"message",
"callback",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L202-L214 |
23,805 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.clear | def clear(self):
"""Clear all waiters.
This method will remove any current scheduled waiter with an
asyncio.CancelledError exception.
"""
for _, waiter in self.waiters():
if isinstance(waiter, asyncio.Future) and not waiter.done():
waiter.set_exception(asyncio.CancelledError())
self._waiters = {} | python | def clear(self):
for _, waiter in self.waiters():
if isinstance(waiter, asyncio.Future) and not waiter.done():
waiter.set_exception(asyncio.CancelledError())
self._waiters = {} | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"_",
",",
"waiter",
"in",
"self",
".",
"waiters",
"(",
")",
":",
"if",
"isinstance",
"(",
"waiter",
",",
"asyncio",
".",
"Future",
")",
"and",
"not",
"waiter",
".",
"done",
"(",
")",
":",
"waiter",
".... | Clear all waiters.
This method will remove any current scheduled waiter with an
asyncio.CancelledError exception. | [
"Clear",
"all",
"waiters",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L216-L227 |
23,806 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.wait_for | def wait_for(self, timeout=None, **kwargs):
"""Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given values will be
returned when this function is awaited.
If no matching message is received within the specified timeout (if
given), then asyncio.TimeoutError will be raised.
This function only matches a single message and removes itself once
the message is seen or the timeout expires.
Args:
timeout (float): Optional timeout, defaults to None for no timeout.
**kwargs: Keys to match in the message with their corresponding values.
You must pass at least one keyword argument so there is something
to look for.
Returns:
awaitable: The response
"""
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
future = self._add_waiter(spec)
future.add_done_callback(lambda x: self._remove_waiter(spec, future))
return asyncio.wait_for(future, timeout=timeout) | python | def wait_for(self, timeout=None, **kwargs):
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
future = self._add_waiter(spec)
future.add_done_callback(lambda x: self._remove_waiter(spec, future))
return asyncio.wait_for(future, timeout=timeout) | [
"def",
"wait_for",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"raise",
"ArgumentError",
"(",
"\"You must specify at least one message field to wait on\"",
")",
"spec",
"=",
"M... | Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given values will be
returned when this function is awaited.
If no matching message is received within the specified timeout (if
given), then asyncio.TimeoutError will be raised.
This function only matches a single message and removes itself once
the message is seen or the timeout expires.
Args:
timeout (float): Optional timeout, defaults to None for no timeout.
**kwargs: Keys to match in the message with their corresponding values.
You must pass at least one keyword argument so there is something
to look for.
Returns:
awaitable: The response | [
"Wait",
"for",
"a",
"specific",
"matching",
"message",
"or",
"timeout",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L229-L260 |
23,807 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.process_message | async def process_message(self, message, wait=True):
"""Process a message to see if it wakes any waiters.
This will check waiters registered to see if they match the given
message. If so, they are awoken and passed the message. All matching
waiters will be woken.
This method returns False if the message matched no waiters so it was
ignored.
Normally you want to use wait=True (the default behavior) to guarantee
that all callbacks have finished before this method returns. However,
sometimes that can cause a deadlock if those callbacks would
themselves invoke behavior that requires whatever is waiting for this
method to be alive. In that case you can pass wait=False to ensure
that the caller of this method does not block.
Args:
message (dict or object): The message that we should process
wait (bool): Whether to block until all callbacks have finished
or to return once the callbacks have been launched.
Returns:
bool: True if at least one waiter matched, otherwise False.
"""
to_check = deque([self._waiters])
ignored = True
while len(to_check) > 0:
context = to_check.popleft()
waiters = context.get(OperationManager._LEAF, [])
for waiter in waiters:
if isinstance(waiter, asyncio.Future):
waiter.set_result(message)
else:
try:
await _wait_or_launch(self._loop, waiter, message, wait)
except: #pylint:disable=bare-except;We can't let a user callback break this routine
self._logger.warning("Error calling every_match callback, callback=%s, message=%s",
waiter, message, exc_info=True)
ignored = False
for key in context:
if key is OperationManager._LEAF:
continue
message_val = _get_key(message, key)
if message_val is _MISSING:
continue
next_level = context[key]
if message_val in next_level:
to_check.append(next_level[message_val])
return not ignored | python | async def process_message(self, message, wait=True):
to_check = deque([self._waiters])
ignored = True
while len(to_check) > 0:
context = to_check.popleft()
waiters = context.get(OperationManager._LEAF, [])
for waiter in waiters:
if isinstance(waiter, asyncio.Future):
waiter.set_result(message)
else:
try:
await _wait_or_launch(self._loop, waiter, message, wait)
except: #pylint:disable=bare-except;We can't let a user callback break this routine
self._logger.warning("Error calling every_match callback, callback=%s, message=%s",
waiter, message, exc_info=True)
ignored = False
for key in context:
if key is OperationManager._LEAF:
continue
message_val = _get_key(message, key)
if message_val is _MISSING:
continue
next_level = context[key]
if message_val in next_level:
to_check.append(next_level[message_val])
return not ignored | [
"async",
"def",
"process_message",
"(",
"self",
",",
"message",
",",
"wait",
"=",
"True",
")",
":",
"to_check",
"=",
"deque",
"(",
"[",
"self",
".",
"_waiters",
"]",
")",
"ignored",
"=",
"True",
"while",
"len",
"(",
"to_check",
")",
">",
"0",
":",
... | Process a message to see if it wakes any waiters.
This will check waiters registered to see if they match the given
message. If so, they are awoken and passed the message. All matching
waiters will be woken.
This method returns False if the message matched no waiters so it was
ignored.
Normally you want to use wait=True (the default behavior) to guarantee
that all callbacks have finished before this method returns. However,
sometimes that can cause a deadlock if those callbacks would
themselves invoke behavior that requires whatever is waiting for this
method to be alive. In that case you can pass wait=False to ensure
that the caller of this method does not block.
Args:
message (dict or object): The message that we should process
wait (bool): Whether to block until all callbacks have finished
or to return once the callbacks have been launched.
Returns:
bool: True if at least one waiter matched, otherwise False. | [
"Process",
"a",
"message",
"to",
"see",
"if",
"it",
"wakes",
"any",
"waiters",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L262-L319 |
23,808 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/zip.py | generate | def generate(env):
"""Add Builders and construction variables for zip to an Environment."""
try:
bld = env['BUILDERS']['Zip']
except KeyError:
bld = ZipBuilder
env['BUILDERS']['Zip'] = bld
env['ZIP'] = 'zip'
env['ZIPFLAGS'] = SCons.Util.CLVar('')
env['ZIPCOM'] = zipAction
env['ZIPCOMPRESSION'] = zipcompression
env['ZIPSUFFIX'] = '.zip'
env['ZIPROOT'] = SCons.Util.CLVar('') | python | def generate(env):
try:
bld = env['BUILDERS']['Zip']
except KeyError:
bld = ZipBuilder
env['BUILDERS']['Zip'] = bld
env['ZIP'] = 'zip'
env['ZIPFLAGS'] = SCons.Util.CLVar('')
env['ZIPCOM'] = zipAction
env['ZIPCOMPRESSION'] = zipcompression
env['ZIPSUFFIX'] = '.zip'
env['ZIPROOT'] = SCons.Util.CLVar('') | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"bld",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Zip'",
"]",
"except",
"KeyError",
":",
"bld",
"=",
"ZipBuilder",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Zip'",
"]",
"=",
"bld",
"env",
"[",
"'ZIP'... | Add Builders and construction variables for zip to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"zip",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/zip.py#L70-L83 |
23,809 | iotile/coretools | iotilecore/iotile/core/scripts/virtualdev_script.py | one_line_desc | def one_line_desc(obj):
"""Get a one line description of a class."""
logger = logging.getLogger(__name__)
try:
doc = ParsedDocstring(obj.__doc__)
return doc.short_desc
except: # pylint:disable=bare-except; We don't want a misbehaving exception to break the program
logger.warning("Could not parse docstring for %s", obj, exc_info=True)
return "" | python | def one_line_desc(obj):
logger = logging.getLogger(__name__)
try:
doc = ParsedDocstring(obj.__doc__)
return doc.short_desc
except: # pylint:disable=bare-except; We don't want a misbehaving exception to break the program
logger.warning("Could not parse docstring for %s", obj, exc_info=True)
return "" | [
"def",
"one_line_desc",
"(",
"obj",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"doc",
"=",
"ParsedDocstring",
"(",
"obj",
".",
"__doc__",
")",
"return",
"doc",
".",
"short_desc",
"except",
":",
"# pylint:disable... | Get a one line description of a class. | [
"Get",
"a",
"one",
"line",
"description",
"of",
"a",
"class",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/virtualdev_script.py#L16-L26 |
23,810 | iotile/coretools | iotilecore/iotile/core/scripts/virtualdev_script.py | instantiate_device | def instantiate_device(virtual_dev, config, loop):
"""Find a virtual device by name and instantiate it
Args:
virtual_dev (string): The name of the pkg_resources entry point corresponding to
the device. It should be in group iotile.virtual_device. If virtual_dev ends
in .py, it is interpreted as a python script and loaded directly from the script.
config (dict): A dictionary with a 'device' key with the config info for configuring
this virtual device. This is optional.
Returns:
VirtualIOTileDevice: The instantiated subclass of VirtualIOTileDevice
"""
conf = {}
if 'device' in config:
conf = config['device']
# If we're given a path to a script, try to load and use that rather than search for an installed module
try:
reg = ComponentRegistry()
if virtual_dev.endswith('.py'):
_name, dev = reg.load_extension(virtual_dev, class_filter=VirtualIOTileDevice, unique=True)
else:
_name, dev = reg.load_extensions('iotile.virtual_device', name_filter=virtual_dev,
class_filter=VirtualIOTileDevice,
product_name="virtual_device", unique=True)
return dev(conf)
except ArgumentError as err:
print("ERROR: Could not load virtual device (%s): %s" % (virtual_dev, err.msg))
sys.exit(1) | python | def instantiate_device(virtual_dev, config, loop):
conf = {}
if 'device' in config:
conf = config['device']
# If we're given a path to a script, try to load and use that rather than search for an installed module
try:
reg = ComponentRegistry()
if virtual_dev.endswith('.py'):
_name, dev = reg.load_extension(virtual_dev, class_filter=VirtualIOTileDevice, unique=True)
else:
_name, dev = reg.load_extensions('iotile.virtual_device', name_filter=virtual_dev,
class_filter=VirtualIOTileDevice,
product_name="virtual_device", unique=True)
return dev(conf)
except ArgumentError as err:
print("ERROR: Could not load virtual device (%s): %s" % (virtual_dev, err.msg))
sys.exit(1) | [
"def",
"instantiate_device",
"(",
"virtual_dev",
",",
"config",
",",
"loop",
")",
":",
"conf",
"=",
"{",
"}",
"if",
"'device'",
"in",
"config",
":",
"conf",
"=",
"config",
"[",
"'device'",
"]",
"# If we're given a path to a script, try to load and use that rather th... | Find a virtual device by name and instantiate it
Args:
virtual_dev (string): The name of the pkg_resources entry point corresponding to
the device. It should be in group iotile.virtual_device. If virtual_dev ends
in .py, it is interpreted as a python script and loaded directly from the script.
config (dict): A dictionary with a 'device' key with the config info for configuring
this virtual device. This is optional.
Returns:
VirtualIOTileDevice: The instantiated subclass of VirtualIOTileDevice | [
"Find",
"a",
"virtual",
"device",
"by",
"name",
"and",
"instantiate",
"it"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/virtualdev_script.py#L165-L196 |
23,811 | iotile/coretools | iotilecore/iotile/core/scripts/virtualdev_script.py | instantiate_interface | def instantiate_interface(virtual_iface, config, loop):
"""Find a virtual interface by name and instantiate it
Args:
virtual_iface (string): The name of the pkg_resources entry point corresponding to
the interface. It should be in group iotile.virtual_interface
config (dict): A dictionary with a 'interface' key with the config info for configuring
this virtual interface. This is optional.
Returns:
VirtualInterface: The instantiated subclass of VirtualInterface
"""
# Allow the null virtual interface for testing
if virtual_iface == 'null':
return StandardDeviceServer(None, {}, loop=loop)
conf = {}
if 'interface' in config:
conf = config['interface']
try:
reg = ComponentRegistry()
if virtual_iface.endswith('.py'):
_name, iface = reg.load_extension(virtual_iface, class_filter=AbstractDeviceServer, unique=True)
else:
_name, iface = reg.load_extensions('iotile.device_server', name_filter=virtual_iface,
class_filter=AbstractDeviceServer, unique=True)
return iface(None, conf, loop=loop)
except ArgumentError as err:
print("ERROR: Could not load device_server (%s): %s" % (virtual_iface, err.msg))
sys.exit(1) | python | def instantiate_interface(virtual_iface, config, loop):
# Allow the null virtual interface for testing
if virtual_iface == 'null':
return StandardDeviceServer(None, {}, loop=loop)
conf = {}
if 'interface' in config:
conf = config['interface']
try:
reg = ComponentRegistry()
if virtual_iface.endswith('.py'):
_name, iface = reg.load_extension(virtual_iface, class_filter=AbstractDeviceServer, unique=True)
else:
_name, iface = reg.load_extensions('iotile.device_server', name_filter=virtual_iface,
class_filter=AbstractDeviceServer, unique=True)
return iface(None, conf, loop=loop)
except ArgumentError as err:
print("ERROR: Could not load device_server (%s): %s" % (virtual_iface, err.msg))
sys.exit(1) | [
"def",
"instantiate_interface",
"(",
"virtual_iface",
",",
"config",
",",
"loop",
")",
":",
"# Allow the null virtual interface for testing",
"if",
"virtual_iface",
"==",
"'null'",
":",
"return",
"StandardDeviceServer",
"(",
"None",
",",
"{",
"}",
",",
"loop",
"=",
... | Find a virtual interface by name and instantiate it
Args:
virtual_iface (string): The name of the pkg_resources entry point corresponding to
the interface. It should be in group iotile.virtual_interface
config (dict): A dictionary with a 'interface' key with the config info for configuring
this virtual interface. This is optional.
Returns:
VirtualInterface: The instantiated subclass of VirtualInterface | [
"Find",
"a",
"virtual",
"interface",
"by",
"name",
"and",
"instantiate",
"it"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/virtualdev_script.py#L199-L231 |
23,812 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tar.py | generate | def generate(env):
"""Add Builders and construction variables for tar to an Environment."""
try:
bld = env['BUILDERS']['Tar']
except KeyError:
bld = TarBuilder
env['BUILDERS']['Tar'] = bld
env['TAR'] = env.Detect(tars) or 'gtar'
env['TARFLAGS'] = SCons.Util.CLVar('-c')
env['TARCOM'] = '$TAR $TARFLAGS -f $TARGET $SOURCES'
env['TARSUFFIX'] = '.tar' | python | def generate(env):
try:
bld = env['BUILDERS']['Tar']
except KeyError:
bld = TarBuilder
env['BUILDERS']['Tar'] = bld
env['TAR'] = env.Detect(tars) or 'gtar'
env['TARFLAGS'] = SCons.Util.CLVar('-c')
env['TARCOM'] = '$TAR $TARFLAGS -f $TARGET $SOURCES'
env['TARSUFFIX'] = '.tar' | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"bld",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Tar'",
"]",
"except",
"KeyError",
":",
"bld",
"=",
"TarBuilder",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Tar'",
"]",
"=",
"bld",
"env",
"[",
"'TAR'... | Add Builders and construction variables for tar to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"tar",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tar.py#L53-L64 |
23,813 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer.register_command | def register_command(self, name, handler, validator):
"""Register a coroutine command handler.
This handler will be called whenever a command message is received
from the client, whose operation key matches ``name``. The handler
will be called as::
response_payload = await handler(cmd_payload, context)
If the coroutine returns, it will be assumed to have completed
correctly and its return value will be sent as the result of the
command. If the coroutine wishes to signal an error handling the
command, it must raise a ServerCommandError exception that contains a
string reason code for the error. This will generate an error
response to the command.
The cmd_payload is first verified using the SchemaVerifier passed in
``validator`` and handler is only called if verification succeeds. If
verification fails, a failure response to the command is returned
automatically to the client.
Args:
name (str): The unique command name that will be used to dispatch
client command messages to this handler.
handler (coroutine function): A coroutine function that will be
called whenever this command is received.
validator (SchemaVerifier): A validator object for checking the
command payload before calling this handler.
"""
self._commands[name] = (handler, validator) | python | def register_command(self, name, handler, validator):
self._commands[name] = (handler, validator) | [
"def",
"register_command",
"(",
"self",
",",
"name",
",",
"handler",
",",
"validator",
")",
":",
"self",
".",
"_commands",
"[",
"name",
"]",
"=",
"(",
"handler",
",",
"validator",
")"
] | Register a coroutine command handler.
This handler will be called whenever a command message is received
from the client, whose operation key matches ``name``. The handler
will be called as::
response_payload = await handler(cmd_payload, context)
If the coroutine returns, it will be assumed to have completed
correctly and its return value will be sent as the result of the
command. If the coroutine wishes to signal an error handling the
command, it must raise a ServerCommandError exception that contains a
string reason code for the error. This will generate an error
response to the command.
The cmd_payload is first verified using the SchemaVerifier passed in
``validator`` and handler is only called if verification succeeds. If
verification fails, a failure response to the command is returned
automatically to the client.
Args:
name (str): The unique command name that will be used to dispatch
client command messages to this handler.
handler (coroutine function): A coroutine function that will be
called whenever this command is received.
validator (SchemaVerifier): A validator object for checking the
command payload before calling this handler. | [
"Register",
"a",
"coroutine",
"command",
"handler",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L95-L125 |
23,814 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer.start | async def start(self):
"""Start the websocket server.
When this method returns, the websocket server will be running and
the port property of this class will have its assigned port number.
This method should be called only once in the lifetime of the server
and must be paired with a call to stop() to cleanly release the
server's resources.
"""
if self._server_task is not None:
self._logger.debug("AsyncValidatingWSServer.start() called twice, ignoring")
return
started_signal = self._loop.create_future()
self._server_task = self._loop.add_task(self._run_server_task(started_signal))
await started_signal
if self.port is None:
self.port = started_signal.result() | python | async def start(self):
if self._server_task is not None:
self._logger.debug("AsyncValidatingWSServer.start() called twice, ignoring")
return
started_signal = self._loop.create_future()
self._server_task = self._loop.add_task(self._run_server_task(started_signal))
await started_signal
if self.port is None:
self.port = started_signal.result() | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server_task",
"is",
"not",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"AsyncValidatingWSServer.start() called twice, ignoring\"",
")",
"return",
"started_signal",
"=",
"self",
".... | Start the websocket server.
When this method returns, the websocket server will be running and
the port property of this class will have its assigned port number.
This method should be called only once in the lifetime of the server
and must be paired with a call to stop() to cleanly release the
server's resources. | [
"Start",
"the",
"websocket",
"server",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L127-L148 |
23,815 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer._run_server_task | async def _run_server_task(self, started_signal):
"""Create a BackgroundTask to manage the server.
This allows subclasess to attach their server related tasks as
subtasks that are properly cleaned up when this parent task is
stopped and not require them all to overload start() and stop()
to perform this action.
"""
try:
server = await websockets.serve(self._manage_connection, self.host, self.port)
port = server.sockets[0].getsockname()[1]
started_signal.set_result(port)
except Exception as err:
self._logger.exception("Error starting server on host %s, port %s", self.host, self.port)
started_signal.set_exception(err)
return
try:
while True:
await asyncio.sleep(1)
except asyncio.CancelledError:
self._logger.info("Stopping server due to stop() command")
finally:
server.close()
await server.wait_closed()
self._logger.debug("Server stopped, exiting task") | python | async def _run_server_task(self, started_signal):
try:
server = await websockets.serve(self._manage_connection, self.host, self.port)
port = server.sockets[0].getsockname()[1]
started_signal.set_result(port)
except Exception as err:
self._logger.exception("Error starting server on host %s, port %s", self.host, self.port)
started_signal.set_exception(err)
return
try:
while True:
await asyncio.sleep(1)
except asyncio.CancelledError:
self._logger.info("Stopping server due to stop() command")
finally:
server.close()
await server.wait_closed()
self._logger.debug("Server stopped, exiting task") | [
"async",
"def",
"_run_server_task",
"(",
"self",
",",
"started_signal",
")",
":",
"try",
":",
"server",
"=",
"await",
"websockets",
".",
"serve",
"(",
"self",
".",
"_manage_connection",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"port",
"="... | Create a BackgroundTask to manage the server.
This allows subclasess to attach their server related tasks as
subtasks that are properly cleaned up when this parent task is
stopped and not require them all to overload start() and stop()
to perform this action. | [
"Create",
"a",
"BackgroundTask",
"to",
"manage",
"the",
"server",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L150-L177 |
23,816 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer.send_event | async def send_event(self, con, name, payload):
"""Send an event to a client connection.
This method will push an event message to the client with the given
name and payload. You need to have access to the the ``connection``
object for the client, which is only available once the client has
connected and passed to self.prepare_conn(connection).
Args:
con (websockets.Connection): The connection to use to send
the event.
name (str): The name of the event to send.
payload (object): The msgpack-serializable object so send
as the event's payload.
"""
message = dict(type="event", name=name, payload=payload)
encoded = pack(message)
await con.send(encoded) | python | async def send_event(self, con, name, payload):
message = dict(type="event", name=name, payload=payload)
encoded = pack(message)
await con.send(encoded) | [
"async",
"def",
"send_event",
"(",
"self",
",",
"con",
",",
"name",
",",
"payload",
")",
":",
"message",
"=",
"dict",
"(",
"type",
"=",
"\"event\"",
",",
"name",
"=",
"name",
",",
"payload",
"=",
"payload",
")",
"encoded",
"=",
"pack",
"(",
"message"... | Send an event to a client connection.
This method will push an event message to the client with the given
name and payload. You need to have access to the the ``connection``
object for the client, which is only available once the client has
connected and passed to self.prepare_conn(connection).
Args:
con (websockets.Connection): The connection to use to send
the event.
name (str): The name of the event to send.
payload (object): The msgpack-serializable object so send
as the event's payload. | [
"Send",
"an",
"event",
"to",
"a",
"client",
"connection",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L191-L209 |
23,817 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py | DviPdfPsFunction | def DviPdfPsFunction(XXXDviAction, target = None, source= None, env=None):
"""A builder for DVI files that sets the TEXPICTS environment
variable before running dvi2ps or dvipdf."""
try:
abspath = source[0].attributes.path
except AttributeError :
abspath = ''
saved_env = SCons.Scanner.LaTeX.modify_env_var(env, 'TEXPICTS', abspath)
result = XXXDviAction(target, source, env)
if saved_env is _null:
try:
del env['ENV']['TEXPICTS']
except KeyError:
pass # was never set
else:
env['ENV']['TEXPICTS'] = saved_env
return result | python | def DviPdfPsFunction(XXXDviAction, target = None, source= None, env=None):
try:
abspath = source[0].attributes.path
except AttributeError :
abspath = ''
saved_env = SCons.Scanner.LaTeX.modify_env_var(env, 'TEXPICTS', abspath)
result = XXXDviAction(target, source, env)
if saved_env is _null:
try:
del env['ENV']['TEXPICTS']
except KeyError:
pass # was never set
else:
env['ENV']['TEXPICTS'] = saved_env
return result | [
"def",
"DviPdfPsFunction",
"(",
"XXXDviAction",
",",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"try",
":",
"abspath",
"=",
"source",
"[",
"0",
"]",
".",
"attributes",
".",
"path",
"except",
"AttributeError",
... | A builder for DVI files that sets the TEXPICTS environment
variable before running dvi2ps or dvipdf. | [
"A",
"builder",
"for",
"DVI",
"files",
"that",
"sets",
"the",
"TEXPICTS",
"environment",
"variable",
"before",
"running",
"dvi2ps",
"or",
"dvipdf",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L43-L64 |
23,818 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py | PDFEmitter | def PDFEmitter(target, source, env):
"""Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file.
"""
def strip_suffixes(n):
return not SCons.Util.splitext(str(n))[1] in ['.aux', '.log']
source = [src for src in source if strip_suffixes(src)]
return (target, source) | python | def PDFEmitter(target, source, env):
def strip_suffixes(n):
return not SCons.Util.splitext(str(n))[1] in ['.aux', '.log']
source = [src for src in source if strip_suffixes(src)]
return (target, source) | [
"def",
"PDFEmitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"def",
"strip_suffixes",
"(",
"n",
")",
":",
"return",
"not",
"SCons",
".",
"Util",
".",
"splitext",
"(",
"str",
"(",
"n",
")",
")",
"[",
"1",
"]",
"in",
"[",
"'.aux'",
",",... | Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file. | [
"Strips",
"any",
".",
"aux",
"or",
".",
"log",
"files",
"from",
"the",
"input",
"source",
"list",
".",
"These",
"are",
"created",
"by",
"the",
"TeX",
"Builder",
"that",
"in",
"all",
"likelihood",
"was",
"used",
"to",
"generate",
"the",
".",
"dvi",
"fil... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L82-L91 |
23,819 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py | generate | def generate(env):
"""Add Builders and construction variables for dvipdf to an Environment."""
global PDFAction
if PDFAction is None:
PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR')
global DVIPDFAction
if DVIPDFAction is None:
DVIPDFAction = SCons.Action.Action(DviPdfFunction, strfunction = DviPdfStrFunction)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.dvi', DVIPDFAction)
bld.add_emitter('.dvi', PDFEmitter)
env['DVIPDF'] = 'dvipdf'
env['DVIPDFFLAGS'] = SCons.Util.CLVar('')
env['DVIPDFCOM'] = 'cd ${TARGET.dir} && $DVIPDF $DVIPDFFLAGS ${SOURCE.file} ${TARGET.file}'
# Deprecated synonym.
env['PDFCOM'] = ['$DVIPDFCOM'] | python | def generate(env):
global PDFAction
if PDFAction is None:
PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR')
global DVIPDFAction
if DVIPDFAction is None:
DVIPDFAction = SCons.Action.Action(DviPdfFunction, strfunction = DviPdfStrFunction)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.dvi', DVIPDFAction)
bld.add_emitter('.dvi', PDFEmitter)
env['DVIPDF'] = 'dvipdf'
env['DVIPDFFLAGS'] = SCons.Util.CLVar('')
env['DVIPDFCOM'] = 'cd ${TARGET.dir} && $DVIPDF $DVIPDFFLAGS ${SOURCE.file} ${TARGET.file}'
# Deprecated synonym.
env['PDFCOM'] = ['$DVIPDFCOM'] | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"PDFAction",
"if",
"PDFAction",
"is",
"None",
":",
"PDFAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$DVIPDFCOM'",
",",
"'$DVIPDFCOMSTR'",
")",
"global",
"DVIPDFAction",
"if",
"DVIPDFAction",
"... | Add Builders and construction variables for dvipdf to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"dvipdf",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L93-L115 |
23,820 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/stop_conditions.py | TimeBasedStopCondition.FromString | def FromString(cls, desc):
"""Parse this stop condition from a string representation.
The string needs to match:
run_time number [seconds|minutes|hours|days|months|years]
Args:
desc (str): The description
Returns:
TimeBasedStopCondition
"""
parse_exp = Literal(u'run_time').suppress() + time_interval(u'interval')
try:
data = parse_exp.parseString(desc)
return TimeBasedStopCondition(data[u'interval'][0])
except ParseException:
raise ArgumentError(u"Could not parse time based stop condition") | python | def FromString(cls, desc):
parse_exp = Literal(u'run_time').suppress() + time_interval(u'interval')
try:
data = parse_exp.parseString(desc)
return TimeBasedStopCondition(data[u'interval'][0])
except ParseException:
raise ArgumentError(u"Could not parse time based stop condition") | [
"def",
"FromString",
"(",
"cls",
",",
"desc",
")",
":",
"parse_exp",
"=",
"Literal",
"(",
"u'run_time'",
")",
".",
"suppress",
"(",
")",
"+",
"time_interval",
"(",
"u'interval'",
")",
"try",
":",
"data",
"=",
"parse_exp",
".",
"parseString",
"(",
"desc",... | Parse this stop condition from a string representation.
The string needs to match:
run_time number [seconds|minutes|hours|days|months|years]
Args:
desc (str): The description
Returns:
TimeBasedStopCondition | [
"Parse",
"this",
"stop",
"condition",
"from",
"a",
"string",
"representation",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/stop_conditions.py#L95-L114 |
23,821 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | collectintargz | def collectintargz(target, source, env):
""" Puts all source files into a tar.gz file. """
# the rpm tool depends on a source package, until this is changed
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the source list for.
sources = [s for s in sources if s not in target]
# find the .spec file for rpm and add it since it is not necessarily found
# by the FindSourceFiles function.
sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
# sort to keep sources from changing order across builds
sources.sort()
# as the source contains the url of the source package this rpm package
# is built from, we extract the target name
tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
try:
tarball = env['SOURCE_URL'].split('/')[-1]
except KeyError as e:
raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
tarball = src_targz.package(env, source=sources, target=tarball,
PACKAGEROOT=env['PACKAGEROOT'], )
return (target, tarball) | python | def collectintargz(target, source, env):
# the rpm tool depends on a source package, until this is changed
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the source list for.
sources = [s for s in sources if s not in target]
# find the .spec file for rpm and add it since it is not necessarily found
# by the FindSourceFiles function.
sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
# sort to keep sources from changing order across builds
sources.sort()
# as the source contains the url of the source package this rpm package
# is built from, we extract the target name
tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
try:
tarball = env['SOURCE_URL'].split('/')[-1]
except KeyError as e:
raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
tarball = src_targz.package(env, source=sources, target=tarball,
PACKAGEROOT=env['PACKAGEROOT'], )
return (target, tarball) | [
"def",
"collectintargz",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"# the rpm tool depends on a source package, until this is changed",
"# this hack needs to be here that tries to pack all sources in.",
"sources",
"=",
"env",
".",
"FindSourceFiles",
"(",
")",
"# filte... | Puts all source files into a tar.gz file. | [
"Puts",
"all",
"source",
"files",
"into",
"a",
"tar",
".",
"gz",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L86-L112 |
23,822 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile | def build_specfile(target, source, env):
""" Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes.
"""
file = open(target[0].get_abspath(), 'w')
try:
file.write( build_specfile_header(env) )
file.write( build_specfile_sections(env) )
file.write( build_specfile_filesection(env, source) )
file.close()
# call a user specified function
if 'CHANGE_SPECFILE' in env:
env['CHANGE_SPECFILE'](target, source)
except KeyError as e:
raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] ) | python | def build_specfile(target, source, env):
file = open(target[0].get_abspath(), 'w')
try:
file.write( build_specfile_header(env) )
file.write( build_specfile_sections(env) )
file.write( build_specfile_filesection(env, source) )
file.close()
# call a user specified function
if 'CHANGE_SPECFILE' in env:
env['CHANGE_SPECFILE'](target, source)
except KeyError as e:
raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] ) | [
"def",
"build_specfile",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"file",
"=",
"open",
"(",
"target",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
",",
"'w'",
")",
"try",
":",
"file",
".",
"write",
"(",
"build_specfile_header",
"(",
"env",... | Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes. | [
"Builds",
"a",
"RPM",
"specfile",
"from",
"a",
"dictionary",
"with",
"string",
"metadata",
"and",
"by",
"analyzing",
"a",
"tree",
"of",
"nodes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L125-L142 |
23,823 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile_sections | def build_specfile_sections(spec):
""" Builds the sections of a rpm specfile.
"""
str = ""
mandatory_sections = {
'DESCRIPTION' : '\n%%description\n%s\n\n', }
str = str + SimpleTagCompiler(mandatory_sections).compile( spec )
optional_sections = {
'DESCRIPTION_' : '%%description -l %s\n%s\n\n',
'CHANGELOG' : '%%changelog\n%s\n\n',
'X_RPM_PREINSTALL' : '%%pre\n%s\n\n',
'X_RPM_POSTINSTALL' : '%%post\n%s\n\n',
'X_RPM_PREUNINSTALL' : '%%preun\n%s\n\n',
'X_RPM_POSTUNINSTALL' : '%%postun\n%s\n\n',
'X_RPM_VERIFY' : '%%verify\n%s\n\n',
# These are for internal use but could possibly be overridden
'X_RPM_PREP' : '%%prep\n%s\n\n',
'X_RPM_BUILD' : '%%build\n%s\n\n',
'X_RPM_INSTALL' : '%%install\n%s\n\n',
'X_RPM_CLEAN' : '%%clean\n%s\n\n',
}
# Default prep, build, install and clean rules
# TODO: optimize those build steps, to not compile the project a second time
if 'X_RPM_PREP' not in spec:
spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q'
if 'X_RPM_BUILD' not in spec:
spec['X_RPM_BUILD'] = '[ ! -e "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && mkdir "$RPM_BUILD_ROOT"'
if 'X_RPM_INSTALL' not in spec:
spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"'
if 'X_RPM_CLEAN' not in spec:
spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"'
str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec )
return str | python | def build_specfile_sections(spec):
str = ""
mandatory_sections = {
'DESCRIPTION' : '\n%%description\n%s\n\n', }
str = str + SimpleTagCompiler(mandatory_sections).compile( spec )
optional_sections = {
'DESCRIPTION_' : '%%description -l %s\n%s\n\n',
'CHANGELOG' : '%%changelog\n%s\n\n',
'X_RPM_PREINSTALL' : '%%pre\n%s\n\n',
'X_RPM_POSTINSTALL' : '%%post\n%s\n\n',
'X_RPM_PREUNINSTALL' : '%%preun\n%s\n\n',
'X_RPM_POSTUNINSTALL' : '%%postun\n%s\n\n',
'X_RPM_VERIFY' : '%%verify\n%s\n\n',
# These are for internal use but could possibly be overridden
'X_RPM_PREP' : '%%prep\n%s\n\n',
'X_RPM_BUILD' : '%%build\n%s\n\n',
'X_RPM_INSTALL' : '%%install\n%s\n\n',
'X_RPM_CLEAN' : '%%clean\n%s\n\n',
}
# Default prep, build, install and clean rules
# TODO: optimize those build steps, to not compile the project a second time
if 'X_RPM_PREP' not in spec:
spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q'
if 'X_RPM_BUILD' not in spec:
spec['X_RPM_BUILD'] = '[ ! -e "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && mkdir "$RPM_BUILD_ROOT"'
if 'X_RPM_INSTALL' not in spec:
spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"'
if 'X_RPM_CLEAN' not in spec:
spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"'
str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec )
return str | [
"def",
"build_specfile_sections",
"(",
"spec",
")",
":",
"str",
"=",
"\"\"",
"mandatory_sections",
"=",
"{",
"'DESCRIPTION'",
":",
"'\\n%%description\\n%s\\n\\n'",
",",
"}",
"str",
"=",
"str",
"+",
"SimpleTagCompiler",
"(",
"mandatory_sections",
")",
".",
"compile... | Builds the sections of a rpm specfile. | [
"Builds",
"the",
"sections",
"of",
"a",
"rpm",
"specfile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L148-L190 |
23,824 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile_header | def build_specfile_header(spec):
""" Builds all sections but the %file of a rpm specfile
"""
str = ""
# first the mandatory sections
mandatory_header_fields = {
'NAME' : '%%define name %s\nName: %%{name}\n',
'VERSION' : '%%define version %s\nVersion: %%{version}\n',
'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
'X_RPM_GROUP' : 'Group: %s\n',
'SUMMARY' : 'Summary: %s\n',
'LICENSE' : 'License: %s\n', }
str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )
# now the optional tags
optional_header_fields = {
'VENDOR' : 'Vendor: %s\n',
'X_RPM_URL' : 'Url: %s\n',
'SOURCE_URL' : 'Source: %s\n',
'SUMMARY_' : 'Summary(%s): %s\n',
'X_RPM_DISTRIBUTION' : 'Distribution: %s\n',
'X_RPM_ICON' : 'Icon: %s\n',
'X_RPM_PACKAGER' : 'Packager: %s\n',
'X_RPM_GROUP_' : 'Group(%s): %s\n',
'X_RPM_REQUIRES' : 'Requires: %s\n',
'X_RPM_PROVIDES' : 'Provides: %s\n',
'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',
'X_RPM_SERIAL' : 'Serial: %s\n',
'X_RPM_EPOCH' : 'Epoch: %s\n',
'X_RPM_AUTOREQPROV' : 'AutoReqProv: %s\n',
'X_RPM_EXCLUDEARCH' : 'ExcludeArch: %s\n',
'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
'X_RPM_PREFIX' : 'Prefix: %s\n',
# internal use
'X_RPM_BUILDROOT' : 'BuildRoot: %s\n', }
# fill in default values:
# Adding a BuildRequires renders the .rpm unbuildable under System, which
# are not managed by rpm, since the database to resolve this dependency is
# missing (take Gentoo as an example)
# if not s.has_key('x_rpm_BuildRequires'):
# s['x_rpm_BuildRequires'] = 'scons'
if 'X_RPM_BUILDROOT' not in spec:
spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'
str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
return str | python | def build_specfile_header(spec):
str = ""
# first the mandatory sections
mandatory_header_fields = {
'NAME' : '%%define name %s\nName: %%{name}\n',
'VERSION' : '%%define version %s\nVersion: %%{version}\n',
'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
'X_RPM_GROUP' : 'Group: %s\n',
'SUMMARY' : 'Summary: %s\n',
'LICENSE' : 'License: %s\n', }
str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )
# now the optional tags
optional_header_fields = {
'VENDOR' : 'Vendor: %s\n',
'X_RPM_URL' : 'Url: %s\n',
'SOURCE_URL' : 'Source: %s\n',
'SUMMARY_' : 'Summary(%s): %s\n',
'X_RPM_DISTRIBUTION' : 'Distribution: %s\n',
'X_RPM_ICON' : 'Icon: %s\n',
'X_RPM_PACKAGER' : 'Packager: %s\n',
'X_RPM_GROUP_' : 'Group(%s): %s\n',
'X_RPM_REQUIRES' : 'Requires: %s\n',
'X_RPM_PROVIDES' : 'Provides: %s\n',
'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',
'X_RPM_SERIAL' : 'Serial: %s\n',
'X_RPM_EPOCH' : 'Epoch: %s\n',
'X_RPM_AUTOREQPROV' : 'AutoReqProv: %s\n',
'X_RPM_EXCLUDEARCH' : 'ExcludeArch: %s\n',
'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
'X_RPM_PREFIX' : 'Prefix: %s\n',
# internal use
'X_RPM_BUILDROOT' : 'BuildRoot: %s\n', }
# fill in default values:
# Adding a BuildRequires renders the .rpm unbuildable under System, which
# are not managed by rpm, since the database to resolve this dependency is
# missing (take Gentoo as an example)
# if not s.has_key('x_rpm_BuildRequires'):
# s['x_rpm_BuildRequires'] = 'scons'
if 'X_RPM_BUILDROOT' not in spec:
spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'
str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
return str | [
"def",
"build_specfile_header",
"(",
"spec",
")",
":",
"str",
"=",
"\"\"",
"# first the mandatory sections",
"mandatory_header_fields",
"=",
"{",
"'NAME'",
":",
"'%%define name %s\\nName: %%{name}\\n'",
",",
"'VERSION'",
":",
"'%%define version %s\\nVersion: %%{version}\\n'",
... | Builds all sections but the %file of a rpm specfile | [
"Builds",
"all",
"sections",
"but",
"the",
"%file",
"of",
"a",
"rpm",
"specfile"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L192-L245 |
23,825 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile_filesection | def build_specfile_filesection(spec, files):
""" builds the %file section of the specfile
"""
str = '%files\n'
if 'X_RPM_DEFATTR' not in spec:
spec['X_RPM_DEFATTR'] = '(-,root,root)'
str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
supported_tags = {
'PACKAGING_CONFIG' : '%%config %s',
'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
'PACKAGING_DOC' : '%%doc %s',
'PACKAGING_UNIX_ATTR' : '%%attr %s',
'PACKAGING_LANG_' : '%%lang(%s) %s',
'PACKAGING_X_RPM_VERIFY' : '%%verify %s',
'PACKAGING_X_RPM_DIR' : '%%dir %s',
'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s',
'PACKAGING_X_RPM_GHOST' : '%%ghost %s', }
for file in files:
# build the tagset
tags = {}
for k in list(supported_tags.keys()):
try:
v = file.GetTag(k)
if v:
tags[k] = v
except AttributeError:
pass
# compile the tagset
str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )
str = str + ' '
str = str + file.GetTag('PACKAGING_INSTALL_LOCATION')
str = str + '\n\n'
return str | python | def build_specfile_filesection(spec, files):
str = '%files\n'
if 'X_RPM_DEFATTR' not in spec:
spec['X_RPM_DEFATTR'] = '(-,root,root)'
str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
supported_tags = {
'PACKAGING_CONFIG' : '%%config %s',
'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
'PACKAGING_DOC' : '%%doc %s',
'PACKAGING_UNIX_ATTR' : '%%attr %s',
'PACKAGING_LANG_' : '%%lang(%s) %s',
'PACKAGING_X_RPM_VERIFY' : '%%verify %s',
'PACKAGING_X_RPM_DIR' : '%%dir %s',
'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s',
'PACKAGING_X_RPM_GHOST' : '%%ghost %s', }
for file in files:
# build the tagset
tags = {}
for k in list(supported_tags.keys()):
try:
v = file.GetTag(k)
if v:
tags[k] = v
except AttributeError:
pass
# compile the tagset
str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )
str = str + ' '
str = str + file.GetTag('PACKAGING_INSTALL_LOCATION')
str = str + '\n\n'
return str | [
"def",
"build_specfile_filesection",
"(",
"spec",
",",
"files",
")",
":",
"str",
"=",
"'%files\\n'",
"if",
"'X_RPM_DEFATTR'",
"not",
"in",
"spec",
":",
"spec",
"[",
"'X_RPM_DEFATTR'",
"]",
"=",
"'(-,root,root)'",
"str",
"=",
"str",
"+",
"'%%defattr %s\\n'",
"%... | builds the %file section of the specfile | [
"builds",
"the",
"%file",
"section",
"of",
"the",
"specfile"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L250-L289 |
23,826 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | SimpleTagCompiler.compile | def compile(self, values):
""" Compiles the tagset and returns a str containing the result
"""
def is_international(tag):
return tag.endswith('_')
def get_country_code(tag):
return tag[-2:]
def strip_country_code(tag):
return tag[:-2]
replacements = list(self.tagset.items())
str = ""
domestic = [t for t in replacements if not is_international(t[0])]
for key, replacement in domestic:
try:
str = str + replacement % values[key]
except KeyError as e:
if self.mandatory:
raise e
international = [t for t in replacements if is_international(t[0])]
for key, replacement in international:
try:
x = [t for t in values.items() if strip_country_code(t[0]) == key]
int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
for v in int_values_for_key:
str = str + replacement % v
except KeyError as e:
if self.mandatory:
raise e
return str | python | def compile(self, values):
def is_international(tag):
return tag.endswith('_')
def get_country_code(tag):
return tag[-2:]
def strip_country_code(tag):
return tag[:-2]
replacements = list(self.tagset.items())
str = ""
domestic = [t for t in replacements if not is_international(t[0])]
for key, replacement in domestic:
try:
str = str + replacement % values[key]
except KeyError as e:
if self.mandatory:
raise e
international = [t for t in replacements if is_international(t[0])]
for key, replacement in international:
try:
x = [t for t in values.items() if strip_country_code(t[0]) == key]
int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
for v in int_values_for_key:
str = str + replacement % v
except KeyError as e:
if self.mandatory:
raise e
return str | [
"def",
"compile",
"(",
"self",
",",
"values",
")",
":",
"def",
"is_international",
"(",
"tag",
")",
":",
"return",
"tag",
".",
"endswith",
"(",
"'_'",
")",
"def",
"get_country_code",
"(",
"tag",
")",
":",
"return",
"tag",
"[",
"-",
"2",
":",
"]",
"... | Compiles the tagset and returns a str containing the result | [
"Compiles",
"the",
"tagset",
"and",
"returns",
"a",
"str",
"containing",
"the",
"result"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L309-L343 |
23,827 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifl.py | generate | def generate(env):
"""Add Builders and construction variables for ifl to an Environment."""
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if 'FORTRANFILESUFFIXES' not in env:
env['FORTRANFILESUFFIXES'] = ['.i']
else:
env['FORTRANFILESUFFIXES'].append('.i')
if 'F90FILESUFFIXES' not in env:
env['F90FILESUFFIXES'] = ['.i90']
else:
env['F90FILESUFFIXES'].append('.i90')
add_all_to_env(env)
env['FORTRAN'] = 'ifl'
env['SHFORTRAN'] = '$FORTRAN'
env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' | python | def generate(env):
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if 'FORTRANFILESUFFIXES' not in env:
env['FORTRANFILESUFFIXES'] = ['.i']
else:
env['FORTRANFILESUFFIXES'].append('.i')
if 'F90FILESUFFIXES' not in env:
env['F90FILESUFFIXES'] = ['.i90']
else:
env['F90FILESUFFIXES'].append('.i90')
add_all_to_env(env)
env['FORTRAN'] = 'ifl'
env['SHFORTRAN'] = '$FORTRAN'
env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' | [
"def",
"generate",
"(",
"env",
")",
":",
"fscan",
"=",
"FortranScan",
"(",
"\"FORTRANPATH\"",
")",
"SCons",
".",
"Tool",
".",
"SourceFileScanner",
".",
"add_scanner",
"(",
"'.i'",
",",
"fscan",
")",
"SCons",
".",
"Tool",
".",
"SourceFileScanner",
".",
"add... | Add Builders and construction variables for ifl to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"ifl",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifl.py#L40-L63 |
23,828 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/bcc32.py | generate | def generate(env):
findIt('bcc32', env)
"""Add Builders and construction variables for bcc to an
Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ['.c', '.cpp']:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['CC'] = 'bcc32'
env['CCFLAGS'] = SCons.Util.CLVar('')
env['CFLAGS'] = SCons.Util.CLVar('')
env['CCCOM'] = '$CC -q $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
env['SHCCCOM'] = '$SHCC -WD $SHCFLAGS $SHCCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = ''
env['SHOBJSUFFIX'] = '.dll'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0
env['CFILESUFFIX'] = '.cpp' | python | def generate(env):
findIt('bcc32', env)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ['.c', '.cpp']:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['CC'] = 'bcc32'
env['CCFLAGS'] = SCons.Util.CLVar('')
env['CFLAGS'] = SCons.Util.CLVar('')
env['CCCOM'] = '$CC -q $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
env['SHCCCOM'] = '$SHCC -WD $SHCFLAGS $SHCCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = ''
env['SHOBJSUFFIX'] = '.dll'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0
env['CFILESUFFIX'] = '.cpp' | [
"def",
"generate",
"(",
"env",
")",
":",
"findIt",
"(",
"'bcc32'",
",",
"env",
")",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"for",
"suffix",
"in",
"[",
"'.c'",
",",
"'.cpp'",
"]",
":",
"s... | Add Builders and construction variables for bcc to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"bcc",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/bcc32.py#L47-L72 |
23,829 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | require | def require(builder_name):
"""Find an advertised autobuilder and return it
This function searches through all installed distributions to find
if any advertise an entry point with group 'iotile.autobuild' and
name equal to builder_name. The first one that is found is returned.
This function raises a BuildError if it cannot find the required
autobuild function
Args:
builder_name (string): The name of the builder to find
Returns:
callable: the autobuilder function found in the search
"""
reg = ComponentRegistry()
for _name, autobuild_func in reg.load_extensions('iotile.autobuild', name_filter=builder_name):
return autobuild_func
raise BuildError('Cannot find required autobuilder, make sure the distribution providing it is installed',
name=builder_name) | python | def require(builder_name):
reg = ComponentRegistry()
for _name, autobuild_func in reg.load_extensions('iotile.autobuild', name_filter=builder_name):
return autobuild_func
raise BuildError('Cannot find required autobuilder, make sure the distribution providing it is installed',
name=builder_name) | [
"def",
"require",
"(",
"builder_name",
")",
":",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_name",
",",
"autobuild_func",
"in",
"reg",
".",
"load_extensions",
"(",
"'iotile.autobuild'",
",",
"name_filter",
"=",
"builder_name",
")",
":",
"return",
"aut... | Find an advertised autobuilder and return it
This function searches through all installed distributions to find
if any advertise an entry point with group 'iotile.autobuild' and
name equal to builder_name. The first one that is found is returned.
This function raises a BuildError if it cannot find the required
autobuild function
Args:
builder_name (string): The name of the builder to find
Returns:
callable: the autobuilder function found in the search | [
"Find",
"an",
"advertised",
"autobuilder",
"and",
"return",
"it"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L32-L54 |
23,830 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_onlycopy | def autobuild_onlycopy():
"""Autobuild a project that does not require building firmware, pcb or documentation
"""
try:
# Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
Alias('release', os.path.join('build', 'output'))
Default(['release'])
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | python | def autobuild_onlycopy():
try:
# Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
Alias('release', os.path.join('build', 'output'))
Default(['release'])
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | [
"def",
"autobuild_onlycopy",
"(",
")",
":",
"try",
":",
"# Build only release information",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_settings.json'",
")",
"autobuild_release",
"(",
"family",
")",
"Alias",
"(",
"'release'",
",",
"os",
".",
"path... | Autobuild a project that does not require building firmware, pcb or documentation | [
"Autobuild",
"a",
"project",
"that",
"does",
"not",
"require",
"building",
"firmware",
"pcb",
"or",
"documentation"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L89-L101 |
23,831 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_docproject | def autobuild_docproject():
"""Autobuild a project that only contains documentation"""
try:
#Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
autobuild_documentation(family.tile)
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | python | def autobuild_docproject():
try:
#Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
autobuild_documentation(family.tile)
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | [
"def",
"autobuild_docproject",
"(",
")",
":",
"try",
":",
"#Build only release information",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_settings.json'",
")",
"autobuild_release",
"(",
"family",
")",
"autobuild_documentation",
"(",
"family",
".",
"til... | Autobuild a project that only contains documentation | [
"Autobuild",
"a",
"project",
"that",
"only",
"contains",
"documentation"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L104-L114 |
23,832 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_arm_program | def autobuild_arm_program(elfname, test_dir=os.path.join('firmware', 'test'), patch=True):
"""
Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those.
"""
try:
#Build for all targets
family = utilities.get_family('module_settings.json')
family.for_all_targets(family.tile.short_name, lambda x: arm.build_program(family.tile, elfname, x, patch=patch))
#Build all unit tests
unit_test.build_units(os.path.join('firmware','test'), family.targets(family.tile.short_name))
Alias('release', os.path.join('build', 'output'))
Alias('test', os.path.join('build', 'test', 'output'))
Default(['release', 'test'])
autobuild_release(family)
if os.path.exists('doc'):
autobuild_documentation(family.tile)
except IOTileException as e:
print(e.format())
sys.exit(1) | python | def autobuild_arm_program(elfname, test_dir=os.path.join('firmware', 'test'), patch=True):
try:
#Build for all targets
family = utilities.get_family('module_settings.json')
family.for_all_targets(family.tile.short_name, lambda x: arm.build_program(family.tile, elfname, x, patch=patch))
#Build all unit tests
unit_test.build_units(os.path.join('firmware','test'), family.targets(family.tile.short_name))
Alias('release', os.path.join('build', 'output'))
Alias('test', os.path.join('build', 'test', 'output'))
Default(['release', 'test'])
autobuild_release(family)
if os.path.exists('doc'):
autobuild_documentation(family.tile)
except IOTileException as e:
print(e.format())
sys.exit(1) | [
"def",
"autobuild_arm_program",
"(",
"elfname",
",",
"test_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'firmware'",
",",
"'test'",
")",
",",
"patch",
"=",
"True",
")",
":",
"try",
":",
"#Build for all targets",
"family",
"=",
"utilities",
".",
"get_fa... | Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those. | [
"Build",
"the",
"an",
"ARM",
"module",
"for",
"all",
"targets",
"and",
"build",
"all",
"unit",
"tests",
".",
"If",
"pcb",
"files",
"are",
"given",
"also",
"build",
"those",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L152-L176 |
23,833 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_doxygen | def autobuild_doxygen(tile):
"""Generate documentation for firmware in this module using doxygen"""
iotile = IOTile('.')
doxydir = os.path.join('build', 'doc')
doxyfile = os.path.join(doxydir, 'doxygen.txt')
outfile = os.path.join(doxydir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
env['IOTILE'] = iotile
# There is no /dev/null on Windows
if platform.system() == 'Windows':
action = 'doxygen %s > NUL' % doxyfile
else:
action = 'doxygen %s > /dev/null' % doxyfile
Alias('doxygen', doxydir)
env.Clean(outfile, doxydir)
inputfile = doxygen_source_path()
env.Command(doxyfile, inputfile, action=env.Action(lambda target, source, env: generate_doxygen_file(str(target[0]), iotile), "Creating Doxygen Config File"))
env.Command(outfile, doxyfile, action=env.Action(action, "Building Firmware Documentation")) | python | def autobuild_doxygen(tile):
iotile = IOTile('.')
doxydir = os.path.join('build', 'doc')
doxyfile = os.path.join(doxydir, 'doxygen.txt')
outfile = os.path.join(doxydir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
env['IOTILE'] = iotile
# There is no /dev/null on Windows
if platform.system() == 'Windows':
action = 'doxygen %s > NUL' % doxyfile
else:
action = 'doxygen %s > /dev/null' % doxyfile
Alias('doxygen', doxydir)
env.Clean(outfile, doxydir)
inputfile = doxygen_source_path()
env.Command(doxyfile, inputfile, action=env.Action(lambda target, source, env: generate_doxygen_file(str(target[0]), iotile), "Creating Doxygen Config File"))
env.Command(outfile, doxyfile, action=env.Action(action, "Building Firmware Documentation")) | [
"def",
"autobuild_doxygen",
"(",
"tile",
")",
":",
"iotile",
"=",
"IOTile",
"(",
"'.'",
")",
"doxydir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'build'",
",",
"'doc'",
")",
"doxyfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"doxydir",
",",
"'... | Generate documentation for firmware in this module using doxygen | [
"Generate",
"documentation",
"for",
"firmware",
"in",
"this",
"module",
"using",
"doxygen"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L178-L202 |
23,834 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_documentation | def autobuild_documentation(tile):
"""Generate documentation for this module using a combination of sphinx and breathe"""
docdir = os.path.join('#doc')
docfile = os.path.join(docdir, 'conf.py')
outdir = os.path.join('build', 'output', 'doc', tile.unique_id)
outfile = os.path.join(outdir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
# Only build doxygen documentation if we have C firmware to build from
if os.path.exists('firmware'):
autobuild_doxygen(tile)
env.Depends(outfile, 'doxygen')
# There is no /dev/null on Windows
# Also disable color output on Windows since it seems to leave powershell
# in a weird state.
if platform.system() == 'Windows':
action = 'sphinx-build --no-color -b html %s %s > NUL' % (docdir[1:], outdir)
else:
action = 'sphinx-build -b html %s %s > /dev/null' % (docdir[1:], outdir)
env.Command(outfile, docfile, action=env.Action(action, "Building Component Documentation"))
Alias('documentation', outdir)
env.Clean(outfile, outdir) | python | def autobuild_documentation(tile):
docdir = os.path.join('#doc')
docfile = os.path.join(docdir, 'conf.py')
outdir = os.path.join('build', 'output', 'doc', tile.unique_id)
outfile = os.path.join(outdir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
# Only build doxygen documentation if we have C firmware to build from
if os.path.exists('firmware'):
autobuild_doxygen(tile)
env.Depends(outfile, 'doxygen')
# There is no /dev/null on Windows
# Also disable color output on Windows since it seems to leave powershell
# in a weird state.
if platform.system() == 'Windows':
action = 'sphinx-build --no-color -b html %s %s > NUL' % (docdir[1:], outdir)
else:
action = 'sphinx-build -b html %s %s > /dev/null' % (docdir[1:], outdir)
env.Command(outfile, docfile, action=env.Action(action, "Building Component Documentation"))
Alias('documentation', outdir)
env.Clean(outfile, outdir) | [
"def",
"autobuild_documentation",
"(",
"tile",
")",
":",
"docdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'#doc'",
")",
"docfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"docdir",
",",
"'conf.py'",
")",
"outdir",
"=",
"os",
".",
"path",
".",
... | Generate documentation for this module using a combination of sphinx and breathe | [
"Generate",
"documentation",
"for",
"this",
"module",
"using",
"a",
"combination",
"of",
"sphinx",
"and",
"breathe"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L205-L230 |
23,835 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_bootstrap_file | def autobuild_bootstrap_file(file_name, image_list):
"""Combine multiple firmware images into a single bootstrap hex file.
The files listed in image_list must be products of either this tile or any
dependency tile and should correspond exactly with the base name listed on
the products section of the module_settings.json file of the corresponding
tile. They must be listed as firmware_image type products.
This function keeps a global map of all of the intermediate files that it
has had to create so that we don't try to build them multiple times.
Args:
file_name(str): Full name of the output bootstrap hex file.
image_list(list of str): List of files that will be combined into a
single hex file that will be used to flash a chip.
"""
family = utilities.get_family('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
env = Environment(tools=[])
output_dir = target.build_dirs()['output']
build_dir = target.build_dirs()['build']
build_output_name = os.path.join(build_dir, file_name)
full_output_name = os.path.join(output_dir, file_name)
processed_input_images = []
for image_name in image_list:
image_info = resolver.find_unique('firmware_image', image_name)
image_path = image_info.full_path
hex_path = arm.ensure_image_is_hex(image_path)
processed_input_images.append(hex_path)
env.Command(build_output_name, processed_input_images,
action=Action(arm.merge_hex_executables,
"Merging %d hex files into $TARGET" % len(processed_input_images)))
env.Command(full_output_name, build_output_name, Copy("$TARGET", "$SOURCE")) | python | def autobuild_bootstrap_file(file_name, image_list):
family = utilities.get_family('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
env = Environment(tools=[])
output_dir = target.build_dirs()['output']
build_dir = target.build_dirs()['build']
build_output_name = os.path.join(build_dir, file_name)
full_output_name = os.path.join(output_dir, file_name)
processed_input_images = []
for image_name in image_list:
image_info = resolver.find_unique('firmware_image', image_name)
image_path = image_info.full_path
hex_path = arm.ensure_image_is_hex(image_path)
processed_input_images.append(hex_path)
env.Command(build_output_name, processed_input_images,
action=Action(arm.merge_hex_executables,
"Merging %d hex files into $TARGET" % len(processed_input_images)))
env.Command(full_output_name, build_output_name, Copy("$TARGET", "$SOURCE")) | [
"def",
"autobuild_bootstrap_file",
"(",
"file_name",
",",
"image_list",
")",
":",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_settings.json'",
")",
"target",
"=",
"family",
".",
"platform_independent_target",
"(",
")",
"resolver",
"=",
"ProductResol... | Combine multiple firmware images into a single bootstrap hex file.
The files listed in image_list must be products of either this tile or any
dependency tile and should correspond exactly with the base name listed on
the products section of the module_settings.json file of the corresponding
tile. They must be listed as firmware_image type products.
This function keeps a global map of all of the intermediate files that it
has had to create so that we don't try to build them multiple times.
Args:
file_name(str): Full name of the output bootstrap hex file.
image_list(list of str): List of files that will be combined into a
single hex file that will be used to flash a chip. | [
"Combine",
"multiple",
"firmware",
"images",
"into",
"a",
"single",
"bootstrap",
"hex",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L262-L303 |
23,836 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/scopes/scope.py | Scope.add_identifier | def add_identifier(self, name, obj):
"""Add a known identifier resolution.
Args:
name (str): The name of the identifier
obj (object): The object that is should resolve to
"""
name = str(name)
self._known_identifiers[name] = obj | python | def add_identifier(self, name, obj):
name = str(name)
self._known_identifiers[name] = obj | [
"def",
"add_identifier",
"(",
"self",
",",
"name",
",",
"obj",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"self",
".",
"_known_identifiers",
"[",
"name",
"]",
"=",
"obj"
] | Add a known identifier resolution.
Args:
name (str): The name of the identifier
obj (object): The object that is should resolve to | [
"Add",
"a",
"known",
"identifier",
"resolution",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/scopes/scope.py#L47-L56 |
23,837 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/scopes/scope.py | Scope.resolve_identifier | def resolve_identifier(self, name, expected_type=None):
"""Resolve an identifier to an object.
There is a single namespace for identifiers so the user also should
pass an expected type that will be checked against what the identifier
actually resolves to so that there are no surprises.
Args:
name (str): The name that we want to resolve
expected_type (type): The type of object that we expect to receive.
This is an optional parameter. If None is passed, no type checking
is performed.
Returns:
object: The resolved object
"""
name = str(name)
if name in self._known_identifiers:
obj = self._known_identifiers[name]
if expected_type is not None and not isinstance(obj, expected_type):
raise UnresolvedIdentifierError(u"Identifier resolved to an object of an unexpected type", name=name, expected_type=expected_type.__name__, resolved_type=obj.__class__.__name__)
return obj
if self.parent is not None:
try:
return self.parent.resolve_identifier(name)
except UnresolvedIdentifierError:
pass
raise UnresolvedIdentifierError(u"Could not resolve identifier", name=name, scope=self.name) | python | def resolve_identifier(self, name, expected_type=None):
name = str(name)
if name in self._known_identifiers:
obj = self._known_identifiers[name]
if expected_type is not None and not isinstance(obj, expected_type):
raise UnresolvedIdentifierError(u"Identifier resolved to an object of an unexpected type", name=name, expected_type=expected_type.__name__, resolved_type=obj.__class__.__name__)
return obj
if self.parent is not None:
try:
return self.parent.resolve_identifier(name)
except UnresolvedIdentifierError:
pass
raise UnresolvedIdentifierError(u"Could not resolve identifier", name=name, scope=self.name) | [
"def",
"resolve_identifier",
"(",
"self",
",",
"name",
",",
"expected_type",
"=",
"None",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"name",
"in",
"self",
".",
"_known_identifiers",
":",
"obj",
"=",
"self",
".",
"_known_identifiers",
"[",
"nam... | Resolve an identifier to an object.
There is a single namespace for identifiers so the user also should
pass an expected type that will be checked against what the identifier
actually resolves to so that there are no surprises.
Args:
name (str): The name that we want to resolve
expected_type (type): The type of object that we expect to receive.
This is an optional parameter. If None is passed, no type checking
is performed.
Returns:
object: The resolved object | [
"Resolve",
"an",
"identifier",
"to",
"an",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/scopes/scope.py#L58-L90 |
23,838 | iotile/coretools | iotilecore/iotile/core/hw/reports/signed_list_format.py | SignedListReport.FromReadings | def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None,
report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0):
"""Generate an instance of the report format from a list of readings and a uuid.
The signed list report is created using the passed readings and signed using the specified method
and AuthProvider. If no auth provider is specified, the report is signed using the default authorization
chain.
Args:
uuid (int): The uuid of the deviec that this report came from
readings (list): A list of IOTileReading objects containing the data in the report
root_key (int): The key that should be used to sign the report (must be supported
by an auth_provider)
signer (AuthProvider): An optional preconfigured AuthProvider that should be used to sign this
report. If no AuthProvider is provided, the default ChainedAuthProvider is used.
report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.
Note that you can specify anything you want for the report id but for actual IOTile devices
the report id will always be greater than the id of all of the readings contained in the report
since devices generate ids sequentially.
selector (int): The streamer selector of this report. This can be anything but if the report came from
a device, it would correspond with the query the device used to pick readings to go into the report.
streamer (int): The streamer id that this reading was sent from.
sent_timestamp (int): The device's uptime that sent this report.
"""
lowest_id = IOTileReading.InvalidReadingID
highest_id = IOTileReading.InvalidReadingID
report_len = 20 + 16*len(readings) + 24
len_low = report_len & 0xFF
len_high = report_len >> 8
unique_readings = [x.reading_id for x in readings if x.reading_id != IOTileReading.InvalidReadingID]
if len(unique_readings) > 0:
lowest_id = min(unique_readings)
highest_id = max(unique_readings)
header = struct.pack("<BBHLLLBBH", cls.ReportType, len_low, len_high, uuid, report_id,
sent_timestamp, root_key, streamer, selector)
header = bytearray(header)
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)
footer_stats = struct.pack("<LL", lowest_id, highest_id)
if signer is None:
signer = ChainedAuthProvider()
# If we are supposed to encrypt this report, do the encryption
if root_key != signer.NoKey:
enc_data = packed_readings
try:
result = signer.encrypt_report(uuid, root_key, enc_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not encrypt report because no AuthProvider supported "
"the requested encryption method for the requested device",
device_id=uuid, root_key=root_key)
signed_data = header + result['data'] + footer_stats
else:
signed_data = header + packed_readings + footer_stats
try:
signature = signer.sign_report(uuid, root_key, signed_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not sign report because no AuthProvider supported the requested "
"signature method for the requested device", device_id=uuid, root_key=root_key)
footer = struct.pack("16s", bytes(signature['signature'][:16]))
footer = bytearray(footer)
data = signed_data + footer
return SignedListReport(data) | python | def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None,
report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0):
lowest_id = IOTileReading.InvalidReadingID
highest_id = IOTileReading.InvalidReadingID
report_len = 20 + 16*len(readings) + 24
len_low = report_len & 0xFF
len_high = report_len >> 8
unique_readings = [x.reading_id for x in readings if x.reading_id != IOTileReading.InvalidReadingID]
if len(unique_readings) > 0:
lowest_id = min(unique_readings)
highest_id = max(unique_readings)
header = struct.pack("<BBHLLLBBH", cls.ReportType, len_low, len_high, uuid, report_id,
sent_timestamp, root_key, streamer, selector)
header = bytearray(header)
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)
footer_stats = struct.pack("<LL", lowest_id, highest_id)
if signer is None:
signer = ChainedAuthProvider()
# If we are supposed to encrypt this report, do the encryption
if root_key != signer.NoKey:
enc_data = packed_readings
try:
result = signer.encrypt_report(uuid, root_key, enc_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not encrypt report because no AuthProvider supported "
"the requested encryption method for the requested device",
device_id=uuid, root_key=root_key)
signed_data = header + result['data'] + footer_stats
else:
signed_data = header + packed_readings + footer_stats
try:
signature = signer.sign_report(uuid, root_key, signed_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not sign report because no AuthProvider supported the requested "
"signature method for the requested device", device_id=uuid, root_key=root_key)
footer = struct.pack("16s", bytes(signature['signature'][:16]))
footer = bytearray(footer)
data = signed_data + footer
return SignedListReport(data) | [
"def",
"FromReadings",
"(",
"cls",
",",
"uuid",
",",
"readings",
",",
"root_key",
"=",
"AuthProvider",
".",
"NoKey",
",",
"signer",
"=",
"None",
",",
"report_id",
"=",
"IOTileReading",
".",
"InvalidReadingID",
",",
"selector",
"=",
"0xFFFF",
",",
"streamer",... | Generate an instance of the report format from a list of readings and a uuid.
The signed list report is created using the passed readings and signed using the specified method
and AuthProvider. If no auth provider is specified, the report is signed using the default authorization
chain.
Args:
uuid (int): The uuid of the deviec that this report came from
readings (list): A list of IOTileReading objects containing the data in the report
root_key (int): The key that should be used to sign the report (must be supported
by an auth_provider)
signer (AuthProvider): An optional preconfigured AuthProvider that should be used to sign this
report. If no AuthProvider is provided, the default ChainedAuthProvider is used.
report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.
Note that you can specify anything you want for the report id but for actual IOTile devices
the report id will always be greater than the id of all of the readings contained in the report
since devices generate ids sequentially.
selector (int): The streamer selector of this report. This can be anything but if the report came from
a device, it would correspond with the query the device used to pick readings to go into the report.
streamer (int): The streamer id that this reading was sent from.
sent_timestamp (int): The device's uptime that sent this report. | [
"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/signed_list_format.py#L44-L124 |
23,839 | iotile/coretools | iotilecore/iotile/core/hw/reports/signed_list_format.py | SignedListReport.decode | def decode(self):
"""Decode this report into a list of readings
"""
fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \
origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20])
assert fmt == 1
length = (len_high << 8) | len_low
self.origin = device_id
self.report_id = report_id
self.sent_timestamp = sent_timestamp
self.origin_streamer = origin_streamer
self.streamer_selector = streamer_selector
self.signature_flags = signature_flags
assert len(self.raw_report) == length
remaining = self.raw_report[20:]
assert len(remaining) >= 24
readings = remaining[:-24]
footer = remaining[-24:]
lowest_id, highest_id, signature = unpack("<LL16s", footer)
signature = bytearray(signature)
self.lowest_id = lowest_id
self.highest_id = highest_id
self.signature = signature
signed_data = self.raw_report[:-16]
signer = ChainedAuthProvider()
if signature_flags == AuthProvider.NoKey:
self.encrypted = False
else:
self.encrypted = True
try:
verification = signer.verify_report(device_id, signature_flags, signed_data, signature,
report_id=report_id, sent_timestamp=sent_timestamp)
self.verified = verification['verified']
except NotFoundError:
self.verified = False
# If we were not able to verify the report, do not try to parse or decrypt it since we
# can't guarantee who it came from.
if not self.verified:
return [], []
# If the report is encrypted, try to decrypt it before parsing the readings
if self.encrypted:
try:
result = signer.decrypt_report(device_id, signature_flags, readings,
report_id=report_id, sent_timestamp=sent_timestamp)
readings = result['data']
except NotFoundError:
return [], []
# Now parse all of the readings
# Make sure this report has an integer number of readings
assert (len(readings) % 16) == 0
time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp)
parsed_readings = []
for i in range(0, len(readings), 16):
reading = readings[i:i+16]
stream, _, reading_id, timestamp, value = unpack("<HHLLL", reading)
parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id)
parsed_readings.append(parsed)
return parsed_readings, [] | python | def decode(self):
fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \
origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20])
assert fmt == 1
length = (len_high << 8) | len_low
self.origin = device_id
self.report_id = report_id
self.sent_timestamp = sent_timestamp
self.origin_streamer = origin_streamer
self.streamer_selector = streamer_selector
self.signature_flags = signature_flags
assert len(self.raw_report) == length
remaining = self.raw_report[20:]
assert len(remaining) >= 24
readings = remaining[:-24]
footer = remaining[-24:]
lowest_id, highest_id, signature = unpack("<LL16s", footer)
signature = bytearray(signature)
self.lowest_id = lowest_id
self.highest_id = highest_id
self.signature = signature
signed_data = self.raw_report[:-16]
signer = ChainedAuthProvider()
if signature_flags == AuthProvider.NoKey:
self.encrypted = False
else:
self.encrypted = True
try:
verification = signer.verify_report(device_id, signature_flags, signed_data, signature,
report_id=report_id, sent_timestamp=sent_timestamp)
self.verified = verification['verified']
except NotFoundError:
self.verified = False
# If we were not able to verify the report, do not try to parse or decrypt it since we
# can't guarantee who it came from.
if not self.verified:
return [], []
# If the report is encrypted, try to decrypt it before parsing the readings
if self.encrypted:
try:
result = signer.decrypt_report(device_id, signature_flags, readings,
report_id=report_id, sent_timestamp=sent_timestamp)
readings = result['data']
except NotFoundError:
return [], []
# Now parse all of the readings
# Make sure this report has an integer number of readings
assert (len(readings) % 16) == 0
time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp)
parsed_readings = []
for i in range(0, len(readings), 16):
reading = readings[i:i+16]
stream, _, reading_id, timestamp, value = unpack("<HHLLL", reading)
parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id)
parsed_readings.append(parsed)
return parsed_readings, [] | [
"def",
"decode",
"(",
"self",
")",
":",
"fmt",
",",
"len_low",
",",
"len_high",
",",
"device_id",
",",
"report_id",
",",
"sent_timestamp",
",",
"signature_flags",
",",
"origin_streamer",
",",
"streamer_selector",
"=",
"unpack",
"(",
"\"<BBHLLLBBH\"",
",",
"sel... | Decode this report into a list of readings | [
"Decode",
"this",
"report",
"into",
"a",
"list",
"of",
"readings"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/signed_list_format.py#L126-L200 |
23,840 | iotile/coretools | iotilesensorgraph/iotile/sg/model.py | DeviceModel._add_property | def _add_property(self, name, default_value):
"""Add a device property with a given default value.
Args:
name (str): The name of the property to add
default_value (int, bool): The value of the property
"""
name = str(name)
self._properties[name] = default_value | python | def _add_property(self, name, default_value):
name = str(name)
self._properties[name] = default_value | [
"def",
"_add_property",
"(",
"self",
",",
"name",
",",
"default_value",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"self",
".",
"_properties",
"[",
"name",
"]",
"=",
"default_value"
] | Add a device property with a given default value.
Args:
name (str): The name of the property to add
default_value (int, bool): The value of the property | [
"Add",
"a",
"device",
"property",
"with",
"a",
"given",
"default",
"value",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/model.py#L28-L37 |
23,841 | iotile/coretools | iotilesensorgraph/iotile/sg/model.py | DeviceModel.set | def set(self, name, value):
"""Set a device model property.
Args:
name (str): The name of the property to set
value (int, bool): The value of the property to set
"""
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
self._properties[name] = value | python | def set(self, name, value):
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
self._properties[name] = value | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"_properties",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown property in DeviceModel\"",
",",
"name",
"=",
"nam... | Set a device model property.
Args:
name (str): The name of the property to set
value (int, bool): The value of the property to set | [
"Set",
"a",
"device",
"model",
"property",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/model.py#L39-L51 |
23,842 | iotile/coretools | iotilesensorgraph/iotile/sg/model.py | DeviceModel.get | def get(self, name):
"""Get a device model property.
Args:
name (str): The name of the property to get
"""
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
return self._properties[name] | python | def get(self, name):
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
return self._properties[name] | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"_properties",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown property in DeviceModel\"",
",",
"name",
"=",
"name",
")",
"retu... | Get a device model property.
Args:
name (str): The name of the property to get | [
"Get",
"a",
"device",
"model",
"property",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/model.py#L53-L64 |
23,843 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | _convert_to_bytes | def _convert_to_bytes(type_name, value):
"""Convert a typed value to a binary array"""
int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'}
type_name = type_name.lower()
if type_name not in int_types and type_name not in ['string', 'binary']:
raise ArgumentError('Type must be a known integer type, integer type array, string', known_integers=int_types.keys(), actual_type=type_name)
if type_name == 'string':
#value should be passed as a string
bytevalue = bytes(value)
elif type_name == 'binary':
bytevalue = bytes(value)
else:
bytevalue = struct.pack("<%s" % int_types[type_name], value)
return bytevalue | python | def _convert_to_bytes(type_name, value):
int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'}
type_name = type_name.lower()
if type_name not in int_types and type_name not in ['string', 'binary']:
raise ArgumentError('Type must be a known integer type, integer type array, string', known_integers=int_types.keys(), actual_type=type_name)
if type_name == 'string':
#value should be passed as a string
bytevalue = bytes(value)
elif type_name == 'binary':
bytevalue = bytes(value)
else:
bytevalue = struct.pack("<%s" % int_types[type_name], value)
return bytevalue | [
"def",
"_convert_to_bytes",
"(",
"type_name",
",",
"value",
")",
":",
"int_types",
"=",
"{",
"'uint8_t'",
":",
"'B'",
",",
"'int8_t'",
":",
"'b'",
",",
"'uint16_t'",
":",
"'H'",
",",
"'int16_t'",
":",
"'h'",
",",
"'uint32_t'",
":",
"'L'",
",",
"'int32_t'... | Convert a typed value to a binary array | [
"Convert",
"a",
"typed",
"value",
"to",
"a",
"binary",
"array"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L378-L396 |
23,844 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigEntry.dump | def dump(self):
"""Serialize this object."""
return {
'target': str(self.target),
'data': base64.b64encode(self.data).decode('utf-8'),
'var_id': self.var_id,
'valid': self.valid
} | python | def dump(self):
return {
'target': str(self.target),
'data': base64.b64encode(self.data).decode('utf-8'),
'var_id': self.var_id,
'valid': self.valid
} | [
"def",
"dump",
"(",
"self",
")",
":",
"return",
"{",
"'target'",
":",
"str",
"(",
"self",
".",
"target",
")",
",",
"'data'",
":",
"base64",
".",
"b64encode",
"(",
"self",
".",
"data",
")",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"'var_id'",
":",
... | Serialize this object. | [
"Serialize",
"this",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L39-L47 |
23,845 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigEntry.generate_rpcs | def generate_rpcs(self, address):
"""Generate the RPCs needed to stream this config variable to a tile.
Args:
address (int): The address of the tile that we should stream to.
Returns:
list of tuples: A list of argument tuples for each RPC.
These tuples can be passed to EmulatedDevice.rpc to actually make
the RPCs.
"""
rpc_list = []
for offset in range(2, len(self.data), 16):
rpc = (address, rpcs.SET_CONFIG_VARIABLE, self.var_id, offset - 2, self.data[offset:offset + 16])
rpc_list.append(rpc)
return rpc_list | python | def generate_rpcs(self, address):
rpc_list = []
for offset in range(2, len(self.data), 16):
rpc = (address, rpcs.SET_CONFIG_VARIABLE, self.var_id, offset - 2, self.data[offset:offset + 16])
rpc_list.append(rpc)
return rpc_list | [
"def",
"generate_rpcs",
"(",
"self",
",",
"address",
")",
":",
"rpc_list",
"=",
"[",
"]",
"for",
"offset",
"in",
"range",
"(",
"2",
",",
"len",
"(",
"self",
".",
"data",
")",
",",
"16",
")",
":",
"rpc",
"=",
"(",
"address",
",",
"rpcs",
".",
"S... | Generate the RPCs needed to stream this config variable to a tile.
Args:
address (int): The address of the tile that we should stream to.
Returns:
list of tuples: A list of argument tuples for each RPC.
These tuples can be passed to EmulatedDevice.rpc to actually make
the RPCs. | [
"Generate",
"the",
"RPCs",
"needed",
"to",
"stream",
"this",
"config",
"variable",
"to",
"a",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L49-L68 |
23,846 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigEntry.Restore | def Restore(cls, state):
"""Unserialize this object."""
target = SlotIdentifier.FromString(state.get('target'))
data = base64.b64decode(state.get('data'))
var_id = state.get('var_id')
valid = state.get('valid')
return ConfigEntry(target, var_id, data, valid) | python | def Restore(cls, state):
target = SlotIdentifier.FromString(state.get('target'))
data = base64.b64decode(state.get('data'))
var_id = state.get('var_id')
valid = state.get('valid')
return ConfigEntry(target, var_id, data, valid) | [
"def",
"Restore",
"(",
"cls",
",",
"state",
")",
":",
"target",
"=",
"SlotIdentifier",
".",
"FromString",
"(",
"state",
".",
"get",
"(",
"'target'",
")",
")",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"state",
".",
"get",
"(",
"'data'",
")",
")",... | Unserialize this object. | [
"Unserialize",
"this",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L71-L79 |
23,847 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.compact | def compact(self):
"""Remove all invalid config entries."""
saved_length = 0
to_remove = []
for i, entry in enumerate(self.entries):
if not entry.valid:
to_remove.append(i)
saved_length += entry.data_space()
for i in reversed(to_remove):
del self.entries[i]
self.data_index -= saved_length | python | def compact(self):
saved_length = 0
to_remove = []
for i, entry in enumerate(self.entries):
if not entry.valid:
to_remove.append(i)
saved_length += entry.data_space()
for i in reversed(to_remove):
del self.entries[i]
self.data_index -= saved_length | [
"def",
"compact",
"(",
"self",
")",
":",
"saved_length",
"=",
"0",
"to_remove",
"=",
"[",
"]",
"for",
"i",
",",
"entry",
"in",
"enumerate",
"(",
"self",
".",
"entries",
")",
":",
"if",
"not",
"entry",
".",
"valid",
":",
"to_remove",
".",
"append",
... | Remove all invalid config entries. | [
"Remove",
"all",
"invalid",
"config",
"entries",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L109-L122 |
23,848 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.start_entry | def start_entry(self, target, var_id):
"""Begin a new config database entry.
If there is a current entry in progress, it is aborted but the
data was already committed to persistent storage so that space
is wasted.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
Returns:
int: An error code from the global Errors enum.
"""
self.in_progress = ConfigEntry(target, var_id, b'')
if self.data_size - self.data_index < self.in_progress.data_space():
return Error.DESTINATION_BUFFER_TOO_SMALL
self.in_progress.data += struct.pack("<H", var_id)
self.data_index += self.in_progress.data_space()
return Error.NO_ERROR | python | def start_entry(self, target, var_id):
self.in_progress = ConfigEntry(target, var_id, b'')
if self.data_size - self.data_index < self.in_progress.data_space():
return Error.DESTINATION_BUFFER_TOO_SMALL
self.in_progress.data += struct.pack("<H", var_id)
self.data_index += self.in_progress.data_space()
return Error.NO_ERROR | [
"def",
"start_entry",
"(",
"self",
",",
"target",
",",
"var_id",
")",
":",
"self",
".",
"in_progress",
"=",
"ConfigEntry",
"(",
"target",
",",
"var_id",
",",
"b''",
")",
"if",
"self",
".",
"data_size",
"-",
"self",
".",
"data_index",
"<",
"self",
".",
... | Begin a new config database entry.
If there is a current entry in progress, it is aborted but the
data was already committed to persistent storage so that space
is wasted.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
Returns:
int: An error code from the global Errors enum. | [
"Begin",
"a",
"new",
"config",
"database",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L131-L154 |
23,849 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.add_data | def add_data(self, data):
"""Add data to the currently in progress entry.
Args:
data (bytes): The data that we want to add.
Returns:
int: An error code
"""
if self.data_size - self.data_index < len(data):
return Error.DESTINATION_BUFFER_TOO_SMALL
if self.in_progress is not None:
self.in_progress.data += data
return Error.NO_ERROR | python | def add_data(self, data):
if self.data_size - self.data_index < len(data):
return Error.DESTINATION_BUFFER_TOO_SMALL
if self.in_progress is not None:
self.in_progress.data += data
return Error.NO_ERROR | [
"def",
"add_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"data_size",
"-",
"self",
".",
"data_index",
"<",
"len",
"(",
"data",
")",
":",
"return",
"Error",
".",
"DESTINATION_BUFFER_TOO_SMALL",
"if",
"self",
".",
"in_progress",
"is",
"not... | Add data to the currently in progress entry.
Args:
data (bytes): The data that we want to add.
Returns:
int: An error code | [
"Add",
"data",
"to",
"the",
"currently",
"in",
"progress",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L156-L172 |
23,850 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.end_entry | def end_entry(self):
"""Finish a previously started config database entry.
This commits the currently in progress entry. The expected flow is
that start_entry() is called followed by 1 or more calls to add_data()
followed by a single call to end_entry().
Returns:
int: An error code
"""
# Matching current firmware behavior
if self.in_progress is None:
return Error.NO_ERROR
# Make sure there was actually data stored
if self.in_progress.data_space() == 2:
return Error.INPUT_BUFFER_WRONG_SIZE
# Invalidate all previous copies of this config variable so we
# can properly compact.
for entry in self.entries:
if entry.target == self.in_progress.target and entry.var_id == self.in_progress.var_id:
entry.valid = False
self.entries.append(self.in_progress)
self.data_index += self.in_progress.data_space() - 2 # Add in the rest of the entry size (we added two bytes at start_entry())
self.in_progress = None
return Error.NO_ERROR | python | def end_entry(self):
# Matching current firmware behavior
if self.in_progress is None:
return Error.NO_ERROR
# Make sure there was actually data stored
if self.in_progress.data_space() == 2:
return Error.INPUT_BUFFER_WRONG_SIZE
# Invalidate all previous copies of this config variable so we
# can properly compact.
for entry in self.entries:
if entry.target == self.in_progress.target and entry.var_id == self.in_progress.var_id:
entry.valid = False
self.entries.append(self.in_progress)
self.data_index += self.in_progress.data_space() - 2 # Add in the rest of the entry size (we added two bytes at start_entry())
self.in_progress = None
return Error.NO_ERROR | [
"def",
"end_entry",
"(",
"self",
")",
":",
"# Matching current firmware behavior",
"if",
"self",
".",
"in_progress",
"is",
"None",
":",
"return",
"Error",
".",
"NO_ERROR",
"# Make sure there was actually data stored",
"if",
"self",
".",
"in_progress",
".",
"data_space... | Finish a previously started config database entry.
This commits the currently in progress entry. The expected flow is
that start_entry() is called followed by 1 or more calls to add_data()
followed by a single call to end_entry().
Returns:
int: An error code | [
"Finish",
"a",
"previously",
"started",
"config",
"database",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L174-L203 |
23,851 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.stream_matching | def stream_matching(self, address, name):
"""Return the RPCs needed to stream matching config variables to the given tile.
This function will return a list of tuples suitable for passing to
EmulatedDevice.deferred_rpc.
Args:
address (int): The address of the tile that we wish to stream to
name (str or bytes): The 6 character name of the target tile.
Returns:
list of tuple: The list of RPCs to send to stream these variables to a tile.
"""
matching = [x for x in self.entries if x.valid and x.target.matches(address, name)]
rpc_list = []
for var in matching:
rpc_list.extend(var.generate_rpcs(address))
return rpc_list | python | def stream_matching(self, address, name):
matching = [x for x in self.entries if x.valid and x.target.matches(address, name)]
rpc_list = []
for var in matching:
rpc_list.extend(var.generate_rpcs(address))
return rpc_list | [
"def",
"stream_matching",
"(",
"self",
",",
"address",
",",
"name",
")",
":",
"matching",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"entries",
"if",
"x",
".",
"valid",
"and",
"x",
".",
"target",
".",
"matches",
"(",
"address",
",",
"name",
")",... | Return the RPCs needed to stream matching config variables to the given tile.
This function will return a list of tuples suitable for passing to
EmulatedDevice.deferred_rpc.
Args:
address (int): The address of the tile that we wish to stream to
name (str or bytes): The 6 character name of the target tile.
Returns:
list of tuple: The list of RPCs to send to stream these variables to a tile. | [
"Return",
"the",
"RPCs",
"needed",
"to",
"stream",
"matching",
"config",
"variables",
"to",
"the",
"given",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L205-L225 |
23,852 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.add_direct | def add_direct(self, target, var_id, var_type, data):
"""Directly add a config variable.
This method is meant to be called from emulation scenarios that
want to directly set config database entries from python.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
var_type (str): The config variable type
data (bytes or int or str): The data that will be encoded according
to var_type.
"""
data = struct.pack("<H", var_id) + _convert_to_bytes(var_type, data)
if self.data_size - self.data_index < len(data):
raise DataError("Not enough space for data in new conig entry", needed_space=len(data), actual_space=(self.data_size - self.data_index))
new_entry = ConfigEntry(target, var_id, data)
for entry in self.entries:
if entry.target == new_entry.target and entry.var_id == new_entry.var_id:
entry.valid = False
self.entries.append(new_entry)
self.data_index += new_entry.data_space() | python | def add_direct(self, target, var_id, var_type, data):
data = struct.pack("<H", var_id) + _convert_to_bytes(var_type, data)
if self.data_size - self.data_index < len(data):
raise DataError("Not enough space for data in new conig entry", needed_space=len(data), actual_space=(self.data_size - self.data_index))
new_entry = ConfigEntry(target, var_id, data)
for entry in self.entries:
if entry.target == new_entry.target and entry.var_id == new_entry.var_id:
entry.valid = False
self.entries.append(new_entry)
self.data_index += new_entry.data_space() | [
"def",
"add_direct",
"(",
"self",
",",
"target",
",",
"var_id",
",",
"var_type",
",",
"data",
")",
":",
"data",
"=",
"struct",
".",
"pack",
"(",
"\"<H\"",
",",
"var_id",
")",
"+",
"_convert_to_bytes",
"(",
"var_type",
",",
"data",
")",
"if",
"self",
... | Directly add a config variable.
This method is meant to be called from emulation scenarios that
want to directly set config database entries from python.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
var_type (str): The config variable type
data (bytes or int or str): The data that will be encoded according
to var_type. | [
"Directly",
"add",
"a",
"config",
"variable",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L227-L253 |
23,853 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.start_config_var_entry | def start_config_var_entry(self, var_id, encoded_selector):
"""Start a new config variable entry."""
selector = SlotIdentifier.FromEncoded(encoded_selector)
err = self.config_database.start_entry(selector, var_id)
return [err] | python | def start_config_var_entry(self, var_id, encoded_selector):
selector = SlotIdentifier.FromEncoded(encoded_selector)
err = self.config_database.start_entry(selector, var_id)
return [err] | [
"def",
"start_config_var_entry",
"(",
"self",
",",
"var_id",
",",
"encoded_selector",
")",
":",
"selector",
"=",
"SlotIdentifier",
".",
"FromEncoded",
"(",
"encoded_selector",
")",
"err",
"=",
"self",
".",
"config_database",
".",
"start_entry",
"(",
"selector",
... | Start a new config variable entry. | [
"Start",
"a",
"new",
"config",
"variable",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L277-L283 |
23,854 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.get_config_var_entry | def get_config_var_entry(self, index):
"""Get the metadata from the selected config variable entry."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, b'\0'*8, 0, 0]
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, 0, 0, 0, b'\0'*8, 0, 0]
offset = sum(x.data_space() for x in self.config_database.entries[:index - 1])
return [Error.NO_ERROR, self.config_database.ENTRY_MAGIC, offset, entry.data_space(), entry.target.encode(), 0xFF, 0] | python | def get_config_var_entry(self, index):
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, b'\0'*8, 0, 0]
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, 0, 0, 0, b'\0'*8, 0, 0]
offset = sum(x.data_space() for x in self.config_database.entries[:index - 1])
return [Error.NO_ERROR, self.config_database.ENTRY_MAGIC, offset, entry.data_space(), entry.target.encode(), 0xFF, 0] | [
"def",
"get_config_var_entry",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"config_database",
".",
"entries",
")",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
"0",
",",
"0"... | Get the metadata from the selected config variable entry. | [
"Get",
"the",
"metadata",
"from",
"the",
"selected",
"config",
"variable",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L300-L311 |
23,855 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.get_config_var_data | def get_config_var_data(self, index, offset):
"""Get a chunk of data for a config variable."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
if offset >= len(entry.data):
return [Error.INVALID_ARRAY_KEY, b'']
data_chunk = entry.data[offset:offset + 16]
return [Error.NO_ERROR, data_chunk] | python | def get_config_var_data(self, index, offset):
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
if offset >= len(entry.data):
return [Error.INVALID_ARRAY_KEY, b'']
data_chunk = entry.data[offset:offset + 16]
return [Error.NO_ERROR, data_chunk] | [
"def",
"get_config_var_data",
"(",
"self",
",",
"index",
",",
"offset",
")",
":",
"if",
"index",
"==",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"config_database",
".",
"entries",
")",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
... | Get a chunk of data for a config variable. | [
"Get",
"a",
"chunk",
"of",
"data",
"for",
"a",
"config",
"variable",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L327-L341 |
23,856 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.invalidate_config_var_entry | def invalidate_config_var_entry(self, index):
"""Mark a config variable as invalid."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
entry.valid = False
return [Error.NO_ERROR] | python | def invalidate_config_var_entry(self, index):
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
entry.valid = False
return [Error.NO_ERROR] | [
"def",
"invalidate_config_var_entry",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"config_database",
".",
"entries",
")",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
"b''",
"... | Mark a config variable as invalid. | [
"Mark",
"a",
"config",
"variable",
"as",
"invalid",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L344-L355 |
23,857 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.get_config_database_info | def get_config_database_info(self):
"""Get memory usage and space statistics on the config database."""
max_size = self.config_database.data_size
max_entries = self.config_database.max_entries()
used_size = self.config_database.data_index
used_entries = len(self.config_database.entries)
invalid_size = sum(x.data_space() for x in self.config_database.entries if not x.valid)
invalid_entries = sum(1 for x in self.config_database.entries if not x.valid)
return [max_size, used_size, invalid_size, used_entries, invalid_entries, max_entries, 0] | python | def get_config_database_info(self):
max_size = self.config_database.data_size
max_entries = self.config_database.max_entries()
used_size = self.config_database.data_index
used_entries = len(self.config_database.entries)
invalid_size = sum(x.data_space() for x in self.config_database.entries if not x.valid)
invalid_entries = sum(1 for x in self.config_database.entries if not x.valid)
return [max_size, used_size, invalid_size, used_entries, invalid_entries, max_entries, 0] | [
"def",
"get_config_database_info",
"(",
"self",
")",
":",
"max_size",
"=",
"self",
".",
"config_database",
".",
"data_size",
"max_entries",
"=",
"self",
".",
"config_database",
".",
"max_entries",
"(",
")",
"used_size",
"=",
"self",
".",
"config_database",
".",
... | Get memory usage and space statistics on the config database. | [
"Get",
"memory",
"usage",
"and",
"space",
"statistics",
"on",
"the",
"config",
"database",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L365-L375 |
23,858 | iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualtile.py | VirtualTile.FindByName | def FindByName(cls, name):
"""Find an installed VirtualTile by name.
This function searches for installed virtual tiles
using the pkg_resources entry_point `iotile.virtual_tile`.
If name is a path ending in .py, it is assumed to point to
a module on disk and loaded directly rather than using
pkg_resources.
Args:
name (str): The name of the tile to search
for.
Returns:
VirtualTile class: A virtual tile subclass that can be
instantiated to create a virtual tile.
"""
if name.endswith('.py'):
return cls.LoadFromFile(name)
reg = ComponentRegistry()
for _name, tile in reg.load_extensions('iotile.virtual_tile', name_filter=name, class_filter=VirtualTile):
return tile
raise ArgumentError("VirtualTile could not be found by name", name=name) | python | def FindByName(cls, name):
if name.endswith('.py'):
return cls.LoadFromFile(name)
reg = ComponentRegistry()
for _name, tile in reg.load_extensions('iotile.virtual_tile', name_filter=name, class_filter=VirtualTile):
return tile
raise ArgumentError("VirtualTile could not be found by name", name=name) | [
"def",
"FindByName",
"(",
"cls",
",",
"name",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'.py'",
")",
":",
"return",
"cls",
".",
"LoadFromFile",
"(",
"name",
")",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_name",
",",
"tile",
"in",
"reg"... | Find an installed VirtualTile by name.
This function searches for installed virtual tiles
using the pkg_resources entry_point `iotile.virtual_tile`.
If name is a path ending in .py, it is assumed to point to
a module on disk and loaded directly rather than using
pkg_resources.
Args:
name (str): The name of the tile to search
for.
Returns:
VirtualTile class: A virtual tile subclass that can be
instantiated to create a virtual tile. | [
"Find",
"an",
"installed",
"VirtualTile",
"by",
"name",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualtile.py#L58-L84 |
23,859 | iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualtile.py | VirtualTile.LoadFromFile | def LoadFromFile(cls, script_path):
"""Import a virtual tile from a file rather than an installed module
script_path must point to a python file ending in .py that contains exactly one
VirtualTile class definition. That class is loaded and executed as if it
were installed.
To facilitate development, if there is a proxy object defined in the same
file, it is also added to the HardwareManager proxy registry so that it
can be found and used with the device.
Args:
script_path (string): The path to the script to load
Returns:
VirtualTile: A subclass of VirtualTile that was loaded from script_path
"""
_name, dev = ComponentRegistry().load_extension(script_path, class_filter=VirtualTile, unique=True)
return dev | python | def LoadFromFile(cls, script_path):
_name, dev = ComponentRegistry().load_extension(script_path, class_filter=VirtualTile, unique=True)
return dev | [
"def",
"LoadFromFile",
"(",
"cls",
",",
"script_path",
")",
":",
"_name",
",",
"dev",
"=",
"ComponentRegistry",
"(",
")",
".",
"load_extension",
"(",
"script_path",
",",
"class_filter",
"=",
"VirtualTile",
",",
"unique",
"=",
"True",
")",
"return",
"dev"
] | Import a virtual tile from a file rather than an installed module
script_path must point to a python file ending in .py that contains exactly one
VirtualTile class definition. That class is loaded and executed as if it
were installed.
To facilitate development, if there is a proxy object defined in the same
file, it is also added to the HardwareManager proxy registry so that it
can be found and used with the device.
Args:
script_path (string): The path to the script to load
Returns:
VirtualTile: A subclass of VirtualTile that was loaded from script_path | [
"Import",
"a",
"virtual",
"tile",
"from",
"a",
"file",
"rather",
"than",
"an",
"installed",
"module"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualtile.py#L87-L106 |
23,860 | iotile/coretools | iotilebuild/iotile/build/release/pypi_provider.py | PyPIReleaseProvider.stage | def stage(self):
"""Stage python packages for release, verifying everything we can about them."""
if 'PYPI_USER' not in os.environ or 'PYPI_PASS' not in os.environ:
raise BuildError("You must set the PYPI_USER and PYPI_PASS environment variables")
try:
import twine
except ImportError:
raise BuildError("You must install twine in order to release python packages",
suggestion="pip install twine")
if not self.component.has_wheel:
raise BuildError("You can't release a component to a PYPI repository if it doesn't have python packages")
# Make sure we have built distributions ready to upload
wheel = self.component.support_wheel
sdist = "%s-%s.tar.gz" % (self.component.support_distribution, self.component.parsed_version.pep440_string())
wheel_path = os.path.realpath(os.path.abspath(os.path.join(self.component.output_folder, 'python', wheel)))
sdist_path = os.path.realpath(os.path.abspath(os.path.join(self.component.output_folder, 'python', sdist)))
if not os.path.isfile(wheel_path) or not os.path.isfile(sdist_path):
raise BuildError("Could not find built wheel or sdist matching current built version",
sdist_path=sdist_path, wheel_path=wheel_path)
self.dists = [sdist_path, wheel_path] | python | def stage(self):
if 'PYPI_USER' not in os.environ or 'PYPI_PASS' not in os.environ:
raise BuildError("You must set the PYPI_USER and PYPI_PASS environment variables")
try:
import twine
except ImportError:
raise BuildError("You must install twine in order to release python packages",
suggestion="pip install twine")
if not self.component.has_wheel:
raise BuildError("You can't release a component to a PYPI repository if it doesn't have python packages")
# Make sure we have built distributions ready to upload
wheel = self.component.support_wheel
sdist = "%s-%s.tar.gz" % (self.component.support_distribution, self.component.parsed_version.pep440_string())
wheel_path = os.path.realpath(os.path.abspath(os.path.join(self.component.output_folder, 'python', wheel)))
sdist_path = os.path.realpath(os.path.abspath(os.path.join(self.component.output_folder, 'python', sdist)))
if not os.path.isfile(wheel_path) or not os.path.isfile(sdist_path):
raise BuildError("Could not find built wheel or sdist matching current built version",
sdist_path=sdist_path, wheel_path=wheel_path)
self.dists = [sdist_path, wheel_path] | [
"def",
"stage",
"(",
"self",
")",
":",
"if",
"'PYPI_USER'",
"not",
"in",
"os",
".",
"environ",
"or",
"'PYPI_PASS'",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"BuildError",
"(",
"\"You must set the PYPI_USER and PYPI_PASS environment variables\"",
")",
"try"... | Stage python packages for release, verifying everything we can about them. | [
"Stage",
"python",
"packages",
"for",
"release",
"verifying",
"everything",
"we",
"can",
"about",
"them",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/release/pypi_provider.py#L32-L58 |
23,861 | iotile/coretools | iotilecore/iotile/core/hw/reports/parser.py | IOTileReportParser.add_data | def add_data(self, data):
"""Add data to our stream, emitting reports as each new one is seen
Args:
data (bytearray): A chunk of new data to add
"""
if self.state == self.ErrorState:
return
self.raw_data += bytearray(data)
still_processing = True
while still_processing:
still_processing = self.process_data() | python | def add_data(self, data):
if self.state == self.ErrorState:
return
self.raw_data += bytearray(data)
still_processing = True
while still_processing:
still_processing = self.process_data() | [
"def",
"add_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"state",
"==",
"self",
".",
"ErrorState",
":",
"return",
"self",
".",
"raw_data",
"+=",
"bytearray",
"(",
"data",
")",
"still_processing",
"=",
"True",
"while",
"still_processing",
... | Add data to our stream, emitting reports as each new one is seen
Args:
data (bytearray): A chunk of new data to add | [
"Add",
"data",
"to",
"our",
"stream",
"emitting",
"reports",
"as",
"each",
"new",
"one",
"is",
"seen"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/parser.py#L51-L65 |
23,862 | iotile/coretools | iotilecore/iotile/core/hw/reports/parser.py | IOTileReportParser.process_data | def process_data(self):
"""Attempt to extract a report from the current data stream contents
Returns:
bool: True if further processing is required and process_data should be
called again.
"""
further_processing = False
if self.state == self.WaitingForReportType and len(self.raw_data) > 0:
self.current_type = self.raw_data[0]
try:
self.current_header_size = self.calculate_header_size(self.current_type)
self.state = self.WaitingForReportHeader
further_processing = True
except Exception as exc:
self.state = self.ErrorState
if self.error_callback:
self.error_callback(self.ErrorFindingReportType, str(exc), self.context)
else:
raise
if self.state == self.WaitingForReportHeader and len(self.raw_data) >= self.current_header_size:
try:
self.current_report_size = self.calculate_report_size(self.current_type,
self.raw_data[:self.current_header_size])
self.state = self.WaitingForCompleteReport
further_processing = True
except Exception as exc:
self.state = self.ErrorState
if self.error_callback:
self.error_callback(self.ErrorParsingReportHeader, str(exc), self.context)
else:
raise
if self.state == self.WaitingForCompleteReport and len(self.raw_data) >= self.current_report_size:
try:
report_data = self.raw_data[:self.current_report_size]
self.raw_data = self.raw_data[self.current_report_size:]
report = self.parse_report(self.current_type, report_data)
self._handle_report(report)
self.state = self.WaitingForReportType
further_processing = True
except Exception as exc:
self.state = self.ErrorState
if self.error_callback:
self.error_callback(self.ErrorParsingCompleteReport, str(exc), self.context)
else:
raise
return further_processing | python | def process_data(self):
further_processing = False
if self.state == self.WaitingForReportType and len(self.raw_data) > 0:
self.current_type = self.raw_data[0]
try:
self.current_header_size = self.calculate_header_size(self.current_type)
self.state = self.WaitingForReportHeader
further_processing = True
except Exception as exc:
self.state = self.ErrorState
if self.error_callback:
self.error_callback(self.ErrorFindingReportType, str(exc), self.context)
else:
raise
if self.state == self.WaitingForReportHeader and len(self.raw_data) >= self.current_header_size:
try:
self.current_report_size = self.calculate_report_size(self.current_type,
self.raw_data[:self.current_header_size])
self.state = self.WaitingForCompleteReport
further_processing = True
except Exception as exc:
self.state = self.ErrorState
if self.error_callback:
self.error_callback(self.ErrorParsingReportHeader, str(exc), self.context)
else:
raise
if self.state == self.WaitingForCompleteReport and len(self.raw_data) >= self.current_report_size:
try:
report_data = self.raw_data[:self.current_report_size]
self.raw_data = self.raw_data[self.current_report_size:]
report = self.parse_report(self.current_type, report_data)
self._handle_report(report)
self.state = self.WaitingForReportType
further_processing = True
except Exception as exc:
self.state = self.ErrorState
if self.error_callback:
self.error_callback(self.ErrorParsingCompleteReport, str(exc), self.context)
else:
raise
return further_processing | [
"def",
"process_data",
"(",
"self",
")",
":",
"further_processing",
"=",
"False",
"if",
"self",
".",
"state",
"==",
"self",
".",
"WaitingForReportType",
"and",
"len",
"(",
"self",
".",
"raw_data",
")",
">",
"0",
":",
"self",
".",
"current_type",
"=",
"se... | Attempt to extract a report from the current data stream contents
Returns:
bool: True if further processing is required and process_data should be
called again. | [
"Attempt",
"to",
"extract",
"a",
"report",
"from",
"the",
"current",
"data",
"stream",
"contents"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/parser.py#L67-L123 |
23,863 | iotile/coretools | iotilecore/iotile/core/hw/reports/parser.py | IOTileReportParser.calculate_report_size | def calculate_report_size(self, current_type, report_header):
"""Determine the size of a report given its type and header"""
fmt = self.known_formats[current_type]
return fmt.ReportLength(report_header) | python | def calculate_report_size(self, current_type, report_header):
fmt = self.known_formats[current_type]
return fmt.ReportLength(report_header) | [
"def",
"calculate_report_size",
"(",
"self",
",",
"current_type",
",",
"report_header",
")",
":",
"fmt",
"=",
"self",
".",
"known_formats",
"[",
"current_type",
"]",
"return",
"fmt",
".",
"ReportLength",
"(",
"report_header",
")"
] | Determine the size of a report given its type and header | [
"Determine",
"the",
"size",
"of",
"a",
"report",
"given",
"its",
"type",
"and",
"header"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/parser.py#L131-L135 |
23,864 | iotile/coretools | iotilecore/iotile/core/hw/reports/parser.py | IOTileReportParser.parse_report | def parse_report(self, current_type, report_data):
"""Parse a report into an IOTileReport subclass"""
fmt = self.known_formats[current_type]
return fmt(report_data) | python | def parse_report(self, current_type, report_data):
fmt = self.known_formats[current_type]
return fmt(report_data) | [
"def",
"parse_report",
"(",
"self",
",",
"current_type",
",",
"report_data",
")",
":",
"fmt",
"=",
"self",
".",
"known_formats",
"[",
"current_type",
"]",
"return",
"fmt",
"(",
"report_data",
")"
] | Parse a report into an IOTileReport subclass | [
"Parse",
"a",
"report",
"into",
"an",
"IOTileReport",
"subclass"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/parser.py#L137-L141 |
23,865 | iotile/coretools | iotilecore/iotile/core/hw/reports/parser.py | IOTileReportParser._handle_report | def _handle_report(self, report):
"""Try to emit a report and possibly keep a copy of it"""
keep_report = True
if self.report_callback is not None:
keep_report = self.report_callback(report, self.context)
if keep_report:
self.reports.append(report) | python | def _handle_report(self, report):
keep_report = True
if self.report_callback is not None:
keep_report = self.report_callback(report, self.context)
if keep_report:
self.reports.append(report) | [
"def",
"_handle_report",
"(",
"self",
",",
"report",
")",
":",
"keep_report",
"=",
"True",
"if",
"self",
".",
"report_callback",
"is",
"not",
"None",
":",
"keep_report",
"=",
"self",
".",
"report_callback",
"(",
"report",
",",
"self",
".",
"context",
")",
... | Try to emit a report and possibly keep a copy of it | [
"Try",
"to",
"emit",
"a",
"report",
"and",
"possibly",
"keep",
"a",
"copy",
"of",
"it"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/parser.py#L160-L169 |
23,866 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msginit.py | _POInitBuilder | def _POInitBuilder(env, **kw):
""" Create builder object for `POInit` builder. """
import SCons.Action
from SCons.Tool.GettextCommon import _init_po_files, _POFileBuilder
action = SCons.Action.Action(_init_po_files, None)
return _POFileBuilder(env, action=action, target_alias='$POCREATE_ALIAS') | python | def _POInitBuilder(env, **kw):
import SCons.Action
from SCons.Tool.GettextCommon import _init_po_files, _POFileBuilder
action = SCons.Action.Action(_init_po_files, None)
return _POFileBuilder(env, action=action, target_alias='$POCREATE_ALIAS') | [
"def",
"_POInitBuilder",
"(",
"env",
",",
"*",
"*",
"kw",
")",
":",
"import",
"SCons",
".",
"Action",
"from",
"SCons",
".",
"Tool",
".",
"GettextCommon",
"import",
"_init_po_files",
",",
"_POFileBuilder",
"action",
"=",
"SCons",
".",
"Action",
".",
"Action... | Create builder object for `POInit` builder. | [
"Create",
"builder",
"object",
"for",
"POInit",
"builder",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msginit.py#L49-L54 |
23,867 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msginit.py | generate | def generate(env,**kw):
""" Generate the `msginit` tool """
import SCons.Util
from SCons.Tool.GettextCommon import _detect_msginit
try:
env['MSGINIT'] = _detect_msginit(env)
except:
env['MSGINIT'] = 'msginit'
msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \
+ ' $MSGINITFLAGS -i $SOURCE -o $TARGET'
# NOTE: We set POTSUFFIX here, in case the 'xgettext' is not loaded
# (sometimes we really don't need it)
env.SetDefault(
POSUFFIX = ['.po'],
POTSUFFIX = ['.pot'],
_MSGINITLOCALE = '${TARGET.filebase}',
_MSGNoTranslator = _optional_no_translator_flag,
MSGINITCOM = msginitcom,
MSGINITCOMSTR = '',
MSGINITFLAGS = [ ],
POAUTOINIT = False,
POCREATE_ALIAS = 'po-create'
)
env.Append( BUILDERS = { '_POInitBuilder' : _POInitBuilder(env) } )
env.AddMethod(_POInitBuilderWrapper, 'POInit')
env.AlwaysBuild(env.Alias('$POCREATE_ALIAS')) | python | def generate(env,**kw):
import SCons.Util
from SCons.Tool.GettextCommon import _detect_msginit
try:
env['MSGINIT'] = _detect_msginit(env)
except:
env['MSGINIT'] = 'msginit'
msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \
+ ' $MSGINITFLAGS -i $SOURCE -o $TARGET'
# NOTE: We set POTSUFFIX here, in case the 'xgettext' is not loaded
# (sometimes we really don't need it)
env.SetDefault(
POSUFFIX = ['.po'],
POTSUFFIX = ['.pot'],
_MSGINITLOCALE = '${TARGET.filebase}',
_MSGNoTranslator = _optional_no_translator_flag,
MSGINITCOM = msginitcom,
MSGINITCOMSTR = '',
MSGINITFLAGS = [ ],
POAUTOINIT = False,
POCREATE_ALIAS = 'po-create'
)
env.Append( BUILDERS = { '_POInitBuilder' : _POInitBuilder(env) } )
env.AddMethod(_POInitBuilderWrapper, 'POInit')
env.AlwaysBuild(env.Alias('$POCREATE_ALIAS')) | [
"def",
"generate",
"(",
"env",
",",
"*",
"*",
"kw",
")",
":",
"import",
"SCons",
".",
"Util",
"from",
"SCons",
".",
"Tool",
".",
"GettextCommon",
"import",
"_detect_msginit",
"try",
":",
"env",
"[",
"'MSGINIT'",
"]",
"=",
"_detect_msginit",
"(",
"env",
... | Generate the `msginit` tool | [
"Generate",
"the",
"msginit",
"tool"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msginit.py#L78-L103 |
23,868 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/utilities.py | open_bled112 | def open_bled112(port, logger):
"""Open a BLED112 adapter either by name or the first available."""
if port is not None and port != '<auto>':
logger.info("Using BLED112 adapter at %s", port)
return serial.Serial(port, _BAUD_RATE, timeout=0.01, rtscts=True, exclusive=True)
return _find_available_bled112(logger) | python | def open_bled112(port, logger):
if port is not None and port != '<auto>':
logger.info("Using BLED112 adapter at %s", port)
return serial.Serial(port, _BAUD_RATE, timeout=0.01, rtscts=True, exclusive=True)
return _find_available_bled112(logger) | [
"def",
"open_bled112",
"(",
"port",
",",
"logger",
")",
":",
"if",
"port",
"is",
"not",
"None",
"and",
"port",
"!=",
"'<auto>'",
":",
"logger",
".",
"info",
"(",
"\"Using BLED112 adapter at %s\"",
",",
"port",
")",
"return",
"serial",
".",
"Serial",
"(",
... | Open a BLED112 adapter either by name or the first available. | [
"Open",
"a",
"BLED112",
"adapter",
"either",
"by",
"name",
"or",
"the",
"first",
"available",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/utilities.py#L41-L48 |
23,869 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._find_ble_controllers | def _find_ble_controllers(self):
"""Get a list of the available and powered BLE controllers"""
controllers = self.bable.list_controllers()
return [ctrl for ctrl in controllers if ctrl.powered and ctrl.low_energy] | python | def _find_ble_controllers(self):
controllers = self.bable.list_controllers()
return [ctrl for ctrl in controllers if ctrl.powered and ctrl.low_energy] | [
"def",
"_find_ble_controllers",
"(",
"self",
")",
":",
"controllers",
"=",
"self",
".",
"bable",
".",
"list_controllers",
"(",
")",
"return",
"[",
"ctrl",
"for",
"ctrl",
"in",
"controllers",
"if",
"ctrl",
".",
"powered",
"and",
"ctrl",
".",
"low_energy",
"... | Get a list of the available and powered BLE controllers | [
"Get",
"a",
"list",
"of",
"the",
"available",
"and",
"powered",
"BLE",
"controllers"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L92-L95 |
23,870 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter.stop_scan | def stop_scan(self):
"""Stop to scan."""
try:
self.bable.stop_scan(sync=True)
except bable_interface.BaBLEException:
# If we errored our it is because we were not currently scanning
pass
self.scanning = False | python | def stop_scan(self):
try:
self.bable.stop_scan(sync=True)
except bable_interface.BaBLEException:
# If we errored our it is because we were not currently scanning
pass
self.scanning = False | [
"def",
"stop_scan",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"bable",
".",
"stop_scan",
"(",
"sync",
"=",
"True",
")",
"except",
"bable_interface",
".",
"BaBLEException",
":",
"# If we errored our it is because we were not currently scanning",
"pass",
"self",... | Stop to scan. | [
"Stop",
"to",
"scan",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L218-L226 |
23,871 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._open_rpc_interface | def _open_rpc_interface(self, connection_id, callback):
"""Enable RPC interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self.connections.begin_operation(connection_id, 'open_interface', callback, self.get_config('default_timeout'))
try:
service = context['services'][TileBusService]
header_characteristic = service[ReceiveHeaderChar]
payload_characteristic = service[ReceivePayloadChar]
except KeyError:
self.connections.finish_operation(connection_id, False, "Can't find characteristics to open rpc interface")
return
# Enable notification from ReceiveHeaderChar characteristic (ReceivePayloadChar will be enable just after)
self.bable.set_notification(
enabled=True,
connection_handle=context['connection_handle'],
characteristic=header_characteristic,
on_notification_set=[self._on_interface_opened, context, payload_characteristic],
on_notification_received=self._on_notification_received,
sync=False
) | python | def _open_rpc_interface(self, connection_id, callback):
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self.connections.begin_operation(connection_id, 'open_interface', callback, self.get_config('default_timeout'))
try:
service = context['services'][TileBusService]
header_characteristic = service[ReceiveHeaderChar]
payload_characteristic = service[ReceivePayloadChar]
except KeyError:
self.connections.finish_operation(connection_id, False, "Can't find characteristics to open rpc interface")
return
# Enable notification from ReceiveHeaderChar characteristic (ReceivePayloadChar will be enable just after)
self.bable.set_notification(
enabled=True,
connection_handle=context['connection_handle'],
characteristic=header_characteristic,
on_notification_set=[self._on_interface_opened, context, payload_characteristic],
on_notification_received=self._on_notification_received,
sync=False
) | [
"def",
"_open_rpc_interface",
"(",
"self",
",",
"connection_id",
",",
"callback",
")",
":",
"try",
":",
"context",
"=",
"self",
".",
"connections",
".",
"get_context",
"(",
"connection_id",
")",
"except",
"ArgumentError",
":",
"callback",
"(",
"connection_id",
... | Enable RPC interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason) | [
"Enable",
"RPC",
"interface",
"for",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L494-L527 |
23,872 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._open_streaming_interface | def _open_streaming_interface(self, connection_id, callback):
"""Enable streaming interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self._logger.info("Attempting to enable streaming")
self.connections.begin_operation(connection_id, 'open_interface', callback, self.get_config('default_timeout'))
try:
characteristic = context['services'][TileBusService][StreamingChar]
except KeyError:
self.connections.finish_operation(
connection_id,
False,
"Can't find characteristic to open streaming interface"
)
return
context['parser'] = IOTileReportParser(report_callback=self._on_report, error_callback=self._on_report_error)
context['parser'].context = connection_id
def on_report_chunk_received(report_chunk):
"""Callback function called when a report chunk has been received."""
context['parser'].add_data(report_chunk)
# Register our callback function in the notifications callbacks
self._register_notification_callback(
context['connection_handle'],
characteristic.value_handle,
on_report_chunk_received
)
self.bable.set_notification(
enabled=True,
connection_handle=context['connection_handle'],
characteristic=characteristic,
on_notification_set=[self._on_interface_opened, context],
on_notification_received=self._on_notification_received,
timeout=1.0,
sync=False
) | python | def _open_streaming_interface(self, connection_id, callback):
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self._logger.info("Attempting to enable streaming")
self.connections.begin_operation(connection_id, 'open_interface', callback, self.get_config('default_timeout'))
try:
characteristic = context['services'][TileBusService][StreamingChar]
except KeyError:
self.connections.finish_operation(
connection_id,
False,
"Can't find characteristic to open streaming interface"
)
return
context['parser'] = IOTileReportParser(report_callback=self._on_report, error_callback=self._on_report_error)
context['parser'].context = connection_id
def on_report_chunk_received(report_chunk):
"""Callback function called when a report chunk has been received."""
context['parser'].add_data(report_chunk)
# Register our callback function in the notifications callbacks
self._register_notification_callback(
context['connection_handle'],
characteristic.value_handle,
on_report_chunk_received
)
self.bable.set_notification(
enabled=True,
connection_handle=context['connection_handle'],
characteristic=characteristic,
on_notification_set=[self._on_interface_opened, context],
on_notification_received=self._on_notification_received,
timeout=1.0,
sync=False
) | [
"def",
"_open_streaming_interface",
"(",
"self",
",",
"connection_id",
",",
"callback",
")",
":",
"try",
":",
"context",
"=",
"self",
".",
"connections",
".",
"get_context",
"(",
"connection_id",
")",
"except",
"ArgumentError",
":",
"callback",
"(",
"connection_... | Enable streaming interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason) | [
"Enable",
"streaming",
"interface",
"for",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L551-L601 |
23,873 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._open_tracing_interface | def _open_tracing_interface(self, connection_id, callback):
"""Enable the tracing interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self._logger.info("Attempting to enable tracing")
self.connections.begin_operation(connection_id, 'open_interface', callback, self.get_config('default_timeout'))
try:
characteristic = context['services'][TileBusService][TracingChar]
except KeyError:
self.connections.finish_operation(
connection_id,
False,
"Can't find characteristic to open tracing interface"
)
return
# Register a callback function in the notifications callbacks, to trigger `on_trace` callback when a trace is
# notified.
self._register_notification_callback(
context['connection_handle'],
characteristic.value_handle,
lambda trace_chunk: self._trigger_callback('on_trace', connection_id, bytearray(trace_chunk))
)
self.bable.set_notification(
enabled=True,
connection_handle=context['connection_handle'],
characteristic=characteristic,
on_notification_set=[self._on_interface_opened, context],
on_notification_received=self._on_notification_received,
timeout=1.0,
sync=False
) | python | def _open_tracing_interface(self, connection_id, callback):
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self._logger.info("Attempting to enable tracing")
self.connections.begin_operation(connection_id, 'open_interface', callback, self.get_config('default_timeout'))
try:
characteristic = context['services'][TileBusService][TracingChar]
except KeyError:
self.connections.finish_operation(
connection_id,
False,
"Can't find characteristic to open tracing interface"
)
return
# Register a callback function in the notifications callbacks, to trigger `on_trace` callback when a trace is
# notified.
self._register_notification_callback(
context['connection_handle'],
characteristic.value_handle,
lambda trace_chunk: self._trigger_callback('on_trace', connection_id, bytearray(trace_chunk))
)
self.bable.set_notification(
enabled=True,
connection_handle=context['connection_handle'],
characteristic=characteristic,
on_notification_set=[self._on_interface_opened, context],
on_notification_received=self._on_notification_received,
timeout=1.0,
sync=False
) | [
"def",
"_open_tracing_interface",
"(",
"self",
",",
"connection_id",
",",
"callback",
")",
":",
"try",
":",
"context",
"=",
"self",
".",
"connections",
".",
"get_context",
"(",
"connection_id",
")",
"except",
"ArgumentError",
":",
"callback",
"(",
"connection_id... | Enable the tracing interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason) | [
"Enable",
"the",
"tracing",
"interface",
"for",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L603-L647 |
23,874 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._close_rpc_interface | def _close_rpc_interface(self, connection_id, callback):
"""Disable RPC interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self.connections.begin_operation(connection_id, 'close_interface', callback, self.get_config('default_timeout'))
try:
service = context['services'][TileBusService]
header_characteristic = service[ReceiveHeaderChar]
payload_characteristic = service[ReceivePayloadChar]
except KeyError:
self.connections.finish_operation(connection_id, False, "Can't find characteristics to open rpc interface")
return
self.bable.set_notification(
enabled=False,
connection_handle=context['connection_handle'],
characteristic=header_characteristic,
on_notification_set=[self._on_interface_closed, context, payload_characteristic],
timeout=1.0
) | python | def _close_rpc_interface(self, connection_id, callback):
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
self.connections.begin_operation(connection_id, 'close_interface', callback, self.get_config('default_timeout'))
try:
service = context['services'][TileBusService]
header_characteristic = service[ReceiveHeaderChar]
payload_characteristic = service[ReceivePayloadChar]
except KeyError:
self.connections.finish_operation(connection_id, False, "Can't find characteristics to open rpc interface")
return
self.bable.set_notification(
enabled=False,
connection_handle=context['connection_handle'],
characteristic=header_characteristic,
on_notification_set=[self._on_interface_closed, context, payload_characteristic],
timeout=1.0
) | [
"def",
"_close_rpc_interface",
"(",
"self",
",",
"connection_id",
",",
"callback",
")",
":",
"try",
":",
"context",
"=",
"self",
".",
"connections",
".",
"get_context",
"(",
"connection_id",
")",
"except",
"ArgumentError",
":",
"callback",
"(",
"connection_id",
... | Disable RPC interface for this IOTile device
Args:
connection_id (int): The unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason) | [
"Disable",
"RPC",
"interface",
"for",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L677-L708 |
23,875 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._on_report | def _on_report(self, report, connection_id):
"""Callback function called when a report has been processed.
Args:
report (IOTileReport): The report object
connection_id (int): The connection id related to this report
Returns:
- True to indicate that IOTileReportParser should also keep a copy of the report
or False to indicate it should delete it.
"""
self._logger.info('Received report: %s', str(report))
self._trigger_callback('on_report', connection_id, report)
return False | python | def _on_report(self, report, connection_id):
self._logger.info('Received report: %s', str(report))
self._trigger_callback('on_report', connection_id, report)
return False | [
"def",
"_on_report",
"(",
"self",
",",
"report",
",",
"connection_id",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Received report: %s'",
",",
"str",
"(",
"report",
")",
")",
"self",
".",
"_trigger_callback",
"(",
"'on_report'",
",",
"connection_id... | Callback function called when a report has been processed.
Args:
report (IOTileReport): The report object
connection_id (int): The connection id related to this report
Returns:
- True to indicate that IOTileReportParser should also keep a copy of the report
or False to indicate it should delete it. | [
"Callback",
"function",
"called",
"when",
"a",
"report",
"has",
"been",
"processed",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L738-L752 |
23,876 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._on_report_error | def _on_report_error(self, code, message, connection_id):
"""Callback function called if an error occured while parsing a report"""
self._logger.critical(
"Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s", code, message
) | python | def _on_report_error(self, code, message, connection_id):
self._logger.critical(
"Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s", code, message
) | [
"def",
"_on_report_error",
"(",
"self",
",",
"code",
",",
"message",
",",
"connection_id",
")",
":",
"self",
".",
"_logger",
".",
"critical",
"(",
"\"Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s\"",
",",
"code",
",",
"message... | Callback function called if an error occured while parsing a report | [
"Callback",
"function",
"called",
"if",
"an",
"error",
"occured",
"while",
"parsing",
"a",
"report"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L754-L758 |
23,877 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter._register_notification_callback | def _register_notification_callback(self, connection_handle, attribute_handle, callback, once=False):
"""Register a callback as a notification callback. It will be called if a notification with the matching
connection_handle and attribute_handle is received.
Args:
connection_handle (int): The connection handle to watch
attribute_handle (int): The attribute handle to watch
callback (func): The callback function to call once the notification has been received
once (bool): Should the callback only be called once (and then removed from the notification callbacks)
"""
notification_id = (connection_handle, attribute_handle)
with self.notification_callbacks_lock:
self.notification_callbacks[notification_id] = (callback, once) | python | def _register_notification_callback(self, connection_handle, attribute_handle, callback, once=False):
notification_id = (connection_handle, attribute_handle)
with self.notification_callbacks_lock:
self.notification_callbacks[notification_id] = (callback, once) | [
"def",
"_register_notification_callback",
"(",
"self",
",",
"connection_handle",
",",
"attribute_handle",
",",
"callback",
",",
"once",
"=",
"False",
")",
":",
"notification_id",
"=",
"(",
"connection_handle",
",",
"attribute_handle",
")",
"with",
"self",
".",
"no... | Register a callback as a notification callback. It will be called if a notification with the matching
connection_handle and attribute_handle is received.
Args:
connection_handle (int): The connection handle to watch
attribute_handle (int): The attribute handle to watch
callback (func): The callback function to call once the notification has been received
once (bool): Should the callback only be called once (and then removed from the notification callbacks) | [
"Register",
"a",
"callback",
"as",
"a",
"notification",
"callback",
".",
"It",
"will",
"be",
"called",
"if",
"a",
"notification",
"with",
"the",
"matching",
"connection_handle",
"and",
"attribute_handle",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L927-L939 |
23,878 | iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | NativeBLEDeviceAdapter.periodic_callback | def periodic_callback(self):
"""Periodic cleanup tasks to maintain this adapter, should be called every second. """
if self.stopped:
return
# Check if we should start scanning again
if not self.scanning and len(self.connections.get_connections()) == 0:
self._logger.info("Restarting scan for devices")
self.start_scan(self._active_scan)
self._logger.info("Finished restarting scan for devices") | python | def periodic_callback(self):
if self.stopped:
return
# Check if we should start scanning again
if not self.scanning and len(self.connections.get_connections()) == 0:
self._logger.info("Restarting scan for devices")
self.start_scan(self._active_scan)
self._logger.info("Finished restarting scan for devices") | [
"def",
"periodic_callback",
"(",
"self",
")",
":",
"if",
"self",
".",
"stopped",
":",
"return",
"# Check if we should start scanning again",
"if",
"not",
"self",
".",
"scanning",
"and",
"len",
"(",
"self",
".",
"connections",
".",
"get_connections",
"(",
")",
... | Periodic cleanup tasks to maintain this adapter, should be called every second. | [
"Periodic",
"cleanup",
"tasks",
"to",
"maintain",
"this",
"adapter",
"should",
"be",
"called",
"every",
"second",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L984-L994 |
23,879 | iotile/coretools | iotilesensorgraph/iotile/sg/output_formats/snippet.py | format_snippet | def format_snippet(sensor_graph):
"""Format this sensor graph as iotile command snippets.
This includes commands to reset and clear previously stored
sensor graphs.
Args:
sensor_graph (SensorGraph): the sensor graph that we want to format
"""
output = []
# Clear any old sensor graph
output.append("disable")
output.append("clear")
output.append("reset")
# Load in the nodes
for node in sensor_graph.dump_nodes():
output.append('add_node "{}"'.format(node))
# Load in the streamers
for streamer in sensor_graph.streamers:
line = "add_streamer '{}' '{}' {} {} {}".format(streamer.selector, streamer.dest, streamer.automatic, streamer.format, streamer.report_type)
if streamer.with_other is not None:
line += ' --withother {}'.format(streamer.with_other)
output.append(line)
# Load all the constants
for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()):
output.append("set_constant '{}' {}".format(stream, value))
# Persist the sensor graph
output.append("persist")
output.append("back")
# If we have an app tag and version set program them in
app_tag = sensor_graph.metadata_database.get('app_tag')
app_version = sensor_graph.metadata_database.get('app_version')
if app_tag is not None:
if app_version is None:
app_version = "0.0"
output.append("test_interface")
output.append("set_version app %d --version '%s'" % (app_tag, app_version))
output.append("back")
# Load in the config variables if any
output.append("config_database")
output.append("clear_variables")
for slot, conf_vars in sensor_graph.config_database.items():
for conf_var, conf_def in conf_vars.items():
conf_type, conf_val = conf_def
if conf_type == 'binary':
conf_val = 'hex:' + hexlify(conf_val)
elif isinstance(conf_val, str):
conf_val = '"%s"' % conf_val
output.append("set_variable '{}' {} {} {}".format(slot, conf_var, conf_type, conf_val))
# Restart the device to load in the new sg
output.append("back")
output.append("reset")
return "\n".join(output) + '\n' | python | def format_snippet(sensor_graph):
output = []
# Clear any old sensor graph
output.append("disable")
output.append("clear")
output.append("reset")
# Load in the nodes
for node in sensor_graph.dump_nodes():
output.append('add_node "{}"'.format(node))
# Load in the streamers
for streamer in sensor_graph.streamers:
line = "add_streamer '{}' '{}' {} {} {}".format(streamer.selector, streamer.dest, streamer.automatic, streamer.format, streamer.report_type)
if streamer.with_other is not None:
line += ' --withother {}'.format(streamer.with_other)
output.append(line)
# Load all the constants
for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()):
output.append("set_constant '{}' {}".format(stream, value))
# Persist the sensor graph
output.append("persist")
output.append("back")
# If we have an app tag and version set program them in
app_tag = sensor_graph.metadata_database.get('app_tag')
app_version = sensor_graph.metadata_database.get('app_version')
if app_tag is not None:
if app_version is None:
app_version = "0.0"
output.append("test_interface")
output.append("set_version app %d --version '%s'" % (app_tag, app_version))
output.append("back")
# Load in the config variables if any
output.append("config_database")
output.append("clear_variables")
for slot, conf_vars in sensor_graph.config_database.items():
for conf_var, conf_def in conf_vars.items():
conf_type, conf_val = conf_def
if conf_type == 'binary':
conf_val = 'hex:' + hexlify(conf_val)
elif isinstance(conf_val, str):
conf_val = '"%s"' % conf_val
output.append("set_variable '{}' {} {} {}".format(slot, conf_var, conf_type, conf_val))
# Restart the device to load in the new sg
output.append("back")
output.append("reset")
return "\n".join(output) + '\n' | [
"def",
"format_snippet",
"(",
"sensor_graph",
")",
":",
"output",
"=",
"[",
"]",
"# Clear any old sensor graph",
"output",
".",
"append",
"(",
"\"disable\"",
")",
"output",
".",
"append",
"(",
"\"clear\"",
")",
"output",
".",
"append",
"(",
"\"reset\"",
")",
... | Format this sensor graph as iotile command snippets.
This includes commands to reset and clear previously stored
sensor graphs.
Args:
sensor_graph (SensorGraph): the sensor graph that we want to format | [
"Format",
"this",
"sensor",
"graph",
"as",
"iotile",
"command",
"snippets",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/output_formats/snippet.py#L6-L76 |
23,880 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter.find_bled112_devices | def find_bled112_devices(cls):
"""Look for BLED112 dongles on this computer and start an instance on each one"""
found_devs = []
ports = serial.tools.list_ports.comports()
for port in ports:
if not hasattr(port, 'pid') or not hasattr(port, 'vid'):
continue
# Check if the device matches the BLED112's PID/VID combination
if port.pid == 1 and port.vid == 9304:
found_devs.append(port.device)
return found_devs | python | def find_bled112_devices(cls):
found_devs = []
ports = serial.tools.list_ports.comports()
for port in ports:
if not hasattr(port, 'pid') or not hasattr(port, 'vid'):
continue
# Check if the device matches the BLED112's PID/VID combination
if port.pid == 1 and port.vid == 9304:
found_devs.append(port.device)
return found_devs | [
"def",
"find_bled112_devices",
"(",
"cls",
")",
":",
"found_devs",
"=",
"[",
"]",
"ports",
"=",
"serial",
".",
"tools",
".",
"list_ports",
".",
"comports",
"(",
")",
"for",
"port",
"in",
"ports",
":",
"if",
"not",
"hasattr",
"(",
"port",
",",
"'pid'",
... | Look for BLED112 dongles on this computer and start an instance on each one | [
"Look",
"for",
"BLED112",
"dongles",
"on",
"this",
"computer",
"and",
"start",
"an",
"instance",
"on",
"each",
"one"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L109-L122 |
23,881 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter.get_scan_stats | def get_scan_stats(self):
"""Return the scan event statistics for this adapter
Returns:
int : total scan events
int : total v1 scan count
int : total v1 scan response count
int : total v2 scan count
dict : device-specific scan counts
float : seconds since last reset
"""
time_spent = time.time()
return self._scan_event_count, self._v1_scan_count, self._v1_scan_response_count, \
self._v2_scan_count, self._device_scan_counts.copy(), \
(time_spent - self._last_reset_time) | python | def get_scan_stats(self):
time_spent = time.time()
return self._scan_event_count, self._v1_scan_count, self._v1_scan_response_count, \
self._v2_scan_count, self._device_scan_counts.copy(), \
(time_spent - self._last_reset_time) | [
"def",
"get_scan_stats",
"(",
"self",
")",
":",
"time_spent",
"=",
"time",
".",
"time",
"(",
")",
"return",
"self",
".",
"_scan_event_count",
",",
"self",
".",
"_v1_scan_count",
",",
"self",
".",
"_v1_scan_response_count",
",",
"self",
".",
"_v2_scan_count",
... | Return the scan event statistics for this adapter
Returns:
int : total scan events
int : total v1 scan count
int : total v1 scan response count
int : total v2 scan count
dict : device-specific scan counts
float : seconds since last reset | [
"Return",
"the",
"scan",
"event",
"statistics",
"for",
"this",
"adapter"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L124-L138 |
23,882 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter.reset_scan_stats | def reset_scan_stats(self):
"""Clears the scan event statistics and updates the last reset time"""
self._scan_event_count = 0
self._v1_scan_count = 0
self._v1_scan_response_count = 0
self._v2_scan_count = 0
self._device_scan_counts = {}
self._last_reset_time = time.time() | python | def reset_scan_stats(self):
self._scan_event_count = 0
self._v1_scan_count = 0
self._v1_scan_response_count = 0
self._v2_scan_count = 0
self._device_scan_counts = {}
self._last_reset_time = time.time() | [
"def",
"reset_scan_stats",
"(",
"self",
")",
":",
"self",
".",
"_scan_event_count",
"=",
"0",
"self",
".",
"_v1_scan_count",
"=",
"0",
"self",
".",
"_v1_scan_response_count",
"=",
"0",
"self",
".",
"_v2_scan_count",
"=",
"0",
"self",
".",
"_device_scan_counts"... | Clears the scan event statistics and updates the last reset time | [
"Clears",
"the",
"scan",
"event",
"statistics",
"and",
"updates",
"the",
"last",
"reset",
"time"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L140-L147 |
23,883 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter.start_scan | def start_scan(self, active):
"""Start the scanning task"""
self._command_task.sync_command(['_start_scan', active])
self.scanning = True | python | def start_scan(self, active):
self._command_task.sync_command(['_start_scan', active])
self.scanning = True | [
"def",
"start_scan",
"(",
"self",
",",
"active",
")",
":",
"self",
".",
"_command_task",
".",
"sync_command",
"(",
"[",
"'_start_scan'",
",",
"active",
"]",
")",
"self",
".",
"scanning",
"=",
"True"
] | Start the scanning task | [
"Start",
"the",
"scanning",
"task"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L181-L184 |
23,884 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._open_tracing_interface | def _open_tracing_interface(self, conn_id, callback):
"""Enable the debug tracing interface for this IOTile device
Args:
conn_id (int): the unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
try:
handle = self._find_handle(conn_id)
services = self._connections[handle]['services']
except (ValueError, KeyError):
callback(conn_id, self.id, False, 'Connection closed unexpectedly before we could open the streaming interface')
return
self._command_task.async_command(['_enable_tracing', handle, services],
self._on_interface_finished, {'connection_id': conn_id, 'callback': callback}) | python | def _open_tracing_interface(self, conn_id, callback):
try:
handle = self._find_handle(conn_id)
services = self._connections[handle]['services']
except (ValueError, KeyError):
callback(conn_id, self.id, False, 'Connection closed unexpectedly before we could open the streaming interface')
return
self._command_task.async_command(['_enable_tracing', handle, services],
self._on_interface_finished, {'connection_id': conn_id, 'callback': callback}) | [
"def",
"_open_tracing_interface",
"(",
"self",
",",
"conn_id",
",",
"callback",
")",
":",
"try",
":",
"handle",
"=",
"self",
".",
"_find_handle",
"(",
"conn_id",
")",
"services",
"=",
"self",
".",
"_connections",
"[",
"handle",
"]",
"[",
"'services'",
"]",... | Enable the debug tracing interface for this IOTile device
Args:
conn_id (int): the unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason) | [
"Enable",
"the",
"debug",
"tracing",
"interface",
"for",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L421-L438 |
23,885 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._process_scan_event | def _process_scan_event(self, response):
"""Parse the BLE advertisement packet.
If it's an IOTile device, parse and add to the scanned devices. Then,
parse advertisement and determine if it matches V1 or V2. There are
two supported type of advertisements:
v1: There is both an advertisement and a scan response (if active scanning
is enabled).
v2: There is only an advertisement and no scan response.
"""
payload = response.payload
length = len(payload) - 10
if length < 0:
return
rssi, packet_type, sender, _addr_type, _bond, data = unpack("<bB6sBB%ds" % length, payload)
string_address = ':'.join([format(x, "02X") for x in bytearray(sender[::-1])])
# Scan data is prepended with a length
if len(data) > 0:
data = bytearray(data[1:])
else:
data = bytearray([])
self._scan_event_count += 1
# If this is an advertisement packet, see if its an IOTile device
# packet_type = 4 is scan_response, 0, 2 and 6 are advertisements
if packet_type in (0, 2, 6):
if len(data) != 31:
return
if data[22] == 0xFF and data[23] == 0xC0 and data[24] == 0x3:
self._v1_scan_count += 1
self._parse_v1_advertisement(rssi, string_address, data)
elif data[3] == 27 and data[4] == 0x16 and data[5] == 0xdd and data[6] == 0xfd:
self._v2_scan_count += 1
self._parse_v2_advertisement(rssi, string_address, data)
else:
pass # This just means the advertisement was from a non-IOTile device
elif packet_type == 4:
self._v1_scan_response_count += 1
self._parse_v1_scan_response(string_address, data) | python | def _process_scan_event(self, response):
payload = response.payload
length = len(payload) - 10
if length < 0:
return
rssi, packet_type, sender, _addr_type, _bond, data = unpack("<bB6sBB%ds" % length, payload)
string_address = ':'.join([format(x, "02X") for x in bytearray(sender[::-1])])
# Scan data is prepended with a length
if len(data) > 0:
data = bytearray(data[1:])
else:
data = bytearray([])
self._scan_event_count += 1
# If this is an advertisement packet, see if its an IOTile device
# packet_type = 4 is scan_response, 0, 2 and 6 are advertisements
if packet_type in (0, 2, 6):
if len(data) != 31:
return
if data[22] == 0xFF and data[23] == 0xC0 and data[24] == 0x3:
self._v1_scan_count += 1
self._parse_v1_advertisement(rssi, string_address, data)
elif data[3] == 27 and data[4] == 0x16 and data[5] == 0xdd and data[6] == 0xfd:
self._v2_scan_count += 1
self._parse_v2_advertisement(rssi, string_address, data)
else:
pass # This just means the advertisement was from a non-IOTile device
elif packet_type == 4:
self._v1_scan_response_count += 1
self._parse_v1_scan_response(string_address, data) | [
"def",
"_process_scan_event",
"(",
"self",
",",
"response",
")",
":",
"payload",
"=",
"response",
".",
"payload",
"length",
"=",
"len",
"(",
"payload",
")",
"-",
"10",
"if",
"length",
"<",
"0",
":",
"return",
"rssi",
",",
"packet_type",
",",
"sender",
... | Parse the BLE advertisement packet.
If it's an IOTile device, parse and add to the scanned devices. Then,
parse advertisement and determine if it matches V1 or V2. There are
two supported type of advertisements:
v1: There is both an advertisement and a scan response (if active scanning
is enabled).
v2: There is only an advertisement and no scan response. | [
"Parse",
"the",
"BLE",
"advertisement",
"packet",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L535-L580 |
23,886 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._parse_v2_advertisement | def _parse_v2_advertisement(self, rssi, sender, data):
""" Parse the IOTile Specific advertisement packet"""
if len(data) != 31:
return
# We have already verified that the device is an IOTile device
# by checking its service data uuid in _process_scan_event so
# here we just parse out the required information
device_id, reboot_low, reboot_high_packed, flags, timestamp, \
battery, counter_packed, broadcast_stream_packed, broadcast_value, \
_mac = unpack("<LHBBLBBHLL", data[7:])
reboots = (reboot_high_packed & 0xF) << 16 | reboot_low
counter = counter_packed & ((1 << 5) - 1)
broadcast_multiplex = counter_packed >> 5
broadcast_toggle = broadcast_stream_packed >> 15
broadcast_stream = broadcast_stream_packed & ((1 << 15) - 1)
# Flags for version 2 are:
# bit 0: Has pending data to stream
# bit 1: Low voltage indication
# bit 2: User connected
# bit 3: Broadcast data is encrypted
# bit 4: Encryption key is device key
# bit 5: Encryption key is user key
# bit 6: broadcast data is time synchronized to avoid leaking
# information about when it changes
self._device_scan_counts.setdefault(device_id, {'v1': 0, 'v2': 0})['v2'] += 1
info = {'connection_string': sender,
'uuid': device_id,
'pending_data': bool(flags & (1 << 0)),
'low_voltage': bool(flags & (1 << 1)),
'user_connected': bool(flags & (1 << 2)),
'signal_strength': rssi,
'reboot_counter': reboots,
'sequence': counter,
'broadcast_toggle': broadcast_toggle,
'timestamp': timestamp,
'battery': battery / 32.0,
'advertising_version':2}
self._trigger_callback('on_scan', self.id, info, self.ExpirationTime)
# If there is a valid reading on the advertising data, broadcast it
if broadcast_stream != 0xFFFF & ((1 << 15) - 1):
if self._throttle_broadcast and \
self._check_update_seen_broadcast(sender, timestamp, broadcast_stream, broadcast_value,
broadcast_toggle, counter=counter, channel=broadcast_multiplex):
return
reading = IOTileReading(timestamp, broadcast_stream, broadcast_value, reading_time=datetime.datetime.utcnow())
report = BroadcastReport.FromReadings(info['uuid'], [reading], timestamp)
self._trigger_callback('on_report', None, report) | python | def _parse_v2_advertisement(self, rssi, sender, data):
if len(data) != 31:
return
# We have already verified that the device is an IOTile device
# by checking its service data uuid in _process_scan_event so
# here we just parse out the required information
device_id, reboot_low, reboot_high_packed, flags, timestamp, \
battery, counter_packed, broadcast_stream_packed, broadcast_value, \
_mac = unpack("<LHBBLBBHLL", data[7:])
reboots = (reboot_high_packed & 0xF) << 16 | reboot_low
counter = counter_packed & ((1 << 5) - 1)
broadcast_multiplex = counter_packed >> 5
broadcast_toggle = broadcast_stream_packed >> 15
broadcast_stream = broadcast_stream_packed & ((1 << 15) - 1)
# Flags for version 2 are:
# bit 0: Has pending data to stream
# bit 1: Low voltage indication
# bit 2: User connected
# bit 3: Broadcast data is encrypted
# bit 4: Encryption key is device key
# bit 5: Encryption key is user key
# bit 6: broadcast data is time synchronized to avoid leaking
# information about when it changes
self._device_scan_counts.setdefault(device_id, {'v1': 0, 'v2': 0})['v2'] += 1
info = {'connection_string': sender,
'uuid': device_id,
'pending_data': bool(flags & (1 << 0)),
'low_voltage': bool(flags & (1 << 1)),
'user_connected': bool(flags & (1 << 2)),
'signal_strength': rssi,
'reboot_counter': reboots,
'sequence': counter,
'broadcast_toggle': broadcast_toggle,
'timestamp': timestamp,
'battery': battery / 32.0,
'advertising_version':2}
self._trigger_callback('on_scan', self.id, info, self.ExpirationTime)
# If there is a valid reading on the advertising data, broadcast it
if broadcast_stream != 0xFFFF & ((1 << 15) - 1):
if self._throttle_broadcast and \
self._check_update_seen_broadcast(sender, timestamp, broadcast_stream, broadcast_value,
broadcast_toggle, counter=counter, channel=broadcast_multiplex):
return
reading = IOTileReading(timestamp, broadcast_stream, broadcast_value, reading_time=datetime.datetime.utcnow())
report = BroadcastReport.FromReadings(info['uuid'], [reading], timestamp)
self._trigger_callback('on_report', None, report) | [
"def",
"_parse_v2_advertisement",
"(",
"self",
",",
"rssi",
",",
"sender",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"!=",
"31",
":",
"return",
"# We have already verified that the device is an IOTile device",
"# by checking its service data uuid in _process_s... | Parse the IOTile Specific advertisement packet | [
"Parse",
"the",
"IOTile",
"Specific",
"advertisement",
"packet"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L582-L638 |
23,887 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter.probe_services | def probe_services(self, handle, conn_id, callback):
"""Given a connected device, probe for its GATT services and characteristics
Args:
handle (int): a handle to the connection on the BLED112 dongle
conn_id (int): a unique identifier for this connection on the DeviceManager
that owns this adapter.
callback (callable): Callback to be called when this procedure finishes
"""
self._command_task.async_command(['_probe_services', handle], callback,
{'connection_id': conn_id, 'handle': handle}) | python | def probe_services(self, handle, conn_id, callback):
self._command_task.async_command(['_probe_services', handle], callback,
{'connection_id': conn_id, 'handle': handle}) | [
"def",
"probe_services",
"(",
"self",
",",
"handle",
",",
"conn_id",
",",
"callback",
")",
":",
"self",
".",
"_command_task",
".",
"async_command",
"(",
"[",
"'_probe_services'",
",",
"handle",
"]",
",",
"callback",
",",
"{",
"'connection_id'",
":",
"conn_id... | Given a connected device, probe for its GATT services and characteristics
Args:
handle (int): a handle to the connection on the BLED112 dongle
conn_id (int): a unique identifier for this connection on the DeviceManager
that owns this adapter.
callback (callable): Callback to be called when this procedure finishes | [
"Given",
"a",
"connected",
"device",
"probe",
"for",
"its",
"GATT",
"services",
"and",
"characteristics"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L721-L732 |
23,888 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter.probe_characteristics | def probe_characteristics(self, conn_id, handle, services):
"""Probe a device for all characteristics defined in its GATT table
This routine must be called after probe_services and passed the services dictionary
produced by that method.
Args:
handle (int): a handle to the connection on the BLED112 dongle
conn_id (int): a unique identifier for this connection on the DeviceManager
that owns this adapter.
services (dict): A dictionary of GATT services produced by probe_services()
"""
self._command_task.async_command(['_probe_characteristics', handle, services],
self._probe_characteristics_finished, {'connection_id': conn_id,
'handle': handle,
'services': services}) | python | def probe_characteristics(self, conn_id, handle, services):
self._command_task.async_command(['_probe_characteristics', handle, services],
self._probe_characteristics_finished, {'connection_id': conn_id,
'handle': handle,
'services': services}) | [
"def",
"probe_characteristics",
"(",
"self",
",",
"conn_id",
",",
"handle",
",",
"services",
")",
":",
"self",
".",
"_command_task",
".",
"async_command",
"(",
"[",
"'_probe_characteristics'",
",",
"handle",
",",
"services",
"]",
",",
"self",
".",
"_probe_char... | Probe a device for all characteristics defined in its GATT table
This routine must be called after probe_services and passed the services dictionary
produced by that method.
Args:
handle (int): a handle to the connection on the BLED112 dongle
conn_id (int): a unique identifier for this connection on the DeviceManager
that owns this adapter.
services (dict): A dictionary of GATT services produced by probe_services() | [
"Probe",
"a",
"device",
"for",
"all",
"characteristics",
"defined",
"in",
"its",
"GATT",
"table"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L734-L749 |
23,889 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._on_disconnect | def _on_disconnect(self, result):
"""Callback called when disconnection command finishes
Args:
result (dict): result returned from diconnection command
"""
success, _, context = self._parse_return(result)
callback = context['callback']
connection_id = context['connection_id']
handle = context['handle']
callback(connection_id, self.id, success, "No reason given")
self._remove_connection(handle) | python | def _on_disconnect(self, result):
success, _, context = self._parse_return(result)
callback = context['callback']
connection_id = context['connection_id']
handle = context['handle']
callback(connection_id, self.id, success, "No reason given")
self._remove_connection(handle) | [
"def",
"_on_disconnect",
"(",
"self",
",",
"result",
")",
":",
"success",
",",
"_",
",",
"context",
"=",
"self",
".",
"_parse_return",
"(",
"result",
")",
"callback",
"=",
"context",
"[",
"'callback'",
"]",
"connection_id",
"=",
"context",
"[",
"'connectio... | Callback called when disconnection command finishes
Args:
result (dict): result returned from diconnection command | [
"Callback",
"called",
"when",
"disconnection",
"command",
"finishes"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L778-L792 |
23,890 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._parse_return | def _parse_return(cls, result):
"""Extract the result, return value and context from a result object
"""
return_value = None
success = result['result']
context = result['context']
if 'return_value' in result:
return_value = result['return_value']
return success, return_value, context | python | def _parse_return(cls, result):
return_value = None
success = result['result']
context = result['context']
if 'return_value' in result:
return_value = result['return_value']
return success, return_value, context | [
"def",
"_parse_return",
"(",
"cls",
",",
"result",
")",
":",
"return_value",
"=",
"None",
"success",
"=",
"result",
"[",
"'result'",
"]",
"context",
"=",
"result",
"[",
"'context'",
"]",
"if",
"'return_value'",
"in",
"result",
":",
"return_value",
"=",
"re... | Extract the result, return value and context from a result object | [
"Extract",
"the",
"result",
"return",
"value",
"and",
"context",
"from",
"a",
"result",
"object"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L795-L806 |
23,891 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._get_connection | def _get_connection(self, handle, expect_state=None):
"""Get a connection object, logging an error if its in an unexpected state
"""
conndata = self._connections.get(handle)
if conndata and expect_state is not None and conndata['state'] != expect_state:
self._logger.error("Connection in unexpected state, wanted=%s, got=%s", expect_state,
conndata['state'])
return conndata | python | def _get_connection(self, handle, expect_state=None):
conndata = self._connections.get(handle)
if conndata and expect_state is not None and conndata['state'] != expect_state:
self._logger.error("Connection in unexpected state, wanted=%s, got=%s", expect_state,
conndata['state'])
return conndata | [
"def",
"_get_connection",
"(",
"self",
",",
"handle",
",",
"expect_state",
"=",
"None",
")",
":",
"conndata",
"=",
"self",
".",
"_connections",
".",
"get",
"(",
"handle",
")",
"if",
"conndata",
"and",
"expect_state",
"is",
"not",
"None",
"and",
"conndata",... | Get a connection object, logging an error if its in an unexpected state | [
"Get",
"a",
"connection",
"object",
"logging",
"an",
"error",
"if",
"its",
"in",
"an",
"unexpected",
"state"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L815-L824 |
23,892 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._on_connection_finished | def _on_connection_finished(self, result):
"""Callback when the connection attempt to a BLE device has finished
This function if called when a new connection is successfully completed
Args:
event (BGAPIPacket): Connection event
"""
success, retval, context = self._parse_return(result)
conn_id = context['connection_id']
callback = context['callback']
if success is False:
callback(conn_id, self.id, False, 'Timeout opening connection')
with self.count_lock:
self.connecting_count -= 1
return
handle = retval['handle']
context['disconnect_handler'] = self._on_connection_failed
context['connect_time'] = time.time()
context['state'] = 'preparing'
self._connections[handle] = context
self.probe_services(handle, conn_id, self._probe_services_finished) | python | def _on_connection_finished(self, result):
success, retval, context = self._parse_return(result)
conn_id = context['connection_id']
callback = context['callback']
if success is False:
callback(conn_id, self.id, False, 'Timeout opening connection')
with self.count_lock:
self.connecting_count -= 1
return
handle = retval['handle']
context['disconnect_handler'] = self._on_connection_failed
context['connect_time'] = time.time()
context['state'] = 'preparing'
self._connections[handle] = context
self.probe_services(handle, conn_id, self._probe_services_finished) | [
"def",
"_on_connection_finished",
"(",
"self",
",",
"result",
")",
":",
"success",
",",
"retval",
",",
"context",
"=",
"self",
".",
"_parse_return",
"(",
"result",
")",
"conn_id",
"=",
"context",
"[",
"'connection_id'",
"]",
"callback",
"=",
"context",
"[",
... | Callback when the connection attempt to a BLE device has finished
This function if called when a new connection is successfully completed
Args:
event (BGAPIPacket): Connection event | [
"Callback",
"when",
"the",
"connection",
"attempt",
"to",
"a",
"BLE",
"device",
"has",
"finished"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L829-L855 |
23,893 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._on_connection_failed | def _on_connection_failed(self, conn_id, handle, clean, reason):
"""Callback called from another thread when a connection attempt has failed.
"""
with self.count_lock:
self.connecting_count -= 1
self._logger.info("_on_connection_failed conn_id=%d, reason=%s", conn_id, str(reason))
conndata = self._get_connection(handle)
if conndata is None:
self._logger.info("Unable to obtain connection data on unknown connection %d", conn_id)
return
callback = conndata['callback']
conn_id = conndata['connection_id']
failure_reason = conndata['failure_reason']
# If this was an early disconnect from the device, automatically retry
if 'error_code' in conndata and conndata['error_code'] == 0x23e and conndata['retries'] > 0:
self._remove_connection(handle)
self.connect_async(conn_id, conndata['connection_string'], callback, conndata['retries'] - 1)
else:
callback(conn_id, self.id, False, failure_reason)
self._remove_connection(handle) | python | def _on_connection_failed(self, conn_id, handle, clean, reason):
with self.count_lock:
self.connecting_count -= 1
self._logger.info("_on_connection_failed conn_id=%d, reason=%s", conn_id, str(reason))
conndata = self._get_connection(handle)
if conndata is None:
self._logger.info("Unable to obtain connection data on unknown connection %d", conn_id)
return
callback = conndata['callback']
conn_id = conndata['connection_id']
failure_reason = conndata['failure_reason']
# If this was an early disconnect from the device, automatically retry
if 'error_code' in conndata and conndata['error_code'] == 0x23e and conndata['retries'] > 0:
self._remove_connection(handle)
self.connect_async(conn_id, conndata['connection_string'], callback, conndata['retries'] - 1)
else:
callback(conn_id, self.id, False, failure_reason)
self._remove_connection(handle) | [
"def",
"_on_connection_failed",
"(",
"self",
",",
"conn_id",
",",
"handle",
",",
"clean",
",",
"reason",
")",
":",
"with",
"self",
".",
"count_lock",
":",
"self",
".",
"connecting_count",
"-=",
"1",
"self",
".",
"_logger",
".",
"info",
"(",
"\"_on_connecti... | Callback called from another thread when a connection attempt has failed. | [
"Callback",
"called",
"from",
"another",
"thread",
"when",
"a",
"connection",
"attempt",
"has",
"failed",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L857-L882 |
23,894 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._probe_services_finished | def _probe_services_finished(self, result):
"""Callback called after a BLE device has had its GATT table completely probed
Args:
result (dict): Parameters determined by the probe and context passed to the call to
probe_device()
"""
#If we were disconnected before this function is called, don't proceed
handle = result['context']['handle']
conn_id = result['context']['connection_id']
conndata = self._get_connection(handle, 'preparing')
if conndata is None:
self._logger.info('Connection disconnected before prob_services_finished, conn_id=%d',
conn_id)
return
if result['result'] is False:
conndata['failed'] = True
conndata['failure_reason'] = 'Could not probe GATT services'
self.disconnect_async(conn_id, self._on_connection_failed)
else:
conndata['services_done_time'] = time.time()
self.probe_characteristics(result['context']['connection_id'], result['context']['handle'], result['return_value']['services']) | python | def _probe_services_finished(self, result):
#If we were disconnected before this function is called, don't proceed
handle = result['context']['handle']
conn_id = result['context']['connection_id']
conndata = self._get_connection(handle, 'preparing')
if conndata is None:
self._logger.info('Connection disconnected before prob_services_finished, conn_id=%d',
conn_id)
return
if result['result'] is False:
conndata['failed'] = True
conndata['failure_reason'] = 'Could not probe GATT services'
self.disconnect_async(conn_id, self._on_connection_failed)
else:
conndata['services_done_time'] = time.time()
self.probe_characteristics(result['context']['connection_id'], result['context']['handle'], result['return_value']['services']) | [
"def",
"_probe_services_finished",
"(",
"self",
",",
"result",
")",
":",
"#If we were disconnected before this function is called, don't proceed",
"handle",
"=",
"result",
"[",
"'context'",
"]",
"[",
"'handle'",
"]",
"conn_id",
"=",
"result",
"[",
"'context'",
"]",
"[... | Callback called after a BLE device has had its GATT table completely probed
Args:
result (dict): Parameters determined by the probe and context passed to the call to
probe_device() | [
"Callback",
"called",
"after",
"a",
"BLE",
"device",
"has",
"had",
"its",
"GATT",
"table",
"completely",
"probed"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L884-L909 |
23,895 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter._probe_characteristics_finished | def _probe_characteristics_finished(self, result):
"""Callback when BLE adapter has finished probing services and characteristics for a device
Args:
result (dict): Result from the probe_characteristics command
"""
handle = result['context']['handle']
conn_id = result['context']['connection_id']
conndata = self._get_connection(handle, 'preparing')
if conndata is None:
self._logger.info('Connection disconnected before probe_char... finished, conn_id=%d',
conn_id)
return
callback = conndata['callback']
if result['result'] is False:
conndata['failed'] = True
conndata['failure_reason'] = 'Could not probe GATT characteristics'
self.disconnect_async(conn_id, self._on_connection_failed)
return
# Validate that this is a proper IOTile device
services = result['return_value']['services']
if TileBusService not in services:
conndata['failed'] = True
conndata['failure_reason'] = 'TileBus service not present in GATT services'
self.disconnect_async(conn_id, self._on_connection_failed)
return
conndata['chars_done_time'] = time.time()
service_time = conndata['services_done_time'] - conndata['connect_time']
char_time = conndata['chars_done_time'] - conndata['services_done_time']
total_time = service_time + char_time
conndata['state'] = 'connected'
conndata['services'] = services
# Create a report parser for this connection for when reports are streamed to us
conndata['parser'] = IOTileReportParser(report_callback=self._on_report, error_callback=self._on_report_error)
conndata['parser'].context = conn_id
del conndata['disconnect_handler']
with self.count_lock:
self.connecting_count -= 1
self._logger.info("Total time to connect to device: %.3f (%.3f enumerating services, %.3f enumerating chars)", total_time, service_time, char_time)
callback(conndata['connection_id'], self.id, True, None) | python | def _probe_characteristics_finished(self, result):
handle = result['context']['handle']
conn_id = result['context']['connection_id']
conndata = self._get_connection(handle, 'preparing')
if conndata is None:
self._logger.info('Connection disconnected before probe_char... finished, conn_id=%d',
conn_id)
return
callback = conndata['callback']
if result['result'] is False:
conndata['failed'] = True
conndata['failure_reason'] = 'Could not probe GATT characteristics'
self.disconnect_async(conn_id, self._on_connection_failed)
return
# Validate that this is a proper IOTile device
services = result['return_value']['services']
if TileBusService not in services:
conndata['failed'] = True
conndata['failure_reason'] = 'TileBus service not present in GATT services'
self.disconnect_async(conn_id, self._on_connection_failed)
return
conndata['chars_done_time'] = time.time()
service_time = conndata['services_done_time'] - conndata['connect_time']
char_time = conndata['chars_done_time'] - conndata['services_done_time']
total_time = service_time + char_time
conndata['state'] = 'connected'
conndata['services'] = services
# Create a report parser for this connection for when reports are streamed to us
conndata['parser'] = IOTileReportParser(report_callback=self._on_report, error_callback=self._on_report_error)
conndata['parser'].context = conn_id
del conndata['disconnect_handler']
with self.count_lock:
self.connecting_count -= 1
self._logger.info("Total time to connect to device: %.3f (%.3f enumerating services, %.3f enumerating chars)", total_time, service_time, char_time)
callback(conndata['connection_id'], self.id, True, None) | [
"def",
"_probe_characteristics_finished",
"(",
"self",
",",
"result",
")",
":",
"handle",
"=",
"result",
"[",
"'context'",
"]",
"[",
"'handle'",
"]",
"conn_id",
"=",
"result",
"[",
"'context'",
"]",
"[",
"'connection_id'",
"]",
"conndata",
"=",
"self",
".",
... | Callback when BLE adapter has finished probing services and characteristics for a device
Args:
result (dict): Result from the probe_characteristics command | [
"Callback",
"when",
"BLE",
"adapter",
"has",
"finished",
"probing",
"services",
"and",
"characteristics",
"for",
"a",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L911-L961 |
23,896 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | BLED112Adapter.periodic_callback | def periodic_callback(self):
"""Periodic cleanup tasks to maintain this adapter, should be called every second
"""
if self.stopped:
return
# Check if we should start scanning again
if not self.scanning and len(self._connections) == 0 and self.connecting_count == 0:
self._logger.info("Restarting scan for devices")
self.start_scan(self._active_scan)
self._logger.info("Finished restarting scan for devices") | python | def periodic_callback(self):
if self.stopped:
return
# Check if we should start scanning again
if not self.scanning and len(self._connections) == 0 and self.connecting_count == 0:
self._logger.info("Restarting scan for devices")
self.start_scan(self._active_scan)
self._logger.info("Finished restarting scan for devices") | [
"def",
"periodic_callback",
"(",
"self",
")",
":",
"if",
"self",
".",
"stopped",
":",
"return",
"# Check if we should start scanning again",
"if",
"not",
"self",
".",
"scanning",
"and",
"len",
"(",
"self",
".",
"_connections",
")",
"==",
"0",
"and",
"self",
... | Periodic cleanup tasks to maintain this adapter, should be called every second | [
"Periodic",
"cleanup",
"tasks",
"to",
"maintain",
"this",
"adapter",
"should",
"be",
"called",
"every",
"second"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L973-L984 |
23,897 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Errors.py | convert_to_BuildError | def convert_to_BuildError(status, exc_info=None):
"""
Convert any return code a BuildError Exception.
:Parameters:
- `status`: can either be a return code or an Exception.
The buildError.status we set here will normally be
used as the exit status of the "scons" process.
"""
if not exc_info and isinstance(status, Exception):
exc_info = (status.__class__, status, None)
if isinstance(status, BuildError):
buildError = status
buildError.exitstatus = 2 # always exit with 2 on build errors
elif isinstance(status, ExplicitExit):
status = status.status
errstr = 'Explicit exit, status %s' % status
buildError = BuildError(
errstr=errstr,
status=status, # might be 0, OK here
exitstatus=status, # might be 0, OK here
exc_info=exc_info)
elif isinstance(status, (StopError, UserError)):
buildError = BuildError(
errstr=str(status),
status=2,
exitstatus=2,
exc_info=exc_info)
elif isinstance(status, shutil.SameFileError):
# PY3 has a exception for when copying file to itself
# It's object provides info differently than below
try:
filename = status.filename
except AttributeError:
filename = None
buildError = BuildError(
errstr=status.args[0],
status=status.errno,
exitstatus=2,
filename=filename,
exc_info=exc_info)
elif isinstance(status, (EnvironmentError, OSError, IOError)):
# If an IOError/OSError happens, raise a BuildError.
# Report the name of the file or directory that caused the
# error, which might be different from the target being built
# (for example, failure to create the directory in which the
# target file will appear).
try:
filename = status.filename
except AttributeError:
filename = None
buildError = BuildError(
errstr=status.strerror,
status=status.errno,
exitstatus=2,
filename=filename,
exc_info=exc_info)
elif isinstance(status, Exception):
buildError = BuildError(
errstr='%s : %s' % (status.__class__.__name__, status),
status=2,
exitstatus=2,
exc_info=exc_info)
elif SCons.Util.is_String(status):
buildError = BuildError(
errstr=status,
status=2,
exitstatus=2)
else:
buildError = BuildError(
errstr="Error %s" % status,
status=status,
exitstatus=2)
#import sys
#sys.stderr.write("convert_to_BuildError: status %s => (errstr %s, status %s)\n"%(status,buildError.errstr, buildError.status))
return buildError | python | def convert_to_BuildError(status, exc_info=None):
if not exc_info and isinstance(status, Exception):
exc_info = (status.__class__, status, None)
if isinstance(status, BuildError):
buildError = status
buildError.exitstatus = 2 # always exit with 2 on build errors
elif isinstance(status, ExplicitExit):
status = status.status
errstr = 'Explicit exit, status %s' % status
buildError = BuildError(
errstr=errstr,
status=status, # might be 0, OK here
exitstatus=status, # might be 0, OK here
exc_info=exc_info)
elif isinstance(status, (StopError, UserError)):
buildError = BuildError(
errstr=str(status),
status=2,
exitstatus=2,
exc_info=exc_info)
elif isinstance(status, shutil.SameFileError):
# PY3 has a exception for when copying file to itself
# It's object provides info differently than below
try:
filename = status.filename
except AttributeError:
filename = None
buildError = BuildError(
errstr=status.args[0],
status=status.errno,
exitstatus=2,
filename=filename,
exc_info=exc_info)
elif isinstance(status, (EnvironmentError, OSError, IOError)):
# If an IOError/OSError happens, raise a BuildError.
# Report the name of the file or directory that caused the
# error, which might be different from the target being built
# (for example, failure to create the directory in which the
# target file will appear).
try:
filename = status.filename
except AttributeError:
filename = None
buildError = BuildError(
errstr=status.strerror,
status=status.errno,
exitstatus=2,
filename=filename,
exc_info=exc_info)
elif isinstance(status, Exception):
buildError = BuildError(
errstr='%s : %s' % (status.__class__.__name__, status),
status=2,
exitstatus=2,
exc_info=exc_info)
elif SCons.Util.is_String(status):
buildError = BuildError(
errstr=status,
status=2,
exitstatus=2)
else:
buildError = BuildError(
errstr="Error %s" % status,
status=status,
exitstatus=2)
#import sys
#sys.stderr.write("convert_to_BuildError: status %s => (errstr %s, status %s)\n"%(status,buildError.errstr, buildError.status))
return buildError | [
"def",
"convert_to_BuildError",
"(",
"status",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"not",
"exc_info",
"and",
"isinstance",
"(",
"status",
",",
"Exception",
")",
":",
"exc_info",
"=",
"(",
"status",
".",
"__class__",
",",
"status",
",",
"None",
... | Convert any return code a BuildError Exception.
:Parameters:
- `status`: can either be a return code or an Exception.
The buildError.status we set here will normally be
used as the exit status of the "scons" process. | [
"Convert",
"any",
"return",
"code",
"a",
"BuildError",
"Exception",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Errors.py#L140-L223 |
23,898 | iotile/coretools | iotilesensorgraph/iotile/sg/output_formats/config.py | format_config | def format_config(sensor_graph):
"""Extract the config variables from this sensor graph in ASCII format.
Args:
sensor_graph (SensorGraph): the sensor graph that we want to format
Returns:
str: The ascii output lines concatenated as a single string
"""
cmdfile = CommandFile("Config Variables", "1.0")
for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()):
for conf_var, conf_def in sorted(sensor_graph.config_database[slot].items()):
conf_type, conf_val = conf_def
if conf_type == 'binary':
conf_val = 'hex:' + hexlify(conf_val)
cmdfile.add("set_variable", slot, conf_var, conf_type, conf_val)
return cmdfile.dump() | python | def format_config(sensor_graph):
cmdfile = CommandFile("Config Variables", "1.0")
for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()):
for conf_var, conf_def in sorted(sensor_graph.config_database[slot].items()):
conf_type, conf_val = conf_def
if conf_type == 'binary':
conf_val = 'hex:' + hexlify(conf_val)
cmdfile.add("set_variable", slot, conf_var, conf_type, conf_val)
return cmdfile.dump() | [
"def",
"format_config",
"(",
"sensor_graph",
")",
":",
"cmdfile",
"=",
"CommandFile",
"(",
"\"Config Variables\"",
",",
"\"1.0\"",
")",
"for",
"slot",
"in",
"sorted",
"(",
"sensor_graph",
".",
"config_database",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",... | Extract the config variables from this sensor graph in ASCII format.
Args:
sensor_graph (SensorGraph): the sensor graph that we want to format
Returns:
str: The ascii output lines concatenated as a single string | [
"Extract",
"the",
"config",
"variables",
"from",
"this",
"sensor",
"graph",
"in",
"ASCII",
"format",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/output_formats/config.py#L12-L33 |
23,899 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/aixf77.py | generate | def generate(env):
"""
Add Builders and construction variables for the Visual Age FORTRAN
compiler to an Environment.
"""
path, _f77, _shf77, version = get_xlf77(env)
if path:
_f77 = os.path.join(path, _f77)
_shf77 = os.path.join(path, _shf77)
f77.generate(env)
env['F77'] = _f77
env['SHF77'] = _shf77 | python | def generate(env):
path, _f77, _shf77, version = get_xlf77(env)
if path:
_f77 = os.path.join(path, _f77)
_shf77 = os.path.join(path, _shf77)
f77.generate(env)
env['F77'] = _f77
env['SHF77'] = _shf77 | [
"def",
"generate",
"(",
"env",
")",
":",
"path",
",",
"_f77",
",",
"_shf77",
",",
"version",
"=",
"get_xlf77",
"(",
"env",
")",
"if",
"path",
":",
"_f77",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"_f77",
")",
"_shf77",
"=",
"os",
... | Add Builders and construction variables for the Visual Age FORTRAN
compiler to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"the",
"Visual",
"Age",
"FORTRAN",
"compiler",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/aixf77.py#L53-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.