Code
stringlengths 103
85.9k
| Summary
sequencelengths 0
94
|
---|---|
Please provide a description of the function:def add_identifier(self, name, obj):
name = str(name)
self._known_identifiers[name] = obj | [
"Add a known identifier resolution.\n\n Args:\n name (str): The name of the identifier\n obj (object): The object that is should resolve to\n "
] |
Please provide a description of the function:def resolve_identifier(self, name, expected_type=None):
name = str(name)
if name in self._known_identifiers:
obj = self._known_identifiers[name]
if expected_type is not None and not isinstance(obj, expected_type):
raise UnresolvedIdentifierError(u"Identifier resolved to an object of an unexpected type", name=name, expected_type=expected_type.__name__, resolved_type=obj.__class__.__name__)
return obj
if self.parent is not None:
try:
return self.parent.resolve_identifier(name)
except UnresolvedIdentifierError:
pass
raise UnresolvedIdentifierError(u"Could not resolve identifier", name=name, scope=self.name) | [
"Resolve an identifier to an object.\n\n There is a single namespace for identifiers so the user also should\n pass an expected type that will be checked against what the identifier\n actually resolves to so that there are no surprises.\n\n Args:\n name (str): The name that we want to resolve\n expected_type (type): The type of object that we expect to receive.\n This is an optional parameter. If None is passed, no type checking\n is performed.\n\n Returns:\n object: The resolved object\n "
] |
Please provide a description of the function:def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None,
report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0):
lowest_id = IOTileReading.InvalidReadingID
highest_id = IOTileReading.InvalidReadingID
report_len = 20 + 16*len(readings) + 24
len_low = report_len & 0xFF
len_high = report_len >> 8
unique_readings = [x.reading_id for x in readings if x.reading_id != IOTileReading.InvalidReadingID]
if len(unique_readings) > 0:
lowest_id = min(unique_readings)
highest_id = max(unique_readings)
header = struct.pack("<BBHLLLBBH", cls.ReportType, len_low, len_high, uuid, report_id,
sent_timestamp, root_key, streamer, selector)
header = bytearray(header)
packed_readings = bytearray()
for reading in readings:
packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id,
reading.raw_time, reading.value)
packed_readings += bytearray(packed_reading)
footer_stats = struct.pack("<LL", lowest_id, highest_id)
if signer is None:
signer = ChainedAuthProvider()
# If we are supposed to encrypt this report, do the encryption
if root_key != signer.NoKey:
enc_data = packed_readings
try:
result = signer.encrypt_report(uuid, root_key, enc_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not encrypt report because no AuthProvider supported "
"the requested encryption method for the requested device",
device_id=uuid, root_key=root_key)
signed_data = header + result['data'] + footer_stats
else:
signed_data = header + packed_readings + footer_stats
try:
signature = signer.sign_report(uuid, root_key, signed_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not sign report because no AuthProvider supported the requested "
"signature method for the requested device", device_id=uuid, root_key=root_key)
footer = struct.pack("16s", bytes(signature['signature'][:16]))
footer = bytearray(footer)
data = signed_data + footer
return SignedListReport(data) | [
"Generate an instance of the report format from a list of readings and a uuid.\n\n The signed list report is created using the passed readings and signed using the specified method\n and AuthProvider. If no auth provider is specified, the report is signed using the default authorization\n chain.\n\n Args:\n uuid (int): The uuid of the deviec that this report came from\n readings (list): A list of IOTileReading objects containing the data in the report\n root_key (int): The key that should be used to sign the report (must be supported\n by an auth_provider)\n signer (AuthProvider): An optional preconfigured AuthProvider that should be used to sign this\n report. If no AuthProvider is provided, the default ChainedAuthProvider is used.\n report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.\n Note that you can specify anything you want for the report id but for actual IOTile devices\n the report id will always be greater than the id of all of the readings contained in the report\n since devices generate ids sequentially.\n selector (int): The streamer selector of this report. This can be anything but if the report came from\n a device, it would correspond with the query the device used to pick readings to go into the report.\n streamer (int): The streamer id that this reading was sent from.\n sent_timestamp (int): The device's uptime that sent this report.\n "
] |
Please provide a description of the function:def decode(self):
fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \
origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20])
assert fmt == 1
length = (len_high << 8) | len_low
self.origin = device_id
self.report_id = report_id
self.sent_timestamp = sent_timestamp
self.origin_streamer = origin_streamer
self.streamer_selector = streamer_selector
self.signature_flags = signature_flags
assert len(self.raw_report) == length
remaining = self.raw_report[20:]
assert len(remaining) >= 24
readings = remaining[:-24]
footer = remaining[-24:]
lowest_id, highest_id, signature = unpack("<LL16s", footer)
signature = bytearray(signature)
self.lowest_id = lowest_id
self.highest_id = highest_id
self.signature = signature
signed_data = self.raw_report[:-16]
signer = ChainedAuthProvider()
if signature_flags == AuthProvider.NoKey:
self.encrypted = False
else:
self.encrypted = True
try:
verification = signer.verify_report(device_id, signature_flags, signed_data, signature,
report_id=report_id, sent_timestamp=sent_timestamp)
self.verified = verification['verified']
except NotFoundError:
self.verified = False
# If we were not able to verify the report, do not try to parse or decrypt it since we
# can't guarantee who it came from.
if not self.verified:
return [], []
# If the report is encrypted, try to decrypt it before parsing the readings
if self.encrypted:
try:
result = signer.decrypt_report(device_id, signature_flags, readings,
report_id=report_id, sent_timestamp=sent_timestamp)
readings = result['data']
except NotFoundError:
return [], []
# Now parse all of the readings
# Make sure this report has an integer number of readings
assert (len(readings) % 16) == 0
time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp)
parsed_readings = []
for i in range(0, len(readings), 16):
reading = readings[i:i+16]
stream, _, reading_id, timestamp, value = unpack("<HHLLL", reading)
parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id)
parsed_readings.append(parsed)
return parsed_readings, [] | [
"Decode this report into a list of readings\n "
] |
Please provide a description of the function:def _add_property(self, name, default_value):
name = str(name)
self._properties[name] = default_value | [
"Add a device property with a given default value.\n\n Args:\n name (str): The name of the property to add\n default_value (int, bool): The value of the property\n "
] |
Please provide a description of the function:def set(self, name, value):
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
self._properties[name] = value | [
"Set a device model property.\n\n Args:\n name (str): The name of the property to set\n value (int, bool): The value of the property to set\n "
] |
Please provide a description of the function:def get(self, name):
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
return self._properties[name] | [
"Get a device model property.\n\n Args:\n name (str): The name of the property to get\n "
] |
Please provide a description of the function:def _convert_to_bytes(type_name, value):
int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'}
type_name = type_name.lower()
if type_name not in int_types and type_name not in ['string', 'binary']:
raise ArgumentError('Type must be a known integer type, integer type array, string', known_integers=int_types.keys(), actual_type=type_name)
if type_name == 'string':
#value should be passed as a string
bytevalue = bytes(value)
elif type_name == 'binary':
bytevalue = bytes(value)
else:
bytevalue = struct.pack("<%s" % int_types[type_name], value)
return bytevalue | [
"Convert a typed value to a binary array"
] |
Please provide a description of the function:def dump(self):
return {
'target': str(self.target),
'data': base64.b64encode(self.data).decode('utf-8'),
'var_id': self.var_id,
'valid': self.valid
} | [
"Serialize this object."
] |
Please provide a description of the function:def generate_rpcs(self, address):
rpc_list = []
for offset in range(2, len(self.data), 16):
rpc = (address, rpcs.SET_CONFIG_VARIABLE, self.var_id, offset - 2, self.data[offset:offset + 16])
rpc_list.append(rpc)
return rpc_list | [
"Generate the RPCs needed to stream this config variable to a tile.\n\n Args:\n address (int): The address of the tile that we should stream to.\n\n Returns:\n list of tuples: A list of argument tuples for each RPC.\n\n These tuples can be passed to EmulatedDevice.rpc to actually make\n the RPCs.\n "
] |
Please provide a description of the function:def Restore(cls, state):
target = SlotIdentifier.FromString(state.get('target'))
data = base64.b64decode(state.get('data'))
var_id = state.get('var_id')
valid = state.get('valid')
return ConfigEntry(target, var_id, data, valid) | [
"Unserialize this object."
] |
Please provide a description of the function:def compact(self):
saved_length = 0
to_remove = []
for i, entry in enumerate(self.entries):
if not entry.valid:
to_remove.append(i)
saved_length += entry.data_space()
for i in reversed(to_remove):
del self.entries[i]
self.data_index -= saved_length | [
"Remove all invalid config entries."
] |
Please provide a description of the function:def start_entry(self, target, var_id):
self.in_progress = ConfigEntry(target, var_id, b'')
if self.data_size - self.data_index < self.in_progress.data_space():
return Error.DESTINATION_BUFFER_TOO_SMALL
self.in_progress.data += struct.pack("<H", var_id)
self.data_index += self.in_progress.data_space()
return Error.NO_ERROR | [
"Begin a new config database entry.\n\n If there is a current entry in progress, it is aborted but the\n data was already committed to persistent storage so that space\n is wasted.\n\n Args:\n target (SlotIdentifer): The target slot for this config variable.\n var_id (int): The config variable ID\n\n Returns:\n int: An error code from the global Errors enum.\n "
] |
Please provide a description of the function:def add_data(self, data):
if self.data_size - self.data_index < len(data):
return Error.DESTINATION_BUFFER_TOO_SMALL
if self.in_progress is not None:
self.in_progress.data += data
return Error.NO_ERROR | [
"Add data to the currently in progress entry.\n\n Args:\n data (bytes): The data that we want to add.\n\n Returns:\n int: An error code\n "
] |
Please provide a description of the function:def end_entry(self):
# Matching current firmware behavior
if self.in_progress is None:
return Error.NO_ERROR
# Make sure there was actually data stored
if self.in_progress.data_space() == 2:
return Error.INPUT_BUFFER_WRONG_SIZE
# Invalidate all previous copies of this config variable so we
# can properly compact.
for entry in self.entries:
if entry.target == self.in_progress.target and entry.var_id == self.in_progress.var_id:
entry.valid = False
self.entries.append(self.in_progress)
self.data_index += self.in_progress.data_space() - 2 # Add in the rest of the entry size (we added two bytes at start_entry())
self.in_progress = None
return Error.NO_ERROR | [
"Finish a previously started config database entry.\n\n This commits the currently in progress entry. The expected flow is\n that start_entry() is called followed by 1 or more calls to add_data()\n followed by a single call to end_entry().\n\n Returns:\n int: An error code\n "
] |
Please provide a description of the function:def stream_matching(self, address, name):
matching = [x for x in self.entries if x.valid and x.target.matches(address, name)]
rpc_list = []
for var in matching:
rpc_list.extend(var.generate_rpcs(address))
return rpc_list | [
"Return the RPCs needed to stream matching config variables to the given tile.\n\n This function will return a list of tuples suitable for passing to\n EmulatedDevice.deferred_rpc.\n\n Args:\n address (int): The address of the tile that we wish to stream to\n name (str or bytes): The 6 character name of the target tile.\n\n Returns:\n list of tuple: The list of RPCs to send to stream these variables to a tile.\n "
] |
Please provide a description of the function:def start_config_var_entry(self, var_id, encoded_selector):
selector = SlotIdentifier.FromEncoded(encoded_selector)
err = self.config_database.start_entry(selector, var_id)
return [err] | [
"Start a new config variable entry."
] |
Please provide a description of the function:def get_config_var_entry(self, index):
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, b'\0'*8, 0, 0]
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, 0, 0, 0, b'\0'*8, 0, 0]
offset = sum(x.data_space() for x in self.config_database.entries[:index - 1])
return [Error.NO_ERROR, self.config_database.ENTRY_MAGIC, offset, entry.data_space(), entry.target.encode(), 0xFF, 0] | [
"Get the metadata from the selected config variable entry."
] |
Please provide a description of the function:def get_config_var_data(self, index, offset):
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
if offset >= len(entry.data):
return [Error.INVALID_ARRAY_KEY, b'']
data_chunk = entry.data[offset:offset + 16]
return [Error.NO_ERROR, data_chunk] | [
"Get a chunk of data for a config variable."
] |
Please provide a description of the function:def invalidate_config_var_entry(self, index):
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
entry.valid = False
return [Error.NO_ERROR] | [
"Mark a config variable as invalid."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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.\n\n This function searches for installed virtual tiles\n using the pkg_resources entry_point `iotile.virtual_tile`.\n\n If name is a path ending in .py, it is assumed to point to\n a module on disk and loaded directly rather than using\n pkg_resources.\n\n Args:\n name (str): The name of the tile to search\n for.\n\n Returns:\n VirtualTile class: A virtual tile subclass that can be\n instantiated to create a virtual tile.\n "
] |
Please provide a description of the function: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\n\n script_path must point to a python file ending in .py that contains exactly one\n VirtualTile class definition. That class is loaded and executed as if it\n were installed.\n\n To facilitate development, if there is a proxy object defined in the same\n file, it is also added to the HardwareManager proxy registry so that it\n can be found and used with the device.\n\n Args:\n script_path (string): The path to the script to load\n\n Returns:\n VirtualTile: A subclass of VirtualTile that was loaded from script_path\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def _upload_dists(self, repo, dists):
from twine.commands.upload import upload
if 'PYPI_USER' in os.environ and 'PYPI_PASS' in os.environ:
pypi_user = os.environ['PYPI_USER']
pypi_pass = os.environ['PYPI_PASS']
else:
pypi_user = None
pypi_pass = None
# Invoke upload this way since subprocess call of twine cli has cross platform issues
upload(dists, repo, False, None, pypi_user, pypi_pass, None, None, '~/.pypirc', False, None, None, None) | [
"Upload a given component to pypi\n\n The pypi username and password must either be specified in a ~/.pypirc\n file or in environment variables PYPI_USER and PYPI_PASS\n "
] |
Please provide a description of the function: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\n\n Args:\n data (bytearray): A chunk of new data to add\n "
] |
Please provide a description of the function: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\n\n Returns:\n bool: True if further processing is required and process_data should be\n called again.\n "
] |
Please provide a description of the function: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"
] |
Please provide a description of the function: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"
] |
Please provide a description of the function:def deserialize_report(self, serialized):
type_map = self.known_formats
if serialized['report_format'] not in type_map:
raise ArgumentError("Unknown report format in DeserializeReport", format=serialized['report_format'])
report = type_map[serialized['report_format']](serialized['encoded_report'])
report.received_time = serialized['received_time']
return report | [
"Deserialize a report that has been serialized by calling report.serialize()\n\n Args:\n serialized (dict): A serialized report object\n "
] |
Please provide a description of the function: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"
] |
Please provide a description of the function:def _optional_no_translator_flag(env):
import SCons.Util
if 'POAUTOINIT' in env:
autoinit = env['POAUTOINIT']
else:
autoinit = False
if autoinit:
return [SCons.Util.CLVar('--no-translator')]
else:
return [SCons.Util.CLVar('')] | [
" Return '--no-translator' flag if we run *msginit(1)* in non-interactive\n mode."
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function:def _POInitBuilderWrapper(env, target=None, source=_null, **kw):
if source is _null:
if 'POTDOMAIN' in kw:
domain = kw['POTDOMAIN']
elif 'POTDOMAIN' in env:
domain = env['POTDOMAIN']
else:
domain = 'messages'
source = [ domain ] # NOTE: Suffix shall be appended automatically
return env._POInitBuilder(target, source, **kw) | [
" Wrapper for _POFileBuilder. We use it to make user's life easier.\n \n This wrapper checks for `$POTDOMAIN` construction variable (or override in\n `**kw`) and treats it appropriatelly. \n "
] |
Please provide a description of the function: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 "
] |
Please provide a description of the function:def generate(env):
path, _cxx, version = get_xlc(env)
if path and _cxx:
_cxx = os.path.join(path, _cxx)
if 'CXX' not in env:
env['CXX'] = _cxx
cplusplus.generate(env)
if version:
env['CXXVERSION'] = version | [
"Add Builders and construction variables for xlC / Visual Age\n suite to an Environment."
] |
Please provide a description of the function:def generate(env):
cc.generate(env)
env['CC'] = 'icc'
env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET'
env['CXXCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET'
env['CPPDEFPREFIX'] = '/D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '/I'
env['INCSUFFIX'] = ''
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cc' | [
"Add Builders and construction variables for the OS/2 to an Environment."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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"
] |
Please provide a description of the function:def _initialize_system_sync(self):
connected_devices = self.bable.list_connected_devices()
for device in connected_devices:
context = {
'connection_id': len(self.connections.get_connections()),
'connection_handle': device.connection_handle,
'connection_string': device.address
}
self.connections.add_connection(context['connection_id'], device.address, context)
self.disconnect_sync(context['connection_id'])
self.stop_scan()
try:
self.bable.set_advertising(enabled=False)
except bable_interface.BaBLEException:
# If advertising is already disabled
pass | [
"Initialize the device adapter by removing all active connections and resetting scan and advertising to have\n a clean starting state."
] |
Please provide a description of the function:def start_scan(self, active):
try:
self.bable.start_scan(self._on_device_found, active_scan=active, sync=True)
except bable_interface.BaBLEException as err:
# If we are already scanning, raise an error only we tried to change the active scan param
if self._active_scan != active:
raise err
self._active_scan = active
self.scanning = True | [
"Start a scan. Will call self._on_device_found for each device scanned.\n Args:\n active (bool): Indicate if it is an active scan (probing for scan response) or not.\n "
] |
Please provide a description of the function:def _on_device_found(self, success, device, failure_reason):
if not success:
self._logger.error("on_device_found() callback called with error: ", failure_reason)
return
# If it is an adverting report
if device['type'] in [0x00, 0x01, 0x02]:
# If it has the TileBusService
if device['uuid'] == TileBusService.uuid:
if len(device['manufacturer_data']) != 6:
self._logger.error("Received advertisement response with wrong manufacturer data length "
"(expected=6, received=%d)", len(device['manufacturer_data']))
return
device_uuid, flags = unpack("<LH", device['manufacturer_data'])
pending = bool(flags & (1 << 0))
low_voltage = bool(flags & (1 << 1))
user_connected = bool(flags & (1 << 2))
info = {
'user_connected': user_connected,
'connection_string': '{},{}'.format(device['address'], device['address_type']),
'uuid': device_uuid,
'pending_data': pending,
'low_voltage': low_voltage,
'signal_strength': device['rssi']
}
if not self._active_scan:
# If scan is not active, we won't receive a scan response so we trigger the `on_scan` callback
self._trigger_callback('on_scan', self.id, info, self.get_config('expiration_time'))
else:
# Else we register the information to get them on scan response received
self.partial_scan_responses[device['address']] = info
# If it is a scan response
elif device['type'] == 0x04 and device['address'] in self.partial_scan_responses:
if len(device['manufacturer_data']) != 16:
self._logger.error("Received scan response with wrong manufacturer data length "
"(expected=16, received=%d)", len(device['manufacturer_data']))
return
voltage, stream, reading, reading_time, curr_time = unpack("<HHLLL", device['manufacturer_data'])
info = self.partial_scan_responses[device['address']]
info['voltage'] = voltage / 256.0
info['current_time'] = curr_time
info['last_seen'] = datetime.datetime.now()
# If there is a valid reading on the advertising data, broadcast it
if stream != 0xFFFF:
reading = IOTileReading(reading_time, stream, reading, reading_time=datetime.datetime.utcnow())
report = BroadcastReport.FromReadings(info['uuid'], [reading], curr_time)
self._trigger_callback('on_report', None, report)
del self.partial_scan_responses[device['address']]
self._trigger_callback('on_scan', self.id, info, self.get_config('expiration_time')) | [
"Callback function called when a device has been scanned.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n device (dict): The scanned device information\n - type (int): Indicates if it is an advertising report or a scan response\n - uuid (uuid.UUID): The service uuid\n - manufacturer_data (bytes): The manufacturer data\n - address (str): The device BT address\n - address_type (str): The device address type (either 'random' or 'public')\n - rssi (int): The signal strength\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def connect_async(self, connection_id, connection_string, callback, retries=4, context=None):
if context is None:
# It is the first attempt to connect: begin a new connection
context = {
'connection_id': connection_id,
'retries': retries,
'retry_connect': False,
'connection_string': connection_string,
'connect_time': time.time(),
'callback': callback
}
self.connections.begin_connection(
connection_id,
connection_string,
callback,
context,
self.get_config('default_timeout')
)
# Don't scan while we attempt to connect to this device
if self.scanning:
self.stop_scan()
address, address_type = connection_string.split(',')
# First, cancel any pending connection to prevent errors when starting a new one
self.bable.cancel_connection(sync=False)
# Send a connect request
self.bable.connect(
address=address,
address_type=address_type,
connection_interval=[7.5, 7.5],
on_connected=[self._on_connection_finished, context],
on_disconnected=[self._on_unexpected_disconnection, context]
) | [
"Connect to a device by its connection_string\n\n This function asynchronously connects to a device by its BLE address + address type passed in the\n connection_string parameter and calls callback when finished. Callback is called on either success\n or failure with the signature:\n callback(connection_id: int, result: bool, value: None)\n The optional retries argument specifies how many times we should retry the connection\n if the connection fails due to an early disconnect. Early disconnects are expected ble failure\n modes in busy environments where the slave device misses the connection packet and the master\n therefore fails immediately. Retrying a few times should succeed in this case.\n\n Args:\n connection_string (string): A BLE address information in AA:BB:CC:DD:EE:FF,<address_type> format\n connection_id (int): A unique integer set by the caller for referring to this connection once created\n callback (callable): A callback function called when the connection has succeeded or failed\n retries (int): The number of attempts to connect to this device that can end in early disconnect\n before we give up and report that we could not connect. A retry count of 0 will mean that\n we fail as soon as we receive the first early disconnect.\n context (dict): If we are retrying to connect, passes the context to not considering it as a new connection.\n "
] |
Please provide a description of the function:def _on_connection_finished(self, success, result, failure_reason, context):
connection_id = context['connection_id']
if not success:
self._logger.error("Error while connecting to the device err=%s", failure_reason)
# If connection failed to be established, we just should retry to connect
if failure_reason.packet.native_class == 'HCI' and failure_reason.packet.native_status == 0x3e:
context['retry_connect'] = True
self._on_connection_failed(connection_id, self.id, success, failure_reason)
return
context['connection_handle'] = result['connection_handle']
# After connection has been done, probe GATT services
self.bable.probe_services(
connection_handle=context['connection_handle'],
on_services_probed=[self._on_services_probed, context]
) | [
"Callback called when the connection attempt to a BLE device has finished.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): The connection information (if successful)\n - connection_handle (int): The connection handle\n - address (str): The device BT address\n - address_type (str): The device address type (either 'random' or 'public')\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n "
] |
Please provide a description of the function:def _on_services_probed(self, success, result, failure_reason, context):
connection_id = context['connection_id']
if not success:
self._logger.error("Error while probing services to the device, err=%s", failure_reason)
context['failure_reason'] = "Error while probing services"
self.disconnect_async(connection_id, self._on_connection_failed)
return
services = {service: {} for service in result['services']}
# Validate that this is a proper IOTile device
if TileBusService not in services:
context['failure_reason'] = 'TileBus service not present in GATT services'
self.disconnect_async(connection_id, self._on_connection_failed)
return
context['services'] = services
# Finally, probe GATT characteristics
self.bable.probe_characteristics(
connection_handle=context['connection_handle'],
start_handle=TileBusService.handle,
end_handle=TileBusService.group_end_handle,
on_characteristics_probed=[self._on_characteristics_probed, context]
) | [
"Callback called when the services has been probed.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information probed (if successful)\n - services (list): The list of services probed (bable_interface.Service instances)\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n "
] |
Please provide a description of the function:def _on_characteristics_probed(self, success, result, failure_reason, context):
connection_id = context['connection_id']
if not success:
self._logger.error("Error while probing characteristics to the device, err=%s", failure_reason)
context['failure_reason'] = "Error while probing characteristics"
self.disconnect_async(connection_id, self._on_connection_failed)
return
context['services'][TileBusService] = {
characteristic: characteristic for characteristic in result['characteristics']
}
total_time = time.time() - context['connect_time']
self._logger.info("Total time to connect to device: %.3f", total_time)
self.connections.finish_connection(
connection_id,
success,
failure_reason
) | [
"Callback called when the characteristics has been probed.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information probed (if successful)\n - characteristics (list): The list of characteristics probed (bable_interface.Characteristic instances)\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n "
] |
Please provide a description of the function:def _on_connection_failed(self, connection_id, adapter_id, success, failure_reason):
self._logger.info("_on_connection_failed connection_id=%d, reason=%s", connection_id, failure_reason)
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
self._logger.info("Unable to obtain connection data on unknown connection %d", connection_id)
context = {}
# Cancel the connection to be able to resend a connect request later (else the controller sends an error)
self.bable.cancel_connection(sync=False)
if context.get('retry_connect') and context.get('retries') > 0:
context['retries'] -= 1
self.connect_async(
connection_id,
context['connection_string'],
context['callback'],
context['retries'],
context
)
else:
self.connections.finish_connection(
connection_id,
False,
context.get('failure_reason', failure_reason)
) | [
"Callback function called when a connection has failed.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter.\n adapter_id (int): A unique identifier for the DeviceManager\n success (bool): A bool indicating that the operation is successful or not\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n "
] |
Please provide a description of the function:def disconnect_async(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_disconnection(connection_id, callback, self.get_config('default_timeout'))
self.bable.disconnect(
connection_handle=context['connection_handle'],
on_disconnected=[self._on_disconnection_finished, context]
) | [
"Asynchronously disconnect from a device that has previously been connected\n\n Args:\n connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter.\n callback (callable): A function called as callback(connection_id, adapter_id, success, failure_reason)\n when the disconnection finishes. Disconnection can only either succeed or timeout.\n "
] |
Please provide a description of the function:def _on_unexpected_disconnection(self, success, result, failure_reason, context):
connection_id = context['connection_id']
self._logger.warn('Unexpected disconnection event, handle=%d, reason=0x%X, state=%s',
result['connection_handle'],
result['code'],
self.connections.get_state(connection_id))
self.connections.unexpected_disconnect(connection_id)
self._trigger_callback('on_disconnect', self.id, connection_id) | [
"Callback function called when an unexpected disconnection occured (meaning that we didn't previously send\n a `disconnect` request).\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Disconnection information (if successful)\n - connection_handle (int): The connection handle that just disconnected\n - code (int): The reason code\n - reason (str): A message explaining the reason code in plain text\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n context (dict): The connection context\n "
] |
Please provide a description of the function:def _on_disconnection_finished(self, success, result, failure_reason, context):
if 'connection_handle' in context:
# Remove all the notification callbacks registered for this connection
with self.notification_callbacks_lock:
for connection_handle, attribute_handle in list(self.notification_callbacks.keys()):
if connection_handle == context['connection_handle']:
del self.notification_callbacks[(connection_handle, attribute_handle)]
self.connections.finish_disconnection(
context['connection_id'],
success,
failure_reason
) | [
"Callback function called when a previously asked disconnection has been finished.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Disconnection information (if successful)\n - connection_handle (int): The connection handle that just disconnected\n - code (int): The reason code\n - reason (str): A message explaining the reason code in plain text\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n context (dict): The connection context\n "
] |
Please provide a description of the function: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\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n "
] |
Please provide a description of the function:def _open_script_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
success = HighSpeedChar in context['services'][TileBusService]
reason = None
if not success:
reason = 'Could not find high speed streaming characteristic'
callback(connection_id, self.id, success, reason) | [
"Enable script streaming interface for this IOTile device\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n "
] |
Please provide a description of the function: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):
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\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n ",
"Callback function called when a report chunk has been received."
] |
Please provide a description of the function: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\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n "
] |
Please provide a description of the function:def _on_interface_opened(self, success, result, failure_reason, context, next_characteristic=None):
if not success:
self.connections.finish_operation(context['connection_id'], False, failure_reason)
return
if next_characteristic is not None:
self.bable.set_notification(
enabled=True,
connection_handle=context['connection_handle'],
characteristic=next_characteristic,
on_notification_set=[self._on_interface_opened, context],
on_notification_received=self._on_notification_received,
sync=False
)
else:
self.connections.finish_operation(context['connection_id'], True, None) | [
"Callback function called when the notification related to an interface has been enabled.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information (if successful)\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n context (dict): The connection context\n next_characteristic (bable_interface.Characteristic): If not None, indicate another characteristic to enable\n notification.\n "
] |
Please provide a description of the function: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\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n "
] |
Please provide a description of the function:def _on_interface_closed(self, success, result, failure_reason, context, next_characteristic=None):
if not success:
self.connections.finish_operation(context['connection_id'], False, failure_reason)
return
if next_characteristic is not None:
self.bable.set_notification(
enabled=False,
connection_handle=context['connection_handle'],
characteristic=next_characteristic,
on_notification_set=[self._on_interface_closed, context],
timeout=1.0,
sync=False
)
else:
self.connections.finish_operation(context['connection_id'], True, None) | [
"Callback function called when the notification related to an interface has been disabled.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information (if successful)\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n context (dict): The connection context\n next_characteristic (bable_interface.Characteristic): If not None, indicate another characteristic to\n disable notification.\n "
] |
Please provide a description of the function: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.\n\n Args:\n report (IOTileReport): The report object\n connection_id (int): The connection id related to this report\n\n Returns:\n - True to indicate that IOTileReportParser should also keep a copy of the report\n or False to indicate it should delete it.\n "
] |
Please provide a description of the function: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"
] |
Please provide a description of the function:def send_rpc_async(self, connection_id, address, rpc_id, payload, timeout, callback):
try:
context = self.connections.get_context(connection_id)
except ArgumentError:
callback(connection_id, self.id, False, "Could not find connection information")
return
connection_handle = context['connection_handle']
self.connections.begin_operation(connection_id, 'rpc', callback, timeout)
try:
service = context['services'][TileBusService]
send_header_characteristic = service[SendHeaderChar]
send_payload_characteristic = service[SendPayloadChar]
receive_header_characteristic = service[ReceiveHeaderChar]
receive_payload_characteristic = service[ReceivePayloadChar]
except KeyError:
self.connections.finish_operation(connection_id, False, "Can't find characteristics to open rpc interface")
return
length = len(payload)
if length < 20:
payload += b'\x00'*(20 - length)
if length > 20:
self.connections.finish_operation(connection_id, False, "Payload is too long, must be at most 20 bytes")
return
header = bytearray([length, 0, rpc_id & 0xFF, (rpc_id >> 8) & 0xFF, address])
result = {}
def on_header_received(value):
result['status'] = value[0]
result['length'] = value[3]
if result['length'] == 0:
# Simulate a empty payload received to end the RPC response
self._on_notification_received(True, {
'connection_handle': connection_handle,
'attribute_handle': receive_payload_characteristic.value_handle,
'value': b'\x00'*20
}, None)
def on_payload_received(value):
result['payload'] = value[:result['length']]
self.connections.finish_operation(
connection_id,
True,
None,
result['status'],
result['payload']
)
# Register the header notification callback
self._register_notification_callback(
connection_handle,
receive_header_characteristic.value_handle,
on_header_received,
once=True
)
# Register the payload notification callback
self._register_notification_callback(
connection_handle,
receive_payload_characteristic.value_handle,
on_payload_received,
once=True
)
if length > 0:
# If payload is not empty, send it first
self.bable.write_without_response(
connection_handle=connection_handle,
attribute_handle=send_payload_characteristic.value_handle,
value=bytes(payload)
)
self.bable.write_without_response(
connection_handle=connection_handle,
attribute_handle=send_header_characteristic.value_handle,
value=bytes(header)
) | [
"Asynchronously send an RPC to this IOTile device\n\n Args:\n connection_id (int): A unique identifier that will refer to this connection\n address (int): The address of the tile that we wish to send the RPC to\n rpc_id (int): The 16-bit id of the RPC we want to call\n payload (bytearray): The payload of the command\n timeout (float): The number of seconds to wait for the RPC to execute\n callback (callable): A callback for when we have finished the RPC. The callback will be called as\n callback(connection_id, adapter_id, success, failure_reason, status, payload)\n 'connection_id': The connection id\n 'adapter_id': This adapter's id\n 'success': A bool indicating whether we received a response to our attempted RPC\n 'failure_reason': A string with the reason for the failure if success == False\n 'status': The one byte status code returned for the RPC if success == True else None\n 'payload': A bytearray with the payload returned by RPC if success == True else None\n ",
"Callback function called when a notification has been received with the RPC header response.",
"Callback function called when a notification has been received with the RPC payload response."
] |
Please provide a description of the function:def send_script_async(self, connection_id, data, progress_callback, 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, 'script', callback, self.get_config('default_timeout'))
mtu = int(self.get_config('mtu', 20)) # Split script payloads larger than this
high_speed_char = context['services'][TileBusService][HighSpeedChar]
# Count number of chunks to send
nb_chunks = 1
if len(data) > mtu:
nb_chunks = len(data) // mtu
if len(data) % mtu != 0:
nb_chunks += 1
def send_script():
for i in range(0, nb_chunks):
start = i * mtu
chunk = data[start: start + mtu]
sent = False
while not sent:
try:
self.bable.write_without_response(
connection_handle=context['connection_handle'],
attribute_handle=high_speed_char.value_handle,
value=bytes(chunk)
)
sent = True
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)
else:
self.connections.finish_operation(connection_id, False, err.message)
return
progress_callback(i, nb_chunks)
self.connections.finish_operation(connection_id, True, None)
# Start the thread to send the script asynchronously
send_script_thread = threading.Thread(target=send_script, name='SendScriptThread')
send_script_thread.daemon = True
send_script_thread.start() | [
"Asynchronously send a a script to this IOTile device\n\n Args:\n connection_id (int): A unique identifier that will refer to this connection\n data (bytes): the script to send to the device\n progress_callback (callable): A function to be called with status on our progress, called as:\n progress_callback(done_count, total_count)\n callback (callable): A callback for when we have finished sending the script. The callback will be called as\n callback(connection_id, adapter_id, success, failure_reason)\n 'connection_id': the connection id\n 'adapter_id': this adapter's id\n 'success': a bool indicating whether we received a response to our attempted RPC\n 'failure_reason': a string with the reason for the failure if success == False\n ",
"Function sending every chunks of the script. Executed in a separated thread."
] |
Please provide a description of the function: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\n connection_handle and attribute_handle is received.\n\n Args:\n connection_handle (int): The connection handle to watch\n attribute_handle (int): The attribute handle to watch\n callback (func): The callback function to call once the notification has been received\n once (bool): Should the callback only be called once (and then removed from the notification callbacks)\n "
] |
Please provide a description of the function:def _on_notification_received(self, success, result, failure_reason):
if not success:
self._logger.info("Notification received with failure failure_reason=%s", failure_reason)
notification_id = (result['connection_handle'], result['attribute_handle'])
callback = None
with self.notification_callbacks_lock:
if notification_id in self.notification_callbacks:
callback, once = self.notification_callbacks[notification_id]
if once:
del self.notification_callbacks[notification_id]
if callback is not None:
callback(result['value']) | [
"Callback function called when a notification has been received.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): The notification information\n - value (bytes): Data notified\n failure_reason (any): An object indicating the reason why the operation is not successful (else None)\n "
] |
Please provide a description of the function:def stop_sync(self):
# Stop to scan
if self.scanning:
self.stop_scan()
# Disconnect all connected devices
for connection_id in list(self.connections.get_connections()):
self.disconnect_sync(connection_id)
# Stop the baBLE interface
self.bable.stop()
# Stop the connection manager
self.connections.stop()
self.stopped = True | [
"Safely stop this BLED112 instance without leaving it in a weird state"
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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.\n\n This includes commands to reset and clear previously stored\n sensor graphs.\n\n Args:\n sensor_graph (SensorGraph): the sensor graph that we want to format\n "
] |
Please provide a description of the function: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"
] |
Please provide a description of the function: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\n\n Returns:\n int : total scan events\n int : total v1 scan count\n int : total v1 scan response count\n int : total v2 scan count\n dict : device-specific scan counts\n float : seconds since last reset\n "
] |
Please provide a description of the function: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"
] |
Please provide a description of the function:def stop_sync(self):
if self.scanning:
self.stop_scan()
# Make a copy since this will change size as we disconnect
con_copy = copy.copy(self._connections)
for _, context in con_copy.items():
self.disconnect_sync(context['connection_id'])
self._command_task.stop()
self._stream.stop()
self._serial_port.close()
self.stopped = True | [
"Safely stop this BLED112 instance without leaving it in a weird state"
] |
Please provide a description of the function:def start_scan(self, active):
self._command_task.sync_command(['_start_scan', active])
self.scanning = True | [
"Start the scanning task"
] |
Please provide a description of the function:def connect_async(self, connection_id, connection_string, callback, retries=4):
context = {}
context['connection_id'] = connection_id
context['callback'] = callback
context['retries'] = retries
context['connection_string'] = connection_string
# Don't scan while we attempt to connect to this device
if self.scanning:
self.stop_scan()
with self.count_lock:
self.connecting_count += 1
self._command_task.async_command(['_connect', connection_string],
self._on_connection_finished, context) | [
"Connect to a device by its connection_string\n\n This function asynchronously connects to a device by its BLE address passed in the\n connection_string parameter and calls callback when finished. Callback is called\n on either success or failure with the signature:\n\n callback(conn_id: int, result: bool, value: None)\n\n The optional retries argument specifies how many times we should retry the connection\n if the connection fails due to an early disconnect. Early disconnects are expected ble failure\n modes in busy environments where the slave device misses the connection packet and the master\n therefore fails immediately. Retrying a few times should succeed in this case.\n\n Args:\n connection_string (string): A BLE address is XX:YY:ZZ:AA:BB:CC format\n connection_id (int): A unique integer set by the caller for referring to this connection\n once created\n callback (callable): A callback function called when the connection has succeeded or\n failed\n retries (int): The number of attempts to connect to this device that can end in early disconnect\n before we give up and report that we could not connect. A retry count of 0 will mean that\n we fail as soon as we receive the first early disconnect.\n "
] |
Please provide a description of the function:def disconnect_async(self, conn_id, callback):
found_handle = None
# Find the handle by connection id
for handle, conn in self._connections.items():
if conn['connection_id'] == conn_id:
found_handle = handle
if found_handle is None:
callback(conn_id, self.id, False, 'Invalid connection_id')
return
self._command_task.async_command(['_disconnect', found_handle], self._on_disconnect,
{'connection_id': conn_id, 'handle': found_handle,
'callback': callback}) | [
"Asynchronously disconnect from a device that has previously been connected\n\n Args:\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n callback (callable): A function called as callback(conn_id, adapter_id, success, failure_reason)\n when the disconnection finishes. Disconnection can only either succeed or timeout.\n "
] |
Please provide a description of the function:def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback):
found_handle = None
# Find the handle by connection id
for handle, conn in self._connections.items():
if conn['connection_id'] == conn_id:
found_handle = handle
if found_handle is None:
callback(conn_id, self.id, False, 'Invalid connection_id', None, None)
return
services = self._connections[found_handle]['services']
self._command_task.async_command(['_send_rpc', found_handle, services, address, rpc_id, payload, timeout], self._send_rpc_finished,
{'connection_id': conn_id, 'handle': found_handle,
'callback': callback}) | [
"Asynchronously send an RPC to this IOTile device\n\n Args:\n conn_id (int): A unique identifer that will refer to this connection\n address (int): the addres of the tile that we wish to send the RPC to\n rpc_id (int): the 16-bit id of the RPC we want to call\n payload (bytearray): the payload of the command\n timeout (float): the number of seconds to wait for the RPC to execute\n callback (callable): A callback for when we have finished the RPC. The callback will be called as\"\n callback(connection_id, adapter_id, success, failure_reason, status, payload)\n 'connection_id': the connection id\n 'adapter_id': this adapter's id\n 'success': a bool indicating whether we received a response to our attempted RPC\n 'failure_reason': a string with the reason for the failure if success == False\n 'status': the one byte status code returned for the RPC if success == True else None\n 'payload': a bytearray with the payload returned by RPC if success == True else None\n "
] |
Please provide a description of the function:def send_script_async(self, conn_id, data, progress_callback, callback):
found_handle = None
# Find the handle by connection id
for handle, conn in self._connections.items():
if conn['connection_id'] == conn_id:
found_handle = handle
if found_handle is None:
callback(conn_id, self.id, False, 'Invalid connection_id')
return
services = self._connections[found_handle]['services']
self._command_task.async_command(['_send_script', found_handle, services, data, 0, progress_callback],
self._send_script_finished, {'connection_id': conn_id,
'callback': callback}) | [
"Asynchronously send a a script to this IOTile device\n\n Args:\n conn_id (int): A unique identifer that will refer to this connection\n data (bytes): the script to send to the device\n progress_callback (callable): A function to be called with status on our progress, called as:\n progress_callback(done_count, total_count)\n callback (callable): A callback for when we have finished sending the script. The callback will be called as\"\n callback(connection_id, adapter_id, success, failure_reason)\n 'connection_id': the connection id\n 'adapter_id': this adapter's id\n 'success': a bool indicating whether we received a response to our attempted RPC\n 'failure_reason': a string with the reason for the failure if success == False\n "
] |
Please provide a description of the function:def _open_script_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 script interface')
return
success = TileBusHighSpeedCharacteristic in services[TileBusService]['characteristics']
reason = None
if not success:
reason = 'Could not find high speed streaming characteristic'
callback(conn_id, self.id, success, reason) | [
"Enable script streaming interface for this IOTile device\n\n Args:\n conn_id (int): the unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n "
] |
Please provide a description of the function: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\n\n Args:\n conn_id (int): the unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n "
] |
Please provide a description of the function: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.\n\n If it's an IOTile device, parse and add to the scanned devices. Then,\n parse advertisement and determine if it matches V1 or V2. There are\n two supported type of advertisements:\n\n v1: There is both an advertisement and a scan response (if active scanning\n is enabled).\n v2: There is only an advertisement and no scan response.\n "
] |
Please provide a description of the function: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"
] |
Please provide a description of the function: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\n\n Args:\n handle (int): a handle to the connection on the BLED112 dongle\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n callback (callable): Callback to be called when this procedure finishes\n "
] |
Please provide a description of the function: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\n\n This routine must be called after probe_services and passed the services dictionary\n produced by that method.\n\n Args:\n handle (int): a handle to the connection on the BLED112 dongle\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n services (dict): A dictionary of GATT services produced by probe_services()\n "
] |
Please provide a description of the function:def initialize_system_sync(self):
retval = self._command_task.sync_command(['_query_systemstate'])
self.maximum_connections = retval['max_connections']
for conn in retval['active_connections']:
self._connections[conn] = {'handle': conn, 'connection_id': len(self._connections)}
self.disconnect_sync(0)
# If the dongle was previously left in a dirty state while still scanning, it will
# not allow new scans to be started. So, forcibly stop any in progress scans.
# This throws a hardware error if scanning is not in progress which should be ignored.
try:
self.stop_scan()
except HardwareError:
# If we errored our it is because we were not currently scanning, so make sure
# we update our self.scanning flag (which would not be updated by stop_scan since
# it raised an exception.)
self.scanning = False
self._command_task.sync_command(['_set_mode', 0, 0]) #Disable advertising
self._logger.info("BLED112 adapter supports %d connections", self.maximum_connections) | [
"Remove all active connections and query the maximum number of supported connections\n "
] |
Please provide a description of the function: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\n\n Args:\n result (dict): result returned from diconnection command\n "
] |
Please provide a description of the function: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\n "
] |
Please provide a description of the function: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\n "
] |
Please provide a description of the function: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\n\n This function if called when a new connection is successfully completed\n\n Args:\n event (BGAPIPacket): Connection event\n "
] |
Please provide a description of the function: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.\n "
] |
Please provide a description of the function: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\n\n Args:\n result (dict): Parameters determined by the probe and context passed to the call to\n probe_device()\n "
] |
Please provide a description of the function: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\n\n Args:\n result (dict): Result from the probe_characteristics command\n "
] |
Please provide a description of the function: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\n "
] |
Please provide a description of the function:def build_update_script(file_name, slot_assignments=None, os_info=None, sensor_graph=None,
app_info=None, use_safeupdate=False):
resolver = ProductResolver.Create()
env = Environment(tools=[])
files = []
if slot_assignments is not None:
slots = [_parse_slot(x[0]) for x in slot_assignments]
files = [ensure_image_is_hex(resolver.find_unique("firmware_image", x[1]).full_path) for x in slot_assignments]
env['SLOTS'] = slots
else:
env['SLOTS'] = None
env['USE_SAFEUPDATE'] = use_safeupdate
env['OS_INFO'] = os_info
env['APP_INFO'] = app_info
env['UPDATE_SENSORGRAPH'] = False
if sensor_graph is not None:
files.append(sensor_graph)
env['UPDATE_SENSORGRAPH'] = True
env.Command([os.path.join('build', 'output', file_name)], files,
action=Action(_build_reflash_script_action, "Building TRUB script at $TARGET")) | [
"Build a trub script that loads given firmware into the given slots.\n\n slot_assignments should be a list of tuples in the following form:\n (\"slot X\" or \"controller\", firmware_image_name)\n\n The output of this autobuild action will be a trub script in\n build/output/<file_name> that assigns the given firmware to each slot in\n the order specified in the slot_assignments list.\n\n Args:\n file_name (str): The name of the output file that we should create.\n This file name should end in .trub\n slot_assignments (list of (str, str)): A list of tuples containing\n the slot name and the firmware image that we should use to build\n our update script. Optional\n os_info (tuple(int, str)): A tuple of OS version tag and X.Y version\n number that will be set as part of the OTA script if included. Optional.\n sensor_graph (str): Name of sgf file. Optional.\n app_info (tuple(int, str)): A tuple of App version tag and X.Y version\n number that will be set as part of the OTA script if included. Optional.\n use_safeupdate (bool): Enables safe firmware update\n "
] |
Please provide a description of the function:def _build_reflash_script_action(target, source, env):
out_path = str(target[0])
source = [str(x) for x in source]
records = []
if env['USE_SAFEUPDATE']:
sgf_off = SendRPCRecord(8,0x2005,bytearray([0])) # Disable Sensorgraph
records.append(sgf_off)
safemode_enable = SendRPCRecord(8,0x1006,bytearray([1])) # Enable Safemode
records.append(safemode_enable)
# Update application firmwares
if env['SLOTS'] is not None:
for (controller, slot_id), image_path in zip(env['SLOTS'], source):
hex_data = IntelHex(image_path)
hex_data.padding = 0xFF
offset = hex_data.minaddr()
bin_data = bytearray(hex_data.tobinarray(offset, hex_data.maxaddr()))
if controller:
record = ReflashControllerRecord(bin_data, offset)
else:
record = ReflashTileRecord(slot_id, bin_data, offset)
records.append(record)
# Update sensorgraph
if env['UPDATE_SENSORGRAPH']:
sensor_graph_file = source[-1]
sensor_graph = compile_sgf(sensor_graph_file)
output = format_script(sensor_graph)
records += UpdateScript.FromBinary(output).records
# Update App and OS Tag
os_info = env['OS_INFO']
app_info = env['APP_INFO']
if os_info is not None:
os_tag, os_version = os_info
records.append(SetDeviceTagRecord(os_tag=os_tag, os_version=os_version))
if app_info is not None:
app_tag, app_version = app_info
records.append(SetDeviceTagRecord(app_tag=app_tag, app_version=app_version))
if env['USE_SAFEUPDATE']:
safemode_disable = SendRPCRecord(8,0x1006,bytearray([0])) # Disable safemode
records.append(safemode_disable)
sgf_on = SendRPCRecord(8,0x2005,bytearray([1])) # Enable Sensorgraph
records.append(sgf_on)
script = UpdateScript(records)
with open(out_path, "wb") as outfile:
outfile.write(script.encode()) | [
"Create a TRUB script containing tile and controller reflashes and/or sensorgraph\n\n If the app_info is provided, then the final source file will be a sensorgraph.\n All subsequent files in source must be in intel hex format. This is guaranteed\n by the ensure_image_is_hex call in build_update_script.\n "
] |
Please provide a description of the function: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 | [
"\n Convert any return code a BuildError Exception.\n\n :Parameters:\n - `status`: can either be a return code or an Exception.\n\n The buildError.status we set here will normally be\n used as the exit status of the \"scons\" process.\n "
] |
Please provide a description of the function: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.\n\n Args:\n sensor_graph (SensorGraph): the sensor graph that we want to format\n\n Returns:\n str: The ascii output lines concatenated as a single string\n "
] |
Please provide a description of the function: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 | [
"\n Add Builders and construction variables for the Visual Age FORTRAN\n compiler to an Environment.\n "
] |
Please provide a description of the function: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\n directories for on-disk files"
] |
Please provide a description of the function: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\"\n directory Nodes for their in-memory entries"
] |
Please provide a description of the function: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) | [
"\n Scans a directory for on-disk files and directories therein.\n\n Looking up the entries will add these to the in-memory Node tree\n representation of the file system, so all we have to do is just\n that and then call the in-memory scanning function.\n "
] |
Please provide a description of the function: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] | [
"\n \"Scans\" a Node.FS.Dir for its in-memory entries.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.