id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
22,900
iotile/coretools
iotilebuild/iotile/build/tilebus/descriptor.py
TBDescriptor._value_length
def _value_length(self, value, t): """Given an integer or list of them, convert it to an array of bytes.""" if isinstance(value, int): fmt = '<%s' % (type_codes[t]) output = struct.pack(fmt, value) return len(output) elif isinstance(value, str): return len(value) + 1 # Account for final 0 len_accum = 0 for x in value: len_accum += self._value_length(x, t) return len_accum
python
def _value_length(self, value, t): if isinstance(value, int): fmt = '<%s' % (type_codes[t]) output = struct.pack(fmt, value) return len(output) elif isinstance(value, str): return len(value) + 1 # Account for final 0 len_accum = 0 for x in value: len_accum += self._value_length(x, t) return len_accum
[ "def", "_value_length", "(", "self", ",", "value", ",", "t", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "fmt", "=", "'<%s'", "%", "(", "type_codes", "[", "t", "]", ")", "output", "=", "struct", ".", "pack", "(", "fmt", ",",...
Given an integer or list of them, convert it to an array of bytes.
[ "Given", "an", "integer", "or", "list", "of", "them", "convert", "it", "to", "an", "array", "of", "bytes", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/descriptor.py#L152-L166
22,901
iotile/coretools
iotilebuild/iotile/build/tilebus/descriptor.py
TBDescriptor._parse_line
def _parse_line(self, line_no, line): """Parse a line in a TileBus file Args: line_no (int): The line number for printing useful error messages line (string): The line that we are trying to parse """ try: matched = statement.parseString(line) except ParseException as exc: raise DataError("Error parsing line in TileBus file", line_number=line_no, column=exc.col, contents=line) if 'symbol' in matched: self._parse_cmd(matched) elif 'filename' in matched: self._parse_include(matched) elif 'variable' in matched: self._parse_assignment(matched) elif 'configvar' in matched: self._parse_configvar(matched)
python
def _parse_line(self, line_no, line): try: matched = statement.parseString(line) except ParseException as exc: raise DataError("Error parsing line in TileBus file", line_number=line_no, column=exc.col, contents=line) if 'symbol' in matched: self._parse_cmd(matched) elif 'filename' in matched: self._parse_include(matched) elif 'variable' in matched: self._parse_assignment(matched) elif 'configvar' in matched: self._parse_configvar(matched)
[ "def", "_parse_line", "(", "self", ",", "line_no", ",", "line", ")", ":", "try", ":", "matched", "=", "statement", ".", "parseString", "(", "line", ")", "except", "ParseException", "as", "exc", ":", "raise", "DataError", "(", "\"Error parsing line in TileBus f...
Parse a line in a TileBus file Args: line_no (int): The line number for printing useful error messages line (string): The line that we are trying to parse
[ "Parse", "a", "line", "in", "a", "TileBus", "file" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/descriptor.py#L213-L233
22,902
iotile/coretools
iotilebuild/iotile/build/tilebus/descriptor.py
TBDescriptor._validate_information
def _validate_information(self): """Validate that all information has been filled in""" needed_variables = ["ModuleName", "ModuleVersion", "APIVersion"] for var in needed_variables: if var not in self.variables: raise DataError("Needed variable was not defined in mib file.", variable=var) # Make sure ModuleName is <= 6 characters if len(self.variables["ModuleName"]) > 6: raise DataError("ModuleName too long, must be 6 or fewer characters.", module_name=self.variables["ModuleName"]) if not isinstance(self.variables["ModuleVersion"], str): raise ValueError("ModuleVersion ('%s') must be a string of the form X.Y.Z" % str(self.variables['ModuleVersion'])) if not isinstance(self.variables["APIVersion"], str): raise ValueError("APIVersion ('%s') must be a string of the form X.Y" % str(self.variables['APIVersion'])) self.variables['ModuleVersion'] = self._convert_module_version(self.variables["ModuleVersion"]) self.variables['APIVersion'] = self._convert_api_version(self.variables["APIVersion"]) self.variables["ModuleName"] = self.variables["ModuleName"].ljust(6) self.valid = True
python
def _validate_information(self): needed_variables = ["ModuleName", "ModuleVersion", "APIVersion"] for var in needed_variables: if var not in self.variables: raise DataError("Needed variable was not defined in mib file.", variable=var) # Make sure ModuleName is <= 6 characters if len(self.variables["ModuleName"]) > 6: raise DataError("ModuleName too long, must be 6 or fewer characters.", module_name=self.variables["ModuleName"]) if not isinstance(self.variables["ModuleVersion"], str): raise ValueError("ModuleVersion ('%s') must be a string of the form X.Y.Z" % str(self.variables['ModuleVersion'])) if not isinstance(self.variables["APIVersion"], str): raise ValueError("APIVersion ('%s') must be a string of the form X.Y" % str(self.variables['APIVersion'])) self.variables['ModuleVersion'] = self._convert_module_version(self.variables["ModuleVersion"]) self.variables['APIVersion'] = self._convert_api_version(self.variables["APIVersion"]) self.variables["ModuleName"] = self.variables["ModuleName"].ljust(6) self.valid = True
[ "def", "_validate_information", "(", "self", ")", ":", "needed_variables", "=", "[", "\"ModuleName\"", ",", "\"ModuleVersion\"", ",", "\"APIVersion\"", "]", "for", "var", "in", "needed_variables", ":", "if", "var", "not", "in", "self", ".", "variables", ":", "...
Validate that all information has been filled in
[ "Validate", "that", "all", "information", "has", "been", "filled", "in" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/descriptor.py#L235-L260
22,903
iotile/coretools
iotilebuild/iotile/build/tilebus/descriptor.py
TBDescriptor.get_block
def get_block(self, config_only=False): """Create a TileBus Block based on the information in this descriptor""" mib = TBBlock() for cid, config in self.configs.items(): mib.add_config(cid, config) if not config_only: for key, val in self.commands.items(): mib.add_command(key, val) if not self.valid: self._validate_information() mib.set_api_version(*self.variables["APIVersion"]) mib.set_module_version(*self.variables["ModuleVersion"]) mib.set_name(self.variables["ModuleName"]) return mib
python
def get_block(self, config_only=False): mib = TBBlock() for cid, config in self.configs.items(): mib.add_config(cid, config) if not config_only: for key, val in self.commands.items(): mib.add_command(key, val) if not self.valid: self._validate_information() mib.set_api_version(*self.variables["APIVersion"]) mib.set_module_version(*self.variables["ModuleVersion"]) mib.set_name(self.variables["ModuleName"]) return mib
[ "def", "get_block", "(", "self", ",", "config_only", "=", "False", ")", ":", "mib", "=", "TBBlock", "(", ")", "for", "cid", ",", "config", "in", "self", ".", "configs", ".", "items", "(", ")", ":", "mib", ".", "add_config", "(", "cid", ",", "config...
Create a TileBus Block based on the information in this descriptor
[ "Create", "a", "TileBus", "Block", "based", "on", "the", "information", "in", "this", "descriptor" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/descriptor.py#L286-L305
22,904
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.add_adapter
def add_adapter(self, adapter): """Add a device adapter to this aggregating adapter.""" if self._started: raise InternalError("New adapters cannot be added after start() is called") if isinstance(adapter, DeviceAdapter): self._logger.warning("Wrapping legacy device adapter %s in async wrapper", adapter) adapter = AsynchronousModernWrapper(adapter, loop=self._loop) self.adapters.append(adapter) adapter_callback = functools.partial(self.handle_adapter_event, len(self.adapters) - 1) events = ['device_seen', 'broadcast', 'report', 'connection', 'disconnection', 'trace', 'progress'] adapter.register_monitor([None], events, adapter_callback)
python
def add_adapter(self, adapter): if self._started: raise InternalError("New adapters cannot be added after start() is called") if isinstance(adapter, DeviceAdapter): self._logger.warning("Wrapping legacy device adapter %s in async wrapper", adapter) adapter = AsynchronousModernWrapper(adapter, loop=self._loop) self.adapters.append(adapter) adapter_callback = functools.partial(self.handle_adapter_event, len(self.adapters) - 1) events = ['device_seen', 'broadcast', 'report', 'connection', 'disconnection', 'trace', 'progress'] adapter.register_monitor([None], events, adapter_callback)
[ "def", "add_adapter", "(", "self", ",", "adapter", ")", ":", "if", "self", ".", "_started", ":", "raise", "InternalError", "(", "\"New adapters cannot be added after start() is called\"", ")", "if", "isinstance", "(", "adapter", ",", "DeviceAdapter", ")", ":", "se...
Add a device adapter to this aggregating adapter.
[ "Add", "a", "device", "adapter", "to", "this", "aggregating", "adapter", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L78-L95
22,905
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.get_config
def get_config(self, name, default=_MISSING): """Get a configuration setting from this DeviceAdapter. See :meth:`AbstractDeviceAdapter.get_config`. """ val = self._config.get(name, default) if val is _MISSING: raise ArgumentError("DeviceAdapter config {} did not exist and no default".format(name)) return val
python
def get_config(self, name, default=_MISSING): val = self._config.get(name, default) if val is _MISSING: raise ArgumentError("DeviceAdapter config {} did not exist and no default".format(name)) return val
[ "def", "get_config", "(", "self", ",", "name", ",", "default", "=", "_MISSING", ")", ":", "val", "=", "self", ".", "_config", ".", "get", "(", "name", ",", "default", ")", "if", "val", "is", "_MISSING", ":", "raise", "ArgumentError", "(", "\"DeviceAdap...
Get a configuration setting from this DeviceAdapter. See :meth:`AbstractDeviceAdapter.get_config`.
[ "Get", "a", "configuration", "setting", "from", "this", "DeviceAdapter", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L110-L120
22,906
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.start
async def start(self): """Start all adapters managed by this device adapter. If there is an error starting one or more adapters, this method will stop any adapters that we successfully started and raise an exception. """ successful = 0 try: for adapter in self.adapters: await adapter.start() successful += 1 self._started = True except: for adapter in self.adapters[:successful]: await adapter.stop() raise
python
async def start(self): successful = 0 try: for adapter in self.adapters: await adapter.start() successful += 1 self._started = True except: for adapter in self.adapters[:successful]: await adapter.stop() raise
[ "async", "def", "start", "(", "self", ")", ":", "successful", "=", "0", "try", ":", "for", "adapter", "in", "self", ".", "adapters", ":", "await", "adapter", ".", "start", "(", ")", "successful", "+=", "1", "self", ".", "_started", "=", "True", "exce...
Start all adapters managed by this device adapter. If there is an error starting one or more adapters, this method will stop any adapters that we successfully started and raise an exception.
[ "Start", "all", "adapters", "managed", "by", "this", "device", "adapter", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L141-L160
22,907
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.visible_devices
def visible_devices(self): """Unify all visible devices across all connected adapters Returns: dict: A dictionary mapping UUIDs to device information dictionaries """ devs = {} for device_id, adapters in self._devices.items(): dev = None max_signal = None best_adapter = None for adapter_id, devinfo in adapters.items(): connstring = "adapter/{0}/{1}".format(adapter_id, devinfo['connection_string']) if dev is None: dev = copy.deepcopy(devinfo) del dev['connection_string'] if 'adapters' not in dev: dev['adapters'] = [] best_adapter = adapter_id dev['adapters'].append((adapter_id, devinfo['signal_strength'], connstring)) if max_signal is None: max_signal = devinfo['signal_strength'] elif devinfo['signal_strength'] > max_signal: max_signal = devinfo['signal_strength'] best_adapter = adapter_id # If device has been seen in no adapters, it will get expired # don't return it if dev is None: continue dev['connection_string'] = "device/%x" % dev['uuid'] dev['adapters'] = sorted(dev['adapters'], key=lambda x: x[1], reverse=True) dev['best_adapter'] = best_adapter dev['signal_strength'] = max_signal devs[device_id] = dev return devs
python
def visible_devices(self): devs = {} for device_id, adapters in self._devices.items(): dev = None max_signal = None best_adapter = None for adapter_id, devinfo in adapters.items(): connstring = "adapter/{0}/{1}".format(adapter_id, devinfo['connection_string']) if dev is None: dev = copy.deepcopy(devinfo) del dev['connection_string'] if 'adapters' not in dev: dev['adapters'] = [] best_adapter = adapter_id dev['adapters'].append((adapter_id, devinfo['signal_strength'], connstring)) if max_signal is None: max_signal = devinfo['signal_strength'] elif devinfo['signal_strength'] > max_signal: max_signal = devinfo['signal_strength'] best_adapter = adapter_id # If device has been seen in no adapters, it will get expired # don't return it if dev is None: continue dev['connection_string'] = "device/%x" % dev['uuid'] dev['adapters'] = sorted(dev['adapters'], key=lambda x: x[1], reverse=True) dev['best_adapter'] = best_adapter dev['signal_strength'] = max_signal devs[device_id] = dev return devs
[ "def", "visible_devices", "(", "self", ")", ":", "devs", "=", "{", "}", "for", "device_id", ",", "adapters", "in", "self", ".", "_devices", ".", "items", "(", ")", ":", "dev", "=", "None", "max_signal", "=", "None", "best_adapter", "=", "None", "for", ...
Unify all visible devices across all connected adapters Returns: dict: A dictionary mapping UUIDs to device information dictionaries
[ "Unify", "all", "visible", "devices", "across", "all", "connected", "adapters" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L168-L212
22,908
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.probe
async def probe(self): """Probe for devices. This method will probe all adapters that can probe and will send a notification for all devices that we have seen from all adapters. See :meth:`AbstractDeviceAdapter.probe`. """ for adapter in self.adapters: if adapter.get_config('probe_supported', False): await adapter.probe()
python
async def probe(self): for adapter in self.adapters: if adapter.get_config('probe_supported', False): await adapter.probe()
[ "async", "def", "probe", "(", "self", ")", ":", "for", "adapter", "in", "self", ".", "adapters", ":", "if", "adapter", ".", "get_config", "(", "'probe_supported'", ",", "False", ")", ":", "await", "adapter", ".", "probe", "(", ")" ]
Probe for devices. This method will probe all adapters that can probe and will send a notification for all devices that we have seen from all adapters. See :meth:`AbstractDeviceAdapter.probe`.
[ "Probe", "for", "devices", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L275-L286
22,909
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.send_script
async def send_script(self, conn_id, data): """Send a script to a device. See :meth:`AbstractDeviceAdapter.send_script`. """ adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_script(conn_id, data)
python
async def send_script(self, conn_id, data): adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_script(conn_id, data)
[ "async", "def", "send_script", "(", "self", ",", "conn_id", ",", "data", ")", ":", "adapter_id", "=", "self", ".", "_get_property", "(", "conn_id", ",", "'adapter'", ")", "return", "await", "self", ".", "adapters", "[", "adapter_id", "]", ".", "send_script...
Send a script to a device. See :meth:`AbstractDeviceAdapter.send_script`.
[ "Send", "a", "script", "to", "a", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L306-L313
22,910
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.handle_adapter_event
async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event): """Handle an event received from an adapter.""" if name == 'device_seen': self._track_device_seen(adapter_id, conn_string, event) event = self._translate_device_seen(adapter_id, conn_string, event) conn_string = self._translate_conn_string(adapter_id, conn_string) elif conn_id is not None and self._get_property(conn_id, 'translate'): conn_string = self._translate_conn_string(adapter_id, conn_string) else: conn_string = "adapter/%d/%s" % (adapter_id, conn_string) await self.notify_event(conn_string, name, event)
python
async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event): if name == 'device_seen': self._track_device_seen(adapter_id, conn_string, event) event = self._translate_device_seen(adapter_id, conn_string, event) conn_string = self._translate_conn_string(adapter_id, conn_string) elif conn_id is not None and self._get_property(conn_id, 'translate'): conn_string = self._translate_conn_string(adapter_id, conn_string) else: conn_string = "adapter/%d/%s" % (adapter_id, conn_string) await self.notify_event(conn_string, name, event)
[ "async", "def", "handle_adapter_event", "(", "self", ",", "adapter_id", ",", "conn_string", ",", "conn_id", ",", "name", ",", "event", ")", ":", "if", "name", "==", "'device_seen'", ":", "self", ".", "_track_device_seen", "(", "adapter_id", ",", "conn_string",...
Handle an event received from an adapter.
[ "Handle", "an", "event", "received", "from", "an", "adapter", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L315-L328
22,911
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter._device_expiry_callback
def _device_expiry_callback(self): """Periodic callback to remove expired devices from visible_devices.""" expired = 0 for adapters in self._devices.values(): to_remove = [] now = monotonic() for adapter_id, dev in adapters.items(): if 'expires' not in dev: continue if now > dev['expires']: to_remove.append(adapter_id) local_conn = "adapter/%d/%s" % (adapter_id, dev['connection_string']) if local_conn in self._conn_strings: del self._conn_strings[local_conn] for entry in to_remove: del adapters[entry] expired += 1 if expired > 0: self._logger.info('Expired %d devices', expired)
python
def _device_expiry_callback(self): expired = 0 for adapters in self._devices.values(): to_remove = [] now = monotonic() for adapter_id, dev in adapters.items(): if 'expires' not in dev: continue if now > dev['expires']: to_remove.append(adapter_id) local_conn = "adapter/%d/%s" % (adapter_id, dev['connection_string']) if local_conn in self._conn_strings: del self._conn_strings[local_conn] for entry in to_remove: del adapters[entry] expired += 1 if expired > 0: self._logger.info('Expired %d devices', expired)
[ "def", "_device_expiry_callback", "(", "self", ")", ":", "expired", "=", "0", "for", "adapters", "in", "self", ".", "_devices", ".", "values", "(", ")", ":", "to_remove", "=", "[", "]", "now", "=", "monotonic", "(", ")", "for", "adapter_id", ",", "dev"...
Periodic callback to remove expired devices from visible_devices.
[ "Periodic", "callback", "to", "remove", "expired", "devices", "from", "visible_devices", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L361-L385
22,912
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/PathVariable.py
_PathVariableClass.PathIsDir
def PathIsDir(self, key, val, env): """Validator to check if Path is a directory.""" if not os.path.isdir(val): if os.path.isfile(val): m = 'Directory path for option %s is a file: %s' else: m = 'Directory path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val))
python
def PathIsDir(self, key, val, env): if not os.path.isdir(val): if os.path.isfile(val): m = 'Directory path for option %s is a file: %s' else: m = 'Directory path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val))
[ "def", "PathIsDir", "(", "self", ",", "key", ",", "val", ",", "env", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "val", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "val", ")", ":", "m", "=", "'Directory path for option...
Validator to check if Path is a directory.
[ "Validator", "to", "check", "if", "Path", "is", "a", "directory", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/PathVariable.py#L85-L92
22,913
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/PathVariable.py
_PathVariableClass.PathExists
def PathExists(self, key, val, env): """Validator to check if Path exists""" if not os.path.exists(val): m = 'Path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val))
python
def PathExists(self, key, val, env): if not os.path.exists(val): m = 'Path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val))
[ "def", "PathExists", "(", "self", ",", "key", ",", "val", ",", "env", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "val", ")", ":", "m", "=", "'Path for option %s does not exist: %s'", "raise", "SCons", ".", "Errors", ".", "UserError", ...
Validator to check if Path exists
[ "Validator", "to", "check", "if", "Path", "exists" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/PathVariable.py#L112-L116
22,914
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem._reset_vector
async def _reset_vector(self): """Background task to initialize this system in the event loop.""" self._logger.debug("sensor_graph subsystem task starting") # If there is a persistent sgf loaded, send reset information. self.initialized.set() while True: stream, reading = await self._inputs.get() try: await process_graph_input(self.graph, stream, reading, self._executor) self.process_streamers() except: #pylint:disable=bare-except;This is a background task that should not die self._logger.exception("Unhandled exception processing sensor_graph input (stream=%s), reading=%s", stream, reading) finally: self._inputs.task_done()
python
async def _reset_vector(self): self._logger.debug("sensor_graph subsystem task starting") # If there is a persistent sgf loaded, send reset information. self.initialized.set() while True: stream, reading = await self._inputs.get() try: await process_graph_input(self.graph, stream, reading, self._executor) self.process_streamers() except: #pylint:disable=bare-except;This is a background task that should not die self._logger.exception("Unhandled exception processing sensor_graph input (stream=%s), reading=%s", stream, reading) finally: self._inputs.task_done()
[ "async", "def", "_reset_vector", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"sensor_graph subsystem task starting\"", ")", "# If there is a persistent sgf loaded, send reset information.", "self", ".", "initialized", ".", "set", "(", ")", "while...
Background task to initialize this system in the event loop.
[ "Background", "task", "to", "initialize", "this", "system", "in", "the", "event", "loop", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L140-L158
22,915
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.process_input
def process_input(self, encoded_stream, value): """Process or drop a graph input. This method asynchronously queued an item to be processed by the sensorgraph worker task in _reset_vector. It must be called from inside the emulation loop and returns immediately before the input is processed. """ if not self.enabled: return if isinstance(encoded_stream, str): stream = DataStream.FromString(encoded_stream) encoded_stream = stream.encode() elif isinstance(encoded_stream, DataStream): stream = encoded_stream encoded_stream = stream.encode() else: stream = DataStream.FromEncoded(encoded_stream) reading = IOTileReading(self.get_timestamp(), encoded_stream, value) self._inputs.put_nowait((stream, reading))
python
def process_input(self, encoded_stream, value): if not self.enabled: return if isinstance(encoded_stream, str): stream = DataStream.FromString(encoded_stream) encoded_stream = stream.encode() elif isinstance(encoded_stream, DataStream): stream = encoded_stream encoded_stream = stream.encode() else: stream = DataStream.FromEncoded(encoded_stream) reading = IOTileReading(self.get_timestamp(), encoded_stream, value) self._inputs.put_nowait((stream, reading))
[ "def", "process_input", "(", "self", ",", "encoded_stream", ",", "value", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "if", "isinstance", "(", "encoded_stream", ",", "str", ")", ":", "stream", "=", "DataStream", ".", "FromString", "(", ...
Process or drop a graph input. This method asynchronously queued an item to be processed by the sensorgraph worker task in _reset_vector. It must be called from inside the emulation loop and returns immediately before the input is processed.
[ "Process", "or", "drop", "a", "graph", "input", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L196-L219
22,916
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem._seek_streamer
def _seek_streamer(self, index, value): """Complex logic for actually seeking a streamer to a reading_id. This routine hides all of the gnarly logic of the various edge cases. In particular, the behavior depends on whether the reading id is found, and if it is found, whether it belongs to the indicated streamer or not. If not, the behavior depends on whether the sought reading it too high or too low. """ highest_id = self._rsl.highest_stored_id() streamer = self.graph.streamers[index] if not streamer.walker.buffered: return _pack_sgerror(SensorLogError.CANNOT_USE_UNBUFFERED_STREAM) find_type = None try: exact = streamer.walker.seek(value, target='id') if exact: find_type = 'exact' else: find_type = 'other_stream' except UnresolvedIdentifierError: if value > highest_id: find_type = 'too_high' else: find_type = 'too_low' # If we found an exact match, move one beyond it if find_type == 'exact': try: streamer.walker.pop() except StreamEmptyError: pass error = Error.NO_ERROR elif find_type == 'too_high': streamer.walker.skip_all() error = _pack_sgerror(SensorLogError.NO_MORE_READINGS) elif find_type == 'too_low': streamer.walker.seek(0, target='offset') error = _pack_sgerror(SensorLogError.NO_MORE_READINGS) else: error = _pack_sgerror(SensorLogError.ID_FOUND_FOR_ANOTHER_STREAM) return error
python
def _seek_streamer(self, index, value): highest_id = self._rsl.highest_stored_id() streamer = self.graph.streamers[index] if not streamer.walker.buffered: return _pack_sgerror(SensorLogError.CANNOT_USE_UNBUFFERED_STREAM) find_type = None try: exact = streamer.walker.seek(value, target='id') if exact: find_type = 'exact' else: find_type = 'other_stream' except UnresolvedIdentifierError: if value > highest_id: find_type = 'too_high' else: find_type = 'too_low' # If we found an exact match, move one beyond it if find_type == 'exact': try: streamer.walker.pop() except StreamEmptyError: pass error = Error.NO_ERROR elif find_type == 'too_high': streamer.walker.skip_all() error = _pack_sgerror(SensorLogError.NO_MORE_READINGS) elif find_type == 'too_low': streamer.walker.seek(0, target='offset') error = _pack_sgerror(SensorLogError.NO_MORE_READINGS) else: error = _pack_sgerror(SensorLogError.ID_FOUND_FOR_ANOTHER_STREAM) return error
[ "def", "_seek_streamer", "(", "self", ",", "index", ",", "value", ")", ":", "highest_id", "=", "self", ".", "_rsl", ".", "highest_stored_id", "(", ")", "streamer", "=", "self", ".", "graph", ".", "streamers", "[", "index", "]", "if", "not", "streamer", ...
Complex logic for actually seeking a streamer to a reading_id. This routine hides all of the gnarly logic of the various edge cases. In particular, the behavior depends on whether the reading id is found, and if it is found, whether it belongs to the indicated streamer or not. If not, the behavior depends on whether the sought reading it too high or too low.
[ "Complex", "logic", "for", "actually", "seeking", "a", "streamer", "to", "a", "reading_id", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L221-L270
22,917
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.acknowledge_streamer
def acknowledge_streamer(self, index, ack, force): """Acknowledge a streamer value as received from the remote side.""" if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) old_ack = self.streamer_acks.get(index, 0) if ack != 0: if ack <= old_ack and not force: return _pack_sgerror(SensorGraphError.OLD_ACKNOWLEDGE_UPDATE) self.streamer_acks[index] = ack current_ack = self.streamer_acks.get(index, 0) return self._seek_streamer(index, current_ack)
python
def acknowledge_streamer(self, index, ack, force): if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) old_ack = self.streamer_acks.get(index, 0) if ack != 0: if ack <= old_ack and not force: return _pack_sgerror(SensorGraphError.OLD_ACKNOWLEDGE_UPDATE) self.streamer_acks[index] = ack current_ack = self.streamer_acks.get(index, 0) return self._seek_streamer(index, current_ack)
[ "def", "acknowledge_streamer", "(", "self", ",", "index", ",", "ack", ",", "force", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "graph", ".", "streamers", ")", ":", "return", "_pack_sgerror", "(", "SensorGraphError", ".", "STREAMER_NOT_ALLOCATED"...
Acknowledge a streamer value as received from the remote side.
[ "Acknowledge", "a", "streamer", "value", "as", "received", "from", "the", "remote", "side", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L272-L287
22,918
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem._handle_streamer_finished
def _handle_streamer_finished(self, index, succeeded, highest_ack): """Callback when a streamer finishes processing.""" self._logger.debug("Rolling back streamer %d after streaming, highest ack from streaming subsystem was %d", index, highest_ack) self.acknowledge_streamer(index, highest_ack, False)
python
def _handle_streamer_finished(self, index, succeeded, highest_ack): self._logger.debug("Rolling back streamer %d after streaming, highest ack from streaming subsystem was %d", index, highest_ack) self.acknowledge_streamer(index, highest_ack, False)
[ "def", "_handle_streamer_finished", "(", "self", ",", "index", ",", "succeeded", ",", "highest_ack", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Rolling back streamer %d after streaming, highest ack from streaming subsystem was %d\"", ",", "index", ",", "highe...
Callback when a streamer finishes processing.
[ "Callback", "when", "a", "streamer", "finishes", "processing", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L289-L293
22,919
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.process_streamers
def process_streamers(self): """Check if any streamers should be handed to the stream manager.""" # Check for any triggered streamers and pass them to stream manager in_progress = self._stream_manager.in_progress() triggered = self.graph.check_streamers(blacklist=in_progress) for streamer in triggered: self._stream_manager.process_streamer(streamer, callback=self._handle_streamer_finished)
python
def process_streamers(self): # Check for any triggered streamers and pass them to stream manager in_progress = self._stream_manager.in_progress() triggered = self.graph.check_streamers(blacklist=in_progress) for streamer in triggered: self._stream_manager.process_streamer(streamer, callback=self._handle_streamer_finished)
[ "def", "process_streamers", "(", "self", ")", ":", "# Check for any triggered streamers and pass them to stream manager", "in_progress", "=", "self", ".", "_stream_manager", ".", "in_progress", "(", ")", "triggered", "=", "self", ".", "graph", ".", "check_streamers", "(...
Check if any streamers should be handed to the stream manager.
[ "Check", "if", "any", "streamers", "should", "be", "handed", "to", "the", "stream", "manager", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L295-L303
22,920
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.trigger_streamer
def trigger_streamer(self, index): """Pass a streamer to the stream manager if it has data.""" self._logger.debug("trigger_streamer RPC called on streamer %d", index) if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) if index in self._stream_manager.in_progress(): return _pack_sgerror(SensorGraphError.STREAM_ALREADY_IN_PROGRESS) streamer = self.graph.streamers[index] if not streamer.triggered(manual=True): return _pack_sgerror(SensorGraphError.STREAMER_HAS_NO_NEW_DATA) self._logger.debug("calling mark_streamer on streamer %d from trigger_streamer RPC", index) self.graph.mark_streamer(index) self.process_streamers() return Error.NO_ERROR
python
def trigger_streamer(self, index): self._logger.debug("trigger_streamer RPC called on streamer %d", index) if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) if index in self._stream_manager.in_progress(): return _pack_sgerror(SensorGraphError.STREAM_ALREADY_IN_PROGRESS) streamer = self.graph.streamers[index] if not streamer.triggered(manual=True): return _pack_sgerror(SensorGraphError.STREAMER_HAS_NO_NEW_DATA) self._logger.debug("calling mark_streamer on streamer %d from trigger_streamer RPC", index) self.graph.mark_streamer(index) self.process_streamers() return Error.NO_ERROR
[ "def", "trigger_streamer", "(", "self", ",", "index", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"trigger_streamer RPC called on streamer %d\"", ",", "index", ")", "if", "index", ">=", "len", "(", "self", ".", "graph", ".", "streamers", ")", ":",...
Pass a streamer to the stream manager if it has data.
[ "Pass", "a", "streamer", "to", "the", "stream", "manager", "if", "it", "has", "data", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L305-L325
22,921
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.persist
def persist(self): """Trigger saving the current sensorgraph to persistent storage.""" self.persisted_nodes = self.graph.dump_nodes() self.persisted_streamers = self.graph.dump_streamers() self.persisted_exists = True self.persisted_constants = self._sensor_log.dump_constants()
python
def persist(self): self.persisted_nodes = self.graph.dump_nodes() self.persisted_streamers = self.graph.dump_streamers() self.persisted_exists = True self.persisted_constants = self._sensor_log.dump_constants()
[ "def", "persist", "(", "self", ")", ":", "self", ".", "persisted_nodes", "=", "self", ".", "graph", ".", "dump_nodes", "(", ")", "self", ".", "persisted_streamers", "=", "self", ".", "graph", ".", "dump_streamers", "(", ")", "self", ".", "persisted_exists"...
Trigger saving the current sensorgraph to persistent storage.
[ "Trigger", "saving", "the", "current", "sensorgraph", "to", "persistent", "storage", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L332-L338
22,922
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.reset
def reset(self): """Clear the sensorgraph from RAM and flash.""" self.persisted_exists = False self.persisted_nodes = [] self.persisted_streamers = [] self.persisted_constants = [] self.graph.clear() self.streamer_status = {}
python
def reset(self): self.persisted_exists = False self.persisted_nodes = [] self.persisted_streamers = [] self.persisted_constants = [] self.graph.clear() self.streamer_status = {}
[ "def", "reset", "(", "self", ")", ":", "self", ".", "persisted_exists", "=", "False", "self", ".", "persisted_nodes", "=", "[", "]", "self", ".", "persisted_streamers", "=", "[", "]", "self", ".", "persisted_constants", "=", "[", "]", "self", ".", "graph...
Clear the sensorgraph from RAM and flash.
[ "Clear", "the", "sensorgraph", "from", "RAM", "and", "flash", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L340-L349
22,923
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.add_node
def add_node(self, binary_descriptor): """Add a node to the sensor_graph using a binary node descriptor. Args: binary_descriptor (bytes): An encoded binary node descriptor. Returns: int: A packed error code. """ try: node_string = parse_binary_descriptor(binary_descriptor) except: self._logger.exception("Error parsing binary node descriptor: %s", binary_descriptor) return _pack_sgerror(SensorGraphError.INVALID_NODE_STREAM) # FIXME: Actually provide the correct error codes here try: self.graph.add_node(node_string) except NodeConnectionError: return _pack_sgerror(SensorGraphError.STREAM_NOT_IN_USE) except ProcessingFunctionError: return _pack_sgerror(SensorGraphError.INVALID_PROCESSING_FUNCTION) except ResourceUsageError: return _pack_sgerror(SensorGraphError.NO_NODE_SPACE_AVAILABLE) return Error.NO_ERROR
python
def add_node(self, binary_descriptor): try: node_string = parse_binary_descriptor(binary_descriptor) except: self._logger.exception("Error parsing binary node descriptor: %s", binary_descriptor) return _pack_sgerror(SensorGraphError.INVALID_NODE_STREAM) # FIXME: Actually provide the correct error codes here try: self.graph.add_node(node_string) except NodeConnectionError: return _pack_sgerror(SensorGraphError.STREAM_NOT_IN_USE) except ProcessingFunctionError: return _pack_sgerror(SensorGraphError.INVALID_PROCESSING_FUNCTION) except ResourceUsageError: return _pack_sgerror(SensorGraphError.NO_NODE_SPACE_AVAILABLE) return Error.NO_ERROR
[ "def", "add_node", "(", "self", ",", "binary_descriptor", ")", ":", "try", ":", "node_string", "=", "parse_binary_descriptor", "(", "binary_descriptor", ")", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Error parsing binary node descriptor: %s\"", ...
Add a node to the sensor_graph using a binary node descriptor. Args: binary_descriptor (bytes): An encoded binary node descriptor. Returns: int: A packed error code.
[ "Add", "a", "node", "to", "the", "sensor_graph", "using", "a", "binary", "node", "descriptor", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L351-L376
22,924
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.add_streamer
def add_streamer(self, binary_descriptor): """Add a streamer to the sensor_graph using a binary streamer descriptor. Args: binary_descriptor (bytes): An encoded binary streamer descriptor. Returns: int: A packed error code """ streamer = streamer_descriptor.parse_binary_descriptor(binary_descriptor) try: self.graph.add_streamer(streamer) self.streamer_status[len(self.graph.streamers) - 1] = StreamerStatus() return Error.NO_ERROR except ResourceUsageError: return _pack_sgerror(SensorGraphError.NO_MORE_STREAMER_RESOURCES)
python
def add_streamer(self, binary_descriptor): streamer = streamer_descriptor.parse_binary_descriptor(binary_descriptor) try: self.graph.add_streamer(streamer) self.streamer_status[len(self.graph.streamers) - 1] = StreamerStatus() return Error.NO_ERROR except ResourceUsageError: return _pack_sgerror(SensorGraphError.NO_MORE_STREAMER_RESOURCES)
[ "def", "add_streamer", "(", "self", ",", "binary_descriptor", ")", ":", "streamer", "=", "streamer_descriptor", ".", "parse_binary_descriptor", "(", "binary_descriptor", ")", "try", ":", "self", ".", "graph", ".", "add_streamer", "(", "streamer", ")", "self", "....
Add a streamer to the sensor_graph using a binary streamer descriptor. Args: binary_descriptor (bytes): An encoded binary streamer descriptor. Returns: int: A packed error code
[ "Add", "a", "streamer", "to", "the", "sensor_graph", "using", "a", "binary", "streamer", "descriptor", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L378-L396
22,925
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.inspect_streamer
def inspect_streamer(self, index): """Inspect the streamer at the given index.""" if index >= len(self.graph.streamers): return [_pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED), b'\0'*14] return [Error.NO_ERROR, streamer_descriptor.create_binary_descriptor(self.graph.streamers[index])]
python
def inspect_streamer(self, index): if index >= len(self.graph.streamers): return [_pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED), b'\0'*14] return [Error.NO_ERROR, streamer_descriptor.create_binary_descriptor(self.graph.streamers[index])]
[ "def", "inspect_streamer", "(", "self", ",", "index", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "graph", ".", "streamers", ")", ":", "return", "[", "_pack_sgerror", "(", "SensorGraphError", ".", "STREAMER_NOT_ALLOCATED", ")", ",", "b'\\0'", "...
Inspect the streamer at the given index.
[ "Inspect", "the", "streamer", "at", "the", "given", "index", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L398-L404
22,926
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.inspect_node
def inspect_node(self, index): """Inspect the graph node at the given index.""" if index >= len(self.graph.nodes): raise RPCErrorCode(6) #FIXME: use actual error code here for UNKNOWN_ERROR status return create_binary_descriptor(str(self.graph.nodes[index]))
python
def inspect_node(self, index): if index >= len(self.graph.nodes): raise RPCErrorCode(6) #FIXME: use actual error code here for UNKNOWN_ERROR status return create_binary_descriptor(str(self.graph.nodes[index]))
[ "def", "inspect_node", "(", "self", ",", "index", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "graph", ".", "nodes", ")", ":", "raise", "RPCErrorCode", "(", "6", ")", "#FIXME: use actual error code here for UNKNOWN_ERROR status", "return", "create_bi...
Inspect the graph node at the given index.
[ "Inspect", "the", "graph", "node", "at", "the", "given", "index", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L406-L412
22,927
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphSubsystem.query_streamer
def query_streamer(self, index): """Query the status of the streamer at the given index.""" if index >= len(self.graph.streamers): return None info = self.streamer_status[index] highest_ack = self.streamer_acks.get(index, 0) return [info.last_attempt_time, info.last_success_time, info.last_error, highest_ack, info.last_status, info.attempt_number, info.comm_status]
python
def query_streamer(self, index): if index >= len(self.graph.streamers): return None info = self.streamer_status[index] highest_ack = self.streamer_acks.get(index, 0) return [info.last_attempt_time, info.last_success_time, info.last_error, highest_ack, info.last_status, info.attempt_number, info.comm_status]
[ "def", "query_streamer", "(", "self", ",", "index", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "graph", ".", "streamers", ")", ":", "return", "None", "info", "=", "self", ".", "streamer_status", "[", "index", "]", "highest_ack", "=", "self...
Query the status of the streamer at the given index.
[ "Query", "the", "status", "of", "the", "streamer", "at", "the", "given", "index", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L414-L423
22,928
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphMixin.sg_graph_input
def sg_graph_input(self, value, stream_id): """"Present a graph input to the sensor_graph subsystem.""" self.sensor_graph.process_input(stream_id, value) return [Error.NO_ERROR]
python
def sg_graph_input(self, value, stream_id): "self.sensor_graph.process_input(stream_id, value) return [Error.NO_ERROR]
[ "def", "sg_graph_input", "(", "self", ",", "value", ",", "stream_id", ")", ":", "self", ".", "sensor_graph", ".", "process_input", "(", "stream_id", ",", "value", ")", "return", "[", "Error", ".", "NO_ERROR", "]" ]
Present a graph input to the sensor_graph subsystem.
[ "Present", "a", "graph", "input", "to", "the", "sensor_graph", "subsystem", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L461-L465
22,929
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphMixin.sg_add_streamer
def sg_add_streamer(self, desc): """Add a graph streamer using a binary descriptor.""" if len(desc) == 13: desc += b'\0' err = self.sensor_graph.add_streamer(desc) return [err]
python
def sg_add_streamer(self, desc): if len(desc) == 13: desc += b'\0' err = self.sensor_graph.add_streamer(desc) return [err]
[ "def", "sg_add_streamer", "(", "self", ",", "desc", ")", ":", "if", "len", "(", "desc", ")", "==", "13", ":", "desc", "+=", "b'\\0'", "err", "=", "self", ".", "sensor_graph", ".", "add_streamer", "(", "desc", ")", "return", "[", "err", "]" ]
Add a graph streamer using a binary descriptor.
[ "Add", "a", "graph", "streamer", "using", "a", "binary", "descriptor", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L488-L495
22,930
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphMixin.sg_seek_streamer
def sg_seek_streamer(self, index, force, value): """Ackowledge a streamer.""" force = bool(force) err = self.sensor_graph.acknowledge_streamer(index, value, force) return [err]
python
def sg_seek_streamer(self, index, force, value): force = bool(force) err = self.sensor_graph.acknowledge_streamer(index, value, force) return [err]
[ "def", "sg_seek_streamer", "(", "self", ",", "index", ",", "force", ",", "value", ")", ":", "force", "=", "bool", "(", "force", ")", "err", "=", "self", ".", "sensor_graph", ".", "acknowledge_streamer", "(", "index", ",", "value", ",", "force", ")", "r...
Ackowledge a streamer.
[ "Ackowledge", "a", "streamer", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L512-L517
22,931
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py
SensorGraphMixin.sg_query_streamer
def sg_query_streamer(self, index): """Query the current status of a streamer.""" resp = self.sensor_graph.query_streamer(index) if resp is None: return [struct.pack("<L", _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED))] return [struct.pack("<LLLLBBBx", *resp)]
python
def sg_query_streamer(self, index): resp = self.sensor_graph.query_streamer(index) if resp is None: return [struct.pack("<L", _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED))] return [struct.pack("<LLLLBBBx", *resp)]
[ "def", "sg_query_streamer", "(", "self", ",", "index", ")", ":", "resp", "=", "self", ".", "sensor_graph", ".", "query_streamer", "(", "index", ")", "if", "resp", "is", "None", ":", "return", "[", "struct", ".", "pack", "(", "\"<L\"", ",", "_pack_sgerror...
Query the current status of a streamer.
[ "Query", "the", "current", "status", "of", "a", "streamer", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_graph.py#L520-L527
22,932
iotile/coretools
iotilecore/iotile/core/utilities/workqueue_thread.py
WorkQueueThread.dispatch
def dispatch(self, value, callback=None): """Dispatch an item to the workqueue and optionally wait. This is the only way to add work to the background work queue. Unless you also pass a callback object, this method will synchronously wait for the work to finish and return the result. If the work raises an exception, the exception will be reraised in this method. If you pass an optional callback(exc_info, return_value), this method will not block and instead your callback will be called when the work finishes. If an exception was raised during processing, exc_info will be set with the contents of sys.exc_info(). Otherwise, exc_info will be None and whatever the work_queue handler returned will be passed as the return_value parameter to the supplied callback. Args: value (object): Arbitrary object that will be passed to the work queue handler. callback (callable): Optional callback to receive the result of the work queue when it finishes. If not passed, this method will be synchronous and return the result from the dispatch() method itself Returns: object: The result of the work_queue handler function or None. If callback is not None, then this method will return immediately with a None return value. Otherwise it will block until the work item is finished (including any work items ahead in the queue) and return whatever the work item handler returned. """ done = None if callback is None: done = threading.Event() shared_data = [None, None] def _callback(exc_info, return_value): shared_data[0] = exc_info shared_data[1] = return_value done.set() callback = _callback workitem = WorkItem(value, callback) self._work_queue.put(workitem) if done is None: return None done.wait() exc_info, return_value = shared_data if exc_info is not None: self.future_raise(*exc_info) return return_value
python
def dispatch(self, value, callback=None): done = None if callback is None: done = threading.Event() shared_data = [None, None] def _callback(exc_info, return_value): shared_data[0] = exc_info shared_data[1] = return_value done.set() callback = _callback workitem = WorkItem(value, callback) self._work_queue.put(workitem) if done is None: return None done.wait() exc_info, return_value = shared_data if exc_info is not None: self.future_raise(*exc_info) return return_value
[ "def", "dispatch", "(", "self", ",", "value", ",", "callback", "=", "None", ")", ":", "done", "=", "None", "if", "callback", "is", "None", ":", "done", "=", "threading", ".", "Event", "(", ")", "shared_data", "=", "[", "None", ",", "None", "]", "de...
Dispatch an item to the workqueue and optionally wait. This is the only way to add work to the background work queue. Unless you also pass a callback object, this method will synchronously wait for the work to finish and return the result. If the work raises an exception, the exception will be reraised in this method. If you pass an optional callback(exc_info, return_value), this method will not block and instead your callback will be called when the work finishes. If an exception was raised during processing, exc_info will be set with the contents of sys.exc_info(). Otherwise, exc_info will be None and whatever the work_queue handler returned will be passed as the return_value parameter to the supplied callback. Args: value (object): Arbitrary object that will be passed to the work queue handler. callback (callable): Optional callback to receive the result of the work queue when it finishes. If not passed, this method will be synchronous and return the result from the dispatch() method itself Returns: object: The result of the work_queue handler function or None. If callback is not None, then this method will return immediately with a None return value. Otherwise it will block until the work item is finished (including any work items ahead in the queue) and return whatever the work item handler returned.
[ "Dispatch", "an", "item", "to", "the", "workqueue", "and", "optionally", "wait", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/workqueue_thread.py#L85-L142
22,933
iotile/coretools
iotilecore/iotile/core/utilities/workqueue_thread.py
WorkQueueThread.future_raise
def future_raise(self, tp, value=None, tb=None): """raise_ implementation from future.utils""" if value is not None and isinstance(tp, Exception): raise TypeError("instance exception may not have a separate value") if value is not None: exc = tp(value) else: exc = tp if exc.__traceback__ is not tb: raise exc.with_traceback(tb) raise exc
python
def future_raise(self, tp, value=None, tb=None): if value is not None and isinstance(tp, Exception): raise TypeError("instance exception may not have a separate value") if value is not None: exc = tp(value) else: exc = tp if exc.__traceback__ is not tb: raise exc.with_traceback(tb) raise exc
[ "def", "future_raise", "(", "self", ",", "tp", ",", "value", "=", "None", ",", "tb", "=", "None", ")", ":", "if", "value", "is", "not", "None", "and", "isinstance", "(", "tp", ",", "Exception", ")", ":", "raise", "TypeError", "(", "\"instance exception...
raise_ implementation from future.utils
[ "raise_", "implementation", "from", "future", ".", "utils" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/workqueue_thread.py#L144-L154
22,934
iotile/coretools
iotilecore/iotile/core/utilities/workqueue_thread.py
WorkQueueThread.flush
def flush(self): """Synchronously wait until this work item is processed. This has the effect of waiting until all work items queued before this method has been called have finished. """ done = threading.Event() def _callback(): done.set() self.defer(_callback) done.wait()
python
def flush(self): done = threading.Event() def _callback(): done.set() self.defer(_callback) done.wait()
[ "def", "flush", "(", "self", ")", ":", "done", "=", "threading", ".", "Event", "(", ")", "def", "_callback", "(", ")", ":", "done", ".", "set", "(", ")", "self", ".", "defer", "(", "_callback", ")", "done", ".", "wait", "(", ")" ]
Synchronously wait until this work item is processed. This has the effect of waiting until all work items queued before this method has been called have finished.
[ "Synchronously", "wait", "until", "this", "work", "item", "is", "processed", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/workqueue_thread.py#L156-L169
22,935
iotile/coretools
iotilecore/iotile/core/utilities/workqueue_thread.py
WorkQueueThread.direct_dispatch
def direct_dispatch(self, arg, callback): """Directly dispatch a work item. This method MUST only be called from inside of another work item and will synchronously invoke the work item as if it was passed to dispatch(). Calling this method from any other thread has undefined consequences since it will be unsynchronized with respect to items dispatched from inside the background work queue itself. """ try: self._current_callbacks.appendleft(callback) exc_info = None retval = None retval = self._routine(arg) except: # pylint:disable=bare-except;We need to capture the exception and feed it back to the caller exc_info = sys.exc_info() finally: self._current_callbacks.popleft() if callback is not None and retval is not self.STILL_PENDING: callback(exc_info, retval) return retval, exc_info
python
def direct_dispatch(self, arg, callback): try: self._current_callbacks.appendleft(callback) exc_info = None retval = None retval = self._routine(arg) except: # pylint:disable=bare-except;We need to capture the exception and feed it back to the caller exc_info = sys.exc_info() finally: self._current_callbacks.popleft() if callback is not None and retval is not self.STILL_PENDING: callback(exc_info, retval) return retval, exc_info
[ "def", "direct_dispatch", "(", "self", ",", "arg", ",", "callback", ")", ":", "try", ":", "self", ".", "_current_callbacks", ".", "appendleft", "(", "callback", ")", "exc_info", "=", "None", "retval", "=", "None", "retval", "=", "self", ".", "_routine", ...
Directly dispatch a work item. This method MUST only be called from inside of another work item and will synchronously invoke the work item as if it was passed to dispatch(). Calling this method from any other thread has undefined consequences since it will be unsynchronized with respect to items dispatched from inside the background work queue itself.
[ "Directly", "dispatch", "a", "work", "item", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/workqueue_thread.py#L237-L262
22,936
iotile/coretools
iotilecore/iotile/core/utilities/workqueue_thread.py
WorkQueueThread.stop
def stop(self, timeout=None, force=False): """Stop the worker thread and synchronously wait for it to finish. Args: timeout (float): The maximum time to wait for the thread to stop before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError is not raised and the thread is just marked as a daemon thread so that it does not block cleanly exiting the process. force (bool): If true and the thread does not exit in timeout seconds no error is raised since the thread is marked as daemon and will be killed when the process exits. """ self.signal_stop() self.wait_stopped(timeout, force)
python
def stop(self, timeout=None, force=False): self.signal_stop() self.wait_stopped(timeout, force)
[ "def", "stop", "(", "self", ",", "timeout", "=", "None", ",", "force", "=", "False", ")", ":", "self", ".", "signal_stop", "(", ")", "self", ".", "wait_stopped", "(", "timeout", ",", "force", ")" ]
Stop the worker thread and synchronously wait for it to finish. Args: timeout (float): The maximum time to wait for the thread to stop before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError is not raised and the thread is just marked as a daemon thread so that it does not block cleanly exiting the process. force (bool): If true and the thread does not exit in timeout seconds no error is raised since the thread is marked as daemon and will be killed when the process exits.
[ "Stop", "the", "worker", "thread", "and", "synchronously", "wait", "for", "it", "to", "finish", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/workqueue_thread.py#L300-L314
22,937
iotile/coretools
iotilecore/iotile/core/utilities/workqueue_thread.py
WorkQueueThread.wait_stopped
def wait_stopped(self, timeout=None, force=False): """Wait for the thread to stop. You must have previously called signal_stop or this function will hang. Args: timeout (float): The maximum time to wait for the thread to stop before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError is not raised and the thread is just marked as a daemon thread so that it does not block cleanly exiting the process. force (bool): If true and the thread does not exit in timeout seconds no error is raised since the thread is marked as daemon and will be killed when the process exits. """ self.join(timeout) if self.is_alive() and force is False: raise TimeoutExpiredError("Error waiting for background thread to exit", timeout=timeout)
python
def wait_stopped(self, timeout=None, force=False): self.join(timeout) if self.is_alive() and force is False: raise TimeoutExpiredError("Error waiting for background thread to exit", timeout=timeout)
[ "def", "wait_stopped", "(", "self", ",", "timeout", "=", "None", ",", "force", "=", "False", ")", ":", "self", ".", "join", "(", "timeout", ")", "if", "self", ".", "is_alive", "(", ")", "and", "force", "is", "False", ":", "raise", "TimeoutExpiredError"...
Wait for the thread to stop. You must have previously called signal_stop or this function will hang. Args: timeout (float): The maximum time to wait for the thread to stop before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError is not raised and the thread is just marked as a daemon thread so that it does not block cleanly exiting the process. force (bool): If true and the thread does not exit in timeout seconds no error is raised since the thread is marked as daemon and will be killed when the process exits.
[ "Wait", "for", "the", "thread", "to", "stop", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/workqueue_thread.py#L325-L346
22,938
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/wix.py
generate
def generate(env): """Add Builders and construction variables for WiX to an Environment.""" if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXLIGHTFLAGS'].append( '-nologo' ) env['WIXLIGHTCOM'] = "$WIXLIGHT $WIXLIGHTFLAGS -out ${TARGET} ${SOURCES}" env['WIXSRCSUF'] = '.wxs' env['WIXOBJSUF'] = '.wixobj' object_builder = SCons.Builder.Builder( action = '$WIXCANDLECOM', suffix = '$WIXOBJSUF', src_suffix = '$WIXSRCSUF') linker_builder = SCons.Builder.Builder( action = '$WIXLIGHTCOM', src_suffix = '$WIXOBJSUF', src_builder = object_builder) env['BUILDERS']['WiX'] = linker_builder
python
def generate(env): if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXLIGHTFLAGS'].append( '-nologo' ) env['WIXLIGHTCOM'] = "$WIXLIGHT $WIXLIGHTFLAGS -out ${TARGET} ${SOURCES}" env['WIXSRCSUF'] = '.wxs' env['WIXOBJSUF'] = '.wixobj' object_builder = SCons.Builder.Builder( action = '$WIXCANDLECOM', suffix = '$WIXOBJSUF', src_suffix = '$WIXSRCSUF') linker_builder = SCons.Builder.Builder( action = '$WIXLIGHTCOM', src_suffix = '$WIXOBJSUF', src_builder = object_builder) env['BUILDERS']['WiX'] = linker_builder
[ "def", "generate", "(", "env", ")", ":", "if", "not", "exists", "(", "env", ")", ":", "return", "env", "[", "'WIXCANDLEFLAGS'", "]", "=", "[", "'-nologo'", "]", "env", "[", "'WIXCANDLEINCLUDE'", "]", "=", "[", "]", "env", "[", "'WIXCANDLECOM'", "]", ...
Add Builders and construction variables for WiX to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "WiX", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/wix.py#L39-L63
22,939
iotile/coretools
iotilesensorgraph/iotile/sg/sim/stimulus.py
SimulationStimulus.FromString
def FromString(cls, desc): """Create a new stimulus from a description string. The string must have the format: [time: ][system ]input X = Y where X and Y are integers. The time, if given must be a time_interval, which is an integer followed by a time unit such as second(s), minute(s), etc. Args: desc (str): A string description of the stimulus. Returns: SimulationStimulus: The parsed stimulus object. """ if language.stream is None: language.get_language() parse_exp = Optional(time_interval('time') - Literal(':').suppress()) - language.stream('stream') - Literal('=').suppress() - number('value') try: data = parse_exp.parseString(desc) time = 0 if 'time' in data: time = data['time'][0] return SimulationStimulus(time, data['stream'][0], data['value']) except (ParseException, ParseSyntaxException): raise ArgumentError("Could not parse stimulus descriptor", descriptor=desc)
python
def FromString(cls, desc): if language.stream is None: language.get_language() parse_exp = Optional(time_interval('time') - Literal(':').suppress()) - language.stream('stream') - Literal('=').suppress() - number('value') try: data = parse_exp.parseString(desc) time = 0 if 'time' in data: time = data['time'][0] return SimulationStimulus(time, data['stream'][0], data['value']) except (ParseException, ParseSyntaxException): raise ArgumentError("Could not parse stimulus descriptor", descriptor=desc)
[ "def", "FromString", "(", "cls", ",", "desc", ")", ":", "if", "language", ".", "stream", "is", "None", ":", "language", ".", "get_language", "(", ")", "parse_exp", "=", "Optional", "(", "time_interval", "(", "'time'", ")", "-", "Literal", "(", "':'", "...
Create a new stimulus from a description string. The string must have the format: [time: ][system ]input X = Y where X and Y are integers. The time, if given must be a time_interval, which is an integer followed by a time unit such as second(s), minute(s), etc. Args: desc (str): A string description of the stimulus. Returns: SimulationStimulus: The parsed stimulus object.
[ "Create", "a", "new", "stimulus", "from", "a", "description", "string", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/stimulus.py#L27-L56
22,940
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py
ConnectionManager.get_connection_id
def get_connection_id(self, conn_or_int_id): """Get the connection id. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if it cannot be found. Raises: ArgumentError: When the key is not found in the list of active connections or is invalid. """ key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: raise ArgumentError("You must supply either an int connection id or a string internal id to _get_connection_state", id=key) try: data = table[key] except KeyError: raise ArgumentError("Could not find connection by id", id=key) return data['conn_id']
python
def get_connection_id(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: raise ArgumentError("You must supply either an int connection id or a string internal id to _get_connection_state", id=key) try: data = table[key] except KeyError: raise ArgumentError("Could not find connection by id", id=key) return data['conn_id']
[ "def", "get_connection_id", "(", "self", ",", "conn_or_int_id", ")", ":", "key", "=", "conn_or_int_id", "if", "isinstance", "(", "key", ",", "str", ")", ":", "table", "=", "self", ".", "_int_connections", "elif", "isinstance", "(", "key", ",", "int", ")", ...
Get the connection id. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if it cannot be found. Raises: ArgumentError: When the key is not found in the list of active connections or is invalid.
[ "Get", "the", "connection", "id", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L174-L203
22,941
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py
ConnectionManager._get_connection
def _get_connection(self, conn_or_int_id): """Get the data for a connection by either conn_id or internal_id Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if it cannot be found. Raises: ArgumentError: When the key is not found in the list of active connections or is invalid. """ key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: return None try: data = table[key] except KeyError: return None return data
python
def _get_connection(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: return None try: data = table[key] except KeyError: return None return data
[ "def", "_get_connection", "(", "self", ",", "conn_or_int_id", ")", ":", "key", "=", "conn_or_int_id", "if", "isinstance", "(", "key", ",", "str", ")", ":", "table", "=", "self", ".", "_int_connections", "elif", "isinstance", "(", "key", ",", "int", ")", ...
Get the data for a connection by either conn_id or internal_id Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if it cannot be found. Raises: ArgumentError: When the key is not found in the list of active connections or is invalid.
[ "Get", "the", "data", "for", "a", "connection", "by", "either", "conn_id", "or", "internal_id" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L205-L234
22,942
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py
ConnectionManager._get_connection_state
def _get_connection_state(self, conn_or_int_id): """Get a connection's state by either conn_id or internal_id This routine must only be called from the internal worker thread. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id """ key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: raise ArgumentError("You must supply either an int connection id or a string internal id to _get_connection_state", id=key) if key not in table: return self.Disconnected data = table[key] return data['state']
python
def _get_connection_state(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: raise ArgumentError("You must supply either an int connection id or a string internal id to _get_connection_state", id=key) if key not in table: return self.Disconnected data = table[key] return data['state']
[ "def", "_get_connection_state", "(", "self", ",", "conn_or_int_id", ")", ":", "key", "=", "conn_or_int_id", "if", "isinstance", "(", "key", ",", "str", ")", ":", "table", "=", "self", ".", "_int_connections", "elif", "isinstance", "(", "key", ",", "int", "...
Get a connection's state by either conn_id or internal_id This routine must only be called from the internal worker thread. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id
[ "Get", "a", "connection", "s", "state", "by", "either", "conn_id", "or", "internal_id" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L236-L258
22,943
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py
ConnectionManager._check_timeouts
def _check_timeouts(self): """Check if any operations in progress need to be timed out Adds the corresponding finish action that fails the request due to a timeout. """ for conn_id, data in self._connections.items(): if 'timeout' in data and data['timeout'].expired: if data['state'] == self.Connecting: self.finish_connection(conn_id, False, 'Connection attempt timed out') elif data['state'] == self.Disconnecting: self.finish_disconnection(conn_id, False, 'Disconnection attempt timed out') elif data['state'] == self.InProgress: if data['microstate'] == 'rpc': self.finish_operation(conn_id, False, 'RPC timed out without response', None, None) elif data['microstate'] == 'open_interface': self.finish_operation(conn_id, False, 'Open interface request timed out')
python
def _check_timeouts(self): for conn_id, data in self._connections.items(): if 'timeout' in data and data['timeout'].expired: if data['state'] == self.Connecting: self.finish_connection(conn_id, False, 'Connection attempt timed out') elif data['state'] == self.Disconnecting: self.finish_disconnection(conn_id, False, 'Disconnection attempt timed out') elif data['state'] == self.InProgress: if data['microstate'] == 'rpc': self.finish_operation(conn_id, False, 'RPC timed out without response', None, None) elif data['microstate'] == 'open_interface': self.finish_operation(conn_id, False, 'Open interface request timed out')
[ "def", "_check_timeouts", "(", "self", ")", ":", "for", "conn_id", ",", "data", "in", "self", ".", "_connections", ".", "items", "(", ")", ":", "if", "'timeout'", "in", "data", "and", "data", "[", "'timeout'", "]", ".", "expired", ":", "if", "data", ...
Check if any operations in progress need to be timed out Adds the corresponding finish action that fails the request due to a timeout.
[ "Check", "if", "any", "operations", "in", "progress", "need", "to", "be", "timed", "out" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L260-L277
22,944
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py
ConnectionManager.unexpected_disconnect
def unexpected_disconnect(self, conn_or_internal_id): """Notify that there was an unexpected disconnection of the device. Any in progress operations are canceled cleanly and the device is transitioned to a disconnected state. Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id """ data = { 'id': conn_or_internal_id } action = ConnectionAction('force_disconnect', data, sync=False) self._actions.put(action)
python
def unexpected_disconnect(self, conn_or_internal_id): data = { 'id': conn_or_internal_id } action = ConnectionAction('force_disconnect', data, sync=False) self._actions.put(action)
[ "def", "unexpected_disconnect", "(", "self", ",", "conn_or_internal_id", ")", ":", "data", "=", "{", "'id'", ":", "conn_or_internal_id", "}", "action", "=", "ConnectionAction", "(", "'force_disconnect'", ",", "data", ",", "sync", "=", "False", ")", "self", "."...
Notify that there was an unexpected disconnection of the device. Any in progress operations are canceled cleanly and the device is transitioned to a disconnected state. Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id
[ "Notify", "that", "there", "was", "an", "unexpected", "disconnection", "of", "the", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L393-L409
22,945
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py
ConnectionManager.finish_operation
def finish_operation(self, conn_or_internal_id, success, *args): """Finish an operation on a connection. Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id success (bool): Whether the operation was successful failure_reason (string): Optional reason why the operation failed result (dict): Optional dictionary containing the results of the operation """ data = { 'id': conn_or_internal_id, 'success': success, 'callback_args': args } action = ConnectionAction('finish_operation', data, sync=False) self._actions.put(action)
python
def finish_operation(self, conn_or_internal_id, success, *args): data = { 'id': conn_or_internal_id, 'success': success, 'callback_args': args } action = ConnectionAction('finish_operation', data, sync=False) self._actions.put(action)
[ "def", "finish_operation", "(", "self", ",", "conn_or_internal_id", ",", "success", ",", "*", "args", ")", ":", "data", "=", "{", "'id'", ":", "conn_or_internal_id", ",", "'success'", ":", "success", ",", "'callback_args'", ":", "args", "}", "action", "=", ...
Finish an operation on a connection. Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id success (bool): Whether the operation was successful failure_reason (string): Optional reason why the operation failed result (dict): Optional dictionary containing the results of the operation
[ "Finish", "an", "operation", "on", "a", "connection", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L593-L611
22,946
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py
ConnectionManager._finish_operation_action
def _finish_operation_action(self, action): """Finish an attempted operation. Args: action (ConnectionAction): the action object describing the result of the operation that we are finishing """ success = action.data['success'] conn_key = action.data['id'] if self._get_connection_state(conn_key) != self.InProgress: self._logger.error("Invalid finish_operation action on a connection whose state is not InProgress, conn_key=%s", str(conn_key)) return # Cannot be None since we checked above to make sure it exists data = self._get_connection(conn_key) callback = data['callback'] conn_id = data['conn_id'] args = action.data['callback_args'] data['state'] = self.Idle data['microstate'] = None callback(conn_id, self.id, success, *args)
python
def _finish_operation_action(self, action): success = action.data['success'] conn_key = action.data['id'] if self._get_connection_state(conn_key) != self.InProgress: self._logger.error("Invalid finish_operation action on a connection whose state is not InProgress, conn_key=%s", str(conn_key)) return # Cannot be None since we checked above to make sure it exists data = self._get_connection(conn_key) callback = data['callback'] conn_id = data['conn_id'] args = action.data['callback_args'] data['state'] = self.Idle data['microstate'] = None callback(conn_id, self.id, success, *args)
[ "def", "_finish_operation_action", "(", "self", ",", "action", ")", ":", "success", "=", "action", ".", "data", "[", "'success'", "]", "conn_key", "=", "action", ".", "data", "[", "'id'", "]", "if", "self", ".", "_get_connection_state", "(", "conn_key", ")...
Finish an attempted operation. Args: action (ConnectionAction): the action object describing the result of the operation that we are finishing
[ "Finish", "an", "attempted", "operation", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L613-L637
22,947
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/LaTeX.py
LaTeX.canonical_text
def canonical_text(self, text): """Standardize an input TeX-file contents. Currently: * removes comments, unwrapping comment-wrapped lines. """ out = [] line_continues_a_comment = False for line in text.splitlines(): line,comment = self.comment_re.findall(line)[0] if line_continues_a_comment == True: out[-1] = out[-1] + line.lstrip() else: out.append(line) line_continues_a_comment = len(comment) > 0 return '\n'.join(out).rstrip()+'\n'
python
def canonical_text(self, text): out = [] line_continues_a_comment = False for line in text.splitlines(): line,comment = self.comment_re.findall(line)[0] if line_continues_a_comment == True: out[-1] = out[-1] + line.lstrip() else: out.append(line) line_continues_a_comment = len(comment) > 0 return '\n'.join(out).rstrip()+'\n'
[ "def", "canonical_text", "(", "self", ",", "text", ")", ":", "out", "=", "[", "]", "line_continues_a_comment", "=", "False", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "line", ",", "comment", "=", "self", ".", "comment_re", ".", "fi...
Standardize an input TeX-file contents. Currently: * removes comments, unwrapping comment-wrapped lines.
[ "Standardize", "an", "input", "TeX", "-", "file", "contents", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/LaTeX.py#L326-L341
22,948
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/LaTeX.py
LaTeX.scan_recurse
def scan_recurse(self, node, path=()): """ do a recursive scan of the top level target file This lets us search for included files based on the directory of the main file just as latex does""" path_dict = dict(list(path)) queue = [] queue.extend( self.scan(node) ) seen = {} # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the \include, \input, etc. line. # TODO: what about the comment in the original Classic scanner: # """which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally.""" nodes = [] source_dir = node.get_dir() #for include in includes: while queue: include = queue.pop() inc_type, inc_subdir, inc_filename = include try: if seen[inc_filename] == 1: continue except KeyError: seen[inc_filename] = 1 # # Handle multiple filenames in include[1] # n, i = self.find_include(include, source_dir, path_dict) if n is None: # Do not bother with 'usepackage' warnings, as they most # likely refer to system-level files if inc_type != 'usepackage': SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: sortkey = self.sort_key(n) nodes.append((sortkey, n)) # recurse down queue.extend( self.scan(n, inc_subdir) ) return [pair[1] for pair in sorted(nodes)]
python
def scan_recurse(self, node, path=()): path_dict = dict(list(path)) queue = [] queue.extend( self.scan(node) ) seen = {} # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the \include, \input, etc. line. # TODO: what about the comment in the original Classic scanner: # """which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally.""" nodes = [] source_dir = node.get_dir() #for include in includes: while queue: include = queue.pop() inc_type, inc_subdir, inc_filename = include try: if seen[inc_filename] == 1: continue except KeyError: seen[inc_filename] = 1 # # Handle multiple filenames in include[1] # n, i = self.find_include(include, source_dir, path_dict) if n is None: # Do not bother with 'usepackage' warnings, as they most # likely refer to system-level files if inc_type != 'usepackage': SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: sortkey = self.sort_key(n) nodes.append((sortkey, n)) # recurse down queue.extend( self.scan(n, inc_subdir) ) return [pair[1] for pair in sorted(nodes)]
[ "def", "scan_recurse", "(", "self", ",", "node", ",", "path", "=", "(", ")", ")", ":", "path_dict", "=", "dict", "(", "list", "(", "path", ")", ")", "queue", "=", "[", "]", "queue", ".", "extend", "(", "self", ".", "scan", "(", "node", ")", ")"...
do a recursive scan of the top level target file This lets us search for included files based on the directory of the main file just as latex does
[ "do", "a", "recursive", "scan", "of", "the", "top", "level", "target", "file", "This", "lets", "us", "search", "for", "included", "files", "based", "on", "the", "directory", "of", "the", "main", "file", "just", "as", "latex", "does" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/LaTeX.py#L383-L431
22,949
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Debug.py
caller_trace
def caller_trace(back=0): """ Trace caller stack and save info into global dicts, which are printed automatically at the end of SCons execution. """ global caller_bases, caller_dicts import traceback tb = traceback.extract_stack(limit=3+back) tb.reverse() callee = tb[1][:3] caller_bases[callee] = caller_bases.get(callee, 0) + 1 for caller in tb[2:]: caller = callee + caller[:3] try: entry = caller_dicts[callee] except KeyError: caller_dicts[callee] = entry = {} entry[caller] = entry.get(caller, 0) + 1 callee = caller
python
def caller_trace(back=0): global caller_bases, caller_dicts import traceback tb = traceback.extract_stack(limit=3+back) tb.reverse() callee = tb[1][:3] caller_bases[callee] = caller_bases.get(callee, 0) + 1 for caller in tb[2:]: caller = callee + caller[:3] try: entry = caller_dicts[callee] except KeyError: caller_dicts[callee] = entry = {} entry[caller] = entry.get(caller, 0) + 1 callee = caller
[ "def", "caller_trace", "(", "back", "=", "0", ")", ":", "global", "caller_bases", ",", "caller_dicts", "import", "traceback", "tb", "=", "traceback", ".", "extract_stack", "(", "limit", "=", "3", "+", "back", ")", "tb", ".", "reverse", "(", ")", "callee"...
Trace caller stack and save info into global dicts, which are printed automatically at the end of SCons execution.
[ "Trace", "caller", "stack", "and", "save", "info", "into", "global", "dicts", "which", "are", "printed", "automatically", "at", "the", "end", "of", "SCons", "execution", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Debug.py#L144-L162
22,950
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
diff_dumps
def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3): """Diff 2 IntelHex objects and produce unified diff output for their hex dumps. @param ih1 first IntelHex object to compare @param ih2 second IntelHex object to compare @param tofile file-like object to write output @param name1 name of the first hex file to show in the diff header @param name2 name of the first hex file to show in the diff header @param n_context number of context lines in the unidiff output """ def prepare_lines(ih): sio = StringIO() ih.dump(sio) dump = sio.getvalue() lines = dump.splitlines() return lines a = prepare_lines(ih1) b = prepare_lines(ih2) import difflib result = list(difflib.unified_diff(a, b, fromfile=name1, tofile=name2, n=n_context, lineterm='')) if tofile is None: tofile = sys.stdout output = '\n'.join(result)+'\n' tofile.write(output)
python
def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3): def prepare_lines(ih): sio = StringIO() ih.dump(sio) dump = sio.getvalue() lines = dump.splitlines() return lines a = prepare_lines(ih1) b = prepare_lines(ih2) import difflib result = list(difflib.unified_diff(a, b, fromfile=name1, tofile=name2, n=n_context, lineterm='')) if tofile is None: tofile = sys.stdout output = '\n'.join(result)+'\n' tofile.write(output)
[ "def", "diff_dumps", "(", "ih1", ",", "ih2", ",", "tofile", "=", "None", ",", "name1", "=", "\"a\"", ",", "name2", "=", "\"b\"", ",", "n_context", "=", "3", ")", ":", "def", "prepare_lines", "(", "ih", ")", ":", "sio", "=", "StringIO", "(", ")", ...
Diff 2 IntelHex objects and produce unified diff output for their hex dumps. @param ih1 first IntelHex object to compare @param ih2 second IntelHex object to compare @param tofile file-like object to write output @param name1 name of the first hex file to show in the diff header @param name2 name of the first hex file to show in the diff header @param n_context number of context lines in the unidiff output
[ "Diff", "2", "IntelHex", "objects", "and", "produce", "unified", "diff", "output", "for", "their", "hex", "dumps", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L1100-L1124
22,951
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex._decode_record
def _decode_record(self, s, line=0): '''Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. ''' s = s.rstrip('\r\n') if not s: return # empty line if s[0] == ':': try: bin = array('B', unhexlify(asbytes(s[1:]))) except (TypeError, ValueError): # this might be raised by unhexlify when odd hexascii digits raise HexRecordError(line=line) length = len(bin) if length < 5: raise HexRecordError(line=line) else: raise HexRecordError(line=line) record_length = bin[0] if length != (5 + record_length): raise RecordLengthError(line=line) addr = bin[1]*256 + bin[2] record_type = bin[3] if not (0 <= record_type <= 5): raise RecordTypeError(line=line) crc = sum(bin) crc &= 0x0FF if crc != 0: raise RecordChecksumError(line=line) if record_type == 0: # data record addr += self._offset for i in range_g(4, 4+record_length): if not self._buf.get(addr, None) is None: raise AddressOverlapError(address=addr, line=line) self._buf[addr] = bin[i] addr += 1 # FIXME: addr should be wrapped # BUT after 02 record (at 64K boundary) # and after 04 record (at 4G boundary) elif record_type == 1: # end of file record if record_length != 0: raise EOFRecordError(line=line) raise _EndOfFile elif record_type == 2: # Extended 8086 Segment Record if record_length != 2 or addr != 0: raise ExtendedSegmentAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 16 elif record_type == 4: # Extended Linear Address Record if record_length != 2 or addr != 0: raise ExtendedLinearAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 65536 elif record_type == 3: # Start Segment Address Record if record_length != 4 or addr != 0: raise StartSegmentAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'CS': bin[4]*256 + bin[5], 'IP': bin[6]*256 + bin[7], } elif record_type == 5: # Start Linear Address Record if record_length != 4 or addr != 0: raise StartLinearAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'EIP': (bin[4]*16777216 + bin[5]*65536 + bin[6]*256 + bin[7]), }
python
def _decode_record(self, s, line=0): '''Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. ''' s = s.rstrip('\r\n') if not s: return # empty line if s[0] == ':': try: bin = array('B', unhexlify(asbytes(s[1:]))) except (TypeError, ValueError): # this might be raised by unhexlify when odd hexascii digits raise HexRecordError(line=line) length = len(bin) if length < 5: raise HexRecordError(line=line) else: raise HexRecordError(line=line) record_length = bin[0] if length != (5 + record_length): raise RecordLengthError(line=line) addr = bin[1]*256 + bin[2] record_type = bin[3] if not (0 <= record_type <= 5): raise RecordTypeError(line=line) crc = sum(bin) crc &= 0x0FF if crc != 0: raise RecordChecksumError(line=line) if record_type == 0: # data record addr += self._offset for i in range_g(4, 4+record_length): if not self._buf.get(addr, None) is None: raise AddressOverlapError(address=addr, line=line) self._buf[addr] = bin[i] addr += 1 # FIXME: addr should be wrapped # BUT after 02 record (at 64K boundary) # and after 04 record (at 4G boundary) elif record_type == 1: # end of file record if record_length != 0: raise EOFRecordError(line=line) raise _EndOfFile elif record_type == 2: # Extended 8086 Segment Record if record_length != 2 or addr != 0: raise ExtendedSegmentAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 16 elif record_type == 4: # Extended Linear Address Record if record_length != 2 or addr != 0: raise ExtendedLinearAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 65536 elif record_type == 3: # Start Segment Address Record if record_length != 4 or addr != 0: raise StartSegmentAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'CS': bin[4]*256 + bin[5], 'IP': bin[6]*256 + bin[7], } elif record_type == 5: # Start Linear Address Record if record_length != 4 or addr != 0: raise StartLinearAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'EIP': (bin[4]*16777216 + bin[5]*65536 + bin[6]*256 + bin[7]), }
[ "def", "_decode_record", "(", "self", ",", "s", ",", "line", "=", "0", ")", ":", "s", "=", "s", ".", "rstrip", "(", "'\\r\\n'", ")", "if", "not", "s", ":", "return", "# empty line", "if", "s", "[", "0", "]", "==", "':'", ":", "try", ":", "bin",...
Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered.
[ "Decode", "one", "record", "of", "HEX", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L109-L197
22,952
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.loadhex
def loadhex(self, fobj): """Load hex file into internal buffer. This is not necessary if object was initialized with source set. This will overwrite addresses if object was already initialized. @param fobj file name or file-like object """ if getattr(fobj, "read", None) is None: fobj = open(fobj, "r") fclose = fobj.close else: fclose = None self._offset = 0 line = 0 try: decode = self._decode_record try: for s in fobj: line += 1 decode(s, line) except _EndOfFile: pass finally: if fclose: fclose()
python
def loadhex(self, fobj): if getattr(fobj, "read", None) is None: fobj = open(fobj, "r") fclose = fobj.close else: fclose = None self._offset = 0 line = 0 try: decode = self._decode_record try: for s in fobj: line += 1 decode(s, line) except _EndOfFile: pass finally: if fclose: fclose()
[ "def", "loadhex", "(", "self", ",", "fobj", ")", ":", "if", "getattr", "(", "fobj", ",", "\"read\"", ",", "None", ")", "is", "None", ":", "fobj", "=", "open", "(", "fobj", ",", "\"r\"", ")", "fclose", "=", "fobj", ".", "close", "else", ":", "fclo...
Load hex file into internal buffer. This is not necessary if object was initialized with source set. This will overwrite addresses if object was already initialized. @param fobj file name or file-like object
[ "Load", "hex", "file", "into", "internal", "buffer", ".", "This", "is", "not", "necessary", "if", "object", "was", "initialized", "with", "source", "set", ".", "This", "will", "overwrite", "addresses", "if", "object", "was", "already", "initialized", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L199-L225
22,953
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.loadbin
def loadbin(self, fobj, offset=0): """Load bin file into internal buffer. Not needed if source set in constructor. This will overwrite addresses without warning if object was already initialized. @param fobj file name or file-like object @param offset starting address offset """ fread = getattr(fobj, "read", None) if fread is None: f = open(fobj, "rb") fread = f.read fclose = f.close else: fclose = None try: self.frombytes(array('B', asbytes(fread())), offset=offset) finally: if fclose: fclose()
python
def loadbin(self, fobj, offset=0): fread = getattr(fobj, "read", None) if fread is None: f = open(fobj, "rb") fread = f.read fclose = f.close else: fclose = None try: self.frombytes(array('B', asbytes(fread())), offset=offset) finally: if fclose: fclose()
[ "def", "loadbin", "(", "self", ",", "fobj", ",", "offset", "=", "0", ")", ":", "fread", "=", "getattr", "(", "fobj", ",", "\"read\"", ",", "None", ")", "if", "fread", "is", "None", ":", "f", "=", "open", "(", "fobj", ",", "\"rb\"", ")", "fread", ...
Load bin file into internal buffer. Not needed if source set in constructor. This will overwrite addresses without warning if object was already initialized. @param fobj file name or file-like object @param offset starting address offset
[ "Load", "bin", "file", "into", "internal", "buffer", ".", "Not", "needed", "if", "source", "set", "in", "constructor", ".", "This", "will", "overwrite", "addresses", "without", "warning", "if", "object", "was", "already", "initialized", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L227-L247
22,954
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.loadfile
def loadfile(self, fobj, format): """Load data file into internal buffer. Preferred wrapper over loadbin or loadhex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == "hex": self.loadhex(fobj) elif format == "bin": self.loadbin(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format)
python
def loadfile(self, fobj, format): if format == "hex": self.loadhex(fobj) elif format == "bin": self.loadbin(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format)
[ "def", "loadfile", "(", "self", ",", "fobj", ",", "format", ")", ":", "if", "format", "==", "\"hex\"", ":", "self", ".", "loadhex", "(", "fobj", ")", "elif", "format", "==", "\"bin\"", ":", "self", ".", "loadbin", "(", "fobj", ")", "else", ":", "ra...
Load data file into internal buffer. Preferred wrapper over loadbin or loadhex. @param fobj file name or file-like object @param format file format ("hex" or "bin")
[ "Load", "data", "file", "into", "internal", "buffer", ".", "Preferred", "wrapper", "over", "loadbin", "or", "loadhex", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L249-L262
22,955
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex._get_start_end
def _get_start_end(self, start=None, end=None, size=None): """Return default values for start and end if they are None. If this IntelHex object is empty then it's error to invoke this method with both start and end as None. """ if (start,end) == (None,None) and self._buf == {}: raise EmptyIntelHexError if size is not None: if None not in (start, end): raise ValueError("tobinarray: you can't use start,end and size" " arguments in the same time") if (start, end) == (None, None): start = self.minaddr() if start is not None: end = start + size - 1 else: start = end - size + 1 if start < 0: raise ValueError("tobinarray: invalid size (%d) " "for given end address (%d)" % (size,end)) else: if start is None: start = self.minaddr() if end is None: end = self.maxaddr() if start > end: start, end = end, start return start, end
python
def _get_start_end(self, start=None, end=None, size=None): if (start,end) == (None,None) and self._buf == {}: raise EmptyIntelHexError if size is not None: if None not in (start, end): raise ValueError("tobinarray: you can't use start,end and size" " arguments in the same time") if (start, end) == (None, None): start = self.minaddr() if start is not None: end = start + size - 1 else: start = end - size + 1 if start < 0: raise ValueError("tobinarray: invalid size (%d) " "for given end address (%d)" % (size,end)) else: if start is None: start = self.minaddr() if end is None: end = self.maxaddr() if start > end: start, end = end, start return start, end
[ "def", "_get_start_end", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "size", "=", "None", ")", ":", "if", "(", "start", ",", "end", ")", "==", "(", "None", ",", "None", ")", "and", "self", ".", "_buf", "==", "{", "}", ...
Return default values for start and end if they are None. If this IntelHex object is empty then it's error to invoke this method with both start and end as None.
[ "Return", "default", "values", "for", "start", "and", "end", "if", "they", "are", "None", ".", "If", "this", "IntelHex", "object", "is", "empty", "then", "it", "s", "error", "to", "invoke", "this", "method", "with", "both", "start", "and", "end", "as", ...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L297-L324
22,956
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.tobinarray
def tobinarray(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return array of unsigned char data. ''' if not isinstance(pad, _DeprecatedParam): print ("IntelHex.tobinarray: 'pad' parameter is deprecated.") if pad is not None: print ("Please, use IntelHex.padding attribute instead.") else: print ("Please, don't pass it explicitly.") print ("Use syntax like this: ih.tobinarray(start=xxx, end=yyy, size=zzz)") else: pad = None return self._tobinarray_really(start, end, pad, size)
python
def tobinarray(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return array of unsigned char data. ''' if not isinstance(pad, _DeprecatedParam): print ("IntelHex.tobinarray: 'pad' parameter is deprecated.") if pad is not None: print ("Please, use IntelHex.padding attribute instead.") else: print ("Please, don't pass it explicitly.") print ("Use syntax like this: ih.tobinarray(start=xxx, end=yyy, size=zzz)") else: pad = None return self._tobinarray_really(start, end, pad, size)
[ "def", "tobinarray", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "pad", "=", "_DEPRECATED", ",", "size", "=", "None", ")", ":", "if", "not", "isinstance", "(", "pad", ",", "_DeprecatedParam", ")", ":", "print", "(", "\"Intel...
Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return array of unsigned char data.
[ "Convert", "this", "object", "to", "binary", "form", "as", "array", ".", "If", "start", "and", "end", "unspecified", "they", "will", "be", "inferred", "from", "the", "data", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L326-L346
22,957
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex._tobinarray_really
def _tobinarray_really(self, start, end, pad, size): """Return binary array.""" if pad is None: pad = self.padding bin = array('B') if self._buf == {} and None in (start, end): return bin if size is not None and size <= 0: raise ValueError("tobinarray: wrong value for size") start, end = self._get_start_end(start, end, size) for i in range_g(start, end+1): bin.append(self._buf.get(i, pad)) return bin
python
def _tobinarray_really(self, start, end, pad, size): if pad is None: pad = self.padding bin = array('B') if self._buf == {} and None in (start, end): return bin if size is not None and size <= 0: raise ValueError("tobinarray: wrong value for size") start, end = self._get_start_end(start, end, size) for i in range_g(start, end+1): bin.append(self._buf.get(i, pad)) return bin
[ "def", "_tobinarray_really", "(", "self", ",", "start", ",", "end", ",", "pad", ",", "size", ")", ":", "if", "pad", "is", "None", ":", "pad", "=", "self", ".", "padding", "bin", "=", "array", "(", "'B'", ")", "if", "self", ".", "_buf", "==", "{",...
Return binary array.
[ "Return", "binary", "array", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L348-L360
22,958
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.tobinstr
def tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert to binary form and return as binary string. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return bytes string of binary data. ''' if not isinstance(pad, _DeprecatedParam): print ("IntelHex.tobinstr: 'pad' parameter is deprecated.") if pad is not None: print ("Please, use IntelHex.padding attribute instead.") else: print ("Please, don't pass it explicitly.") print ("Use syntax like this: ih.tobinstr(start=xxx, end=yyy, size=zzz)") else: pad = None return self._tobinstr_really(start, end, pad, size)
python
def tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert to binary form and return as binary string. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return bytes string of binary data. ''' if not isinstance(pad, _DeprecatedParam): print ("IntelHex.tobinstr: 'pad' parameter is deprecated.") if pad is not None: print ("Please, use IntelHex.padding attribute instead.") else: print ("Please, don't pass it explicitly.") print ("Use syntax like this: ih.tobinstr(start=xxx, end=yyy, size=zzz)") else: pad = None return self._tobinstr_really(start, end, pad, size)
[ "def", "tobinstr", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "pad", "=", "_DEPRECATED", ",", "size", "=", "None", ")", ":", "if", "not", "isinstance", "(", "pad", ",", "_DeprecatedParam", ")", ":", "print", "(", "\"IntelHe...
Convert to binary form and return as binary string. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return bytes string of binary data.
[ "Convert", "to", "binary", "form", "and", "return", "as", "binary", "string", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L362-L381
22,959
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.tobinfile
def tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None): '''Convert to binary and write to file. @param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. ''' if not isinstance(pad, _DeprecatedParam): print ("IntelHex.tobinfile: 'pad' parameter is deprecated.") if pad is not None: print ("Please, use IntelHex.padding attribute instead.") else: print ("Please, don't pass it explicitly.") print ("Use syntax like this: ih.tobinfile(start=xxx, end=yyy, size=zzz)") else: pad = None if getattr(fobj, "write", None) is None: fobj = open(fobj, "wb") close_fd = True else: close_fd = False fobj.write(self._tobinstr_really(start, end, pad, size)) if close_fd: fobj.close()
python
def tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None): '''Convert to binary and write to file. @param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. ''' if not isinstance(pad, _DeprecatedParam): print ("IntelHex.tobinfile: 'pad' parameter is deprecated.") if pad is not None: print ("Please, use IntelHex.padding attribute instead.") else: print ("Please, don't pass it explicitly.") print ("Use syntax like this: ih.tobinfile(start=xxx, end=yyy, size=zzz)") else: pad = None if getattr(fobj, "write", None) is None: fobj = open(fobj, "wb") close_fd = True else: close_fd = False fobj.write(self._tobinstr_really(start, end, pad, size)) if close_fd: fobj.close()
[ "def", "tobinfile", "(", "self", ",", "fobj", ",", "start", "=", "None", ",", "end", "=", "None", ",", "pad", "=", "_DEPRECATED", ",", "size", "=", "None", ")", ":", "if", "not", "isinstance", "(", "pad", ",", "_DeprecatedParam", ")", ":", "print", ...
Convert to binary and write to file. @param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter.
[ "Convert", "to", "binary", "and", "write", "to", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L386-L415
22,960
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.todict
def todict(self): '''Convert to python dictionary. @return dict suitable for initializing another IntelHex object. ''' r = {} r.update(self._buf) if self.start_addr: r['start_addr'] = self.start_addr return r
python
def todict(self): '''Convert to python dictionary. @return dict suitable for initializing another IntelHex object. ''' r = {} r.update(self._buf) if self.start_addr: r['start_addr'] = self.start_addr return r
[ "def", "todict", "(", "self", ")", ":", "r", "=", "{", "}", "r", ".", "update", "(", "self", ".", "_buf", ")", "if", "self", ".", "start_addr", ":", "r", "[", "'start_addr'", "]", "=", "self", ".", "start_addr", "return", "r" ]
Convert to python dictionary. @return dict suitable for initializing another IntelHex object.
[ "Convert", "to", "python", "dictionary", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L417-L426
22,961
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.tofile
def tofile(self, fobj, format): """Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == 'hex': self.write_hex_file(fobj) elif format == 'bin': self.tobinfile(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format)
python
def tofile(self, fobj, format): if format == 'hex': self.write_hex_file(fobj) elif format == 'bin': self.tobinfile(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format)
[ "def", "tofile", "(", "self", ",", "fobj", ",", "format", ")", ":", "if", "format", "==", "'hex'", ":", "self", ".", "write_hex_file", "(", "fobj", ")", "elif", "format", "==", "'bin'", ":", "self", ".", "tobinfile", "(", "fobj", ")", "else", ":", ...
Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin")
[ "Write", "data", "to", "hex", "or", "bin", "file", ".", "Preferred", "method", "over", "tobin", "or", "tohex", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L720-L732
22,962
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.gets
def gets(self, addr, length): """Get string of bytes from given address. If any entries are blank from addr through addr+length, a NotEnoughDataError exception will be raised. Padding is not used. """ a = array('B', asbytes('\0'*length)) try: for i in range_g(length): a[i] = self._buf[addr+i] except KeyError: raise NotEnoughDataError(address=addr, length=length) return array_tobytes(a)
python
def gets(self, addr, length): a = array('B', asbytes('\0'*length)) try: for i in range_g(length): a[i] = self._buf[addr+i] except KeyError: raise NotEnoughDataError(address=addr, length=length) return array_tobytes(a)
[ "def", "gets", "(", "self", ",", "addr", ",", "length", ")", ":", "a", "=", "array", "(", "'B'", ",", "asbytes", "(", "'\\0'", "*", "length", ")", ")", "try", ":", "for", "i", "in", "range_g", "(", "length", ")", ":", "a", "[", "i", "]", "=",...
Get string of bytes from given address. If any entries are blank from addr through addr+length, a NotEnoughDataError exception will be raised. Padding is not used.
[ "Get", "string", "of", "bytes", "from", "given", "address", ".", "If", "any", "entries", "are", "blank", "from", "addr", "through", "addr", "+", "length", "a", "NotEnoughDataError", "exception", "will", "be", "raised", ".", "Padding", "is", "not", "used", ...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L734-L745
22,963
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.puts
def puts(self, addr, s): """Put string of bytes at given address. Will overwrite any previous entries. """ a = array('B', asbytes(s)) for i in range_g(len(a)): self._buf[addr+i] = a[i]
python
def puts(self, addr, s): a = array('B', asbytes(s)) for i in range_g(len(a)): self._buf[addr+i] = a[i]
[ "def", "puts", "(", "self", ",", "addr", ",", "s", ")", ":", "a", "=", "array", "(", "'B'", ",", "asbytes", "(", "s", ")", ")", "for", "i", "in", "range_g", "(", "len", "(", "a", ")", ")", ":", "self", ".", "_buf", "[", "addr", "+", "i", ...
Put string of bytes at given address. Will overwrite any previous entries.
[ "Put", "string", "of", "bytes", "at", "given", "address", ".", "Will", "overwrite", "any", "previous", "entries", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L747-L753
22,964
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.getsz
def getsz(self, addr): """Get zero-terminated bytes string from given address. Will raise NotEnoughDataError exception if a hole is encountered before a 0. """ i = 0 try: while True: if self._buf[addr+i] == 0: break i += 1 except KeyError: raise NotEnoughDataError(msg=('Bad access at 0x%X: ' 'not enough data to read zero-terminated string') % addr) return self.gets(addr, i)
python
def getsz(self, addr): i = 0 try: while True: if self._buf[addr+i] == 0: break i += 1 except KeyError: raise NotEnoughDataError(msg=('Bad access at 0x%X: ' 'not enough data to read zero-terminated string') % addr) return self.gets(addr, i)
[ "def", "getsz", "(", "self", ",", "addr", ")", ":", "i", "=", "0", "try", ":", "while", "True", ":", "if", "self", ".", "_buf", "[", "addr", "+", "i", "]", "==", "0", ":", "break", "i", "+=", "1", "except", "KeyError", ":", "raise", "NotEnoughD...
Get zero-terminated bytes string from given address. Will raise NotEnoughDataError exception if a hole is encountered before a 0.
[ "Get", "zero", "-", "terminated", "bytes", "string", "from", "given", "address", ".", "Will", "raise", "NotEnoughDataError", "exception", "if", "a", "hole", "is", "encountered", "before", "a", "0", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L755-L768
22,965
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.putsz
def putsz(self, addr, s): """Put bytes string in object at addr and append terminating zero at end.""" self.puts(addr, s) self._buf[addr+len(s)] = 0
python
def putsz(self, addr, s): self.puts(addr, s) self._buf[addr+len(s)] = 0
[ "def", "putsz", "(", "self", ",", "addr", ",", "s", ")", ":", "self", ".", "puts", "(", "addr", ",", "s", ")", "self", ".", "_buf", "[", "addr", "+", "len", "(", "s", ")", "]", "=", "0" ]
Put bytes string in object at addr and append terminating zero at end.
[ "Put", "bytes", "string", "in", "object", "at", "addr", "and", "append", "terminating", "zero", "at", "end", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L770-L773
22,966
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.dump
def dump(self, tofile=None, width=16, withpadding=False): """Dump object content to specified file object or to stdout if None. Format is a hexdump with some header information at the beginning, addresses on the left, and data on right. @param tofile file-like object to dump to @param width number of bytes per line (i.e. columns) @param withpadding print padding character instead of '--' @raise ValueError if width is not a positive integer """ if not isinstance(width,int) or width < 1: raise ValueError('width must be a positive integer.') # The integer can be of float type - does not work with bit operations width = int(width) if tofile is None: tofile = sys.stdout # start addr possibly if self.start_addr is not None: cs = self.start_addr.get('CS') ip = self.start_addr.get('IP') eip = self.start_addr.get('EIP') if eip is not None and cs is None and ip is None: tofile.write('EIP = 0x%08X\n' % eip) elif eip is None and cs is not None and ip is not None: tofile.write('CS = 0x%04X, IP = 0x%04X\n' % (cs, ip)) else: tofile.write('start_addr = %r\n' % start_addr) # actual data addresses = dict_keys(self._buf) if addresses: addresses.sort() minaddr = addresses[0] maxaddr = addresses[-1] startaddr = (minaddr // width) * width endaddr = ((maxaddr // width) + 1) * width maxdigits = max(len(hex(endaddr)) - 2, 4) # Less 2 to exclude '0x' templa = '%%0%dX' % maxdigits rangewidth = range_l(width) if withpadding: pad = self.padding else: pad = None for i in range_g(startaddr, endaddr, width): tofile.write(templa % i) tofile.write(' ') s = [] for j in rangewidth: x = self._buf.get(i+j, pad) if x is not None: tofile.write(' %02X' % x) if 32 <= x < 127: # GNU less does not like 0x7F (128 decimal) so we'd better show it as dot s.append(chr(x)) else: s.append('.') else: tofile.write(' --') s.append(' ') tofile.write(' |' + ''.join(s) + '|\n')
python
def dump(self, tofile=None, width=16, withpadding=False): if not isinstance(width,int) or width < 1: raise ValueError('width must be a positive integer.') # The integer can be of float type - does not work with bit operations width = int(width) if tofile is None: tofile = sys.stdout # start addr possibly if self.start_addr is not None: cs = self.start_addr.get('CS') ip = self.start_addr.get('IP') eip = self.start_addr.get('EIP') if eip is not None and cs is None and ip is None: tofile.write('EIP = 0x%08X\n' % eip) elif eip is None and cs is not None and ip is not None: tofile.write('CS = 0x%04X, IP = 0x%04X\n' % (cs, ip)) else: tofile.write('start_addr = %r\n' % start_addr) # actual data addresses = dict_keys(self._buf) if addresses: addresses.sort() minaddr = addresses[0] maxaddr = addresses[-1] startaddr = (minaddr // width) * width endaddr = ((maxaddr // width) + 1) * width maxdigits = max(len(hex(endaddr)) - 2, 4) # Less 2 to exclude '0x' templa = '%%0%dX' % maxdigits rangewidth = range_l(width) if withpadding: pad = self.padding else: pad = None for i in range_g(startaddr, endaddr, width): tofile.write(templa % i) tofile.write(' ') s = [] for j in rangewidth: x = self._buf.get(i+j, pad) if x is not None: tofile.write(' %02X' % x) if 32 <= x < 127: # GNU less does not like 0x7F (128 decimal) so we'd better show it as dot s.append(chr(x)) else: s.append('.') else: tofile.write(' --') s.append(' ') tofile.write(' |' + ''.join(s) + '|\n')
[ "def", "dump", "(", "self", ",", "tofile", "=", "None", ",", "width", "=", "16", ",", "withpadding", "=", "False", ")", ":", "if", "not", "isinstance", "(", "width", ",", "int", ")", "or", "width", "<", "1", ":", "raise", "ValueError", "(", "'width...
Dump object content to specified file object or to stdout if None. Format is a hexdump with some header information at the beginning, addresses on the left, and data on right. @param tofile file-like object to dump to @param width number of bytes per line (i.e. columns) @param withpadding print padding character instead of '--' @raise ValueError if width is not a positive integer
[ "Dump", "object", "content", "to", "specified", "file", "object", "or", "to", "stdout", "if", "None", ".", "Format", "is", "a", "hexdump", "with", "some", "header", "information", "at", "the", "beginning", "addresses", "on", "the", "left", "and", "data", "...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L775-L834
22,967
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.segments
def segments(self): """Return a list of ordered tuple objects, representing contiguous occupied data addresses. Each tuple has a length of two and follows the semantics of the range and xrange objects. The second entry of the tuple is always an integer greater than the first entry. """ addresses = self.addresses() if not addresses: return [] elif len(addresses) == 1: return([(addresses[0], addresses[0]+1)]) adjacent_differences = [(b - a) for (a, b) in zip(addresses[:-1], addresses[1:])] breaks = [i for (i, x) in enumerate(adjacent_differences) if x > 1] endings = [addresses[b] for b in breaks] endings.append(addresses[-1]) beginings = [addresses[b+1] for b in breaks] beginings.insert(0, addresses[0]) return [(a, b+1) for (a, b) in zip(beginings, endings)]
python
def segments(self): addresses = self.addresses() if not addresses: return [] elif len(addresses) == 1: return([(addresses[0], addresses[0]+1)]) adjacent_differences = [(b - a) for (a, b) in zip(addresses[:-1], addresses[1:])] breaks = [i for (i, x) in enumerate(adjacent_differences) if x > 1] endings = [addresses[b] for b in breaks] endings.append(addresses[-1]) beginings = [addresses[b+1] for b in breaks] beginings.insert(0, addresses[0]) return [(a, b+1) for (a, b) in zip(beginings, endings)]
[ "def", "segments", "(", "self", ")", ":", "addresses", "=", "self", ".", "addresses", "(", ")", "if", "not", "addresses", ":", "return", "[", "]", "elif", "len", "(", "addresses", ")", "==", "1", ":", "return", "(", "[", "(", "addresses", "[", "0",...
Return a list of ordered tuple objects, representing contiguous occupied data addresses. Each tuple has a length of two and follows the semantics of the range and xrange objects. The second entry of the tuple is always an integer greater than the first entry.
[ "Return", "a", "list", "of", "ordered", "tuple", "objects", "representing", "contiguous", "occupied", "data", "addresses", ".", "Each", "tuple", "has", "a", "length", "of", "two", "and", "follows", "the", "semantics", "of", "the", "range", "and", "xrange", "...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L884-L900
22,968
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
IntelHex.get_memory_size
def get_memory_size(self): """Returns the approximate memory footprint for data.""" n = sys.getsizeof(self) n += sys.getsizeof(self.padding) n += total_size(self.start_addr) n += total_size(self._buf) n += sys.getsizeof(self._offset) return n
python
def get_memory_size(self): n = sys.getsizeof(self) n += sys.getsizeof(self.padding) n += total_size(self.start_addr) n += total_size(self._buf) n += sys.getsizeof(self._offset) return n
[ "def", "get_memory_size", "(", "self", ")", ":", "n", "=", "sys", ".", "getsizeof", "(", "self", ")", "n", "+=", "sys", ".", "getsizeof", "(", "self", ".", "padding", ")", "n", "+=", "total_size", "(", "self", ".", "start_addr", ")", "n", "+=", "to...
Returns the approximate memory footprint for data.
[ "Returns", "the", "approximate", "memory", "footprint", "for", "data", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L902-L909
22,969
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
Record._from_bytes
def _from_bytes(bytes): """Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String representation of one HEX record """ assert len(bytes) >= 4 # calculate checksum s = (-sum(bytes)) & 0x0FF bin = array('B', bytes + [s]) return ':' + asstr(hexlify(array_tobytes(bin))).upper()
python
def _from_bytes(bytes): assert len(bytes) >= 4 # calculate checksum s = (-sum(bytes)) & 0x0FF bin = array('B', bytes + [s]) return ':' + asstr(hexlify(array_tobytes(bin))).upper()
[ "def", "_from_bytes", "(", "bytes", ")", ":", "assert", "len", "(", "bytes", ")", ">=", "4", "# calculate checksum", "s", "=", "(", "-", "sum", "(", "bytes", ")", ")", "&", "0x0FF", "bin", "=", "array", "(", "'B'", ",", "bytes", "+", "[", "s", "]...
Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String representation of one HEX record
[ "Takes", "a", "list", "of", "bytes", "computes", "the", "checksum", "and", "outputs", "the", "entire", "record", "as", "a", "string", ".", "bytes", "should", "be", "the", "hex", "record", "without", "the", "colon", "or", "final", "checksum", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L1130-L1142
22,970
iotile/coretools
iotilebuild/iotile/build/config/site_scons/release.py
create_release_settings_action
def create_release_settings_action(target, source, env): """Copy module_settings.json and add release and build information """ with open(str(source[0]), "r") as fileobj: settings = json.load(fileobj) settings['release'] = True settings['release_date'] = datetime.datetime.utcnow().isoformat() settings['dependency_versions'] = {} #Also insert the versions of every dependency that we used to build this component for dep in env['TILE'].dependencies: tile = IOTile(os.path.join('build', 'deps', dep['unique_id'])) settings['dependency_versions'][dep['unique_id']] = str(tile.parsed_version) with open(str(target[0]), "w") as fileobj: json.dump(settings, fileobj, indent=4)
python
def create_release_settings_action(target, source, env): with open(str(source[0]), "r") as fileobj: settings = json.load(fileobj) settings['release'] = True settings['release_date'] = datetime.datetime.utcnow().isoformat() settings['dependency_versions'] = {} #Also insert the versions of every dependency that we used to build this component for dep in env['TILE'].dependencies: tile = IOTile(os.path.join('build', 'deps', dep['unique_id'])) settings['dependency_versions'][dep['unique_id']] = str(tile.parsed_version) with open(str(target[0]), "w") as fileobj: json.dump(settings, fileobj, indent=4)
[ "def", "create_release_settings_action", "(", "target", ",", "source", ",", "env", ")", ":", "with", "open", "(", "str", "(", "source", "[", "0", "]", ")", ",", "\"r\"", ")", "as", "fileobj", ":", "settings", "=", "json", ".", "load", "(", "fileobj", ...
Copy module_settings.json and add release and build information
[ "Copy", "module_settings", ".", "json", "and", "add", "release", "and", "build", "information" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/release.py#L16-L34
22,971
iotile/coretools
iotilebuild/iotile/build/config/site_scons/release.py
copy_extra_files
def copy_extra_files(tile): """Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_products will be looked up with a ProductResolver and copied copied to the specified path in the output folder. There is not currently a way to specify what type of product is being resolved. The `short_name` given must be unique across all products from this component and its direct dependencies. """ env = Environment(tools=[]) outputbase = os.path.join('build', 'output') for src, dest in tile.settings.get('copy_files', {}).items(): outputfile = os.path.join(outputbase, dest) env.Command([outputfile], [src], Copy("$TARGET", "$SOURCE")) resolver = ProductResolver.Create() for src, dest in tile.settings.get('copy_products', {}).items(): prod = resolver.find_unique(None, src) outputfile = os.path.join(outputbase, dest) env.Command([outputfile], [prod.full_path], Copy("$TARGET", "$SOURCE"))
python
def copy_extra_files(tile): env = Environment(tools=[]) outputbase = os.path.join('build', 'output') for src, dest in tile.settings.get('copy_files', {}).items(): outputfile = os.path.join(outputbase, dest) env.Command([outputfile], [src], Copy("$TARGET", "$SOURCE")) resolver = ProductResolver.Create() for src, dest in tile.settings.get('copy_products', {}).items(): prod = resolver.find_unique(None, src) outputfile = os.path.join(outputbase, dest) env.Command([outputfile], [prod.full_path], Copy("$TARGET", "$SOURCE"))
[ "def", "copy_extra_files", "(", "tile", ")", ":", "env", "=", "Environment", "(", "tools", "=", "[", "]", ")", "outputbase", "=", "os", ".", "path", ".", "join", "(", "'build'", ",", "'output'", ")", "for", "src", ",", "dest", "in", "tile", ".", "s...
Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_products will be looked up with a ProductResolver and copied copied to the specified path in the output folder. There is not currently a way to specify what type of product is being resolved. The `short_name` given must be unique across all products from this component and its direct dependencies.
[ "Copy", "all", "files", "listed", "in", "a", "copy_files", "and", "copy_products", "section", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/release.py#L99-L125
22,972
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/masm.py
generate
def generate(env): """Add Builders and construction variables for masm to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) shared_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASPPAction) shared_obj.add_action(suffix, SCons.Defaults.ASPPAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) env['AS'] = 'ml' env['ASFLAGS'] = SCons.Util.CLVar('/nologo') env['ASPPFLAGS'] = '$ASFLAGS' env['ASCOM'] = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
python
def generate(env): static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) shared_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASPPAction) shared_obj.add_action(suffix, SCons.Defaults.ASPPAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) env['AS'] = 'ml' env['ASFLAGS'] = SCons.Util.CLVar('/nologo') env['ASPPFLAGS'] = '$ASFLAGS' env['ASCOM'] = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
[ "def", "generate", "(", "env", ")", ":", "static_obj", ",", "shared_obj", "=", "SCons", ".", "Tool", ".", "createObjBuilders", "(", "env", ")", "for", "suffix", "in", "ASSuffixes", ":", "static_obj", ".", "add_action", "(", "suffix", ",", "SCons", ".", "...
Add Builders and construction variables for masm to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "masm", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/masm.py#L47-L68
22,973
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/bench.py
median
def median(values): """Return median value for the list of values. @param values: list of values for processing. @return: median value. """ values.sort() n = int(len(values) / 2) return values[n]
python
def median(values): values.sort() n = int(len(values) / 2) return values[n]
[ "def", "median", "(", "values", ")", ":", "values", ".", "sort", "(", ")", "n", "=", "int", "(", "len", "(", "values", ")", "/", "2", ")", "return", "values", "[", "n", "]" ]
Return median value for the list of values. @param values: list of values for processing. @return: median value.
[ "Return", "median", "value", "for", "the", "list", "of", "values", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L45-L52
22,974
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/bench.py
time_coef
def time_coef(tc, nc, tb, nb): """Return time coefficient relative to base numbers. @param tc: current test time @param nc: current test data size @param tb: base test time @param nb: base test data size @return: time coef. """ tc = float(tc) nc = float(nc) tb = float(tb) nb = float(nb) q = (tc * nb) / (tb * nc) return q
python
def time_coef(tc, nc, tb, nb): tc = float(tc) nc = float(nc) tb = float(tb) nb = float(nb) q = (tc * nb) / (tb * nc) return q
[ "def", "time_coef", "(", "tc", ",", "nc", ",", "tb", ",", "nb", ")", ":", "tc", "=", "float", "(", "tc", ")", "nc", "=", "float", "(", "nc", ")", "tb", "=", "float", "(", "tb", ")", "nb", "=", "float", "(", "nb", ")", "q", "=", "(", "tc",...
Return time coefficient relative to base numbers. @param tc: current test time @param nc: current test data size @param tb: base test time @param nb: base test data size @return: time coef.
[ "Return", "time", "coefficient", "relative", "to", "base", "numbers", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L100-L113
22,975
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/bench.py
main
def main(argv=None): """Main function to run benchmarks. @param argv: command-line arguments. @return: exit code (0 is OK). """ import getopt # default values test_read = None test_write = None n = 3 # number of repeat if argv is None: argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, 'hn:rw', []) for o,a in opts: if o == '-h': print(HELP) return 0 elif o == '-n': n = int(a) elif o == '-r': test_read = True elif o == '-w': test_write = True if args: raise getopt.GetoptError('Arguments are not used.') except getopt.GetoptError: msg = sys.exc_info()[1] # current exception txt = str(msg) print(txt) return 1 if (test_read, test_write) == (None, None): test_read = test_write = True m = Measure(n, test_read, test_write) m.measure_all() m.print_report() return 0
python
def main(argv=None): import getopt # default values test_read = None test_write = None n = 3 # number of repeat if argv is None: argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, 'hn:rw', []) for o,a in opts: if o == '-h': print(HELP) return 0 elif o == '-n': n = int(a) elif o == '-r': test_read = True elif o == '-w': test_write = True if args: raise getopt.GetoptError('Arguments are not used.') except getopt.GetoptError: msg = sys.exc_info()[1] # current exception txt = str(msg) print(txt) return 1 if (test_read, test_write) == (None, None): test_read = test_write = True m = Measure(n, test_read, test_write) m.measure_all() m.print_report() return 0
[ "def", "main", "(", "argv", "=", "None", ")", ":", "import", "getopt", "# default values", "test_read", "=", "None", "test_write", "=", "None", "n", "=", "3", "# number of repeat", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", ...
Main function to run benchmarks. @param argv: command-line arguments. @return: exit code (0 is OK).
[ "Main", "function", "to", "run", "benchmarks", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L240-L284
22,976
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/bench.py
Measure.measure_one
def measure_one(self, data): """Do measuring of read and write operations. @param data: 3-tuple from get_test_data @return: (time readhex, time writehex) """ _unused, hexstr, ih = data tread, twrite = 0.0, 0.0 if self.read: tread = run_readtest_N_times(intelhex.IntelHex, hexstr, self.n)[0] if self.write: twrite = run_writetest_N_times(ih.write_hex_file, self.n)[0] return tread, twrite
python
def measure_one(self, data): _unused, hexstr, ih = data tread, twrite = 0.0, 0.0 if self.read: tread = run_readtest_N_times(intelhex.IntelHex, hexstr, self.n)[0] if self.write: twrite = run_writetest_N_times(ih.write_hex_file, self.n)[0] return tread, twrite
[ "def", "measure_one", "(", "self", ",", "data", ")", ":", "_unused", ",", "hexstr", ",", "ih", "=", "data", "tread", ",", "twrite", "=", "0.0", ",", "0.0", "if", "self", ".", "read", ":", "tread", "=", "run_readtest_N_times", "(", "intelhex", ".", "I...
Do measuring of read and write operations. @param data: 3-tuple from get_test_data @return: (time readhex, time writehex)
[ "Do", "measuring", "of", "read", "and", "write", "operations", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L174-L185
22,977
iotile/coretools
iotilecore/iotile/core/hw/auth/env_auth_provider.py
EnvAuthProvider._get_key
def _get_key(cls, device_id): """Attempt to get a user key from an environment variable """ var_name = "USER_KEY_{0:08X}".format(device_id) if var_name not in os.environ: raise NotFoundError("No user key could be found for devices", device_id=device_id, expected_variable_name=var_name) key_var = os.environ[var_name] if len(key_var) != 64: raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters", device_id=device_id, key_value=key_var) try: key = binascii.unhexlify(key_var) except ValueError: raise NotFoundError("User key in variable could not be decoded from hex", device_id=device_id, key_value=key_var) if len(key) != 32: raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters", device_id=device_id, key_value=key_var) return key
python
def _get_key(cls, device_id): var_name = "USER_KEY_{0:08X}".format(device_id) if var_name not in os.environ: raise NotFoundError("No user key could be found for devices", device_id=device_id, expected_variable_name=var_name) key_var = os.environ[var_name] if len(key_var) != 64: raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters", device_id=device_id, key_value=key_var) try: key = binascii.unhexlify(key_var) except ValueError: raise NotFoundError("User key in variable could not be decoded from hex", device_id=device_id, key_value=key_var) if len(key) != 32: raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters", device_id=device_id, key_value=key_var) return key
[ "def", "_get_key", "(", "cls", ",", "device_id", ")", ":", "var_name", "=", "\"USER_KEY_{0:08X}\"", ".", "format", "(", "device_id", ")", "if", "var_name", "not", "in", "os", ".", "environ", ":", "raise", "NotFoundError", "(", "\"No user key could be found for d...
Attempt to get a user key from an environment variable
[ "Attempt", "to", "get", "a", "user", "key", "from", "an", "environment", "variable" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/env_auth_provider.py#L23-L48
22,978
iotile/coretools
iotilecore/iotile/core/hw/auth/env_auth_provider.py
EnvAuthProvider.decrypt_report
def decrypt_report(self, device_id, root, data, **kwargs): """Decrypt a buffer of report data on behalf of a device. Args: device_id (int): The id of the device that we should encrypt for root (int): The root key type that should be used to generate the report data (bytearray): The data that we should decrypt **kwargs: There are additional specific keyword args that are required depending on the root key used. Typically, you must specify - report_id (int): The report id - sent_timestamp (int): The sent timestamp of the report These two bits of information are used to construct the per report signing and encryption key from the specific root key type. Returns: dict: The decrypted data and any associated metadata about the data. The data itself must always be a bytearray stored under the 'data' key, however additional keys may be present depending on the encryption method used. Raises: NotFoundError: If the auth provider is not able to decrypt the data. """ report_key = self._verify_derive_key(device_id, root, **kwargs) try: from Crypto.Cipher import AES import Crypto.Util.Counter except ImportError: raise NotFoundError ctr = Crypto.Util.Counter.new(128) # We use AES-128 for encryption encryptor = AES.new(bytes(report_key[:16]), AES.MODE_CTR, counter=ctr) decrypted = encryptor.decrypt(bytes(data)) return {'data': decrypted}
python
def decrypt_report(self, device_id, root, data, **kwargs): report_key = self._verify_derive_key(device_id, root, **kwargs) try: from Crypto.Cipher import AES import Crypto.Util.Counter except ImportError: raise NotFoundError ctr = Crypto.Util.Counter.new(128) # We use AES-128 for encryption encryptor = AES.new(bytes(report_key[:16]), AES.MODE_CTR, counter=ctr) decrypted = encryptor.decrypt(bytes(data)) return {'data': decrypted}
[ "def", "decrypt_report", "(", "self", ",", "device_id", ",", "root", ",", "data", ",", "*", "*", "kwargs", ")", ":", "report_key", "=", "self", ".", "_verify_derive_key", "(", "device_id", ",", "root", ",", "*", "*", "kwargs", ")", "try", ":", "from", ...
Decrypt a buffer of report data on behalf of a device. Args: device_id (int): The id of the device that we should encrypt for root (int): The root key type that should be used to generate the report data (bytearray): The data that we should decrypt **kwargs: There are additional specific keyword args that are required depending on the root key used. Typically, you must specify - report_id (int): The report id - sent_timestamp (int): The sent timestamp of the report These two bits of information are used to construct the per report signing and encryption key from the specific root key type. Returns: dict: The decrypted data and any associated metadata about the data. The data itself must always be a bytearray stored under the 'data' key, however additional keys may be present depending on the encryption method used. Raises: NotFoundError: If the auth provider is not able to decrypt the data.
[ "Decrypt", "a", "buffer", "of", "report", "data", "on", "behalf", "of", "a", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/env_auth_provider.py#L147-L186
22,979
iotile/coretools
iotilebuild/iotile/build/config/site_scons/utilities.py
join_path
def join_path(path): """If given a string, return it, otherwise combine a list into a string using os.path.join""" if isinstance(path, str): return path return os.path.join(*path)
python
def join_path(path): if isinstance(path, str): return path return os.path.join(*path)
[ "def", "join_path", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "str", ")", ":", "return", "path", "return", "os", ".", "path", ".", "join", "(", "*", "path", ")" ]
If given a string, return it, otherwise combine a list into a string using os.path.join
[ "If", "given", "a", "string", "return", "it", "otherwise", "combine", "a", "list", "into", "a", "string", "using", "os", ".", "path", ".", "join" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/utilities.py#L49-L55
22,980
iotile/coretools
iotilebuild/iotile/build/config/site_scons/utilities.py
build_defines
def build_defines(defines): """Build a list of `-D` directives to pass to the compiler. This will drop any definitions whose value is None so that you can get rid of a define from another architecture by setting its value to null in the `module_settings.json`. """ return ['-D"%s=%s"' % (x, str(y)) for x, y in defines.items() if y is not None]
python
def build_defines(defines): return ['-D"%s=%s"' % (x, str(y)) for x, y in defines.items() if y is not None]
[ "def", "build_defines", "(", "defines", ")", ":", "return", "[", "'-D\"%s=%s\"'", "%", "(", "x", ",", "str", "(", "y", ")", ")", "for", "x", ",", "y", "in", "defines", ".", "items", "(", ")", "if", "y", "is", "not", "None", "]" ]
Build a list of `-D` directives to pass to the compiler. This will drop any definitions whose value is None so that you can get rid of a define from another architecture by setting its value to null in the `module_settings.json`.
[ "Build", "a", "list", "of", "-", "D", "directives", "to", "pass", "to", "the", "compiler", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/utilities.py#L58-L66
22,981
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._open_interface
def _open_interface(self, conn_id, iface, callback): """Open an interface on this device Args: conn_id (int): the unique identifier for the connection iface (string): the interface name to open callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason) """ try: context = self.conns.get_context(conn_id) except ArgumentError: callback(conn_id, self.id, False, "Could not find connection information") return self.conns.begin_operation(conn_id, 'open_interface', callback, self.get_config('default_timeout')) topics = context['topics'] open_iface_message = {'key': context['key'], 'type': 'command', 'operation': 'open_interface', 'client': self.name, 'interface': iface} self.client.publish(topics.action, open_iface_message)
python
def _open_interface(self, conn_id, iface, callback): try: context = self.conns.get_context(conn_id) except ArgumentError: callback(conn_id, self.id, False, "Could not find connection information") return self.conns.begin_operation(conn_id, 'open_interface', callback, self.get_config('default_timeout')) topics = context['topics'] open_iface_message = {'key': context['key'], 'type': 'command', 'operation': 'open_interface', 'client': self.name, 'interface': iface} self.client.publish(topics.action, open_iface_message)
[ "def", "_open_interface", "(", "self", ",", "conn_id", ",", "iface", ",", "callback", ")", ":", "try", ":", "context", "=", "self", ".", "conns", ".", "get_context", "(", "conn_id", ")", "except", "ArgumentError", ":", "callback", "(", "conn_id", ",", "s...
Open an interface on this device Args: conn_id (int): the unique identifier for the connection iface (string): the interface name to open callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
[ "Open", "an", "interface", "on", "this", "device" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L259-L280
22,982
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter.stop_sync
def stop_sync(self): """Synchronously stop this adapter """ conn_ids = self.conns.get_connections() # If we have any open connections, try to close them here before shutting down for conn in list(conn_ids): try: self.disconnect_sync(conn) except HardwareError: pass self.client.disconnect() self.conns.stop()
python
def stop_sync(self): conn_ids = self.conns.get_connections() # If we have any open connections, try to close them here before shutting down for conn in list(conn_ids): try: self.disconnect_sync(conn) except HardwareError: pass self.client.disconnect() self.conns.stop()
[ "def", "stop_sync", "(", "self", ")", ":", "conn_ids", "=", "self", ".", "conns", ".", "get_connections", "(", ")", "# If we have any open connections, try to close them here before shutting down", "for", "conn", "in", "list", "(", "conn_ids", ")", ":", "try", ":", ...
Synchronously stop this adapter
[ "Synchronously", "stop", "this", "adapter" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L282-L296
22,983
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter.probe_async
def probe_async(self, callback): """Probe for visible devices connected to this DeviceAdapter. Args: callback (callable): A callback for when the probe operation has completed. callback should have signature callback(adapter_id, success, failure_reason) where: success: bool failure_reason: None if success is True, otherwise a reason for why we could not probe """ topics = MQTTTopicValidator(self.prefix) self.client.publish(topics.probe, {'type': 'command', 'operation': 'probe', 'client': self.name}) callback(self.id, True, None)
python
def probe_async(self, callback): topics = MQTTTopicValidator(self.prefix) self.client.publish(topics.probe, {'type': 'command', 'operation': 'probe', 'client': self.name}) callback(self.id, True, None)
[ "def", "probe_async", "(", "self", ",", "callback", ")", ":", "topics", "=", "MQTTTopicValidator", "(", "self", ".", "prefix", ")", "self", ".", "client", ".", "publish", "(", "topics", ".", "probe", ",", "{", "'type'", ":", "'command'", ",", "'operation...
Probe for visible devices connected to this DeviceAdapter. Args: callback (callable): A callback for when the probe operation has completed. callback should have signature callback(adapter_id, success, failure_reason) where: success: bool failure_reason: None if success is True, otherwise a reason for why we could not probe
[ "Probe", "for", "visible", "devices", "connected", "to", "this", "DeviceAdapter", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L298-L310
22,984
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter.periodic_callback
def periodic_callback(self): """Periodically help maintain adapter internal state """ while True: try: action = self._deferred.get(False) action() except queue.Empty: break except Exception: self._logger.exception('Exception in periodic callback')
python
def periodic_callback(self): while True: try: action = self._deferred.get(False) action() except queue.Empty: break except Exception: self._logger.exception('Exception in periodic callback')
[ "def", "periodic_callback", "(", "self", ")", ":", "while", "True", ":", "try", ":", "action", "=", "self", ".", "_deferred", ".", "get", "(", "False", ")", "action", "(", ")", "except", "queue", ".", "Empty", ":", "break", "except", "Exception", ":", ...
Periodically help maintain adapter internal state
[ "Periodically", "help", "maintain", "adapter", "internal", "state" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L312-L323
22,985
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._bind_topics
def _bind_topics(self, topics): """Subscribe to all the topics we need to communication with this device Args: topics (MQTTTopicValidator): The topic validator for this device that we are connecting to. """ # FIXME: Allow for these subscriptions to fail and clean up the previous ones # so that this function is atomic self.client.subscribe(topics.status, self._on_status_message) self.client.subscribe(topics.tracing, self._on_trace) self.client.subscribe(topics.streaming, self._on_report) self.client.subscribe(topics.response, self._on_response_message)
python
def _bind_topics(self, topics): # FIXME: Allow for these subscriptions to fail and clean up the previous ones # so that this function is atomic self.client.subscribe(topics.status, self._on_status_message) self.client.subscribe(topics.tracing, self._on_trace) self.client.subscribe(topics.streaming, self._on_report) self.client.subscribe(topics.response, self._on_response_message)
[ "def", "_bind_topics", "(", "self", ",", "topics", ")", ":", "# FIXME: Allow for these subscriptions to fail and clean up the previous ones", "# so that this function is atomic", "self", ".", "client", ".", "subscribe", "(", "topics", ".", "status", ",", "self", ".", "_on...
Subscribe to all the topics we need to communication with this device Args: topics (MQTTTopicValidator): The topic validator for this device that we are connecting to.
[ "Subscribe", "to", "all", "the", "topics", "we", "need", "to", "communication", "with", "this", "device" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L325-L339
22,986
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._unbind_topics
def _unbind_topics(self, topics): """Unsubscribe to all of the topics we needed for communication with device Args: topics (MQTTTopicValidator): The topic validator for this device that we have connected to. """ self.client.unsubscribe(topics.status) self.client.unsubscribe(topics.tracing) self.client.unsubscribe(topics.streaming) self.client.unsubscribe(topics.response)
python
def _unbind_topics(self, topics): self.client.unsubscribe(topics.status) self.client.unsubscribe(topics.tracing) self.client.unsubscribe(topics.streaming) self.client.unsubscribe(topics.response)
[ "def", "_unbind_topics", "(", "self", ",", "topics", ")", ":", "self", ".", "client", ".", "unsubscribe", "(", "topics", ".", "status", ")", "self", ".", "client", ".", "unsubscribe", "(", "topics", ".", "tracing", ")", "self", ".", "client", ".", "uns...
Unsubscribe to all of the topics we needed for communication with device Args: topics (MQTTTopicValidator): The topic validator for this device that we have connected to.
[ "Unsubscribe", "to", "all", "of", "the", "topics", "we", "needed", "for", "communication", "with", "device" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L341-L352
22,987
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._find_connection
def _find_connection(self, topic): """Attempt to find a connection id corresponding with a topic The device is found by assuming the topic ends in <slug>/[control|data]/channel Args: topic (string): The topic we received a message on Returns: int: The internal connect id (device slug) associated with this topic """ parts = topic.split('/') if len(parts) < 3: return None slug = parts[-3] return slug
python
def _find_connection(self, topic): parts = topic.split('/') if len(parts) < 3: return None slug = parts[-3] return slug
[ "def", "_find_connection", "(", "self", ",", "topic", ")", ":", "parts", "=", "topic", ".", "split", "(", "'/'", ")", "if", "len", "(", "parts", ")", "<", "3", ":", "return", "None", "slug", "=", "parts", "[", "-", "3", "]", "return", "slug" ]
Attempt to find a connection id corresponding with a topic The device is found by assuming the topic ends in <slug>/[control|data]/channel Args: topic (string): The topic we received a message on Returns: int: The internal connect id (device slug) associated with this topic
[ "Attempt", "to", "find", "a", "connection", "id", "corresponding", "with", "a", "topic" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L364-L381
22,988
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._on_report
def _on_report(self, sequence, topic, message): """Process a report received from a device. Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself """ try: conn_key = self._find_connection(topic) conn_id = self.conns.get_connection_id(conn_key) except ArgumentError: self._logger.warn("Dropping report message that does not correspond with a known connection, topic=%s", topic) return try: rep_msg = messages.ReportNotification.verify(message) serialized_report = {} serialized_report['report_format'] = rep_msg['report_format'] serialized_report['encoded_report'] = rep_msg['report'] serialized_report['received_time'] = datetime.datetime.strptime(rep_msg['received_time'].encode().decode(), "%Y%m%dT%H:%M:%S.%fZ") report = self.report_parser.deserialize_report(serialized_report) self._trigger_callback('on_report', conn_id, report) except Exception: self._logger.exception("Error processing report conn_id=%d", conn_id)
python
def _on_report(self, sequence, topic, message): try: conn_key = self._find_connection(topic) conn_id = self.conns.get_connection_id(conn_key) except ArgumentError: self._logger.warn("Dropping report message that does not correspond with a known connection, topic=%s", topic) return try: rep_msg = messages.ReportNotification.verify(message) serialized_report = {} serialized_report['report_format'] = rep_msg['report_format'] serialized_report['encoded_report'] = rep_msg['report'] serialized_report['received_time'] = datetime.datetime.strptime(rep_msg['received_time'].encode().decode(), "%Y%m%dT%H:%M:%S.%fZ") report = self.report_parser.deserialize_report(serialized_report) self._trigger_callback('on_report', conn_id, report) except Exception: self._logger.exception("Error processing report conn_id=%d", conn_id)
[ "def", "_on_report", "(", "self", ",", "sequence", ",", "topic", ",", "message", ")", ":", "try", ":", "conn_key", "=", "self", ".", "_find_connection", "(", "topic", ")", "conn_id", "=", "self", ".", "conns", ".", "get_connection_id", "(", "conn_key", "...
Process a report received from a device. Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself
[ "Process", "a", "report", "received", "from", "a", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L394-L421
22,989
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._on_trace
def _on_trace(self, sequence, topic, message): """Process a trace received from a device. Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself """ try: conn_key = self._find_connection(topic) conn_id = self.conns.get_connection_id(conn_key) except ArgumentError: self._logger.warn("Dropping trace message that does not correspond with a known connection, topic=%s", topic) return try: tracing = messages.TracingNotification.verify(message) self._trigger_callback('on_trace', conn_id, tracing['trace']) except Exception: self._logger.exception("Error processing trace conn_id=%d", conn_id)
python
def _on_trace(self, sequence, topic, message): try: conn_key = self._find_connection(topic) conn_id = self.conns.get_connection_id(conn_key) except ArgumentError: self._logger.warn("Dropping trace message that does not correspond with a known connection, topic=%s", topic) return try: tracing = messages.TracingNotification.verify(message) self._trigger_callback('on_trace', conn_id, tracing['trace']) except Exception: self._logger.exception("Error processing trace conn_id=%d", conn_id)
[ "def", "_on_trace", "(", "self", ",", "sequence", ",", "topic", ",", "message", ")", ":", "try", ":", "conn_key", "=", "self", ".", "_find_connection", "(", "topic", ")", "conn_id", "=", "self", ".", "conns", ".", "get_connection_id", "(", "conn_key", ")...
Process a trace received from a device. Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself
[ "Process", "a", "trace", "received", "from", "a", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L423-L443
22,990
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._on_status_message
def _on_status_message(self, sequence, topic, message): """Process a status message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself """ self._logger.debug("Received message on (topic=%s): %s" % (topic, message)) try: conn_key = self._find_connection(topic) except ArgumentError: self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message) return if messages.ConnectionResponse.matches(message): if self.name != message['client']: self._logger.debug("Connection response received for a different client, client=%s, name=%s", message['client'], self.name) return self.conns.finish_connection(conn_key, message['success'], message.get('failure_reason', None)) else: self._logger.warn("Dropping message that did not correspond with a known schema, message=%s", message)
python
def _on_status_message(self, sequence, topic, message): self._logger.debug("Received message on (topic=%s): %s" % (topic, message)) try: conn_key = self._find_connection(topic) except ArgumentError: self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message) return if messages.ConnectionResponse.matches(message): if self.name != message['client']: self._logger.debug("Connection response received for a different client, client=%s, name=%s", message['client'], self.name) return self.conns.finish_connection(conn_key, message['success'], message.get('failure_reason', None)) else: self._logger.warn("Dropping message that did not correspond with a known schema, message=%s", message)
[ "def", "_on_status_message", "(", "self", ",", "sequence", ",", "topic", ",", "message", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Received message on (topic=%s): %s\"", "%", "(", "topic", ",", "message", ")", ")", "try", ":", "conn_key", "=", ...
Process a status message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself
[ "Process", "a", "status", "message", "received" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L445-L469
22,991
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._on_response_message
def _on_response_message(self, sequence, topic, message): """Process a response message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself """ try: conn_key = self._find_connection(topic) context = self.conns.get_context(conn_key) except ArgumentError: self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message) return if 'client' in message and message['client'] != self.name: self._logger.debug("Dropping message that is for another client %s, we are %s", message['client'], self.name) if messages.DisconnectionResponse.matches(message): self.conns.finish_disconnection(conn_key, message['success'], message.get('failure_reason', None)) elif messages.OpenInterfaceResponse.matches(message): self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None)) elif messages.RPCResponse.matches(message): rpc_message = messages.RPCResponse.verify(message) self.conns.finish_operation(conn_key, rpc_message['success'], rpc_message.get('failure_reason', None), rpc_message.get('status', None), rpc_message.get('payload', None)) elif messages.ProgressNotification.matches(message): progress_callback = context.get('progress_callback', None) if progress_callback is not None: progress_callback(message['done_count'], message['total_count']) elif messages.ScriptResponse.matches(message): if 'progress_callback' in context: del context['progress_callback'] self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None)) elif messages.DisconnectionNotification.matches(message): try: conn_key = self._find_connection(topic) conn_id = self.conns.get_connection_id(conn_key) except ArgumentError: self._logger.warn("Dropping disconnect notification that does not correspond with a known connection, topic=%s", topic) return self.conns.unexpected_disconnect(conn_key) self._trigger_callback('on_disconnect', self.id, conn_id) else: self._logger.warn("Invalid response message received, message=%s", message)
python
def _on_response_message(self, sequence, topic, message): try: conn_key = self._find_connection(topic) context = self.conns.get_context(conn_key) except ArgumentError: self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message) return if 'client' in message and message['client'] != self.name: self._logger.debug("Dropping message that is for another client %s, we are %s", message['client'], self.name) if messages.DisconnectionResponse.matches(message): self.conns.finish_disconnection(conn_key, message['success'], message.get('failure_reason', None)) elif messages.OpenInterfaceResponse.matches(message): self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None)) elif messages.RPCResponse.matches(message): rpc_message = messages.RPCResponse.verify(message) self.conns.finish_operation(conn_key, rpc_message['success'], rpc_message.get('failure_reason', None), rpc_message.get('status', None), rpc_message.get('payload', None)) elif messages.ProgressNotification.matches(message): progress_callback = context.get('progress_callback', None) if progress_callback is not None: progress_callback(message['done_count'], message['total_count']) elif messages.ScriptResponse.matches(message): if 'progress_callback' in context: del context['progress_callback'] self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None)) elif messages.DisconnectionNotification.matches(message): try: conn_key = self._find_connection(topic) conn_id = self.conns.get_connection_id(conn_key) except ArgumentError: self._logger.warn("Dropping disconnect notification that does not correspond with a known connection, topic=%s", topic) return self.conns.unexpected_disconnect(conn_key) self._trigger_callback('on_disconnect', self.id, conn_id) else: self._logger.warn("Invalid response message received, message=%s", message)
[ "def", "_on_response_message", "(", "self", ",", "sequence", ",", "topic", ",", "message", ")", ":", "try", ":", "conn_key", "=", "self", ".", "_find_connection", "(", "topic", ")", "context", "=", "self", ".", "conns", ".", "get_context", "(", "conn_key",...
Process a response message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself
[ "Process", "a", "response", "message", "received" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L471-L517
22,992
iotile/coretools
iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py
write_output
def write_output(output, text=True, output_path=None): """Write binary or text output to a file or stdout.""" if output_path is None and text is False: print("ERROR: You must specify an output file using -o/--output for binary output formats") sys.exit(1) if output_path is not None: if text: outfile = open(output_path, "w", encoding="utf-8") else: outfile = open(output_path, "wb") else: outfile = sys.stdout try: if text and isinstance(output, bytes): output = output.decode('utf-8') outfile.write(output) finally: if outfile is not sys.stdout: outfile.close()
python
def write_output(output, text=True, output_path=None): if output_path is None and text is False: print("ERROR: You must specify an output file using -o/--output for binary output formats") sys.exit(1) if output_path is not None: if text: outfile = open(output_path, "w", encoding="utf-8") else: outfile = open(output_path, "wb") else: outfile = sys.stdout try: if text and isinstance(output, bytes): output = output.decode('utf-8') outfile.write(output) finally: if outfile is not sys.stdout: outfile.close()
[ "def", "write_output", "(", "output", ",", "text", "=", "True", ",", "output_path", "=", "None", ")", ":", "if", "output_path", "is", "None", "and", "text", "is", "False", ":", "print", "(", "\"ERROR: You must specify an output file using -o/--output for binary outp...
Write binary or text output to a file or stdout.
[ "Write", "binary", "or", "text", "output", "to", "a", "file", "or", "stdout", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py#L23-L45
22,993
iotile/coretools
iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py
main
def main(): """Main entry point for iotile-sgcompile.""" arg_parser = build_args() args = arg_parser.parse_args() model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(args.sensor_graph) if args.format == u'ast': write_output(parser.dump_tree(), True, args.output) sys.exit(0) parser.compile(model) if not args.disable_optimizer: opt = SensorGraphOptimizer() opt.optimize(parser.sensor_graph, model=model) if args.format == u'nodes': output = u'\n'.join(parser.sensor_graph.dump_nodes()) + u'\n' write_output(output, True, args.output) else: if args.format not in KNOWN_FORMATS: print("Unknown output format: {}".format(args.format)) sys.exit(1) output_format = KNOWN_FORMATS[args.format] output = output_format.format(parser.sensor_graph) write_output(output, output_format.text, args.output)
python
def main(): arg_parser = build_args() args = arg_parser.parse_args() model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(args.sensor_graph) if args.format == u'ast': write_output(parser.dump_tree(), True, args.output) sys.exit(0) parser.compile(model) if not args.disable_optimizer: opt = SensorGraphOptimizer() opt.optimize(parser.sensor_graph, model=model) if args.format == u'nodes': output = u'\n'.join(parser.sensor_graph.dump_nodes()) + u'\n' write_output(output, True, args.output) else: if args.format not in KNOWN_FORMATS: print("Unknown output format: {}".format(args.format)) sys.exit(1) output_format = KNOWN_FORMATS[args.format] output = output_format.format(parser.sensor_graph) write_output(output, output_format.text, args.output)
[ "def", "main", "(", ")", ":", "arg_parser", "=", "build_args", "(", ")", "args", "=", "arg_parser", ".", "parse_args", "(", ")", "model", "=", "DeviceModel", "(", ")", "parser", "=", "SensorGraphFileParser", "(", ")", "parser", ".", "parse_file", "(", "a...
Main entry point for iotile-sgcompile.
[ "Main", "entry", "point", "for", "iotile", "-", "sgcompile", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py#L48-L80
22,994
iotile/coretools
iotilecore/iotile/core/utilities/typedargs/__init__.py
load_external_components
def load_external_components(typesys): """Load all external types defined by iotile plugins. This allows plugins to register their own types for type annotations and allows all registered iotile components that have associated type libraries to add themselves to the global type system. """ # Find all of the registered IOTile components and see if we need to add any type libraries for them from iotile.core.dev.registry import ComponentRegistry reg = ComponentRegistry() modules = reg.list_components() typelibs = reduce(lambda x, y: x+y, [reg.find_component(x).find_products('type_package') for x in modules], []) for lib in typelibs: if lib.endswith('.py'): lib = lib[:-3] typesys.load_external_types(lib)
python
def load_external_components(typesys): # Find all of the registered IOTile components and see if we need to add any type libraries for them from iotile.core.dev.registry import ComponentRegistry reg = ComponentRegistry() modules = reg.list_components() typelibs = reduce(lambda x, y: x+y, [reg.find_component(x).find_products('type_package') for x in modules], []) for lib in typelibs: if lib.endswith('.py'): lib = lib[:-3] typesys.load_external_types(lib)
[ "def", "load_external_components", "(", "typesys", ")", ":", "# Find all of the registered IOTile components and see if we need to add any type libraries for them", "from", "iotile", ".", "core", ".", "dev", ".", "registry", "import", "ComponentRegistry", "reg", "=", "Component...
Load all external types defined by iotile plugins. This allows plugins to register their own types for type annotations and allows all registered iotile components that have associated type libraries to add themselves to the global type system.
[ "Load", "all", "external", "types", "defined", "by", "iotile", "plugins", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/typedargs/__init__.py#L10-L29
22,995
iotile/coretools
iotileship/iotile/ship/recipe_manager.py
RecipeManager.add_recipe_folder
def add_recipe_folder(self, recipe_folder, whitelist=None): """Add all recipes inside a folder to this RecipeManager with an optional whitelist. Args: recipe_folder (str): The path to the folder of recipes to add. whitelist (list): Only include files whose os.basename() matches something on the whitelist """ if whitelist is not None: whitelist = set(whitelist) if recipe_folder == '': recipe_folder = '.' for yaml_file in [x for x in os.listdir(recipe_folder) if x.endswith('.yaml')]: if whitelist is not None and yaml_file not in whitelist: continue recipe = RecipeObject.FromFile(os.path.join(recipe_folder, yaml_file), self._recipe_actions, self._recipe_resources) self._recipes[recipe.name] = recipe for ship_file in [x for x in os.listdir(recipe_folder) if x.endswith('.ship')]: if whitelist is not None and ship_file not in whitelist: continue recipe = RecipeObject.FromArchive(os.path.join(recipe_folder, ship_file), self._recipe_actions, self._recipe_resources) self._recipes[recipe.name] = recipe
python
def add_recipe_folder(self, recipe_folder, whitelist=None): if whitelist is not None: whitelist = set(whitelist) if recipe_folder == '': recipe_folder = '.' for yaml_file in [x for x in os.listdir(recipe_folder) if x.endswith('.yaml')]: if whitelist is not None and yaml_file not in whitelist: continue recipe = RecipeObject.FromFile(os.path.join(recipe_folder, yaml_file), self._recipe_actions, self._recipe_resources) self._recipes[recipe.name] = recipe for ship_file in [x for x in os.listdir(recipe_folder) if x.endswith('.ship')]: if whitelist is not None and ship_file not in whitelist: continue recipe = RecipeObject.FromArchive(os.path.join(recipe_folder, ship_file), self._recipe_actions, self._recipe_resources) self._recipes[recipe.name] = recipe
[ "def", "add_recipe_folder", "(", "self", ",", "recipe_folder", ",", "whitelist", "=", "None", ")", ":", "if", "whitelist", "is", "not", "None", ":", "whitelist", "=", "set", "(", "whitelist", ")", "if", "recipe_folder", "==", "''", ":", "recipe_folder", "=...
Add all recipes inside a folder to this RecipeManager with an optional whitelist. Args: recipe_folder (str): The path to the folder of recipes to add. whitelist (list): Only include files whose os.basename() matches something on the whitelist
[ "Add", "all", "recipes", "inside", "a", "folder", "to", "this", "RecipeManager", "with", "an", "optional", "whitelist", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe_manager.py#L58-L85
22,996
iotile/coretools
iotileship/iotile/ship/recipe_manager.py
RecipeManager.add_recipe_actions
def add_recipe_actions(self, recipe_actions): """Add additional valid recipe actions to RecipeManager args: recipe_actions (list): List of tuples. First value of tuple is the classname, second value of tuple is RecipeAction Object """ for action_name, action in recipe_actions: self._recipe_actions[action_name] = action
python
def add_recipe_actions(self, recipe_actions): for action_name, action in recipe_actions: self._recipe_actions[action_name] = action
[ "def", "add_recipe_actions", "(", "self", ",", "recipe_actions", ")", ":", "for", "action_name", ",", "action", "in", "recipe_actions", ":", "self", ".", "_recipe_actions", "[", "action_name", "]", "=", "action" ]
Add additional valid recipe actions to RecipeManager args: recipe_actions (list): List of tuples. First value of tuple is the classname, second value of tuple is RecipeAction Object
[ "Add", "additional", "valid", "recipe", "actions", "to", "RecipeManager" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe_manager.py#L87-L96
22,997
iotile/coretools
iotileship/iotile/ship/recipe_manager.py
RecipeManager.get_recipe
def get_recipe(self, recipe_name): """Get a recipe by name. Args: recipe_name (str): The name of the recipe to fetch. Can be either the yaml file name or the name of the recipe. """ if recipe_name.endswith('.yaml'): recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name) else: recipe = self._recipes.get(recipe_name) if recipe is None: raise RecipeNotFoundError("Could not find recipe", recipe_name=recipe_name, known_recipes=[x for x in self._recipes.keys()]) return recipe
python
def get_recipe(self, recipe_name): if recipe_name.endswith('.yaml'): recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name) else: recipe = self._recipes.get(recipe_name) if recipe is None: raise RecipeNotFoundError("Could not find recipe", recipe_name=recipe_name, known_recipes=[x for x in self._recipes.keys()]) return recipe
[ "def", "get_recipe", "(", "self", ",", "recipe_name", ")", ":", "if", "recipe_name", ".", "endswith", "(", "'.yaml'", ")", ":", "recipe", "=", "self", ".", "_recipes", ".", "get", "(", "RecipeObject", ".", "FromFile", "(", "recipe_name", ",", "self", "."...
Get a recipe by name. Args: recipe_name (str): The name of the recipe to fetch. Can be either the yaml file name or the name of the recipe.
[ "Get", "a", "recipe", "by", "name", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe_manager.py#L98-L112
22,998
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/timeout.py
TimeoutInterval._check_time_backwards
def _check_time_backwards(self): """Make sure a clock reset didn't cause time to go backwards """ now = time.time() if now < self.start: self.start = now self.end = self.start + self.length
python
def _check_time_backwards(self): now = time.time() if now < self.start: self.start = now self.end = self.start + self.length
[ "def", "_check_time_backwards", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "now", "<", "self", ".", "start", ":", "self", ".", "start", "=", "now", "self", ".", "end", "=", "self", ".", "start", "+", "self", ".", "len...
Make sure a clock reset didn't cause time to go backwards
[ "Make", "sure", "a", "clock", "reset", "didn", "t", "cause", "time", "to", "go", "backwards" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/timeout.py#L27-L35
22,999
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/timeout.py
TimeoutInterval.expired
def expired(self): """Boolean property if this timeout has expired """ if self._expired_latch: return True self._check_time_backwards() if time.time() > self.end: self._expired_latch = True return True return False
python
def expired(self): if self._expired_latch: return True self._check_time_backwards() if time.time() > self.end: self._expired_latch = True return True return False
[ "def", "expired", "(", "self", ")", ":", "if", "self", ".", "_expired_latch", ":", "return", "True", "self", ".", "_check_time_backwards", "(", ")", "if", "time", ".", "time", "(", ")", ">", "self", ".", "end", ":", "self", ".", "_expired_latch", "=", ...
Boolean property if this timeout has expired
[ "Boolean", "property", "if", "this", "timeout", "has", "expired" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/timeout.py#L38-L50