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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
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): """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]
[ "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", "]" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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
[ "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
train
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): """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]
[ "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", "]" ]
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
train
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): """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()
[ "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", "(", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """Determine the size of a report given its type and 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
train
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): """Parse a report into an IOTileReport subclass""" 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
train
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): """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)
[ "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", ")" ]
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
train
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): """ 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')
[ "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'", ")" ]
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
train
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): """ 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'))
[ "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'", ")", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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]
[ "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
train
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): """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
[ "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" ]
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
train
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): """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 )
[ "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", ")" ]
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
train
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): """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 )
[ "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", ")" ]
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
train
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): """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 )
[ "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", ")" ]
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
train
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): """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 )
[ "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", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """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 )
[ "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
train
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): """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)
[ "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", ")" ]
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
train
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): """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")
[ "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\"", ")" ]
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
train
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): """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'
[ "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'" ]
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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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()
[ "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", "(", ")" ]
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
train
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): """Start the scanning task""" 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
train
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): """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})
[ "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", "}", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """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})
[ "def", "probe_services", "(", "self", ",", "handle", ",", "conn_id", ",", "callback", ")", ":", "self", ".", "_command_task", ".", "async_command", "(", "[", "'_probe_services'", ",", "handle", "]", ",", "callback", ",", "{", "'connection_id'", ":", "conn_id", ",", "'handle'", ":", "handle", "}", ")" ]
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
train
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): """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})
[ "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", "}", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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'])
[ "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'", "]", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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")
[ "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\"", ")" ]
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
train
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): """ 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
[ "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" ]
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
train
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): """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()
[ "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", "(", ")" ]
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
train
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): """ 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
[ "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" ]
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
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py
DirScanner
def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw)
python
def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw)
[ "def", "DirScanner", "(", "*", "*", "kw", ")", ":", "kw", "[", "'node_factory'", "]", "=", "SCons", ".", "Node", ".", "FS", ".", "Entry", "kw", "[", "'recursive'", "]", "=", "only_dirs", "return", "SCons", ".", "Scanner", ".", "Base", "(", "scan_on_disk", ",", "\"DirScanner\"", ",", "*", "*", "kw", ")" ]
Return a prototype Scanner instance for scanning directories for on-disk files
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "directories", "for", "on", "-", "disk", "files" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L32-L37
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py
DirEntryScanner
def DirEntryScanner(**kw): """Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw)
python
def DirEntryScanner(**kw): """Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw)
[ "def", "DirEntryScanner", "(", "*", "*", "kw", ")", ":", "kw", "[", "'node_factory'", "]", "=", "SCons", ".", "Node", ".", "FS", ".", "Entry", "kw", "[", "'recursive'", "]", "=", "None", "return", "SCons", ".", "Scanner", ".", "Base", "(", "scan_in_memory", ",", "\"DirEntryScanner\"", ",", "*", "*", "kw", ")" ]
Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "directory", "Nodes", "for", "their", "in", "-", "memory", "entries" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L39-L44
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py
scan_on_disk
def scan_on_disk(node, env, path=()): """ Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function. """ try: flist = node.fs.listdir(node.get_abspath()) except (IOError, OSError): return [] e = node.Entry for f in filter(do_not_scan, flist): # Add ./ to the beginning of the file name so if it begins with a # '#' we don't look it up relative to the top-level directory. e('./' + f) return scan_in_memory(node, env, path)
python
def scan_on_disk(node, env, path=()): """ Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function. """ try: flist = node.fs.listdir(node.get_abspath()) except (IOError, OSError): return [] e = node.Entry for f in filter(do_not_scan, flist): # Add ./ to the beginning of the file name so if it begins with a # '#' we don't look it up relative to the top-level directory. e('./' + f) return scan_in_memory(node, env, path)
[ "def", "scan_on_disk", "(", "node", ",", "env", ",", "path", "=", "(", ")", ")", ":", "try", ":", "flist", "=", "node", ".", "fs", ".", "listdir", "(", "node", ".", "get_abspath", "(", ")", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "return", "[", "]", "e", "=", "node", ".", "Entry", "for", "f", "in", "filter", "(", "do_not_scan", ",", "flist", ")", ":", "# Add ./ to the beginning of the file name so if it begins with a", "# '#' we don't look it up relative to the top-level directory.", "e", "(", "'./'", "+", "f", ")", "return", "scan_in_memory", "(", "node", ",", "env", ",", "path", ")" ]
Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function.
[ "Scans", "a", "directory", "for", "on", "-", "disk", "files", "and", "directories", "therein", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L71-L88
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py
scan_in_memory
def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing # mixed Node types (Dirs and Files, for example) has a Dir as # the first entry. return [] entry_list = sorted(filter(do_not_scan, list(entries.keys()))) return [entries[n] for n in entry_list]
python
def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing # mixed Node types (Dirs and Files, for example) has a Dir as # the first entry. return [] entry_list = sorted(filter(do_not_scan, list(entries.keys()))) return [entries[n] for n in entry_list]
[ "def", "scan_in_memory", "(", "node", ",", "env", ",", "path", "=", "(", ")", ")", ":", "try", ":", "entries", "=", "node", ".", "entries", "except", "AttributeError", ":", "# It's not a Node.FS.Dir (or doesn't look enough like one for", "# our purposes), which can happen if a target list containing", "# mixed Node types (Dirs and Files, for example) has a Dir as", "# the first entry.", "return", "[", "]", "entry_list", "=", "sorted", "(", "filter", "(", "do_not_scan", ",", "list", "(", "entries", ".", "keys", "(", ")", ")", ")", ")", "return", "[", "entries", "[", "n", "]", "for", "n", "in", "entry_list", "]" ]
"Scans" a Node.FS.Dir for its in-memory entries.
[ "Scans", "a", "Node", ".", "FS", ".", "Dir", "for", "its", "in", "-", "memory", "entries", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L90-L103
train
iotile/coretools
iotileemulate/iotile/emulate/internal/response.py
GenericResponse.set_result
def set_result(self, result): """Finish this response and set the result.""" if self.is_finished(): raise InternalError("set_result called on finished AsynchronousResponse", result=self._result, exception=self._exception) self._result = result self.finish()
python
def set_result(self, result): """Finish this response and set the result.""" if self.is_finished(): raise InternalError("set_result called on finished AsynchronousResponse", result=self._result, exception=self._exception) self._result = result self.finish()
[ "def", "set_result", "(", "self", ",", "result", ")", ":", "if", "self", ".", "is_finished", "(", ")", ":", "raise", "InternalError", "(", "\"set_result called on finished AsynchronousResponse\"", ",", "result", "=", "self", ".", "_result", ",", "exception", "=", "self", ".", "_exception", ")", "self", ".", "_result", "=", "result", "self", ".", "finish", "(", ")" ]
Finish this response and set the result.
[ "Finish", "this", "response", "and", "set", "the", "result", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/response.py#L23-L31
train
iotile/coretools
iotileemulate/iotile/emulate/internal/response.py
GenericResponse.set_exception
def set_exception(self, exc_class, exc_info, exc_stack): """Set an exception as the result of this operation. Args: exc_class (object): The exception type """ if self.is_finished(): raise InternalError("set_exception called on finished AsynchronousResponse", result=self._result, exception=self._exception) self._exception = (exc_class, exc_info, exc_stack) self.finish()
python
def set_exception(self, exc_class, exc_info, exc_stack): """Set an exception as the result of this operation. Args: exc_class (object): The exception type """ if self.is_finished(): raise InternalError("set_exception called on finished AsynchronousResponse", result=self._result, exception=self._exception) self._exception = (exc_class, exc_info, exc_stack) self.finish()
[ "def", "set_exception", "(", "self", ",", "exc_class", ",", "exc_info", ",", "exc_stack", ")", ":", "if", "self", ".", "is_finished", "(", ")", ":", "raise", "InternalError", "(", "\"set_exception called on finished AsynchronousResponse\"", ",", "result", "=", "self", ".", "_result", ",", "exception", "=", "self", ".", "_exception", ")", "self", ".", "_exception", "=", "(", "exc_class", ",", "exc_info", ",", "exc_stack", ")", "self", ".", "finish", "(", ")" ]
Set an exception as the result of this operation. Args: exc_class (object): The exception type
[ "Set", "an", "exception", "as", "the", "result", "of", "this", "operation", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/response.py#L33-L44
train
iotile/coretools
scripts/status.py
get_released_versions
def get_released_versions(component): """Get all released versions of the given component ordered newest to oldest """ releases = get_tags() releases = sorted([(x[0], [int(y) for y in x[1].split('.')]) for x in releases], key=lambda x: x[1])[::-1] return [(x[0], ".".join(map(str, x[1]))) for x in releases if x[0] == component]
python
def get_released_versions(component): """Get all released versions of the given component ordered newest to oldest """ releases = get_tags() releases = sorted([(x[0], [int(y) for y in x[1].split('.')]) for x in releases], key=lambda x: x[1])[::-1] return [(x[0], ".".join(map(str, x[1]))) for x in releases if x[0] == component]
[ "def", "get_released_versions", "(", "component", ")", ":", "releases", "=", "get_tags", "(", ")", "releases", "=", "sorted", "(", "[", "(", "x", "[", "0", "]", ",", "[", "int", "(", "y", ")", "for", "y", "in", "x", "[", "1", "]", ".", "split", "(", "'.'", ")", "]", ")", "for", "x", "in", "releases", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "[", ":", ":", "-", "1", "]", "return", "[", "(", "x", "[", "0", "]", ",", "\".\"", ".", "join", "(", "map", "(", "str", ",", "x", "[", "1", "]", ")", ")", ")", "for", "x", "in", "releases", "if", "x", "[", "0", "]", "==", "component", "]" ]
Get all released versions of the given component ordered newest to oldest
[ "Get", "all", "released", "versions", "of", "the", "given", "component", "ordered", "newest", "to", "oldest" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/scripts/status.py#L22-L29
train
iotile/coretools
iotilebuild/iotile/build/config/site_scons/dependencies.py
load_dependencies
def load_dependencies(orig_tile, build_env): """Load all tile dependencies and filter only the products from each that we use build_env must define the architecture that we are targeting so that we get the correct dependency list and products per dependency since that may change when building for different architectures """ if 'DEPENDENCIES' not in build_env: build_env['DEPENDENCIES'] = [] dep_targets = [] chip = build_env['ARCH'] raw_arch_deps = chip.property('depends') # Properly separate out the version information from the name of the dependency # The raw keys come back as name,version arch_deps = {} for key, value in raw_arch_deps.items(): name, _, _ = key.partition(',') arch_deps[name] = value for dep in orig_tile.dependencies: try: tile = IOTile(os.path.join('build', 'deps', dep['unique_id'])) # Make sure we filter products using the view of module dependency products # as seen in the target we are targeting. if dep['name'] not in arch_deps: tile.filter_products([]) else: tile.filter_products(arch_deps[dep['name']]) except (ArgumentError, EnvironmentError): raise BuildError("Could not find required dependency", name=dep['name']) build_env['DEPENDENCIES'].append(tile) target = os.path.join(tile.folder, 'module_settings.json') dep_targets.append(target) return dep_targets
python
def load_dependencies(orig_tile, build_env): """Load all tile dependencies and filter only the products from each that we use build_env must define the architecture that we are targeting so that we get the correct dependency list and products per dependency since that may change when building for different architectures """ if 'DEPENDENCIES' not in build_env: build_env['DEPENDENCIES'] = [] dep_targets = [] chip = build_env['ARCH'] raw_arch_deps = chip.property('depends') # Properly separate out the version information from the name of the dependency # The raw keys come back as name,version arch_deps = {} for key, value in raw_arch_deps.items(): name, _, _ = key.partition(',') arch_deps[name] = value for dep in orig_tile.dependencies: try: tile = IOTile(os.path.join('build', 'deps', dep['unique_id'])) # Make sure we filter products using the view of module dependency products # as seen in the target we are targeting. if dep['name'] not in arch_deps: tile.filter_products([]) else: tile.filter_products(arch_deps[dep['name']]) except (ArgumentError, EnvironmentError): raise BuildError("Could not find required dependency", name=dep['name']) build_env['DEPENDENCIES'].append(tile) target = os.path.join(tile.folder, 'module_settings.json') dep_targets.append(target) return dep_targets
[ "def", "load_dependencies", "(", "orig_tile", ",", "build_env", ")", ":", "if", "'DEPENDENCIES'", "not", "in", "build_env", ":", "build_env", "[", "'DEPENDENCIES'", "]", "=", "[", "]", "dep_targets", "=", "[", "]", "chip", "=", "build_env", "[", "'ARCH'", "]", "raw_arch_deps", "=", "chip", ".", "property", "(", "'depends'", ")", "# Properly separate out the version information from the name of the dependency", "# The raw keys come back as name,version", "arch_deps", "=", "{", "}", "for", "key", ",", "value", "in", "raw_arch_deps", ".", "items", "(", ")", ":", "name", ",", "_", ",", "_", "=", "key", ".", "partition", "(", "','", ")", "arch_deps", "[", "name", "]", "=", "value", "for", "dep", "in", "orig_tile", ".", "dependencies", ":", "try", ":", "tile", "=", "IOTile", "(", "os", ".", "path", ".", "join", "(", "'build'", ",", "'deps'", ",", "dep", "[", "'unique_id'", "]", ")", ")", "# Make sure we filter products using the view of module dependency products", "# as seen in the target we are targeting.", "if", "dep", "[", "'name'", "]", "not", "in", "arch_deps", ":", "tile", ".", "filter_products", "(", "[", "]", ")", "else", ":", "tile", ".", "filter_products", "(", "arch_deps", "[", "dep", "[", "'name'", "]", "]", ")", "except", "(", "ArgumentError", ",", "EnvironmentError", ")", ":", "raise", "BuildError", "(", "\"Could not find required dependency\"", ",", "name", "=", "dep", "[", "'name'", "]", ")", "build_env", "[", "'DEPENDENCIES'", "]", ".", "append", "(", "tile", ")", "target", "=", "os", ".", "path", ".", "join", "(", "tile", ".", "folder", ",", "'module_settings.json'", ")", "dep_targets", ".", "append", "(", "target", ")", "return", "dep_targets" ]
Load all tile dependencies and filter only the products from each that we use build_env must define the architecture that we are targeting so that we get the correct dependency list and products per dependency since that may change when building for different architectures
[ "Load", "all", "tile", "dependencies", "and", "filter", "only", "the", "products", "from", "each", "that", "we", "use" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/dependencies.py#L9-L49
train
iotile/coretools
iotilebuild/iotile/build/config/site_scons/dependencies.py
find_dependency_wheels
def find_dependency_wheels(tile): """Return a list of all python wheel objects created by dependencies of this tile Args: tile (IOTile): Tile that we should scan for dependencies Returns: list: A list of paths to dependency wheels """ return [os.path.join(x.folder, 'python', x.support_wheel) for x in _iter_dependencies(tile) if x.has_wheel]
python
def find_dependency_wheels(tile): """Return a list of all python wheel objects created by dependencies of this tile Args: tile (IOTile): Tile that we should scan for dependencies Returns: list: A list of paths to dependency wheels """ return [os.path.join(x.folder, 'python', x.support_wheel) for x in _iter_dependencies(tile) if x.has_wheel]
[ "def", "find_dependency_wheels", "(", "tile", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "x", ".", "folder", ",", "'python'", ",", "x", ".", "support_wheel", ")", "for", "x", "in", "_iter_dependencies", "(", "tile", ")", "if", "x", ".", "has_wheel", "]" ]
Return a list of all python wheel objects created by dependencies of this tile Args: tile (IOTile): Tile that we should scan for dependencies Returns: list: A list of paths to dependency wheels
[ "Return", "a", "list", "of", "all", "python", "wheel", "objects", "created", "by", "dependencies", "of", "this", "tile" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/dependencies.py#L60-L70
train
iotile/coretools
iotilecore/iotile/core/dev/semver.py
SemanticVersionRange._check_ver_range
def _check_ver_range(self, version, ver_range): """Check if version is included in ver_range """ lower, upper, lower_inc, upper_inc = ver_range #If the range extends over everything, we automatically match if lower is None and upper is None: return True if lower is not None: if lower_inc and version < lower: return False elif not lower_inc and version <= lower: return False if upper is not None: if upper_inc and version > upper: return False elif not upper_inc and version >= upper: return False # Prereleases have special matching requirements if version.is_prerelease: # Prereleases cannot match ranges that are not defined as prereleases if (lower is None or not lower.is_prerelease) and (upper is None or not upper.is_prerelease): return False # Prereleases without the same major.minor.patch as a range end point cannot match if (lower is not None and version.release_tuple != lower.release_tuple) and \ (upper is not None and version.release_tuple != upper.release_tuple): return False return True
python
def _check_ver_range(self, version, ver_range): """Check if version is included in ver_range """ lower, upper, lower_inc, upper_inc = ver_range #If the range extends over everything, we automatically match if lower is None and upper is None: return True if lower is not None: if lower_inc and version < lower: return False elif not lower_inc and version <= lower: return False if upper is not None: if upper_inc and version > upper: return False elif not upper_inc and version >= upper: return False # Prereleases have special matching requirements if version.is_prerelease: # Prereleases cannot match ranges that are not defined as prereleases if (lower is None or not lower.is_prerelease) and (upper is None or not upper.is_prerelease): return False # Prereleases without the same major.minor.patch as a range end point cannot match if (lower is not None and version.release_tuple != lower.release_tuple) and \ (upper is not None and version.release_tuple != upper.release_tuple): return False return True
[ "def", "_check_ver_range", "(", "self", ",", "version", ",", "ver_range", ")", ":", "lower", ",", "upper", ",", "lower_inc", ",", "upper_inc", "=", "ver_range", "#If the range extends over everything, we automatically match", "if", "lower", "is", "None", "and", "upper", "is", "None", ":", "return", "True", "if", "lower", "is", "not", "None", ":", "if", "lower_inc", "and", "version", "<", "lower", ":", "return", "False", "elif", "not", "lower_inc", "and", "version", "<=", "lower", ":", "return", "False", "if", "upper", "is", "not", "None", ":", "if", "upper_inc", "and", "version", ">", "upper", ":", "return", "False", "elif", "not", "upper_inc", "and", "version", ">=", "upper", ":", "return", "False", "# Prereleases have special matching requirements", "if", "version", ".", "is_prerelease", ":", "# Prereleases cannot match ranges that are not defined as prereleases", "if", "(", "lower", "is", "None", "or", "not", "lower", ".", "is_prerelease", ")", "and", "(", "upper", "is", "None", "or", "not", "upper", ".", "is_prerelease", ")", ":", "return", "False", "# Prereleases without the same major.minor.patch as a range end point cannot match", "if", "(", "lower", "is", "not", "None", "and", "version", ".", "release_tuple", "!=", "lower", ".", "release_tuple", ")", "and", "(", "upper", "is", "not", "None", "and", "version", ".", "release_tuple", "!=", "upper", ".", "release_tuple", ")", ":", "return", "False", "return", "True" ]
Check if version is included in ver_range
[ "Check", "if", "version", "is", "included", "in", "ver_range" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L298-L331
train
iotile/coretools
iotilecore/iotile/core/dev/semver.py
SemanticVersionRange._check_insersection
def _check_insersection(self, version, ranges): """Check that a version is inside all of a list of ranges""" for ver_range in ranges: if not self._check_ver_range(version, ver_range): return False return True
python
def _check_insersection(self, version, ranges): """Check that a version is inside all of a list of ranges""" for ver_range in ranges: if not self._check_ver_range(version, ver_range): return False return True
[ "def", "_check_insersection", "(", "self", ",", "version", ",", "ranges", ")", ":", "for", "ver_range", "in", "ranges", ":", "if", "not", "self", ".", "_check_ver_range", "(", "version", ",", "ver_range", ")", ":", "return", "False", "return", "True" ]
Check that a version is inside all of a list of ranges
[ "Check", "that", "a", "version", "is", "inside", "all", "of", "a", "list", "of", "ranges" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L333-L340
train
iotile/coretools
iotilecore/iotile/core/dev/semver.py
SemanticVersionRange.check
def check(self, version): """Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not """ for disjunct in self._disjuncts: if self._check_insersection(version, disjunct): return True return False
python
def check(self, version): """Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not """ for disjunct in self._disjuncts: if self._check_insersection(version, disjunct): return True return False
[ "def", "check", "(", "self", ",", "version", ")", ":", "for", "disjunct", "in", "self", ".", "_disjuncts", ":", "if", "self", ".", "_check_insersection", "(", "version", ",", "disjunct", ")", ":", "return", "True", "return", "False" ]
Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not
[ "Check", "that", "a", "version", "is", "inside", "this", "SemanticVersionRange" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L342-L356
train
iotile/coretools
iotilecore/iotile/core/dev/semver.py
SemanticVersionRange.filter
def filter(self, versions, key=lambda x: x): """Filter all of the versions in an iterable that match this version range Args: versions (iterable): An iterable of SemanticVersion objects Returns: list: A list of the SemanticVersion objects that matched this range """ return [x for x in versions if self.check(key(x))]
python
def filter(self, versions, key=lambda x: x): """Filter all of the versions in an iterable that match this version range Args: versions (iterable): An iterable of SemanticVersion objects Returns: list: A list of the SemanticVersion objects that matched this range """ return [x for x in versions if self.check(key(x))]
[ "def", "filter", "(", "self", ",", "versions", ",", "key", "=", "lambda", "x", ":", "x", ")", ":", "return", "[", "x", "for", "x", "in", "versions", "if", "self", ".", "check", "(", "key", "(", "x", ")", ")", "]" ]
Filter all of the versions in an iterable that match this version range Args: versions (iterable): An iterable of SemanticVersion objects Returns: list: A list of the SemanticVersion objects that matched this range
[ "Filter", "all", "of", "the", "versions", "in", "an", "iterable", "that", "match", "this", "version", "range" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L358-L368
train
iotile/coretools
iotilecore/iotile/core/dev/semver.py
SemanticVersionRange.FromString
def FromString(cls, range_string): """Parse a version range string into a SemanticVersionRange Currently, the only possible range strings are: ^X.Y.Z - matches all versions with the same leading nonzero digit greater than or equal the given range. * - matches everything =X.Y.Z - matches only the exact version given Args: range_string (string): A string specifying the version range Returns: SemanticVersionRange: The resulting version range object Raises: ArgumentError: if the range string does not define a valid range. """ disjuncts = None range_string = range_string.strip() if len(range_string) == 0: raise ArgumentError("You must pass a finite string to SemanticVersionRange.FromString", range_string=range_string) # Check for * if len(range_string) == 1 and range_string[0] == '*': conj = (None, None, True, True) disjuncts = [[conj]] # Check for ^X.Y.Z elif range_string[0] == '^': ver = range_string[1:] try: ver = SemanticVersion.FromString(ver) except DataError as err: raise ArgumentError("Could not parse ^X.Y.Z version", parse_error=str(err), range_string=range_string) lower = ver upper = ver.inc_first_nonzero() conj = (lower, upper, True, False) disjuncts = [[conj]] elif range_string[0] == '=': ver = range_string[1:] try: ver = SemanticVersion.FromString(ver) except DataError as err: raise ArgumentError("Could not parse =X.Y.Z version", parse_error=str(err), range_string=range_string) conj = (ver, ver, True, True) disjuncts = [[conj]] if disjuncts is None: raise ArgumentError("Invalid range specification that could not be parsed", range_string=range_string) return SemanticVersionRange(disjuncts)
python
def FromString(cls, range_string): """Parse a version range string into a SemanticVersionRange Currently, the only possible range strings are: ^X.Y.Z - matches all versions with the same leading nonzero digit greater than or equal the given range. * - matches everything =X.Y.Z - matches only the exact version given Args: range_string (string): A string specifying the version range Returns: SemanticVersionRange: The resulting version range object Raises: ArgumentError: if the range string does not define a valid range. """ disjuncts = None range_string = range_string.strip() if len(range_string) == 0: raise ArgumentError("You must pass a finite string to SemanticVersionRange.FromString", range_string=range_string) # Check for * if len(range_string) == 1 and range_string[0] == '*': conj = (None, None, True, True) disjuncts = [[conj]] # Check for ^X.Y.Z elif range_string[0] == '^': ver = range_string[1:] try: ver = SemanticVersion.FromString(ver) except DataError as err: raise ArgumentError("Could not parse ^X.Y.Z version", parse_error=str(err), range_string=range_string) lower = ver upper = ver.inc_first_nonzero() conj = (lower, upper, True, False) disjuncts = [[conj]] elif range_string[0] == '=': ver = range_string[1:] try: ver = SemanticVersion.FromString(ver) except DataError as err: raise ArgumentError("Could not parse =X.Y.Z version", parse_error=str(err), range_string=range_string) conj = (ver, ver, True, True) disjuncts = [[conj]] if disjuncts is None: raise ArgumentError("Invalid range specification that could not be parsed", range_string=range_string) return SemanticVersionRange(disjuncts)
[ "def", "FromString", "(", "cls", ",", "range_string", ")", ":", "disjuncts", "=", "None", "range_string", "=", "range_string", ".", "strip", "(", ")", "if", "len", "(", "range_string", ")", "==", "0", ":", "raise", "ArgumentError", "(", "\"You must pass a finite string to SemanticVersionRange.FromString\"", ",", "range_string", "=", "range_string", ")", "# Check for *", "if", "len", "(", "range_string", ")", "==", "1", "and", "range_string", "[", "0", "]", "==", "'*'", ":", "conj", "=", "(", "None", ",", "None", ",", "True", ",", "True", ")", "disjuncts", "=", "[", "[", "conj", "]", "]", "# Check for ^X.Y.Z", "elif", "range_string", "[", "0", "]", "==", "'^'", ":", "ver", "=", "range_string", "[", "1", ":", "]", "try", ":", "ver", "=", "SemanticVersion", ".", "FromString", "(", "ver", ")", "except", "DataError", "as", "err", ":", "raise", "ArgumentError", "(", "\"Could not parse ^X.Y.Z version\"", ",", "parse_error", "=", "str", "(", "err", ")", ",", "range_string", "=", "range_string", ")", "lower", "=", "ver", "upper", "=", "ver", ".", "inc_first_nonzero", "(", ")", "conj", "=", "(", "lower", ",", "upper", ",", "True", ",", "False", ")", "disjuncts", "=", "[", "[", "conj", "]", "]", "elif", "range_string", "[", "0", "]", "==", "'='", ":", "ver", "=", "range_string", "[", "1", ":", "]", "try", ":", "ver", "=", "SemanticVersion", ".", "FromString", "(", "ver", ")", "except", "DataError", "as", "err", ":", "raise", "ArgumentError", "(", "\"Could not parse =X.Y.Z version\"", ",", "parse_error", "=", "str", "(", "err", ")", ",", "range_string", "=", "range_string", ")", "conj", "=", "(", "ver", ",", "ver", ",", "True", ",", "True", ")", "disjuncts", "=", "[", "[", "conj", "]", "]", "if", "disjuncts", "is", "None", ":", "raise", "ArgumentError", "(", "\"Invalid range specification that could not be parsed\"", ",", "range_string", "=", "range_string", ")", "return", "SemanticVersionRange", "(", "disjuncts", ")" ]
Parse a version range string into a SemanticVersionRange Currently, the only possible range strings are: ^X.Y.Z - matches all versions with the same leading nonzero digit greater than or equal the given range. * - matches everything =X.Y.Z - matches only the exact version given Args: range_string (string): A string specifying the version range Returns: SemanticVersionRange: The resulting version range object Raises: ArgumentError: if the range string does not define a valid range.
[ "Parse", "a", "version", "range", "string", "into", "a", "SemanticVersionRange" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L371-L433
train
iotile/coretools
iotilesensorgraph/iotile/sg/sim/hosted_executor.py
SemihostedRPCExecutor._call_rpc
def _call_rpc(self, address, rpc_id, payload): """Call an RPC with the given information and return its response. Must raise a hardware error of the appropriate kind if the RPC can not be executed correctly. Otherwise it should return the binary response payload received from the RPC. Args: address (int): The address of the tile we want to call the RPC on rpc_id (int): The id of the RPC that we want to call payload (bytes, bytearray): The data that we want to send as the payload """ # FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but # this should be long enough to accommodate any actual RPCs we need to send. status, response = self.hw.stream.send_rpc(address, rpc_id, payload, timeout=1.1) return response
python
def _call_rpc(self, address, rpc_id, payload): """Call an RPC with the given information and return its response. Must raise a hardware error of the appropriate kind if the RPC can not be executed correctly. Otherwise it should return the binary response payload received from the RPC. Args: address (int): The address of the tile we want to call the RPC on rpc_id (int): The id of the RPC that we want to call payload (bytes, bytearray): The data that we want to send as the payload """ # FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but # this should be long enough to accommodate any actual RPCs we need to send. status, response = self.hw.stream.send_rpc(address, rpc_id, payload, timeout=1.1) return response
[ "def", "_call_rpc", "(", "self", ",", "address", ",", "rpc_id", ",", "payload", ")", ":", "# FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but", "# this should be long enough to accommodate any actual RPCs we need to send.", "status", ",", "response", "=", "self", ".", "hw", ".", "stream", ".", "send_rpc", "(", "address", ",", "rpc_id", ",", "payload", ",", "timeout", "=", "1.1", ")", "return", "response" ]
Call an RPC with the given information and return its response. Must raise a hardware error of the appropriate kind if the RPC can not be executed correctly. Otherwise it should return the binary response payload received from the RPC. Args: address (int): The address of the tile we want to call the RPC on rpc_id (int): The id of the RPC that we want to call payload (bytes, bytearray): The data that we want to send as the payload
[ "Call", "an", "RPC", "with", "the", "given", "information", "and", "return", "its", "response", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/hosted_executor.py#L38-L56
train
iotile/coretools
iotilecore/iotile/core/hw/reports/individual_format.py
IndividualReadingReport.FromReadings
def FromReadings(cls, uuid, readings): """Generate an instance of the report format from a list of readings and a uuid """ if len(readings) != 1: raise ArgumentError("IndividualReading reports must be created with exactly one reading", num_readings=len(readings)) reading = readings[0] data = struct.pack("<BBHLLLL", 0, 0, reading.stream, uuid, 0, reading.raw_time, reading.value) return IndividualReadingReport(data)
python
def FromReadings(cls, uuid, readings): """Generate an instance of the report format from a list of readings and a uuid """ if len(readings) != 1: raise ArgumentError("IndividualReading reports must be created with exactly one reading", num_readings=len(readings)) reading = readings[0] data = struct.pack("<BBHLLLL", 0, 0, reading.stream, uuid, 0, reading.raw_time, reading.value) return IndividualReadingReport(data)
[ "def", "FromReadings", "(", "cls", ",", "uuid", ",", "readings", ")", ":", "if", "len", "(", "readings", ")", "!=", "1", ":", "raise", "ArgumentError", "(", "\"IndividualReading reports must be created with exactly one reading\"", ",", "num_readings", "=", "len", "(", "readings", ")", ")", "reading", "=", "readings", "[", "0", "]", "data", "=", "struct", ".", "pack", "(", "\"<BBHLLLL\"", ",", "0", ",", "0", ",", "reading", ".", "stream", ",", "uuid", ",", "0", ",", "reading", ".", "raw_time", ",", "reading", ".", "value", ")", "return", "IndividualReadingReport", "(", "data", ")" ]
Generate an instance of the report format from a list of readings and a uuid
[ "Generate", "an", "instance", "of", "the", "report", "format", "from", "a", "list", "of", "readings", "and", "a", "uuid" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/individual_format.py#L39-L49
train
iotile/coretools
iotilecore/iotile/core/hw/reports/individual_format.py
IndividualReadingReport.decode
def decode(self): """Decode this report into a single reading """ fmt, _, stream, uuid, sent_timestamp, reading_timestamp, reading_value = unpack("<BBHLLLL", self.raw_report) assert fmt == 0 # Estimate the UTC time when this device was turned on time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp) reading = IOTileReading(reading_timestamp, stream, reading_value, time_base=time_base) self.origin = uuid self.sent_timestamp = sent_timestamp return [reading], []
python
def decode(self): """Decode this report into a single reading """ fmt, _, stream, uuid, sent_timestamp, reading_timestamp, reading_value = unpack("<BBHLLLL", self.raw_report) assert fmt == 0 # Estimate the UTC time when this device was turned on time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp) reading = IOTileReading(reading_timestamp, stream, reading_value, time_base=time_base) self.origin = uuid self.sent_timestamp = sent_timestamp return [reading], []
[ "def", "decode", "(", "self", ")", ":", "fmt", ",", "_", ",", "stream", ",", "uuid", ",", "sent_timestamp", ",", "reading_timestamp", ",", "reading_value", "=", "unpack", "(", "\"<BBHLLLL\"", ",", "self", ".", "raw_report", ")", "assert", "fmt", "==", "0", "# Estimate the UTC time when this device was turned on", "time_base", "=", "self", ".", "received_time", "-", "datetime", ".", "timedelta", "(", "seconds", "=", "sent_timestamp", ")", "reading", "=", "IOTileReading", "(", "reading_timestamp", ",", "stream", ",", "reading_value", ",", "time_base", "=", "time_base", ")", "self", ".", "origin", "=", "uuid", "self", ".", "sent_timestamp", "=", "sent_timestamp", "return", "[", "reading", "]", ",", "[", "]" ]
Decode this report into a single reading
[ "Decode", "this", "report", "into", "a", "single", "reading" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/individual_format.py#L51-L65
train
iotile/coretools
iotilecore/iotile/core/hw/reports/individual_format.py
IndividualReadingReport.encode
def encode(self): """Turn this report into a serialized bytearray that could be decoded with a call to decode""" reading = self.visible_readings[0] data = struct.pack("<BBHLLLL", 0, 0, reading.stream, self.origin, self.sent_timestamp, reading.raw_time, reading.value) return bytearray(data)
python
def encode(self): """Turn this report into a serialized bytearray that could be decoded with a call to decode""" reading = self.visible_readings[0] data = struct.pack("<BBHLLLL", 0, 0, reading.stream, self.origin, self.sent_timestamp, reading.raw_time, reading.value) return bytearray(data)
[ "def", "encode", "(", "self", ")", ":", "reading", "=", "self", ".", "visible_readings", "[", "0", "]", "data", "=", "struct", ".", "pack", "(", "\"<BBHLLLL\"", ",", "0", ",", "0", ",", "reading", ".", "stream", ",", "self", ".", "origin", ",", "self", ".", "sent_timestamp", ",", "reading", ".", "raw_time", ",", "reading", ".", "value", ")", "return", "bytearray", "(", "data", ")" ]
Turn this report into a serialized bytearray that could be decoded with a call to decode
[ "Turn", "this", "report", "into", "a", "serialized", "bytearray", "that", "could", "be", "decoded", "with", "a", "call", "to", "decode" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/individual_format.py#L67-L74
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py
is_LaTeX
def is_LaTeX(flist,env,abspath): """Scan a file list to decide if it's TeX- or LaTeX-flavored.""" # We need to scan files that are included in case the # \documentclass command is in them. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXINPUTS', abspath) paths = env['ENV']['TEXINPUTS'] if SCons.Util.is_List(paths): pass else: # Split at os.pathsep to convert into absolute path paths = paths.split(os.pathsep) # now that we have the path list restore the env if savedpath is _null: try: del env['ENV']['TEXINPUTS'] except KeyError: pass # was never set else: env['ENV']['TEXINPUTS'] = savedpath if Verbose: print("is_LaTeX search path ",paths) print("files to search :",flist) # Now that we have the search path and file list, check each one for f in flist: if Verbose: print(" checking for Latex source ",str(f)) content = f.get_text_contents() if LaTeX_re.search(content): if Verbose: print("file %s is a LaTeX file" % str(f)) return 1 if Verbose: print("file %s is not a LaTeX file" % str(f)) # now find included files inc_files = [ ] inc_files.extend( include_re.findall(content) ) if Verbose: print("files included by '%s': "%str(f),inc_files) # inc_files is list of file names as given. need to find them # using TEXINPUTS paths. # search the included files for src in inc_files: srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False) # make this a list since is_LaTeX takes a list. fileList = [srcNode,] if Verbose: print("FindFile found ",srcNode) if srcNode is not None: file_test = is_LaTeX(fileList, env, abspath) # return on first file that finds latex is needed. if file_test: return file_test if Verbose: print(" done scanning ",str(f)) return 0
python
def is_LaTeX(flist,env,abspath): """Scan a file list to decide if it's TeX- or LaTeX-flavored.""" # We need to scan files that are included in case the # \documentclass command is in them. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXINPUTS', abspath) paths = env['ENV']['TEXINPUTS'] if SCons.Util.is_List(paths): pass else: # Split at os.pathsep to convert into absolute path paths = paths.split(os.pathsep) # now that we have the path list restore the env if savedpath is _null: try: del env['ENV']['TEXINPUTS'] except KeyError: pass # was never set else: env['ENV']['TEXINPUTS'] = savedpath if Verbose: print("is_LaTeX search path ",paths) print("files to search :",flist) # Now that we have the search path and file list, check each one for f in flist: if Verbose: print(" checking for Latex source ",str(f)) content = f.get_text_contents() if LaTeX_re.search(content): if Verbose: print("file %s is a LaTeX file" % str(f)) return 1 if Verbose: print("file %s is not a LaTeX file" % str(f)) # now find included files inc_files = [ ] inc_files.extend( include_re.findall(content) ) if Verbose: print("files included by '%s': "%str(f),inc_files) # inc_files is list of file names as given. need to find them # using TEXINPUTS paths. # search the included files for src in inc_files: srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False) # make this a list since is_LaTeX takes a list. fileList = [srcNode,] if Verbose: print("FindFile found ",srcNode) if srcNode is not None: file_test = is_LaTeX(fileList, env, abspath) # return on first file that finds latex is needed. if file_test: return file_test if Verbose: print(" done scanning ",str(f)) return 0
[ "def", "is_LaTeX", "(", "flist", ",", "env", ",", "abspath", ")", ":", "# We need to scan files that are included in case the", "# \\documentclass command is in them.", "# get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS']", "savedpath", "=", "modify_env_var", "(", "env", ",", "'TEXINPUTS'", ",", "abspath", ")", "paths", "=", "env", "[", "'ENV'", "]", "[", "'TEXINPUTS'", "]", "if", "SCons", ".", "Util", ".", "is_List", "(", "paths", ")", ":", "pass", "else", ":", "# Split at os.pathsep to convert into absolute path", "paths", "=", "paths", ".", "split", "(", "os", ".", "pathsep", ")", "# now that we have the path list restore the env", "if", "savedpath", "is", "_null", ":", "try", ":", "del", "env", "[", "'ENV'", "]", "[", "'TEXINPUTS'", "]", "except", "KeyError", ":", "pass", "# was never set", "else", ":", "env", "[", "'ENV'", "]", "[", "'TEXINPUTS'", "]", "=", "savedpath", "if", "Verbose", ":", "print", "(", "\"is_LaTeX search path \"", ",", "paths", ")", "print", "(", "\"files to search :\"", ",", "flist", ")", "# Now that we have the search path and file list, check each one", "for", "f", "in", "flist", ":", "if", "Verbose", ":", "print", "(", "\" checking for Latex source \"", ",", "str", "(", "f", ")", ")", "content", "=", "f", ".", "get_text_contents", "(", ")", "if", "LaTeX_re", ".", "search", "(", "content", ")", ":", "if", "Verbose", ":", "print", "(", "\"file %s is a LaTeX file\"", "%", "str", "(", "f", ")", ")", "return", "1", "if", "Verbose", ":", "print", "(", "\"file %s is not a LaTeX file\"", "%", "str", "(", "f", ")", ")", "# now find included files", "inc_files", "=", "[", "]", "inc_files", ".", "extend", "(", "include_re", ".", "findall", "(", "content", ")", ")", "if", "Verbose", ":", "print", "(", "\"files included by '%s': \"", "%", "str", "(", "f", ")", ",", "inc_files", ")", "# inc_files is list of file names as given. need to find them", "# using TEXINPUTS paths.", "# search the included files", "for", "src", "in", "inc_files", ":", "srcNode", "=", "FindFile", "(", "src", ",", "[", "'.tex'", ",", "'.ltx'", ",", "'.latex'", "]", ",", "paths", ",", "env", ",", "requireExt", "=", "False", ")", "# make this a list since is_LaTeX takes a list.", "fileList", "=", "[", "srcNode", ",", "]", "if", "Verbose", ":", "print", "(", "\"FindFile found \"", ",", "srcNode", ")", "if", "srcNode", "is", "not", "None", ":", "file_test", "=", "is_LaTeX", "(", "fileList", ",", "env", ",", "abspath", ")", "# return on first file that finds latex is needed.", "if", "file_test", ":", "return", "file_test", "if", "Verbose", ":", "print", "(", "\" done scanning \"", ",", "str", "(", "f", ")", ")", "return", "0" ]
Scan a file list to decide if it's TeX- or LaTeX-flavored.
[ "Scan", "a", "file", "list", "to", "decide", "if", "it", "s", "TeX", "-", "or", "LaTeX", "-", "flavored", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L495-L560
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py
TeXLaTeXStrFunction
def TeXLaTeXStrFunction(target = None, source= None, env=None): """A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.""" if env.GetOption("no_exec"): # find these paths for use in is_LaTeX to search for included files basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) if is_LaTeX(source,env,abspath): result = env.subst('$LATEXCOM',0,target,source)+" ..." else: result = env.subst("$TEXCOM",0,target,source)+" ..." else: result = '' return result
python
def TeXLaTeXStrFunction(target = None, source= None, env=None): """A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.""" if env.GetOption("no_exec"): # find these paths for use in is_LaTeX to search for included files basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) if is_LaTeX(source,env,abspath): result = env.subst('$LATEXCOM',0,target,source)+" ..." else: result = env.subst("$TEXCOM",0,target,source)+" ..." else: result = '' return result
[ "def", "TeXLaTeXStrFunction", "(", "target", "=", "None", ",", "source", "=", "None", ",", "env", "=", "None", ")", ":", "if", "env", ".", "GetOption", "(", "\"no_exec\"", ")", ":", "# find these paths for use in is_LaTeX to search for included files", "basedir", "=", "os", ".", "path", ".", "split", "(", "str", "(", "source", "[", "0", "]", ")", ")", "[", "0", "]", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "basedir", ")", "if", "is_LaTeX", "(", "source", ",", "env", ",", "abspath", ")", ":", "result", "=", "env", ".", "subst", "(", "'$LATEXCOM'", ",", "0", ",", "target", ",", "source", ")", "+", "\" ...\"", "else", ":", "result", "=", "env", ".", "subst", "(", "\"$TEXCOM\"", ",", "0", ",", "target", ",", "source", ")", "+", "\" ...\"", "else", ":", "result", "=", "''", "return", "result" ]
A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.
[ "A", "strfunction", "for", "TeX", "and", "LaTeX", "that", "scans", "the", "source", "file", "to", "decide", "the", "flavor", "of", "the", "source", "and", "then", "returns", "the", "appropriate", "command", "string", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L581-L597
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py
tex_eps_emitter
def tex_eps_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing tex or latex. It will accept .ps and .eps graphics files """ (target, source) = tex_emitter_core(target, source, env, TexGraphics) return (target, source)
python
def tex_eps_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing tex or latex. It will accept .ps and .eps graphics files """ (target, source) = tex_emitter_core(target, source, env, TexGraphics) return (target, source)
[ "def", "tex_eps_emitter", "(", "target", ",", "source", ",", "env", ")", ":", "(", "target", ",", "source", ")", "=", "tex_emitter_core", "(", "target", ",", "source", ",", "env", ",", "TexGraphics", ")", "return", "(", "target", ",", "source", ")" ]
An emitter for TeX and LaTeX sources when executing tex or latex. It will accept .ps and .eps graphics files
[ "An", "emitter", "for", "TeX", "and", "LaTeX", "sources", "when", "executing", "tex", "or", "latex", ".", "It", "will", "accept", ".", "ps", "and", ".", "eps", "graphics", "files" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L599-L606
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py
tex_pdf_emitter
def tex_pdf_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing pdftex or pdflatex. It will accept graphics files of types .pdf, .jpg, .png, .gif, and .tif """ (target, source) = tex_emitter_core(target, source, env, LatexGraphics) return (target, source)
python
def tex_pdf_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing pdftex or pdflatex. It will accept graphics files of types .pdf, .jpg, .png, .gif, and .tif """ (target, source) = tex_emitter_core(target, source, env, LatexGraphics) return (target, source)
[ "def", "tex_pdf_emitter", "(", "target", ",", "source", ",", "env", ")", ":", "(", "target", ",", "source", ")", "=", "tex_emitter_core", "(", "target", ",", "source", ",", "env", ",", "LatexGraphics", ")", "return", "(", "target", ",", "source", ")" ]
An emitter for TeX and LaTeX sources when executing pdftex or pdflatex. It will accept graphics files of types .pdf, .jpg, .png, .gif, and .tif
[ "An", "emitter", "for", "TeX", "and", "LaTeX", "sources", "when", "executing", "pdftex", "or", "pdflatex", ".", "It", "will", "accept", "graphics", "files", "of", "types", ".", "pdf", ".", "jpg", ".", "png", ".", "gif", "and", ".", "tif" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L608-L615
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py
generate
def generate(env): """Add Builders and construction variables for TeX to an Environment.""" global TeXLaTeXAction if TeXLaTeXAction is None: TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction, strfunction=TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) generate_common(env) from . import dvi dvi.generate(env) bld = env['BUILDERS']['DVI'] bld.add_action('.tex', TeXLaTeXAction) bld.add_emitter('.tex', tex_eps_emitter)
python
def generate(env): """Add Builders and construction variables for TeX to an Environment.""" global TeXLaTeXAction if TeXLaTeXAction is None: TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction, strfunction=TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) generate_common(env) from . import dvi dvi.generate(env) bld = env['BUILDERS']['DVI'] bld.add_action('.tex', TeXLaTeXAction) bld.add_emitter('.tex', tex_eps_emitter)
[ "def", "generate", "(", "env", ")", ":", "global", "TeXLaTeXAction", "if", "TeXLaTeXAction", "is", "None", ":", "TeXLaTeXAction", "=", "SCons", ".", "Action", ".", "Action", "(", "TeXLaTeXFunction", ",", "strfunction", "=", "TeXLaTeXStrFunction", ")", "env", ".", "AppendUnique", "(", "LATEXSUFFIXES", "=", "SCons", ".", "Tool", ".", "LaTeXSuffixes", ")", "generate_common", "(", "env", ")", "from", ".", "import", "dvi", "dvi", ".", "generate", "(", "env", ")", "bld", "=", "env", "[", "'BUILDERS'", "]", "[", "'DVI'", "]", "bld", ".", "add_action", "(", "'.tex'", ",", "TeXLaTeXAction", ")", "bld", ".", "add_emitter", "(", "'.tex'", ",", "tex_eps_emitter", ")" ]
Add Builders and construction variables for TeX to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "TeX", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L831-L848
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py
is_win64
def is_win64(): """Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.""" # Unfortunately, python does not provide a useful way to determine # if the underlying Windows OS is 32-bit or 64-bit. Worse, whether # the Python itself is 32-bit or 64-bit affects what it returns, # so nothing in sys.* or os.* help. # Apparently the best solution is to use env vars that Windows # sets. If PROCESSOR_ARCHITECTURE is not x86, then the python # process is running in 64 bit mode (on a 64-bit OS, 64-bit # hardware, obviously). # If this python is 32-bit but the OS is 64, Windows will set # ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null. # (Checking for HKLM\Software\Wow6432Node in the registry doesn't # work, because some 32-bit installers create it.) global _is_win64 if _is_win64 is None: # I structured these tests to make it easy to add new ones or # add exceptions in the future, because this is a bit fragile. _is_win64 = False if os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') != 'x86': _is_win64 = True if os.environ.get('PROCESSOR_ARCHITEW6432'): _is_win64 = True if os.environ.get('ProgramW6432'): _is_win64 = True return _is_win64
python
def is_win64(): """Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.""" # Unfortunately, python does not provide a useful way to determine # if the underlying Windows OS is 32-bit or 64-bit. Worse, whether # the Python itself is 32-bit or 64-bit affects what it returns, # so nothing in sys.* or os.* help. # Apparently the best solution is to use env vars that Windows # sets. If PROCESSOR_ARCHITECTURE is not x86, then the python # process is running in 64 bit mode (on a 64-bit OS, 64-bit # hardware, obviously). # If this python is 32-bit but the OS is 64, Windows will set # ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null. # (Checking for HKLM\Software\Wow6432Node in the registry doesn't # work, because some 32-bit installers create it.) global _is_win64 if _is_win64 is None: # I structured these tests to make it easy to add new ones or # add exceptions in the future, because this is a bit fragile. _is_win64 = False if os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') != 'x86': _is_win64 = True if os.environ.get('PROCESSOR_ARCHITEW6432'): _is_win64 = True if os.environ.get('ProgramW6432'): _is_win64 = True return _is_win64
[ "def", "is_win64", "(", ")", ":", "# Unfortunately, python does not provide a useful way to determine", "# if the underlying Windows OS is 32-bit or 64-bit. Worse, whether", "# the Python itself is 32-bit or 64-bit affects what it returns,", "# so nothing in sys.* or os.* help.", "# Apparently the best solution is to use env vars that Windows", "# sets. If PROCESSOR_ARCHITECTURE is not x86, then the python", "# process is running in 64 bit mode (on a 64-bit OS, 64-bit", "# hardware, obviously).", "# If this python is 32-bit but the OS is 64, Windows will set", "# ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null.", "# (Checking for HKLM\\Software\\Wow6432Node in the registry doesn't", "# work, because some 32-bit installers create it.)", "global", "_is_win64", "if", "_is_win64", "is", "None", ":", "# I structured these tests to make it easy to add new ones or", "# add exceptions in the future, because this is a bit fragile.", "_is_win64", "=", "False", "if", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITECTURE'", ",", "'x86'", ")", "!=", "'x86'", ":", "_is_win64", "=", "True", "if", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITEW6432'", ")", ":", "_is_win64", "=", "True", "if", "os", ".", "environ", ".", "get", "(", "'ProgramW6432'", ")", ":", "_is_win64", "=", "True", "return", "_is_win64" ]
Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.
[ "Return", "true", "if", "running", "on", "windows", "64", "bits", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L55-L83
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py
has_reg
def has_reg(value): """Return True if the given key exists in HKEY_LOCAL_MACHINE, False otherwise.""" try: SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value) ret = True except SCons.Util.WinError: ret = False return ret
python
def has_reg(value): """Return True if the given key exists in HKEY_LOCAL_MACHINE, False otherwise.""" try: SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value) ret = True except SCons.Util.WinError: ret = False return ret
[ "def", "has_reg", "(", "value", ")", ":", "try", ":", "SCons", ".", "Util", ".", "RegOpenKeyEx", "(", "SCons", ".", "Util", ".", "HKEY_LOCAL_MACHINE", ",", "value", ")", "ret", "=", "True", "except", "SCons", ".", "Util", ".", "WinError", ":", "ret", "=", "False", "return", "ret" ]
Return True if the given key exists in HKEY_LOCAL_MACHINE, False otherwise.
[ "Return", "True", "if", "the", "given", "key", "exists", "in", "HKEY_LOCAL_MACHINE", "False", "otherwise", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L89-L97
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py
normalize_env
def normalize_env(env, keys, force=False): """Given a dictionary representing a shell environment, add the variables from os.environ needed for the processing of .bat files; the keys are controlled by the keys argument. It also makes sure the environment values are correctly encoded. If force=True, then all of the key values that exist are copied into the returned dictionary. If force=false, values are only copied if the key does not already exist in the copied dictionary. Note: the environment is copied.""" normenv = {} if env: for k in list(env.keys()): normenv[k] = copy.deepcopy(env[k]) for k in keys: if k in os.environ and (force or not k in normenv): normenv[k] = os.environ[k] # This shouldn't be necessary, since the default environment should include system32, # but keep this here to be safe, since it's needed to find reg.exe which the MSVC # bat scripts use. sys32_dir = os.path.join(os.environ.get("SystemRoot", os.environ.get("windir", r"C:\Windows\system32")), "System32") if sys32_dir not in normenv['PATH']: normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_dir # Without Wbem in PATH, vcvarsall.bat has a "'wmic' is not recognized" # error starting with Visual Studio 2017, although the script still # seems to work anyway. sys32_wbem_dir = os.path.join(sys32_dir, 'Wbem') if sys32_wbem_dir not in normenv['PATH']: normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_wbem_dir debug("PATH: %s"%normenv['PATH']) return normenv
python
def normalize_env(env, keys, force=False): """Given a dictionary representing a shell environment, add the variables from os.environ needed for the processing of .bat files; the keys are controlled by the keys argument. It also makes sure the environment values are correctly encoded. If force=True, then all of the key values that exist are copied into the returned dictionary. If force=false, values are only copied if the key does not already exist in the copied dictionary. Note: the environment is copied.""" normenv = {} if env: for k in list(env.keys()): normenv[k] = copy.deepcopy(env[k]) for k in keys: if k in os.environ and (force or not k in normenv): normenv[k] = os.environ[k] # This shouldn't be necessary, since the default environment should include system32, # but keep this here to be safe, since it's needed to find reg.exe which the MSVC # bat scripts use. sys32_dir = os.path.join(os.environ.get("SystemRoot", os.environ.get("windir", r"C:\Windows\system32")), "System32") if sys32_dir not in normenv['PATH']: normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_dir # Without Wbem in PATH, vcvarsall.bat has a "'wmic' is not recognized" # error starting with Visual Studio 2017, although the script still # seems to work anyway. sys32_wbem_dir = os.path.join(sys32_dir, 'Wbem') if sys32_wbem_dir not in normenv['PATH']: normenv['PATH'] = normenv['PATH'] + os.pathsep + sys32_wbem_dir debug("PATH: %s"%normenv['PATH']) return normenv
[ "def", "normalize_env", "(", "env", ",", "keys", ",", "force", "=", "False", ")", ":", "normenv", "=", "{", "}", "if", "env", ":", "for", "k", "in", "list", "(", "env", ".", "keys", "(", ")", ")", ":", "normenv", "[", "k", "]", "=", "copy", ".", "deepcopy", "(", "env", "[", "k", "]", ")", "for", "k", "in", "keys", ":", "if", "k", "in", "os", ".", "environ", "and", "(", "force", "or", "not", "k", "in", "normenv", ")", ":", "normenv", "[", "k", "]", "=", "os", ".", "environ", "[", "k", "]", "# This shouldn't be necessary, since the default environment should include system32,", "# but keep this here to be safe, since it's needed to find reg.exe which the MSVC", "# bat scripts use.", "sys32_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", ".", "get", "(", "\"SystemRoot\"", ",", "os", ".", "environ", ".", "get", "(", "\"windir\"", ",", "r\"C:\\Windows\\system32\"", ")", ")", ",", "\"System32\"", ")", "if", "sys32_dir", "not", "in", "normenv", "[", "'PATH'", "]", ":", "normenv", "[", "'PATH'", "]", "=", "normenv", "[", "'PATH'", "]", "+", "os", ".", "pathsep", "+", "sys32_dir", "# Without Wbem in PATH, vcvarsall.bat has a \"'wmic' is not recognized\"", "# error starting with Visual Studio 2017, although the script still", "# seems to work anyway.", "sys32_wbem_dir", "=", "os", ".", "path", ".", "join", "(", "sys32_dir", ",", "'Wbem'", ")", "if", "sys32_wbem_dir", "not", "in", "normenv", "[", "'PATH'", "]", ":", "normenv", "[", "'PATH'", "]", "=", "normenv", "[", "'PATH'", "]", "+", "os", ".", "pathsep", "+", "sys32_wbem_dir", "debug", "(", "\"PATH: %s\"", "%", "normenv", "[", "'PATH'", "]", ")", "return", "normenv" ]
Given a dictionary representing a shell environment, add the variables from os.environ needed for the processing of .bat files; the keys are controlled by the keys argument. It also makes sure the environment values are correctly encoded. If force=True, then all of the key values that exist are copied into the returned dictionary. If force=false, values are only copied if the key does not already exist in the copied dictionary. Note: the environment is copied.
[ "Given", "a", "dictionary", "representing", "a", "shell", "environment", "add", "the", "variables", "from", "os", ".", "environ", "needed", "for", "the", "processing", "of", ".", "bat", "files", ";", "the", "keys", "are", "controlled", "by", "the", "keys", "argument", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L101-L141
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py
get_output
def get_output(vcbat, args = None, env = None): """Parse the output of given bat file, with given args.""" if env is None: # Create a blank environment, for use in launching the tools env = SCons.Environment.Environment(tools=[]) # TODO: This is a hard-coded list of the variables that (may) need # to be imported from os.environ[] for v[sc]*vars*.bat file # execution to work. This list should really be either directly # controlled by vc.py, or else derived from the common_tools_var # settings in vs.py. vs_vc_vars = [ 'COMSPEC', # VS100 and VS110: Still set, but modern MSVC setup scripts will # discard these if registry has values. However Intel compiler setup # script still requires these as of 2013/2014. 'VS140COMNTOOLS', 'VS120COMNTOOLS', 'VS110COMNTOOLS', 'VS100COMNTOOLS', 'VS90COMNTOOLS', 'VS80COMNTOOLS', 'VS71COMNTOOLS', 'VS70COMNTOOLS', 'VS60COMNTOOLS', ] env['ENV'] = normalize_env(env['ENV'], vs_vc_vars, force=False) if args: debug("Calling '%s %s'" % (vcbat, args)) popen = SCons.Action._subproc(env, '"%s" %s & set' % (vcbat, args), stdin='devnull', stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: debug("Calling '%s'" % vcbat) popen = SCons.Action._subproc(env, '"%s" & set' % vcbat, stdin='devnull', stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Use the .stdout and .stderr attributes directly because the # .communicate() method uses the threading module on Windows # and won't work under Pythons not built with threading. stdout = popen.stdout.read() stderr = popen.stderr.read() # Extra debug logic, uncomment if necessary # debug('get_output():stdout:%s'%stdout) # debug('get_output():stderr:%s'%stderr) if stderr: # TODO: find something better to do with stderr; # this at least prevents errors from getting swallowed. import sys sys.stderr.write(stderr) if popen.wait() != 0: raise IOError(stderr.decode("mbcs")) output = stdout.decode("mbcs") return output
python
def get_output(vcbat, args = None, env = None): """Parse the output of given bat file, with given args.""" if env is None: # Create a blank environment, for use in launching the tools env = SCons.Environment.Environment(tools=[]) # TODO: This is a hard-coded list of the variables that (may) need # to be imported from os.environ[] for v[sc]*vars*.bat file # execution to work. This list should really be either directly # controlled by vc.py, or else derived from the common_tools_var # settings in vs.py. vs_vc_vars = [ 'COMSPEC', # VS100 and VS110: Still set, but modern MSVC setup scripts will # discard these if registry has values. However Intel compiler setup # script still requires these as of 2013/2014. 'VS140COMNTOOLS', 'VS120COMNTOOLS', 'VS110COMNTOOLS', 'VS100COMNTOOLS', 'VS90COMNTOOLS', 'VS80COMNTOOLS', 'VS71COMNTOOLS', 'VS70COMNTOOLS', 'VS60COMNTOOLS', ] env['ENV'] = normalize_env(env['ENV'], vs_vc_vars, force=False) if args: debug("Calling '%s %s'" % (vcbat, args)) popen = SCons.Action._subproc(env, '"%s" %s & set' % (vcbat, args), stdin='devnull', stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: debug("Calling '%s'" % vcbat) popen = SCons.Action._subproc(env, '"%s" & set' % vcbat, stdin='devnull', stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Use the .stdout and .stderr attributes directly because the # .communicate() method uses the threading module on Windows # and won't work under Pythons not built with threading. stdout = popen.stdout.read() stderr = popen.stderr.read() # Extra debug logic, uncomment if necessary # debug('get_output():stdout:%s'%stdout) # debug('get_output():stderr:%s'%stderr) if stderr: # TODO: find something better to do with stderr; # this at least prevents errors from getting swallowed. import sys sys.stderr.write(stderr) if popen.wait() != 0: raise IOError(stderr.decode("mbcs")) output = stdout.decode("mbcs") return output
[ "def", "get_output", "(", "vcbat", ",", "args", "=", "None", ",", "env", "=", "None", ")", ":", "if", "env", "is", "None", ":", "# Create a blank environment, for use in launching the tools", "env", "=", "SCons", ".", "Environment", ".", "Environment", "(", "tools", "=", "[", "]", ")", "# TODO: This is a hard-coded list of the variables that (may) need", "# to be imported from os.environ[] for v[sc]*vars*.bat file", "# execution to work. This list should really be either directly", "# controlled by vc.py, or else derived from the common_tools_var", "# settings in vs.py.", "vs_vc_vars", "=", "[", "'COMSPEC'", ",", "# VS100 and VS110: Still set, but modern MSVC setup scripts will", "# discard these if registry has values. However Intel compiler setup", "# script still requires these as of 2013/2014.", "'VS140COMNTOOLS'", ",", "'VS120COMNTOOLS'", ",", "'VS110COMNTOOLS'", ",", "'VS100COMNTOOLS'", ",", "'VS90COMNTOOLS'", ",", "'VS80COMNTOOLS'", ",", "'VS71COMNTOOLS'", ",", "'VS70COMNTOOLS'", ",", "'VS60COMNTOOLS'", ",", "]", "env", "[", "'ENV'", "]", "=", "normalize_env", "(", "env", "[", "'ENV'", "]", ",", "vs_vc_vars", ",", "force", "=", "False", ")", "if", "args", ":", "debug", "(", "\"Calling '%s %s'\"", "%", "(", "vcbat", ",", "args", ")", ")", "popen", "=", "SCons", ".", "Action", ".", "_subproc", "(", "env", ",", "'\"%s\" %s & set'", "%", "(", "vcbat", ",", "args", ")", ",", "stdin", "=", "'devnull'", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "else", ":", "debug", "(", "\"Calling '%s'\"", "%", "vcbat", ")", "popen", "=", "SCons", ".", "Action", ".", "_subproc", "(", "env", ",", "'\"%s\" & set'", "%", "vcbat", ",", "stdin", "=", "'devnull'", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "# Use the .stdout and .stderr attributes directly because the", "# .communicate() method uses the threading module on Windows", "# and won't work under Pythons not built with threading.", "stdout", "=", "popen", ".", "stdout", ".", "read", "(", ")", "stderr", "=", "popen", ".", "stderr", ".", "read", "(", ")", "# Extra debug logic, uncomment if necessary", "# debug('get_output():stdout:%s'%stdout)", "# debug('get_output():stderr:%s'%stderr)", "if", "stderr", ":", "# TODO: find something better to do with stderr;", "# this at least prevents errors from getting swallowed.", "import", "sys", "sys", ".", "stderr", ".", "write", "(", "stderr", ")", "if", "popen", ".", "wait", "(", ")", "!=", "0", ":", "raise", "IOError", "(", "stderr", ".", "decode", "(", "\"mbcs\"", ")", ")", "output", "=", "stdout", ".", "decode", "(", "\"mbcs\"", ")", "return", "output" ]
Parse the output of given bat file, with given args.
[ "Parse", "the", "output", "of", "given", "bat", "file", "with", "given", "args", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/common.py#L143-L206
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/default.py
generate
def generate(env): """Add default tools.""" for t in SCons.Tool.tool_list(env['PLATFORM'], env): SCons.Tool.Tool(t)(env)
python
def generate(env): """Add default tools.""" for t in SCons.Tool.tool_list(env['PLATFORM'], env): SCons.Tool.Tool(t)(env)
[ "def", "generate", "(", "env", ")", ":", "for", "t", "in", "SCons", ".", "Tool", ".", "tool_list", "(", "env", "[", "'PLATFORM'", "]", ",", "env", ")", ":", "SCons", ".", "Tool", ".", "Tool", "(", "t", ")", "(", "env", ")" ]
Add default tools.
[ "Add", "default", "tools", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/default.py#L38-L41
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py
_PathList.subst_path
def subst_path(self, env, target, source): """ Performs construction variable substitution on a pre-digested PathList for a specific target and source. """ result = [] for type, value in self.pathlist: if type == TYPE_STRING_SUBST: value = env.subst(value, target=target, source=source, conv=node_conv) if SCons.Util.is_Sequence(value): result.extend(SCons.Util.flatten(value)) elif value: result.append(value) elif type == TYPE_OBJECT: value = node_conv(value) if value: result.append(value) elif value: result.append(value) return tuple(result)
python
def subst_path(self, env, target, source): """ Performs construction variable substitution on a pre-digested PathList for a specific target and source. """ result = [] for type, value in self.pathlist: if type == TYPE_STRING_SUBST: value = env.subst(value, target=target, source=source, conv=node_conv) if SCons.Util.is_Sequence(value): result.extend(SCons.Util.flatten(value)) elif value: result.append(value) elif type == TYPE_OBJECT: value = node_conv(value) if value: result.append(value) elif value: result.append(value) return tuple(result)
[ "def", "subst_path", "(", "self", ",", "env", ",", "target", ",", "source", ")", ":", "result", "=", "[", "]", "for", "type", ",", "value", "in", "self", ".", "pathlist", ":", "if", "type", "==", "TYPE_STRING_SUBST", ":", "value", "=", "env", ".", "subst", "(", "value", ",", "target", "=", "target", ",", "source", "=", "source", ",", "conv", "=", "node_conv", ")", "if", "SCons", ".", "Util", ".", "is_Sequence", "(", "value", ")", ":", "result", ".", "extend", "(", "SCons", ".", "Util", ".", "flatten", "(", "value", ")", ")", "elif", "value", ":", "result", ".", "append", "(", "value", ")", "elif", "type", "==", "TYPE_OBJECT", ":", "value", "=", "node_conv", "(", "value", ")", "if", "value", ":", "result", ".", "append", "(", "value", ")", "elif", "value", ":", "result", ".", "append", "(", "value", ")", "return", "tuple", "(", "result", ")" ]
Performs construction variable substitution on a pre-digested PathList for a specific target and source.
[ "Performs", "construction", "variable", "substitution", "on", "a", "pre", "-", "digested", "PathList", "for", "a", "specific", "target", "and", "source", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py#L123-L143
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py
PathListCache._PathList_key
def _PathList_key(self, pathlist): """ Returns the key for memoization of PathLists. Note that we want this to be pretty quick, so we don't completely canonicalize all forms of the same list. For example, 'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically represent the same list if you're executing from $ROOT, but we're not going to bother splitting strings into path elements, or massaging strings into Nodes, to identify that equivalence. We just want to eliminate obvious redundancy from the normal case of re-using exactly the same cloned value for a path. """ if SCons.Util.is_Sequence(pathlist): pathlist = tuple(SCons.Util.flatten(pathlist)) return pathlist
python
def _PathList_key(self, pathlist): """ Returns the key for memoization of PathLists. Note that we want this to be pretty quick, so we don't completely canonicalize all forms of the same list. For example, 'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically represent the same list if you're executing from $ROOT, but we're not going to bother splitting strings into path elements, or massaging strings into Nodes, to identify that equivalence. We just want to eliminate obvious redundancy from the normal case of re-using exactly the same cloned value for a path. """ if SCons.Util.is_Sequence(pathlist): pathlist = tuple(SCons.Util.flatten(pathlist)) return pathlist
[ "def", "_PathList_key", "(", "self", ",", "pathlist", ")", ":", "if", "SCons", ".", "Util", ".", "is_Sequence", "(", "pathlist", ")", ":", "pathlist", "=", "tuple", "(", "SCons", ".", "Util", ".", "flatten", "(", "pathlist", ")", ")", "return", "pathlist" ]
Returns the key for memoization of PathLists. Note that we want this to be pretty quick, so we don't completely canonicalize all forms of the same list. For example, 'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically represent the same list if you're executing from $ROOT, but we're not going to bother splitting strings into path elements, or massaging strings into Nodes, to identify that equivalence. We just want to eliminate obvious redundancy from the normal case of re-using exactly the same cloned value for a path.
[ "Returns", "the", "key", "for", "memoization", "of", "PathLists", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py#L177-L192
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py
PathListCache.PathList
def PathList(self, pathlist): """ Returns the cached _PathList object for the specified pathlist, creating and caching a new object as necessary. """ pathlist = self._PathList_key(pathlist) try: memo_dict = self._memo['PathList'] except KeyError: memo_dict = {} self._memo['PathList'] = memo_dict else: try: return memo_dict[pathlist] except KeyError: pass result = _PathList(pathlist) memo_dict[pathlist] = result return result
python
def PathList(self, pathlist): """ Returns the cached _PathList object for the specified pathlist, creating and caching a new object as necessary. """ pathlist = self._PathList_key(pathlist) try: memo_dict = self._memo['PathList'] except KeyError: memo_dict = {} self._memo['PathList'] = memo_dict else: try: return memo_dict[pathlist] except KeyError: pass result = _PathList(pathlist) memo_dict[pathlist] = result return result
[ "def", "PathList", "(", "self", ",", "pathlist", ")", ":", "pathlist", "=", "self", ".", "_PathList_key", "(", "pathlist", ")", "try", ":", "memo_dict", "=", "self", ".", "_memo", "[", "'PathList'", "]", "except", "KeyError", ":", "memo_dict", "=", "{", "}", "self", ".", "_memo", "[", "'PathList'", "]", "=", "memo_dict", "else", ":", "try", ":", "return", "memo_dict", "[", "pathlist", "]", "except", "KeyError", ":", "pass", "result", "=", "_PathList", "(", "pathlist", ")", "memo_dict", "[", "pathlist", "]", "=", "result", "return", "result" ]
Returns the cached _PathList object for the specified pathlist, creating and caching a new object as necessary.
[ "Returns", "the", "cached", "_PathList", "object", "for", "the", "specified", "pathlist", "creating", "and", "caching", "a", "new", "object", "as", "necessary", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/PathList.py#L195-L216
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py
DefaultEnvironment
def DefaultEnvironment(*args, **kw): """ Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default construction environment without checking for its existence. (This function still exists with its _default_check because someone else (*cough* Script/__init__.py *cough*) may keep a reference to this function. So we can't use the fully functional idiom of having the name originally be a something that *only* creates the construction environment and then overwrites the name.) """ global _default_env if not _default_env: import SCons.Util _default_env = SCons.Environment.Environment(*args, **kw) if SCons.Util.md5: _default_env.Decider('MD5') else: _default_env.Decider('timestamp-match') global DefaultEnvironment DefaultEnvironment = _fetch_DefaultEnvironment _default_env._CacheDir_path = None return _default_env
python
def DefaultEnvironment(*args, **kw): """ Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default construction environment without checking for its existence. (This function still exists with its _default_check because someone else (*cough* Script/__init__.py *cough*) may keep a reference to this function. So we can't use the fully functional idiom of having the name originally be a something that *only* creates the construction environment and then overwrites the name.) """ global _default_env if not _default_env: import SCons.Util _default_env = SCons.Environment.Environment(*args, **kw) if SCons.Util.md5: _default_env.Decider('MD5') else: _default_env.Decider('timestamp-match') global DefaultEnvironment DefaultEnvironment = _fetch_DefaultEnvironment _default_env._CacheDir_path = None return _default_env
[ "def", "DefaultEnvironment", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "global", "_default_env", "if", "not", "_default_env", ":", "import", "SCons", ".", "Util", "_default_env", "=", "SCons", ".", "Environment", ".", "Environment", "(", "*", "args", ",", "*", "*", "kw", ")", "if", "SCons", ".", "Util", ".", "md5", ":", "_default_env", ".", "Decider", "(", "'MD5'", ")", "else", ":", "_default_env", ".", "Decider", "(", "'timestamp-match'", ")", "global", "DefaultEnvironment", "DefaultEnvironment", "=", "_fetch_DefaultEnvironment", "_default_env", ".", "_CacheDir_path", "=", "None", "return", "_default_env" ]
Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default construction environment without checking for its existence. (This function still exists with its _default_check because someone else (*cough* Script/__init__.py *cough*) may keep a reference to this function. So we can't use the fully functional idiom of having the name originally be a something that *only* creates the construction environment and then overwrites the name.)
[ "Initial", "public", "entry", "point", "for", "creating", "the", "default", "construction", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L68-L95
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py
_concat
def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None): """ Creates a new list from 'list' by first interpolating each element in the list using the 'env' dictionary and then calling f on the list, and finally calling _concat_ixes to concatenate 'prefix' and 'suffix' onto each element of the list. """ if not list: return list l = f(SCons.PathList.PathList(list).subst_path(env, target, source)) if l is not None: list = l return _concat_ixes(prefix, list, suffix, env)
python
def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None): """ Creates a new list from 'list' by first interpolating each element in the list using the 'env' dictionary and then calling f on the list, and finally calling _concat_ixes to concatenate 'prefix' and 'suffix' onto each element of the list. """ if not list: return list l = f(SCons.PathList.PathList(list).subst_path(env, target, source)) if l is not None: list = l return _concat_ixes(prefix, list, suffix, env)
[ "def", "_concat", "(", "prefix", ",", "list", ",", "suffix", ",", "env", ",", "f", "=", "lambda", "x", ":", "x", ",", "target", "=", "None", ",", "source", "=", "None", ")", ":", "if", "not", "list", ":", "return", "list", "l", "=", "f", "(", "SCons", ".", "PathList", ".", "PathList", "(", "list", ")", ".", "subst_path", "(", "env", ",", "target", ",", "source", ")", ")", "if", "l", "is", "not", "None", ":", "list", "=", "l", "return", "_concat_ixes", "(", "prefix", ",", "list", ",", "suffix", ",", "env", ")" ]
Creates a new list from 'list' by first interpolating each element in the list using the 'env' dictionary and then calling f on the list, and finally calling _concat_ixes to concatenate 'prefix' and 'suffix' onto each element of the list.
[ "Creates", "a", "new", "list", "from", "list", "by", "first", "interpolating", "each", "element", "in", "the", "list", "using", "the", "env", "dictionary", "and", "then", "calling", "f", "on", "the", "list", "and", "finally", "calling", "_concat_ixes", "to", "concatenate", "prefix", "and", "suffix", "onto", "each", "element", "of", "the", "list", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L344-L358
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py
_concat_ixes
def _concat_ixes(prefix, list, suffix, env): """ Creates a new list from 'list' by concatenating the 'prefix' and 'suffix' arguments onto each element of the list. A trailing space on 'prefix' or leading space on 'suffix' will cause them to be put into separate list elements rather than being concatenated. """ result = [] # ensure that prefix and suffix are strings prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW)) suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW)) for x in list: if isinstance(x, SCons.Node.FS.File): result.append(x) continue x = str(x) if x: if prefix: if prefix[-1] == ' ': result.append(prefix[:-1]) elif x[:len(prefix)] != prefix: x = prefix + x result.append(x) if suffix: if suffix[0] == ' ': result.append(suffix[1:]) elif x[-len(suffix):] != suffix: result[-1] = result[-1]+suffix return result
python
def _concat_ixes(prefix, list, suffix, env): """ Creates a new list from 'list' by concatenating the 'prefix' and 'suffix' arguments onto each element of the list. A trailing space on 'prefix' or leading space on 'suffix' will cause them to be put into separate list elements rather than being concatenated. """ result = [] # ensure that prefix and suffix are strings prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW)) suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW)) for x in list: if isinstance(x, SCons.Node.FS.File): result.append(x) continue x = str(x) if x: if prefix: if prefix[-1] == ' ': result.append(prefix[:-1]) elif x[:len(prefix)] != prefix: x = prefix + x result.append(x) if suffix: if suffix[0] == ' ': result.append(suffix[1:]) elif x[-len(suffix):] != suffix: result[-1] = result[-1]+suffix return result
[ "def", "_concat_ixes", "(", "prefix", ",", "list", ",", "suffix", ",", "env", ")", ":", "result", "=", "[", "]", "# ensure that prefix and suffix are strings", "prefix", "=", "str", "(", "env", ".", "subst", "(", "prefix", ",", "SCons", ".", "Subst", ".", "SUBST_RAW", ")", ")", "suffix", "=", "str", "(", "env", ".", "subst", "(", "suffix", ",", "SCons", ".", "Subst", ".", "SUBST_RAW", ")", ")", "for", "x", "in", "list", ":", "if", "isinstance", "(", "x", ",", "SCons", ".", "Node", ".", "FS", ".", "File", ")", ":", "result", ".", "append", "(", "x", ")", "continue", "x", "=", "str", "(", "x", ")", "if", "x", ":", "if", "prefix", ":", "if", "prefix", "[", "-", "1", "]", "==", "' '", ":", "result", ".", "append", "(", "prefix", "[", ":", "-", "1", "]", ")", "elif", "x", "[", ":", "len", "(", "prefix", ")", "]", "!=", "prefix", ":", "x", "=", "prefix", "+", "x", "result", ".", "append", "(", "x", ")", "if", "suffix", ":", "if", "suffix", "[", "0", "]", "==", "' '", ":", "result", ".", "append", "(", "suffix", "[", "1", ":", "]", ")", "elif", "x", "[", "-", "len", "(", "suffix", ")", ":", "]", "!=", "suffix", ":", "result", "[", "-", "1", "]", "=", "result", "[", "-", "1", "]", "+", "suffix", "return", "result" ]
Creates a new list from 'list' by concatenating the 'prefix' and 'suffix' arguments onto each element of the list. A trailing space on 'prefix' or leading space on 'suffix' will cause them to be put into separate list elements rather than being concatenated.
[ "Creates", "a", "new", "list", "from", "list", "by", "concatenating", "the", "prefix", "and", "suffix", "arguments", "onto", "each", "element", "of", "the", "list", ".", "A", "trailing", "space", "on", "prefix", "or", "leading", "space", "on", "suffix", "will", "cause", "them", "to", "be", "put", "into", "separate", "list", "elements", "rather", "than", "being", "concatenated", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L360-L395
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py
processDefines
def processDefines(defs): """process defines, resolving strings, lists, dictionaries, into a list of strings """ if SCons.Util.is_List(defs): l = [] for d in defs: if d is None: continue elif SCons.Util.is_List(d) or isinstance(d, tuple): if len(d) >= 2: l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d[0])) elif SCons.Util.is_Dict(d): for macro,value in d.items(): if value is not None: l.append(str(macro) + '=' + str(value)) else: l.append(str(macro)) elif SCons.Util.is_String(d): l.append(str(d)) else: raise SCons.Errors.UserError("DEFINE %s is not a list, dict, string or None."%repr(d)) elif SCons.Util.is_Dict(defs): # The items in a dictionary are stored in random order, but # if the order of the command-line options changes from # invocation to invocation, then the signature of the command # line will change and we'll get random unnecessary rebuilds. # Consequently, we have to sort the keys to ensure a # consistent order... l = [] for k,v in sorted(defs.items()): if v is None: l.append(str(k)) else: l.append(str(k) + '=' + str(v)) else: l = [str(defs)] return l
python
def processDefines(defs): """process defines, resolving strings, lists, dictionaries, into a list of strings """ if SCons.Util.is_List(defs): l = [] for d in defs: if d is None: continue elif SCons.Util.is_List(d) or isinstance(d, tuple): if len(d) >= 2: l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d[0])) elif SCons.Util.is_Dict(d): for macro,value in d.items(): if value is not None: l.append(str(macro) + '=' + str(value)) else: l.append(str(macro)) elif SCons.Util.is_String(d): l.append(str(d)) else: raise SCons.Errors.UserError("DEFINE %s is not a list, dict, string or None."%repr(d)) elif SCons.Util.is_Dict(defs): # The items in a dictionary are stored in random order, but # if the order of the command-line options changes from # invocation to invocation, then the signature of the command # line will change and we'll get random unnecessary rebuilds. # Consequently, we have to sort the keys to ensure a # consistent order... l = [] for k,v in sorted(defs.items()): if v is None: l.append(str(k)) else: l.append(str(k) + '=' + str(v)) else: l = [str(defs)] return l
[ "def", "processDefines", "(", "defs", ")", ":", "if", "SCons", ".", "Util", ".", "is_List", "(", "defs", ")", ":", "l", "=", "[", "]", "for", "d", "in", "defs", ":", "if", "d", "is", "None", ":", "continue", "elif", "SCons", ".", "Util", ".", "is_List", "(", "d", ")", "or", "isinstance", "(", "d", ",", "tuple", ")", ":", "if", "len", "(", "d", ")", ">=", "2", ":", "l", ".", "append", "(", "str", "(", "d", "[", "0", "]", ")", "+", "'='", "+", "str", "(", "d", "[", "1", "]", ")", ")", "else", ":", "l", ".", "append", "(", "str", "(", "d", "[", "0", "]", ")", ")", "elif", "SCons", ".", "Util", ".", "is_Dict", "(", "d", ")", ":", "for", "macro", ",", "value", "in", "d", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "l", ".", "append", "(", "str", "(", "macro", ")", "+", "'='", "+", "str", "(", "value", ")", ")", "else", ":", "l", ".", "append", "(", "str", "(", "macro", ")", ")", "elif", "SCons", ".", "Util", ".", "is_String", "(", "d", ")", ":", "l", ".", "append", "(", "str", "(", "d", ")", ")", "else", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "\"DEFINE %s is not a list, dict, string or None.\"", "%", "repr", "(", "d", ")", ")", "elif", "SCons", ".", "Util", ".", "is_Dict", "(", "defs", ")", ":", "# The items in a dictionary are stored in random order, but", "# if the order of the command-line options changes from", "# invocation to invocation, then the signature of the command", "# line will change and we'll get random unnecessary rebuilds.", "# Consequently, we have to sort the keys to ensure a", "# consistent order...", "l", "=", "[", "]", "for", "k", ",", "v", "in", "sorted", "(", "defs", ".", "items", "(", ")", ")", ":", "if", "v", "is", "None", ":", "l", ".", "append", "(", "str", "(", "k", ")", ")", "else", ":", "l", ".", "append", "(", "str", "(", "k", ")", "+", "'='", "+", "str", "(", "v", ")", ")", "else", ":", "l", "=", "[", "str", "(", "defs", ")", "]", "return", "l" ]
process defines, resolving strings, lists, dictionaries, into a list of strings
[ "process", "defines", "resolving", "strings", "lists", "dictionaries", "into", "a", "list", "of", "strings" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L449-L488
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py
_defines
def _defines(prefix, defs, suffix, env, c=_concat_ixes): """A wrapper around _concat_ixes that turns a list or string into a list of C preprocessor command-line definitions. """ return c(prefix, env.subst_path(processDefines(defs)), suffix, env)
python
def _defines(prefix, defs, suffix, env, c=_concat_ixes): """A wrapper around _concat_ixes that turns a list or string into a list of C preprocessor command-line definitions. """ return c(prefix, env.subst_path(processDefines(defs)), suffix, env)
[ "def", "_defines", "(", "prefix", ",", "defs", ",", "suffix", ",", "env", ",", "c", "=", "_concat_ixes", ")", ":", "return", "c", "(", "prefix", ",", "env", ".", "subst_path", "(", "processDefines", "(", "defs", ")", ")", ",", "suffix", ",", "env", ")" ]
A wrapper around _concat_ixes that turns a list or string into a list of C preprocessor command-line definitions.
[ "A", "wrapper", "around", "_concat_ixes", "that", "turns", "a", "list", "or", "string", "into", "a", "list", "of", "C", "preprocessor", "command", "-", "line", "definitions", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Defaults.py#L491-L496
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/__init__.py
Scanner
def Scanner(function, *args, **kw): """ Public interface factory function for creating different types of Scanners based on the different types of "functions" that may be supplied. TODO: Deprecate this some day. We've moved the functionality inside the Base class and really don't need this factory function any more. It was, however, used by some of our Tool modules, so the call probably ended up in various people's custom modules patterned on SCons code. """ if SCons.Util.is_Dict(function): return Selector(function, *args, **kw) else: return Base(function, *args, **kw)
python
def Scanner(function, *args, **kw): """ Public interface factory function for creating different types of Scanners based on the different types of "functions" that may be supplied. TODO: Deprecate this some day. We've moved the functionality inside the Base class and really don't need this factory function any more. It was, however, used by some of our Tool modules, so the call probably ended up in various people's custom modules patterned on SCons code. """ if SCons.Util.is_Dict(function): return Selector(function, *args, **kw) else: return Base(function, *args, **kw)
[ "def", "Scanner", "(", "function", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "SCons", ".", "Util", ".", "is_Dict", "(", "function", ")", ":", "return", "Selector", "(", "function", ",", "*", "args", ",", "*", "*", "kw", ")", "else", ":", "return", "Base", "(", "function", ",", "*", "args", ",", "*", "*", "kw", ")" ]
Public interface factory function for creating different types of Scanners based on the different types of "functions" that may be supplied. TODO: Deprecate this some day. We've moved the functionality inside the Base class and really don't need this factory function any more. It was, however, used by some of our Tool modules, so the call probably ended up in various people's custom modules patterned on SCons code.
[ "Public", "interface", "factory", "function", "for", "creating", "different", "types", "of", "Scanners", "based", "on", "the", "different", "types", "of", "functions", "that", "may", "be", "supplied", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/__init__.py#L45-L60
train
iotile/coretools
iotilecore/iotile/core/hw/reports/broadcast.py
BroadcastReport.ReportLength
def ReportLength(cls, header): """Given a header of HeaderLength bytes, calculate the size of this report. Returns: int: The total length of the report including the header that we are passed. """ parsed_header = cls._parse_header(header) auth_size = cls._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type) if auth_size is None: raise DataError("Unknown auth block size in BroadcastReport") return cls._HEADER_LENGTH + parsed_header.reading_length + auth_size
python
def ReportLength(cls, header): """Given a header of HeaderLength bytes, calculate the size of this report. Returns: int: The total length of the report including the header that we are passed. """ parsed_header = cls._parse_header(header) auth_size = cls._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type) if auth_size is None: raise DataError("Unknown auth block size in BroadcastReport") return cls._HEADER_LENGTH + parsed_header.reading_length + auth_size
[ "def", "ReportLength", "(", "cls", ",", "header", ")", ":", "parsed_header", "=", "cls", ".", "_parse_header", "(", "header", ")", "auth_size", "=", "cls", ".", "_AUTH_BLOCK_LENGTHS", ".", "get", "(", "parsed_header", ".", "auth_type", ")", "if", "auth_size", "is", "None", ":", "raise", "DataError", "(", "\"Unknown auth block size in BroadcastReport\"", ")", "return", "cls", ".", "_HEADER_LENGTH", "+", "parsed_header", ".", "reading_length", "+", "auth_size" ]
Given a header of HeaderLength bytes, calculate the size of this report. Returns: int: The total length of the report including the header that we are passed.
[ "Given", "a", "header", "of", "HeaderLength", "bytes", "calculate", "the", "size", "of", "this", "report", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/broadcast.py#L68-L81
train
iotile/coretools
iotilecore/iotile/core/hw/reports/broadcast.py
BroadcastReport.FromReadings
def FromReadings(cls, uuid, readings, sent_timestamp=0): """Generate a broadcast report from a list of readings and a uuid.""" header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0) packed_readings = bytearray() for reading in readings: packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id, reading.raw_time, reading.value) packed_readings += bytearray(packed_reading) return BroadcastReport(bytearray(header) + packed_readings)
python
def FromReadings(cls, uuid, readings, sent_timestamp=0): """Generate a broadcast report from a list of readings and a uuid.""" header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0) packed_readings = bytearray() for reading in readings: packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id, reading.raw_time, reading.value) packed_readings += bytearray(packed_reading) return BroadcastReport(bytearray(header) + packed_readings)
[ "def", "FromReadings", "(", "cls", ",", "uuid", ",", "readings", ",", "sent_timestamp", "=", "0", ")", ":", "header", "=", "struct", ".", "pack", "(", "\"<BBHLLL\"", ",", "cls", ".", "ReportType", ",", "0", ",", "len", "(", "readings", ")", "*", "16", ",", "uuid", ",", "sent_timestamp", ",", "0", ")", "packed_readings", "=", "bytearray", "(", ")", "for", "reading", "in", "readings", ":", "packed_reading", "=", "struct", ".", "pack", "(", "\"<HHLLL\"", ",", "reading", ".", "stream", ",", "0", ",", "reading", ".", "reading_id", ",", "reading", ".", "raw_time", ",", "reading", ".", "value", ")", "packed_readings", "+=", "bytearray", "(", "packed_reading", ")", "return", "BroadcastReport", "(", "bytearray", "(", "header", ")", "+", "packed_readings", ")" ]
Generate a broadcast report from a list of readings and a uuid.
[ "Generate", "a", "broadcast", "report", "from", "a", "list", "of", "readings", "and", "a", "uuid", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/broadcast.py#L84-L96
train
iotile/coretools
iotilecore/iotile/core/hw/reports/broadcast.py
BroadcastReport.decode
def decode(self): """Decode this report into a list of visible readings.""" parsed_header = self._parse_header(self.raw_report[:self._HEADER_LENGTH]) auth_size = self._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type) assert auth_size is not None assert parsed_header.reading_length % 16 == 0 time_base = self.received_time - datetime.timedelta(seconds=parsed_header.sent_timestamp) readings = self.raw_report[self._HEADER_LENGTH:self._HEADER_LENGTH + parsed_header.reading_length] parsed_readings = [] for i in range(0, len(readings), 16): reading = readings[i:i+16] stream, _, reading_id, timestamp, value = struct.unpack("<HHLLL", reading) parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id) parsed_readings.append(parsed) self.sent_timestamp = parsed_header.sent_timestamp self.origin = parsed_header.uuid return parsed_readings, []
python
def decode(self): """Decode this report into a list of visible readings.""" parsed_header = self._parse_header(self.raw_report[:self._HEADER_LENGTH]) auth_size = self._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type) assert auth_size is not None assert parsed_header.reading_length % 16 == 0 time_base = self.received_time - datetime.timedelta(seconds=parsed_header.sent_timestamp) readings = self.raw_report[self._HEADER_LENGTH:self._HEADER_LENGTH + parsed_header.reading_length] parsed_readings = [] for i in range(0, len(readings), 16): reading = readings[i:i+16] stream, _, reading_id, timestamp, value = struct.unpack("<HHLLL", reading) parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id) parsed_readings.append(parsed) self.sent_timestamp = parsed_header.sent_timestamp self.origin = parsed_header.uuid return parsed_readings, []
[ "def", "decode", "(", "self", ")", ":", "parsed_header", "=", "self", ".", "_parse_header", "(", "self", ".", "raw_report", "[", ":", "self", ".", "_HEADER_LENGTH", "]", ")", "auth_size", "=", "self", ".", "_AUTH_BLOCK_LENGTHS", ".", "get", "(", "parsed_header", ".", "auth_type", ")", "assert", "auth_size", "is", "not", "None", "assert", "parsed_header", ".", "reading_length", "%", "16", "==", "0", "time_base", "=", "self", ".", "received_time", "-", "datetime", ".", "timedelta", "(", "seconds", "=", "parsed_header", ".", "sent_timestamp", ")", "readings", "=", "self", ".", "raw_report", "[", "self", ".", "_HEADER_LENGTH", ":", "self", ".", "_HEADER_LENGTH", "+", "parsed_header", ".", "reading_length", "]", "parsed_readings", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "readings", ")", ",", "16", ")", ":", "reading", "=", "readings", "[", "i", ":", "i", "+", "16", "]", "stream", ",", "_", ",", "reading_id", ",", "timestamp", ",", "value", "=", "struct", ".", "unpack", "(", "\"<HHLLL\"", ",", "reading", ")", "parsed", "=", "IOTileReading", "(", "timestamp", ",", "stream", ",", "value", ",", "time_base", "=", "time_base", ",", "reading_id", "=", "reading_id", ")", "parsed_readings", ".", "append", "(", "parsed", ")", "self", ".", "sent_timestamp", "=", "parsed_header", ".", "sent_timestamp", "self", ".", "origin", "=", "parsed_header", ".", "uuid", "return", "parsed_readings", ",", "[", "]" ]
Decode this report into a list of visible readings.
[ "Decode", "this", "report", "into", "a", "list", "of", "visible", "readings", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/broadcast.py#L98-L122
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface.start
def start(self, device): """Start serving access to this VirtualIOTileDevice Args: device (VirtualIOTileDevice): The device we will be providing access to """ super(NativeBLEVirtualInterface, self).start(device) self.set_advertising(True)
python
def start(self, device): """Start serving access to this VirtualIOTileDevice Args: device (VirtualIOTileDevice): The device we will be providing access to """ super(NativeBLEVirtualInterface, self).start(device) self.set_advertising(True)
[ "def", "start", "(", "self", ",", "device", ")", ":", "super", "(", "NativeBLEVirtualInterface", ",", "self", ")", ".", "start", "(", "device", ")", "self", ".", "set_advertising", "(", "True", ")" ]
Start serving access to this VirtualIOTileDevice Args: device (VirtualIOTileDevice): The device we will be providing access to
[ "Start", "serving", "access", "to", "this", "VirtualIOTileDevice" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L116-L124
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface.register_gatt_table
def register_gatt_table(self): """Register the GATT table into baBLE.""" services = [BLEService, TileBusService] characteristics = [ NameChar, AppearanceChar, ReceiveHeaderChar, ReceivePayloadChar, SendHeaderChar, SendPayloadChar, StreamingChar, HighSpeedChar, TracingChar ] self.bable.set_gatt_table(services, characteristics)
python
def register_gatt_table(self): """Register the GATT table into baBLE.""" services = [BLEService, TileBusService] characteristics = [ NameChar, AppearanceChar, ReceiveHeaderChar, ReceivePayloadChar, SendHeaderChar, SendPayloadChar, StreamingChar, HighSpeedChar, TracingChar ] self.bable.set_gatt_table(services, characteristics)
[ "def", "register_gatt_table", "(", "self", ")", ":", "services", "=", "[", "BLEService", ",", "TileBusService", "]", "characteristics", "=", "[", "NameChar", ",", "AppearanceChar", ",", "ReceiveHeaderChar", ",", "ReceivePayloadChar", ",", "SendHeaderChar", ",", "SendPayloadChar", ",", "StreamingChar", ",", "HighSpeedChar", ",", "TracingChar", "]", "self", ".", "bable", ".", "set_gatt_table", "(", "services", ",", "characteristics", ")" ]
Register the GATT table into baBLE.
[ "Register", "the", "GATT", "table", "into", "baBLE", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L134-L150
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface.set_advertising
def set_advertising(self, enabled): """Toggle advertising.""" if enabled: self.bable.set_advertising( enabled=True, uuids=[TileBusService.uuid], name="V_IOTile ", company_id=ArchManuID, advertising_data=self._advertisement(), scan_response=self._scan_response(), sync=True ) else: try: self.bable.set_advertising(enabled=False, sync=True) except bable_interface.BaBLEException: # If advertising is already disabled pass
python
def set_advertising(self, enabled): """Toggle advertising.""" if enabled: self.bable.set_advertising( enabled=True, uuids=[TileBusService.uuid], name="V_IOTile ", company_id=ArchManuID, advertising_data=self._advertisement(), scan_response=self._scan_response(), sync=True ) else: try: self.bable.set_advertising(enabled=False, sync=True) except bable_interface.BaBLEException: # If advertising is already disabled pass
[ "def", "set_advertising", "(", "self", ",", "enabled", ")", ":", "if", "enabled", ":", "self", ".", "bable", ".", "set_advertising", "(", "enabled", "=", "True", ",", "uuids", "=", "[", "TileBusService", ".", "uuid", "]", ",", "name", "=", "\"V_IOTile \"", ",", "company_id", "=", "ArchManuID", ",", "advertising_data", "=", "self", ".", "_advertisement", "(", ")", ",", "scan_response", "=", "self", ".", "_scan_response", "(", ")", ",", "sync", "=", "True", ")", "else", ":", "try", ":", "self", ".", "bable", ".", "set_advertising", "(", "enabled", "=", "False", ",", "sync", "=", "True", ")", "except", "bable_interface", ".", "BaBLEException", ":", "# If advertising is already disabled", "pass" ]
Toggle advertising.
[ "Toggle", "advertising", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L160-L177
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface._advertisement
def _advertisement(self): """Create advertisement data.""" # Flags are # bit 0: whether we have pending data # bit 1: whether we are in a low voltage state # bit 2: whether another user is connected # bit 3: whether we support robust reports # bit 4: whether we allow fast writes flags = int(self.device.pending_data) | (0 << 1) | (0 << 2) | (1 << 3) | (1 << 4) return struct.pack("<LH", self.device.iotile_id, flags)
python
def _advertisement(self): """Create advertisement data.""" # Flags are # bit 0: whether we have pending data # bit 1: whether we are in a low voltage state # bit 2: whether another user is connected # bit 3: whether we support robust reports # bit 4: whether we allow fast writes flags = int(self.device.pending_data) | (0 << 1) | (0 << 2) | (1 << 3) | (1 << 4) return struct.pack("<LH", self.device.iotile_id, flags)
[ "def", "_advertisement", "(", "self", ")", ":", "# Flags are", "# bit 0: whether we have pending data", "# bit 1: whether we are in a low voltage state", "# bit 2: whether another user is connected", "# bit 3: whether we support robust reports", "# bit 4: whether we allow fast writes", "flags", "=", "int", "(", "self", ".", "device", ".", "pending_data", ")", "|", "(", "0", "<<", "1", ")", "|", "(", "0", "<<", "2", ")", "|", "(", "1", "<<", "3", ")", "|", "(", "1", "<<", "4", ")", "return", "struct", ".", "pack", "(", "\"<LH\"", ",", "self", ".", "device", ".", "iotile_id", ",", "flags", ")" ]
Create advertisement data.
[ "Create", "advertisement", "data", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L179-L189
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface._scan_response
def _scan_response(self): """Create scan response data.""" voltage = struct.pack("<H", int(self.voltage*256)) reading = struct.pack("<HLLL", 0xFFFF, 0, 0, 0) response = voltage + reading return response
python
def _scan_response(self): """Create scan response data.""" voltage = struct.pack("<H", int(self.voltage*256)) reading = struct.pack("<HLLL", 0xFFFF, 0, 0, 0) response = voltage + reading return response
[ "def", "_scan_response", "(", "self", ")", ":", "voltage", "=", "struct", ".", "pack", "(", "\"<H\"", ",", "int", "(", "self", ".", "voltage", "*", "256", ")", ")", "reading", "=", "struct", ".", "pack", "(", "\"<HLLL\"", ",", "0xFFFF", ",", "0", ",", "0", ",", "0", ")", "response", "=", "voltage", "+", "reading", "return", "response" ]
Create scan response data.
[ "Create", "scan", "response", "data", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L191-L198
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface.stop_sync
def stop_sync(self): """Safely stop this BLED112 instance without leaving it in a weird state.""" # Disconnect connected device if self.connected: self.disconnect_sync(self._connection_handle) # Disable advertising self.set_advertising(False) # Stop the baBLE interface self.bable.stop() self.actions.queue.clear()
python
def stop_sync(self): """Safely stop this BLED112 instance without leaving it in a weird state.""" # Disconnect connected device if self.connected: self.disconnect_sync(self._connection_handle) # Disable advertising self.set_advertising(False) # Stop the baBLE interface self.bable.stop() self.actions.queue.clear()
[ "def", "stop_sync", "(", "self", ")", ":", "# Disconnect connected device", "if", "self", ".", "connected", ":", "self", ".", "disconnect_sync", "(", "self", ".", "_connection_handle", ")", "# Disable advertising", "self", ".", "set_advertising", "(", "False", ")", "# Stop the baBLE interface", "self", ".", "bable", ".", "stop", "(", ")", "self", ".", "actions", ".", "queue", ".", "clear", "(", ")" ]
Safely stop this BLED112 instance without leaving it in a weird state.
[ "Safely", "stop", "this", "BLED112", "instance", "without", "leaving", "it", "in", "a", "weird", "state", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L200-L212
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface.disconnect_sync
def disconnect_sync(self, connection_handle): """Synchronously disconnect from whoever has connected to us Args: connection_handle (int): The handle of the connection we wish to disconnect. """ self.bable.disconnect(connection_handle=connection_handle, sync=True)
python
def disconnect_sync(self, connection_handle): """Synchronously disconnect from whoever has connected to us Args: connection_handle (int): The handle of the connection we wish to disconnect. """ self.bable.disconnect(connection_handle=connection_handle, sync=True)
[ "def", "disconnect_sync", "(", "self", ",", "connection_handle", ")", ":", "self", ".", "bable", ".", "disconnect", "(", "connection_handle", "=", "connection_handle", ",", "sync", "=", "True", ")" ]
Synchronously disconnect from whoever has connected to us Args: connection_handle (int): The handle of the connection we wish to disconnect.
[ "Synchronously", "disconnect", "from", "whoever", "has", "connected", "to", "us" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L214-L221
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface._stream_data
def _stream_data(self, chunk=None): """Stream reports to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports. """ # If we failed to transmit a chunk, we will be requeued with an argument self._stream_sm_running = True if chunk is None: chunk = self._next_streaming_chunk(20) if chunk is None or len(chunk) == 0: self._stream_sm_running = False return try: self._send_notification(StreamingChar.value_handle, chunk) self._defer(self._stream_data) except bable_interface.BaBLEException as err: if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again time.sleep(0.05) self._defer(self._stream_data, [chunk]) else: self._audit('ErrorStreamingReport') # If there was an error, stop streaming but don't choke self._logger.exception("Error while streaming data")
python
def _stream_data(self, chunk=None): """Stream reports to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports. """ # If we failed to transmit a chunk, we will be requeued with an argument self._stream_sm_running = True if chunk is None: chunk = self._next_streaming_chunk(20) if chunk is None or len(chunk) == 0: self._stream_sm_running = False return try: self._send_notification(StreamingChar.value_handle, chunk) self._defer(self._stream_data) except bable_interface.BaBLEException as err: if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again time.sleep(0.05) self._defer(self._stream_data, [chunk]) else: self._audit('ErrorStreamingReport') # If there was an error, stop streaming but don't choke self._logger.exception("Error while streaming data")
[ "def", "_stream_data", "(", "self", ",", "chunk", "=", "None", ")", ":", "# If we failed to transmit a chunk, we will be requeued with an argument", "self", ".", "_stream_sm_running", "=", "True", "if", "chunk", "is", "None", ":", "chunk", "=", "self", ".", "_next_streaming_chunk", "(", "20", ")", "if", "chunk", "is", "None", "or", "len", "(", "chunk", ")", "==", "0", ":", "self", ".", "_stream_sm_running", "=", "False", "return", "try", ":", "self", ".", "_send_notification", "(", "StreamingChar", ".", "value_handle", ",", "chunk", ")", "self", ".", "_defer", "(", "self", ".", "_stream_data", ")", "except", "bable_interface", ".", "BaBLEException", "as", "err", ":", "if", "err", ".", "packet", ".", "status", "==", "'Rejected'", ":", "# If we are streaming too fast, back off and try again", "time", ".", "sleep", "(", "0.05", ")", "self", ".", "_defer", "(", "self", ".", "_stream_data", ",", "[", "chunk", "]", ")", "else", ":", "self", ".", "_audit", "(", "'ErrorStreamingReport'", ")", "# If there was an error, stop streaming but don't choke", "self", ".", "_logger", ".", "exception", "(", "\"Error while streaming data\"", ")" ]
Stream reports to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports.
[ "Stream", "reports", "to", "the", "ble", "client", "in", "20", "byte", "chunks" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L446-L473
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface._send_trace
def _send_trace(self, chunk=None): """Stream tracing data to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports. """ self._trace_sm_running = True # If we failed to transmit a chunk, we will be requeued with an argument if chunk is None: chunk = self._next_tracing_chunk(20) if chunk is None or len(chunk) == 0: self._trace_sm_running = False return try: self._send_notification(TracingChar.value_handle, chunk) self._defer(self._send_trace) except bable_interface.BaBLEException as err: if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again time.sleep(0.05) self._defer(self._send_trace, [chunk]) else: self._audit('ErrorStreamingTrace') # If there was an error, stop streaming but don't choke self._logger.exception("Error while tracing data")
python
def _send_trace(self, chunk=None): """Stream tracing data to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports. """ self._trace_sm_running = True # If we failed to transmit a chunk, we will be requeued with an argument if chunk is None: chunk = self._next_tracing_chunk(20) if chunk is None or len(chunk) == 0: self._trace_sm_running = False return try: self._send_notification(TracingChar.value_handle, chunk) self._defer(self._send_trace) except bable_interface.BaBLEException as err: if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again time.sleep(0.05) self._defer(self._send_trace, [chunk]) else: self._audit('ErrorStreamingTrace') # If there was an error, stop streaming but don't choke self._logger.exception("Error while tracing data")
[ "def", "_send_trace", "(", "self", ",", "chunk", "=", "None", ")", ":", "self", ".", "_trace_sm_running", "=", "True", "# If we failed to transmit a chunk, we will be requeued with an argument", "if", "chunk", "is", "None", ":", "chunk", "=", "self", ".", "_next_tracing_chunk", "(", "20", ")", "if", "chunk", "is", "None", "or", "len", "(", "chunk", ")", "==", "0", ":", "self", ".", "_trace_sm_running", "=", "False", "return", "try", ":", "self", ".", "_send_notification", "(", "TracingChar", ".", "value_handle", ",", "chunk", ")", "self", ".", "_defer", "(", "self", ".", "_send_trace", ")", "except", "bable_interface", ".", "BaBLEException", "as", "err", ":", "if", "err", ".", "packet", ".", "status", "==", "'Rejected'", ":", "# If we are streaming too fast, back off and try again", "time", ".", "sleep", "(", "0.05", ")", "self", ".", "_defer", "(", "self", ".", "_send_trace", ",", "[", "chunk", "]", ")", "else", ":", "self", ".", "_audit", "(", "'ErrorStreamingTrace'", ")", "# If there was an error, stop streaming but don't choke", "self", ".", "_logger", ".", "exception", "(", "\"Error while tracing data\"", ")" ]
Stream tracing data to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports.
[ "Stream", "tracing", "data", "to", "the", "ble", "client", "in", "20", "byte", "chunks" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L475-L501
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py
NativeBLEVirtualInterface.process
def process(self): """Periodic nonblocking processes""" super(NativeBLEVirtualInterface, self).process() if (not self._stream_sm_running) and (not self.reports.empty()): self._stream_data() if (not self._trace_sm_running) and (not self.traces.empty()): self._send_trace()
python
def process(self): """Periodic nonblocking processes""" super(NativeBLEVirtualInterface, self).process() if (not self._stream_sm_running) and (not self.reports.empty()): self._stream_data() if (not self._trace_sm_running) and (not self.traces.empty()): self._send_trace()
[ "def", "process", "(", "self", ")", ":", "super", "(", "NativeBLEVirtualInterface", ",", "self", ")", ".", "process", "(", ")", "if", "(", "not", "self", ".", "_stream_sm_running", ")", "and", "(", "not", "self", ".", "reports", ".", "empty", "(", ")", ")", ":", "self", ".", "_stream_data", "(", ")", "if", "(", "not", "self", ".", "_trace_sm_running", ")", "and", "(", "not", "self", ".", "traces", ".", "empty", "(", ")", ")", ":", "self", ".", "_send_trace", "(", ")" ]
Periodic nonblocking processes
[ "Periodic", "nonblocking", "processes" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/virtual_ble.py#L503-L512
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
AsyncSupervisorClient._populate_name_map
async def _populate_name_map(self): """Populate the name map of services as reported by the supervisor""" services = await self.sync_services() with self._state_lock: self.services = services for i, name in enumerate(self.services.keys()): self._name_map[i] = name
python
async def _populate_name_map(self): """Populate the name map of services as reported by the supervisor""" services = await self.sync_services() with self._state_lock: self.services = services for i, name in enumerate(self.services.keys()): self._name_map[i] = name
[ "async", "def", "_populate_name_map", "(", "self", ")", ":", "services", "=", "await", "self", ".", "sync_services", "(", ")", "with", "self", ".", "_state_lock", ":", "self", ".", "services", "=", "services", "for", "i", ",", "name", "in", "enumerate", "(", "self", ".", "services", ".", "keys", "(", ")", ")", ":", "self", ".", "_name_map", "[", "i", "]", "=", "name" ]
Populate the name map of services as reported by the supervisor
[ "Populate", "the", "name", "map", "of", "services", "as", "reported", "by", "the", "supervisor" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L87-L96
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
AsyncSupervisorClient.local_service
def local_service(self, name_or_id): """Get the locally synced information for a service. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that it cannot change while this method is iterating over it. Args: name_or_id (string or int): Either a short name for the service or a numeric id. Returns: ServiceState: the current state of the service synced locally at the time of the call. """ if not self._loop.inside_loop(): self._state_lock.acquire() try: if isinstance(name_or_id, int): if name_or_id not in self._name_map: raise ArgumentError("Unknown ID used to look up service", id=name_or_id) name = self._name_map[name_or_id] else: name = name_or_id if name not in self.services: raise ArgumentError("Unknown service name", name=name) return copy(self.services[name]) finally: if not self._loop.inside_loop(): self._state_lock.release()
python
def local_service(self, name_or_id): """Get the locally synced information for a service. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that it cannot change while this method is iterating over it. Args: name_or_id (string or int): Either a short name for the service or a numeric id. Returns: ServiceState: the current state of the service synced locally at the time of the call. """ if not self._loop.inside_loop(): self._state_lock.acquire() try: if isinstance(name_or_id, int): if name_or_id not in self._name_map: raise ArgumentError("Unknown ID used to look up service", id=name_or_id) name = self._name_map[name_or_id] else: name = name_or_id if name not in self.services: raise ArgumentError("Unknown service name", name=name) return copy(self.services[name]) finally: if not self._loop.inside_loop(): self._state_lock.release()
[ "def", "local_service", "(", "self", ",", "name_or_id", ")", ":", "if", "not", "self", ".", "_loop", ".", "inside_loop", "(", ")", ":", "self", ".", "_state_lock", ".", "acquire", "(", ")", "try", ":", "if", "isinstance", "(", "name_or_id", ",", "int", ")", ":", "if", "name_or_id", "not", "in", "self", ".", "_name_map", ":", "raise", "ArgumentError", "(", "\"Unknown ID used to look up service\"", ",", "id", "=", "name_or_id", ")", "name", "=", "self", ".", "_name_map", "[", "name_or_id", "]", "else", ":", "name", "=", "name_or_id", "if", "name", "not", "in", "self", ".", "services", ":", "raise", "ArgumentError", "(", "\"Unknown service name\"", ",", "name", "=", "name", ")", "return", "copy", "(", "self", ".", "services", "[", "name", "]", ")", "finally", ":", "if", "not", "self", ".", "_loop", ".", "inside_loop", "(", ")", ":", "self", ".", "_state_lock", ".", "release", "(", ")" ]
Get the locally synced information for a service. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that it cannot change while this method is iterating over it. Args: name_or_id (string or int): Either a short name for the service or a numeric id. Returns: ServiceState: the current state of the service synced locally at the time of the call.
[ "Get", "the", "locally", "synced", "information", "for", "a", "service", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L108-L141
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
AsyncSupervisorClient.local_services
def local_services(self): """Get a list of id, name pairs for all of the known synced services. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that it cannot change while this method is iterating over it. Returns: list (id, name): A list of tuples with id and service name sorted by id from low to high """ if not self._loop.inside_loop(): self._state_lock.acquire() try: return sorted([(index, name) for index, name in self._name_map.items()], key=lambda element: element[0]) finally: if not self._loop.inside_loop(): self._state_lock.release()
python
def local_services(self): """Get a list of id, name pairs for all of the known synced services. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that it cannot change while this method is iterating over it. Returns: list (id, name): A list of tuples with id and service name sorted by id from low to high """ if not self._loop.inside_loop(): self._state_lock.acquire() try: return sorted([(index, name) for index, name in self._name_map.items()], key=lambda element: element[0]) finally: if not self._loop.inside_loop(): self._state_lock.release()
[ "def", "local_services", "(", "self", ")", ":", "if", "not", "self", ".", "_loop", ".", "inside_loop", "(", ")", ":", "self", ".", "_state_lock", ".", "acquire", "(", ")", "try", ":", "return", "sorted", "(", "[", "(", "index", ",", "name", ")", "for", "index", ",", "name", "in", "self", ".", "_name_map", ".", "items", "(", ")", "]", ",", "key", "=", "lambda", "element", ":", "element", "[", "0", "]", ")", "finally", ":", "if", "not", "self", ".", "_loop", ".", "inside_loop", "(", ")", ":", "self", ".", "_state_lock", ".", "release", "(", ")" ]
Get a list of id, name pairs for all of the known synced services. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that it cannot change while this method is iterating over it. Returns: list (id, name): A list of tuples with id and service name sorted by id from low to high
[ "Get", "a", "list", "of", "id", "name", "pairs", "for", "all", "of", "the", "known", "synced", "services", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L143-L163
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
AsyncSupervisorClient.sync_services
async def sync_services(self): """Poll the current state of all services. Returns: dict: A dictionary mapping service name to service status """ services = {} servs = await self.list_services() for i, serv in enumerate(servs): info = await self.service_info(serv) status = await self.service_status(serv) messages = await self.get_messages(serv) headline = await self.get_headline(serv) services[serv] = states.ServiceState(info['short_name'], info['long_name'], info['preregistered'], i) services[serv].state = status['numeric_status'] for message in messages: services[serv].post_message(message.level, message.message, message.count, message.created) if headline is not None: services[serv].set_headline(headline.level, headline.message, headline.created) return services
python
async def sync_services(self): """Poll the current state of all services. Returns: dict: A dictionary mapping service name to service status """ services = {} servs = await self.list_services() for i, serv in enumerate(servs): info = await self.service_info(serv) status = await self.service_status(serv) messages = await self.get_messages(serv) headline = await self.get_headline(serv) services[serv] = states.ServiceState(info['short_name'], info['long_name'], info['preregistered'], i) services[serv].state = status['numeric_status'] for message in messages: services[serv].post_message(message.level, message.message, message.count, message.created) if headline is not None: services[serv].set_headline(headline.level, headline.message, headline.created) return services
[ "async", "def", "sync_services", "(", "self", ")", ":", "services", "=", "{", "}", "servs", "=", "await", "self", ".", "list_services", "(", ")", "for", "i", ",", "serv", "in", "enumerate", "(", "servs", ")", ":", "info", "=", "await", "self", ".", "service_info", "(", "serv", ")", "status", "=", "await", "self", ".", "service_status", "(", "serv", ")", "messages", "=", "await", "self", ".", "get_messages", "(", "serv", ")", "headline", "=", "await", "self", ".", "get_headline", "(", "serv", ")", "services", "[", "serv", "]", "=", "states", ".", "ServiceState", "(", "info", "[", "'short_name'", "]", ",", "info", "[", "'long_name'", "]", ",", "info", "[", "'preregistered'", "]", ",", "i", ")", "services", "[", "serv", "]", ".", "state", "=", "status", "[", "'numeric_status'", "]", "for", "message", "in", "messages", ":", "services", "[", "serv", "]", ".", "post_message", "(", "message", ".", "level", ",", "message", ".", "message", ",", "message", ".", "count", ",", "message", ".", "created", ")", "if", "headline", "is", "not", "None", ":", "services", "[", "serv", "]", ".", "set_headline", "(", "headline", ".", "level", ",", "headline", ".", "message", ",", "headline", ".", "created", ")", "return", "services" ]
Poll the current state of all services. Returns: dict: A dictionary mapping service name to service status
[ "Poll", "the", "current", "state", "of", "all", "services", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L165-L189
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
AsyncSupervisorClient.post_state
def post_state(self, name, state): """Asynchronously try to update the state for a service. If the update fails, nothing is reported because we don't wait for a response from the server. This function will return immmediately and not block. Args: name (string): The name of the service state (int): The new state of the service """ self.post_command(OPERATIONS.CMD_UPDATE_STATE, {'name': name, 'new_status': state})
python
def post_state(self, name, state): """Asynchronously try to update the state for a service. If the update fails, nothing is reported because we don't wait for a response from the server. This function will return immmediately and not block. Args: name (string): The name of the service state (int): The new state of the service """ self.post_command(OPERATIONS.CMD_UPDATE_STATE, {'name': name, 'new_status': state})
[ "def", "post_state", "(", "self", ",", "name", ",", "state", ")", ":", "self", ".", "post_command", "(", "OPERATIONS", ".", "CMD_UPDATE_STATE", ",", "{", "'name'", ":", "name", ",", "'new_status'", ":", "state", "}", ")" ]
Asynchronously try to update the state for a service. If the update fails, nothing is reported because we don't wait for a response from the server. This function will return immmediately and not block. Args: name (string): The name of the service state (int): The new state of the service
[ "Asynchronously", "try", "to", "update", "the", "state", "for", "a", "service", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L287-L300
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
AsyncSupervisorClient.post_error
def post_error(self, name, message): """Asynchronously post a user facing error message about a service. Args: name (string): The name of the service message (string): The user facing error message that will be stored for the service and can be queried later. """ self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.ERROR_LEVEL, message))
python
def post_error(self, name, message): """Asynchronously post a user facing error message about a service. Args: name (string): The name of the service message (string): The user facing error message that will be stored for the service and can be queried later. """ self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.ERROR_LEVEL, message))
[ "def", "post_error", "(", "self", ",", "name", ",", "message", ")", ":", "self", ".", "post_command", "(", "OPERATIONS", ".", "CMD_POST_MESSAGE", ",", "_create_message", "(", "name", ",", "states", ".", "ERROR_LEVEL", ",", "message", ")", ")" ]
Asynchronously post a user facing error message about a service. Args: name (string): The name of the service message (string): The user facing error message that will be stored for the service and can be queried later.
[ "Asynchronously", "post", "a", "user", "facing", "error", "message", "about", "a", "service", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L302-L312
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
AsyncSupervisorClient.post_warning
def post_warning(self, name, message): """Asynchronously post a user facing warning message about a service. Args: name (string): The name of the service message (string): The user facing warning message that will be stored for the service and can be queried later. """ self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.WARNING_LEVEL, message))
python
def post_warning(self, name, message): """Asynchronously post a user facing warning message about a service. Args: name (string): The name of the service message (string): The user facing warning message that will be stored for the service and can be queried later. """ self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.WARNING_LEVEL, message))
[ "def", "post_warning", "(", "self", ",", "name", ",", "message", ")", ":", "self", ".", "post_command", "(", "OPERATIONS", ".", "CMD_POST_MESSAGE", ",", "_create_message", "(", "name", ",", "states", ".", "WARNING_LEVEL", ",", "message", ")", ")" ]
Asynchronously post a user facing warning message about a service. Args: name (string): The name of the service message (string): The user facing warning message that will be stored for the service and can be queried later.
[ "Asynchronously", "post", "a", "user", "facing", "warning", "message", "about", "a", "service", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L314-L324
train