id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,000 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink_background.py | JLinkControlThread.command | def command(self, cmd_name, callback, *args):
"""Run an asynchronous command.
Args:
cmd_name (int): The unique code for the command to execute.
callback (callable): The optional callback to run when the command finishes.
The signature should be callback(cmd_name, result, exception)
*args: Any arguments that are passed to the underlying command handler
"""
cmd = JLinkCommand(cmd_name, args, callback)
self._commands.put(cmd) | python | def command(self, cmd_name, callback, *args):
cmd = JLinkCommand(cmd_name, args, callback)
self._commands.put(cmd) | [
"def",
"command",
"(",
"self",
",",
"cmd_name",
",",
"callback",
",",
"*",
"args",
")",
":",
"cmd",
"=",
"JLinkCommand",
"(",
"cmd_name",
",",
"args",
",",
"callback",
")",
"self",
".",
"_commands",
".",
"put",
"(",
"cmd",
")"
] | Run an asynchronous command.
Args:
cmd_name (int): The unique code for the command to execute.
callback (callable): The optional callback to run when the command finishes.
The signature should be callback(cmd_name, result, exception)
*args: Any arguments that are passed to the underlying command handler | [
"Run",
"an",
"asynchronous",
"command",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L96-L106 |
23,001 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink_background.py | JLinkControlThread._send_rpc | def _send_rpc(self, device_info, control_info, address, rpc_id, payload, poll_interval, timeout):
"""Write and trigger an RPC."""
write_address, write_data = control_info.format_rpc(address, rpc_id, payload)
self._jlink.memory_write32(write_address, write_data)
self._trigger_rpc(device_info)
start = monotonic()
now = start
poll_address, poll_mask = control_info.poll_info()
while (now - start) < timeout:
time.sleep(poll_interval)
value, = self._jlink.memory_read8(poll_address, 1)
if value & poll_mask:
break
now = monotonic()
if (now - start) >= timeout:
raise HardwareError("Timeout waiting for RPC response", timeout=timeout, poll_interval=poll_interval)
read_address, read_length = control_info.response_info()
read_data = self._read_memory(read_address, read_length, join=True)
return control_info.format_response(read_data) | python | def _send_rpc(self, device_info, control_info, address, rpc_id, payload, poll_interval, timeout):
write_address, write_data = control_info.format_rpc(address, rpc_id, payload)
self._jlink.memory_write32(write_address, write_data)
self._trigger_rpc(device_info)
start = monotonic()
now = start
poll_address, poll_mask = control_info.poll_info()
while (now - start) < timeout:
time.sleep(poll_interval)
value, = self._jlink.memory_read8(poll_address, 1)
if value & poll_mask:
break
now = monotonic()
if (now - start) >= timeout:
raise HardwareError("Timeout waiting for RPC response", timeout=timeout, poll_interval=poll_interval)
read_address, read_length = control_info.response_info()
read_data = self._read_memory(read_address, read_length, join=True)
return control_info.format_response(read_data) | [
"def",
"_send_rpc",
"(",
"self",
",",
"device_info",
",",
"control_info",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"poll_interval",
",",
"timeout",
")",
":",
"write_address",
",",
"write_data",
"=",
"control_info",
".",
"format_rpc",
"(",
"address",... | Write and trigger an RPC. | [
"Write",
"and",
"trigger",
"an",
"RPC",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L112-L140 |
23,002 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink_background.py | JLinkControlThread._send_script | def _send_script(self, device_info, control_info, script, progress_callback):
"""Send a script by repeatedly sending it as a bunch of RPCs.
This function doesn't do anything special, it just sends a bunch of RPCs
with each chunk of the script until it's finished.
"""
for i in range(0, len(script), 20):
chunk = script[i:i+20]
self._send_rpc(device_info, control_info, 8, 0x2101, chunk, 0.001, 1.0)
if progress_callback is not None:
progress_callback(i + len(chunk), len(script)) | python | def _send_script(self, device_info, control_info, script, progress_callback):
for i in range(0, len(script), 20):
chunk = script[i:i+20]
self._send_rpc(device_info, control_info, 8, 0x2101, chunk, 0.001, 1.0)
if progress_callback is not None:
progress_callback(i + len(chunk), len(script)) | [
"def",
"_send_script",
"(",
"self",
",",
"device_info",
",",
"control_info",
",",
"script",
",",
"progress_callback",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"script",
")",
",",
"20",
")",
":",
"chunk",
"=",
"script",
"[",
"i"... | Send a script by repeatedly sending it as a bunch of RPCs.
This function doesn't do anything special, it just sends a bunch of RPCs
with each chunk of the script until it's finished. | [
"Send",
"a",
"script",
"by",
"repeatedly",
"sending",
"it",
"as",
"a",
"bunch",
"of",
"RPCs",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L142-L153 |
23,003 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink_background.py | JLinkControlThread._trigger_rpc | def _trigger_rpc(self, device_info):
"""Trigger an RPC in a device specific way."""
method = device_info.rpc_trigger
if isinstance(method, devices.RPCTriggerViaSWI):
self._jlink.memory_write32(method.register, [1 << method.bit])
else:
raise HardwareError("Unknown RPC trigger method", method=method) | python | def _trigger_rpc(self, device_info):
method = device_info.rpc_trigger
if isinstance(method, devices.RPCTriggerViaSWI):
self._jlink.memory_write32(method.register, [1 << method.bit])
else:
raise HardwareError("Unknown RPC trigger method", method=method) | [
"def",
"_trigger_rpc",
"(",
"self",
",",
"device_info",
")",
":",
"method",
"=",
"device_info",
".",
"rpc_trigger",
"if",
"isinstance",
"(",
"method",
",",
"devices",
".",
"RPCTriggerViaSWI",
")",
":",
"self",
".",
"_jlink",
".",
"memory_write32",
"(",
"meth... | Trigger an RPC in a device specific way. | [
"Trigger",
"an",
"RPC",
"in",
"a",
"device",
"specific",
"way",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L155-L162 |
23,004 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink_background.py | JLinkControlThread._find_control_structure | def _find_control_structure(self, start_address, search_length):
"""Find the control structure in RAM for this device.
Returns:
ControlStructure: The decoded contents of the shared memory control structure
used for communication with this IOTile device.
"""
words = self._read_memory(start_address, search_length, chunk_size=4, join=False)
found_offset = None
for i, word in enumerate(words):
if word == ControlStructure.CONTROL_MAGIC_1:
if (len(words) - i) < 4:
continue
if words[i + 1] == ControlStructure.CONTROL_MAGIC_2 and words[i + 2] == ControlStructure.CONTROL_MAGIC_3 and words[i + 3] == ControlStructure.CONTROL_MAGIC_4:
found_offset = i
break
if found_offset is None:
raise HardwareError("Could not find control structure magic value in search area")
struct_info = words[found_offset + 4]
_version, _flags, length = struct.unpack("<BBH", struct.pack("<L", struct_info))
if length % 4 != 0:
raise HardwareError("Invalid control structure length that was not a multiple of 4", length=length)
word_length = length // 4
control_data = struct.pack("<%dL" % word_length, *words[found_offset:found_offset + word_length])
logger.info("Found control stucture at address 0x%08X, word_length=%d", start_address + 4*found_offset, word_length)
return ControlStructure(start_address + 4*found_offset, control_data) | python | def _find_control_structure(self, start_address, search_length):
words = self._read_memory(start_address, search_length, chunk_size=4, join=False)
found_offset = None
for i, word in enumerate(words):
if word == ControlStructure.CONTROL_MAGIC_1:
if (len(words) - i) < 4:
continue
if words[i + 1] == ControlStructure.CONTROL_MAGIC_2 and words[i + 2] == ControlStructure.CONTROL_MAGIC_3 and words[i + 3] == ControlStructure.CONTROL_MAGIC_4:
found_offset = i
break
if found_offset is None:
raise HardwareError("Could not find control structure magic value in search area")
struct_info = words[found_offset + 4]
_version, _flags, length = struct.unpack("<BBH", struct.pack("<L", struct_info))
if length % 4 != 0:
raise HardwareError("Invalid control structure length that was not a multiple of 4", length=length)
word_length = length // 4
control_data = struct.pack("<%dL" % word_length, *words[found_offset:found_offset + word_length])
logger.info("Found control stucture at address 0x%08X, word_length=%d", start_address + 4*found_offset, word_length)
return ControlStructure(start_address + 4*found_offset, control_data) | [
"def",
"_find_control_structure",
"(",
"self",
",",
"start_address",
",",
"search_length",
")",
":",
"words",
"=",
"self",
".",
"_read_memory",
"(",
"start_address",
",",
"search_length",
",",
"chunk_size",
"=",
"4",
",",
"join",
"=",
"False",
")",
"found_offs... | Find the control structure in RAM for this device.
Returns:
ControlStructure: The decoded contents of the shared memory control structure
used for communication with this IOTile device. | [
"Find",
"the",
"control",
"structure",
"in",
"RAM",
"for",
"this",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L213-L247 |
23,005 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/jlink_background.py | JLinkControlThread._verify_control_structure | def _verify_control_structure(self, device_info, control_info=None):
"""Verify that a control structure is still valid or find one.
Returns:
ControlStructure: The verified or discovered control structure.
"""
if control_info is None:
control_info = self._find_control_structure(device_info.ram_start, device_info.ram_size)
#FIXME: Actually reread the memory here to verify that the control structure is still valid
return control_info | python | def _verify_control_structure(self, device_info, control_info=None):
if control_info is None:
control_info = self._find_control_structure(device_info.ram_start, device_info.ram_size)
#FIXME: Actually reread the memory here to verify that the control structure is still valid
return control_info | [
"def",
"_verify_control_structure",
"(",
"self",
",",
"device_info",
",",
"control_info",
"=",
"None",
")",
":",
"if",
"control_info",
"is",
"None",
":",
"control_info",
"=",
"self",
".",
"_find_control_structure",
"(",
"device_info",
".",
"ram_start",
",",
"dev... | Verify that a control structure is still valid or find one.
Returns:
ControlStructure: The verified or discovered control structure. | [
"Verify",
"that",
"a",
"control",
"structure",
"is",
"still",
"valid",
"or",
"find",
"one",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L249-L260 |
23,006 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/trace.py | SimulationTrace.save | def save(self, out_path):
"""Save an ascii representation of this simulation trace.
Args:
out_path (str): The output path to save this simulation trace.
"""
out = {
'selectors': [str(x) for x in self.selectors],
'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]
}
with open(out_path, "wb") as outfile:
json.dump(out, outfile, indent=4) | python | def save(self, out_path):
out = {
'selectors': [str(x) for x in self.selectors],
'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]
}
with open(out_path, "wb") as outfile:
json.dump(out, outfile, indent=4) | [
"def",
"save",
"(",
"self",
",",
"out_path",
")",
":",
"out",
"=",
"{",
"'selectors'",
":",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"selectors",
"]",
",",
"'trace'",
":",
"[",
"{",
"'stream'",
":",
"str",
"(",
"DataStream",
".",... | Save an ascii representation of this simulation trace.
Args:
out_path (str): The output path to save this simulation trace. | [
"Save",
"an",
"ascii",
"representation",
"of",
"this",
"simulation",
"trace",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/trace.py#L39-L52 |
23,007 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/trace.py | SimulationTrace.FromFile | def FromFile(cls, in_path):
"""Load a previously saved ascii representation of this simulation trace.
Args:
in_path (str): The path of the input file that we should load.
Returns:
SimulationTrace: The loaded trace object.
"""
with open(in_path, "rb") as infile:
in_data = json.load(infile)
if not ('trace', 'selectors') in in_data:
raise ArgumentError("Invalid trace file format", keys=in_data.keys(), expected=('trace', 'selectors'))
selectors = [DataStreamSelector.FromString(x) for x in in_data['selectors']]
readings = [IOTileReading(x['time'], DataStream.FromString(x['stream']).encode(), x['value'], reading_id=x['reading_id']) for x in in_data['trace']]
return SimulationTrace(readings, selectors=selectors) | python | def FromFile(cls, in_path):
with open(in_path, "rb") as infile:
in_data = json.load(infile)
if not ('trace', 'selectors') in in_data:
raise ArgumentError("Invalid trace file format", keys=in_data.keys(), expected=('trace', 'selectors'))
selectors = [DataStreamSelector.FromString(x) for x in in_data['selectors']]
readings = [IOTileReading(x['time'], DataStream.FromString(x['stream']).encode(), x['value'], reading_id=x['reading_id']) for x in in_data['trace']]
return SimulationTrace(readings, selectors=selectors) | [
"def",
"FromFile",
"(",
"cls",
",",
"in_path",
")",
":",
"with",
"open",
"(",
"in_path",
",",
"\"rb\"",
")",
"as",
"infile",
":",
"in_data",
"=",
"json",
".",
"load",
"(",
"infile",
")",
"if",
"not",
"(",
"'trace'",
",",
"'selectors'",
")",
"in",
"... | Load a previously saved ascii representation of this simulation trace.
Args:
in_path (str): The path of the input file that we should load.
Returns:
SimulationTrace: The loaded trace object. | [
"Load",
"a",
"previously",
"saved",
"ascii",
"representation",
"of",
"this",
"simulation",
"trace",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/trace.py#L55-L74 |
23,008 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | _on_scan | def _on_scan(_loop, adapter, _adapter_id, info, expiration_time):
"""Callback when a new device is seen."""
info['validity_period'] = expiration_time
adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info) | python | def _on_scan(_loop, adapter, _adapter_id, info, expiration_time):
info['validity_period'] = expiration_time
adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info) | [
"def",
"_on_scan",
"(",
"_loop",
",",
"adapter",
",",
"_adapter_id",
",",
"info",
",",
"expiration_time",
")",
":",
"info",
"[",
"'validity_period'",
"]",
"=",
"expiration_time",
"adapter",
".",
"notify_event_nowait",
"(",
"info",
".",
"get",
"(",
"'connection... | Callback when a new device is seen. | [
"Callback",
"when",
"a",
"new",
"device",
"is",
"seen",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L227-L231 |
23,009 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | _on_report | def _on_report(_loop, adapter, conn_id, report):
"""Callback when a report is received."""
conn_string = None
if conn_id is not None:
conn_string = adapter._get_property(conn_id, 'connection_string')
if isinstance(report, BroadcastReport):
adapter.notify_event_nowait(conn_string, 'broadcast', report)
elif conn_string is not None:
adapter.notify_event_nowait(conn_string, 'report', report)
else:
adapter._logger.debug("Dropping report with unknown conn_id=%s", conn_id) | python | def _on_report(_loop, adapter, conn_id, report):
conn_string = None
if conn_id is not None:
conn_string = adapter._get_property(conn_id, 'connection_string')
if isinstance(report, BroadcastReport):
adapter.notify_event_nowait(conn_string, 'broadcast', report)
elif conn_string is not None:
adapter.notify_event_nowait(conn_string, 'report', report)
else:
adapter._logger.debug("Dropping report with unknown conn_id=%s", conn_id) | [
"def",
"_on_report",
"(",
"_loop",
",",
"adapter",
",",
"conn_id",
",",
"report",
")",
":",
"conn_string",
"=",
"None",
"if",
"conn_id",
"is",
"not",
"None",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'"... | Callback when a report is received. | [
"Callback",
"when",
"a",
"report",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L234-L246 |
23,010 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | _on_trace | def _on_trace(_loop, adapter, conn_id, trace):
"""Callback when tracing data is received."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping trace data with unknown conn_id=%s", conn_id)
return
adapter.notify_event_nowait(conn_string, 'trace', trace) | python | def _on_trace(_loop, adapter, conn_id, trace):
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping trace data with unknown conn_id=%s", conn_id)
return
adapter.notify_event_nowait(conn_string, 'trace', trace) | [
"def",
"_on_trace",
"(",
"_loop",
",",
"adapter",
",",
"conn_id",
",",
"trace",
")",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'",
")",
"if",
"conn_string",
"is",
"None",
":",
"adapter",
".",
"_logger",... | Callback when tracing data is received. | [
"Callback",
"when",
"tracing",
"data",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L249-L257 |
23,011 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | _on_disconnect | def _on_disconnect(_loop, adapter, _adapter_id, conn_id):
"""Callback when a device disconnects unexpectedly."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping disconnect notification with unknown conn_id=%s", conn_id)
return
adapter._teardown_connection(conn_id, force=True)
event = dict(reason='no reason passed from legacy adapter', expected=False)
adapter.notify_event_nowait(conn_string, 'disconnection', event) | python | def _on_disconnect(_loop, adapter, _adapter_id, conn_id):
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping disconnect notification with unknown conn_id=%s", conn_id)
return
adapter._teardown_connection(conn_id, force=True)
event = dict(reason='no reason passed from legacy adapter', expected=False)
adapter.notify_event_nowait(conn_string, 'disconnection', event) | [
"def",
"_on_disconnect",
"(",
"_loop",
",",
"adapter",
",",
"_adapter_id",
",",
"conn_id",
")",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'",
")",
"if",
"conn_string",
"is",
"None",
":",
"adapter",
".",
... | Callback when a device disconnects unexpectedly. | [
"Callback",
"when",
"a",
"device",
"disconnects",
"unexpectedly",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L260-L270 |
23,012 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | _on_progress | def _on_progress(adapter, operation, conn_id, done, total):
"""Callback when progress is reported."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
return
adapter.notify_progress(conn_string, operation, done, total) | python | def _on_progress(adapter, operation, conn_id, done, total):
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
return
adapter.notify_progress(conn_string, operation, done, total) | [
"def",
"_on_progress",
"(",
"adapter",
",",
"operation",
",",
"conn_id",
",",
"done",
",",
"total",
")",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'",
")",
"if",
"conn_string",
"is",
"None",
":",
"retur... | Callback when progress is reported. | [
"Callback",
"when",
"progress",
"is",
"reported",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L273-L280 |
23,013 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | AsynchronousModernWrapper.start | async def start(self):
"""Start the device adapter.
See :meth:`AbstractDeviceAdapter.start`.
"""
self._loop.add_task(self._periodic_loop, name="periodic task for %s" % self._adapter.__class__.__name__,
parent=self._task)
self._adapter.add_callback('on_scan', functools.partial(_on_scan, self._loop, self))
self._adapter.add_callback('on_report', functools.partial(_on_report, self._loop, self))
self._adapter.add_callback('on_trace', functools.partial(_on_trace, self._loop, self))
self._adapter.add_callback('on_disconnect', functools.partial(_on_disconnect, self._loop, self)) | python | async def start(self):
self._loop.add_task(self._periodic_loop, name="periodic task for %s" % self._adapter.__class__.__name__,
parent=self._task)
self._adapter.add_callback('on_scan', functools.partial(_on_scan, self._loop, self))
self._adapter.add_callback('on_report', functools.partial(_on_report, self._loop, self))
self._adapter.add_callback('on_trace', functools.partial(_on_trace, self._loop, self))
self._adapter.add_callback('on_disconnect', functools.partial(_on_disconnect, self._loop, self)) | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_loop",
".",
"add_task",
"(",
"self",
".",
"_periodic_loop",
",",
"name",
"=",
"\"periodic task for %s\"",
"%",
"self",
".",
"_adapter",
".",
"__class__",
".",
"__name__",
",",
"parent",
"=",
... | Start the device adapter.
See :meth:`AbstractDeviceAdapter.start`. | [
"Start",
"the",
"device",
"adapter",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L74-L86 |
23,014 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | AsynchronousModernWrapper.stop | async def stop(self, _task=None):
"""Stop the device adapter.
See :meth:`AbstractDeviceAdapter.stop`.
"""
self._logger.info("Stopping adapter wrapper")
if self._task.stopped:
return
for task in self._task.subtasks:
await task.stop()
self._logger.debug("Stopping underlying adapter %s", self._adapter.__class__.__name__)
await self._execute(self._adapter.stop_sync) | python | async def stop(self, _task=None):
self._logger.info("Stopping adapter wrapper")
if self._task.stopped:
return
for task in self._task.subtasks:
await task.stop()
self._logger.debug("Stopping underlying adapter %s", self._adapter.__class__.__name__)
await self._execute(self._adapter.stop_sync) | [
"async",
"def",
"stop",
"(",
"self",
",",
"_task",
"=",
"None",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Stopping adapter wrapper\"",
")",
"if",
"self",
".",
"_task",
".",
"stopped",
":",
"return",
"for",
"task",
"in",
"self",
".",
"_task... | Stop the device adapter.
See :meth:`AbstractDeviceAdapter.stop`. | [
"Stop",
"the",
"device",
"adapter",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L88-L103 |
23,015 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | AsynchronousModernWrapper.probe | async def probe(self):
"""Probe for devices connected to this adapter.
See :meth:`AbstractDeviceAdapter.probe`.
"""
resp = await self._execute(self._adapter.probe_sync)
_raise_error(None, 'probe', resp) | python | async def probe(self):
resp = await self._execute(self._adapter.probe_sync)
_raise_error(None, 'probe', resp) | [
"async",
"def",
"probe",
"(",
"self",
")",
":",
"resp",
"=",
"await",
"self",
".",
"_execute",
"(",
"self",
".",
"_adapter",
".",
"probe_sync",
")",
"_raise_error",
"(",
"None",
",",
"'probe'",
",",
"resp",
")"
] | Probe for devices connected to this adapter.
See :meth:`AbstractDeviceAdapter.probe`. | [
"Probe",
"for",
"devices",
"connected",
"to",
"this",
"adapter",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L173-L180 |
23,016 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py | AsynchronousModernWrapper.send_script | async def send_script(self, conn_id, data):
"""Send a a script to a device.
See :meth:`AbstractDeviceAdapter.send_script`.
"""
progress_callback = functools.partial(_on_progress, self, 'script', conn_id)
resp = await self._execute(self._adapter.send_script_sync, conn_id, data, progress_callback)
_raise_error(conn_id, 'send_rpc', resp) | python | async def send_script(self, conn_id, data):
progress_callback = functools.partial(_on_progress, self, 'script', conn_id)
resp = await self._execute(self._adapter.send_script_sync, conn_id, data, progress_callback)
_raise_error(conn_id, 'send_rpc', resp) | [
"async",
"def",
"send_script",
"(",
"self",
",",
"conn_id",
",",
"data",
")",
":",
"progress_callback",
"=",
"functools",
".",
"partial",
"(",
"_on_progress",
",",
"self",
",",
"'script'",
",",
"conn_id",
")",
"resp",
"=",
"await",
"self",
".",
"_execute",... | Send a a script to a device.
See :meth:`AbstractDeviceAdapter.send_script`. | [
"Send",
"a",
"a",
"script",
"to",
"a",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L210-L219 |
23,017 | iotile/coretools | iotileship/iotile/ship/autobuild/ship_file.py | autobuild_shiparchive | def autobuild_shiparchive(src_file):
"""Create a ship file archive containing a yaml_file and its dependencies.
If yaml_file depends on any build products as external files, it must
be a jinja2 template that references the file using the find_product
filter so that we can figure out where those build products are going
and create the right dependency graph.
Args:
src_file (str): The path to the input yaml file template. This
file path must end .yaml.tpl and is rendered into a .yaml
file and then packaged into a .ship file along with any
products that are referenced in it.
"""
if not src_file.endswith('.tpl'):
raise BuildError("You must pass a .tpl file to autobuild_shiparchive", src_file=src_file)
env = Environment(tools=[])
family = ArchitectureGroup('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
#Parse through build_step products to see what needs to imported
custom_steps = []
for build_step in family.tile.find_products('build_step'):
full_file_name = build_step.split(":")[0]
basename = os.path.splitext(os.path.basename(full_file_name))[0]
folder = os.path.dirname(full_file_name)
fileobj, pathname, description = imp.find_module(basename, [folder])
mod = imp.load_module(basename, fileobj, pathname, description)
full_file_name, class_name = build_step.split(":")
custom_steps.append((class_name, getattr(mod, class_name)))
env['CUSTOM_STEPS'] = custom_steps
env["RESOLVER"] = resolver
base_name, tpl_name = _find_basename(src_file)
yaml_name = tpl_name[:-4]
ship_name = yaml_name[:-5] + ".ship"
output_dir = target.build_dirs()['output']
build_dir = os.path.join(target.build_dirs()['build'], base_name)
tpl_path = os.path.join(build_dir, tpl_name)
yaml_path = os.path.join(build_dir, yaml_name)
ship_path = os.path.join(build_dir, ship_name)
output_path = os.path.join(output_dir, ship_name)
# We want to build up all related files in
# <build_dir>/<ship archive_folder>/
# - First copy the template yaml over
# - Then render the template yaml
# - Then find all products referenced in the template yaml and copy them
# - over
# - Then build a .ship archive
# - Then copy that archive into output_dir
ship_deps = [yaml_path]
env.Command([tpl_path], [src_file], Copy("$TARGET", "$SOURCE"))
prod_deps = _find_product_dependencies(src_file, resolver)
env.Command([yaml_path], [tpl_path], action=Action(template_shipfile_action, "Rendering $TARGET"))
for prod in prod_deps:
dest_file = os.path.join(build_dir, prod.short_name)
ship_deps.append(dest_file)
env.Command([dest_file], [prod.full_path], Copy("$TARGET", "$SOURCE"))
env.Command([ship_path], [ship_deps], action=Action(create_shipfile, "Archiving Ship Recipe $TARGET"))
env.Command([output_path], [ship_path], Copy("$TARGET", "$SOURCE")) | python | def autobuild_shiparchive(src_file):
if not src_file.endswith('.tpl'):
raise BuildError("You must pass a .tpl file to autobuild_shiparchive", src_file=src_file)
env = Environment(tools=[])
family = ArchitectureGroup('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
#Parse through build_step products to see what needs to imported
custom_steps = []
for build_step in family.tile.find_products('build_step'):
full_file_name = build_step.split(":")[0]
basename = os.path.splitext(os.path.basename(full_file_name))[0]
folder = os.path.dirname(full_file_name)
fileobj, pathname, description = imp.find_module(basename, [folder])
mod = imp.load_module(basename, fileobj, pathname, description)
full_file_name, class_name = build_step.split(":")
custom_steps.append((class_name, getattr(mod, class_name)))
env['CUSTOM_STEPS'] = custom_steps
env["RESOLVER"] = resolver
base_name, tpl_name = _find_basename(src_file)
yaml_name = tpl_name[:-4]
ship_name = yaml_name[:-5] + ".ship"
output_dir = target.build_dirs()['output']
build_dir = os.path.join(target.build_dirs()['build'], base_name)
tpl_path = os.path.join(build_dir, tpl_name)
yaml_path = os.path.join(build_dir, yaml_name)
ship_path = os.path.join(build_dir, ship_name)
output_path = os.path.join(output_dir, ship_name)
# We want to build up all related files in
# <build_dir>/<ship archive_folder>/
# - First copy the template yaml over
# - Then render the template yaml
# - Then find all products referenced in the template yaml and copy them
# - over
# - Then build a .ship archive
# - Then copy that archive into output_dir
ship_deps = [yaml_path]
env.Command([tpl_path], [src_file], Copy("$TARGET", "$SOURCE"))
prod_deps = _find_product_dependencies(src_file, resolver)
env.Command([yaml_path], [tpl_path], action=Action(template_shipfile_action, "Rendering $TARGET"))
for prod in prod_deps:
dest_file = os.path.join(build_dir, prod.short_name)
ship_deps.append(dest_file)
env.Command([dest_file], [prod.full_path], Copy("$TARGET", "$SOURCE"))
env.Command([ship_path], [ship_deps], action=Action(create_shipfile, "Archiving Ship Recipe $TARGET"))
env.Command([output_path], [ship_path], Copy("$TARGET", "$SOURCE")) | [
"def",
"autobuild_shiparchive",
"(",
"src_file",
")",
":",
"if",
"not",
"src_file",
".",
"endswith",
"(",
"'.tpl'",
")",
":",
"raise",
"BuildError",
"(",
"\"You must pass a .tpl file to autobuild_shiparchive\"",
",",
"src_file",
"=",
"src_file",
")",
"env",
"=",
"... | Create a ship file archive containing a yaml_file and its dependencies.
If yaml_file depends on any build products as external files, it must
be a jinja2 template that references the file using the find_product
filter so that we can figure out where those build products are going
and create the right dependency graph.
Args:
src_file (str): The path to the input yaml file template. This
file path must end .yaml.tpl and is rendered into a .yaml
file and then packaged into a .ship file along with any
products that are referenced in it. | [
"Create",
"a",
"ship",
"file",
"archive",
"containing",
"a",
"yaml_file",
"and",
"its",
"dependencies",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/autobuild/ship_file.py#L15-L88 |
23,018 | iotile/coretools | iotileship/iotile/ship/autobuild/ship_file.py | create_shipfile | def create_shipfile(target, source, env):
"""Create a .ship file with all dependencies."""
source_dir = os.path.dirname(str(source[0]))
recipe_name = os.path.basename(str(source[0]))[:-5]
resman = RecipeManager()
resman.add_recipe_actions(env['CUSTOM_STEPS'])
resman.add_recipe_folder(source_dir, whitelist=[os.path.basename(str(source[0]))])
recipe = resman.get_recipe(recipe_name)
recipe.archive(str(target[0])) | python | def create_shipfile(target, source, env):
source_dir = os.path.dirname(str(source[0]))
recipe_name = os.path.basename(str(source[0]))[:-5]
resman = RecipeManager()
resman.add_recipe_actions(env['CUSTOM_STEPS'])
resman.add_recipe_folder(source_dir, whitelist=[os.path.basename(str(source[0]))])
recipe = resman.get_recipe(recipe_name)
recipe.archive(str(target[0])) | [
"def",
"create_shipfile",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"source_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
")",
"recipe_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"st... | Create a .ship file with all dependencies. | [
"Create",
"a",
".",
"ship",
"file",
"with",
"all",
"dependencies",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/autobuild/ship_file.py#L113-L125 |
23,019 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | SensorGraphSimulator.record_trace | def record_trace(self, selectors=None):
"""Record a trace of readings produced by this simulator.
This causes the property `self.trace` to be populated with a
SimulationTrace object that contains all of the readings that
are produced during the course of the simulation. Only readings
that respond to specific selectors are given.
You can pass whatever selectors you want in the optional selectors
argument. If you pass None, then the default behavior to trace
all of the output streams of the sensor graph, which are defined
as the streams that are selected by a DataStreamer object in the
sensor graph. This is typically what is meant by sensor graph
output.
You can inspect the current trace by looking at the trace
property. It will initially be an empty list and will be updated
with each call to step() or run() that results in new readings
responsive to the selectors you pick (or the graph streamers if
you did not explicitly pass a list of DataStreamSelector objects).
Args:
selectors (list of DataStreamSelector): The selectors to add watch
statements on to produce this trace. This is optional.
If it is not specified, a the streamers of the sensor
graph are used.
"""
if selectors is None:
selectors = [x.selector for x in self.sensor_graph.streamers]
self.trace = SimulationTrace(selectors=selectors)
for sel in selectors:
self.sensor_graph.sensor_log.watch(sel, self._on_trace_callback) | python | def record_trace(self, selectors=None):
if selectors is None:
selectors = [x.selector for x in self.sensor_graph.streamers]
self.trace = SimulationTrace(selectors=selectors)
for sel in selectors:
self.sensor_graph.sensor_log.watch(sel, self._on_trace_callback) | [
"def",
"record_trace",
"(",
"self",
",",
"selectors",
"=",
"None",
")",
":",
"if",
"selectors",
"is",
"None",
":",
"selectors",
"=",
"[",
"x",
".",
"selector",
"for",
"x",
"in",
"self",
".",
"sensor_graph",
".",
"streamers",
"]",
"self",
".",
"trace",
... | Record a trace of readings produced by this simulator.
This causes the property `self.trace` to be populated with a
SimulationTrace object that contains all of the readings that
are produced during the course of the simulation. Only readings
that respond to specific selectors are given.
You can pass whatever selectors you want in the optional selectors
argument. If you pass None, then the default behavior to trace
all of the output streams of the sensor graph, which are defined
as the streams that are selected by a DataStreamer object in the
sensor graph. This is typically what is meant by sensor graph
output.
You can inspect the current trace by looking at the trace
property. It will initially be an empty list and will be updated
with each call to step() or run() that results in new readings
responsive to the selectors you pick (or the graph streamers if
you did not explicitly pass a list of DataStreamSelector objects).
Args:
selectors (list of DataStreamSelector): The selectors to add watch
statements on to produce this trace. This is optional.
If it is not specified, a the streamers of the sensor
graph are used. | [
"Record",
"a",
"trace",
"of",
"readings",
"produced",
"by",
"this",
"simulator",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L56-L90 |
23,020 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | SensorGraphSimulator.step | def step(self, input_stream, value):
"""Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
value into
value (int): The reading value to push as an integer
"""
reading = IOTileReading(input_stream.encode(), self.tick_count, value)
self.sensor_graph.process_input(input_stream, reading, self.rpc_executor) | python | def step(self, input_stream, value):
reading = IOTileReading(input_stream.encode(), self.tick_count, value)
self.sensor_graph.process_input(input_stream, reading, self.rpc_executor) | [
"def",
"step",
"(",
"self",
",",
"input_stream",
",",
"value",
")",
":",
"reading",
"=",
"IOTileReading",
"(",
"input_stream",
".",
"encode",
"(",
")",
",",
"self",
".",
"tick_count",
",",
"value",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
... | Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
value into
value (int): The reading value to push as an integer | [
"Step",
"the",
"sensor",
"graph",
"through",
"one",
"since",
"input",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L95-L109 |
23,021 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | SensorGraphSimulator.run | def run(self, include_reset=True, accelerated=True):
"""Run this sensor graph until a stop condition is hit.
Multiple calls to this function are useful only if
there has been some change in the stop conditions that would
cause the second call to not exit immediately.
Args:
include_reset (bool): Start the sensor graph run with
a reset event to match what would happen when an
actual device powers on.
accelerated (bool): Whether to run this sensor graph as
fast as possible or to delay tick events to simulate
the actual passage of wall clock time.
"""
self._start_tick = self.tick_count
if self._check_stop_conditions(self.sensor_graph):
return
if include_reset:
pass # TODO: include a reset event here
# Process all stimuli that occur at the start of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != 0:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
while not self._check_stop_conditions(self.sensor_graph):
# Process one more one second tick
now = monotonic()
next_tick = now + 1.0
# To match what is done in actual hardware, we increment tick count so the first tick
# is 1.
self.tick_count += 1
# Process all stimuli that occur at this tick of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != self.tick_count:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
self._check_additional_ticks(self.tick_count)
if (self.tick_count % 10) == 0:
reading = IOTileReading(self.tick_count, system_tick.encode(), self.tick_count)
self.sensor_graph.process_input(system_tick, reading, self.rpc_executor)
# Every 10 seconds the battery voltage is reported in 16.16 fixed point format in volts
reading = IOTileReading(self.tick_count, battery_voltage.encode(), int(self.voltage * 65536))
self.sensor_graph.process_input(battery_voltage, reading, self.rpc_executor)
now = monotonic()
# If we are trying to execute this sensor graph in realtime, wait for
# the remaining slice of this tick.
if (not accelerated) and (now < next_tick):
time.sleep(next_tick - now) | python | def run(self, include_reset=True, accelerated=True):
self._start_tick = self.tick_count
if self._check_stop_conditions(self.sensor_graph):
return
if include_reset:
pass # TODO: include a reset event here
# Process all stimuli that occur at the start of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != 0:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
while not self._check_stop_conditions(self.sensor_graph):
# Process one more one second tick
now = monotonic()
next_tick = now + 1.0
# To match what is done in actual hardware, we increment tick count so the first tick
# is 1.
self.tick_count += 1
# Process all stimuli that occur at this tick of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != self.tick_count:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
self._check_additional_ticks(self.tick_count)
if (self.tick_count % 10) == 0:
reading = IOTileReading(self.tick_count, system_tick.encode(), self.tick_count)
self.sensor_graph.process_input(system_tick, reading, self.rpc_executor)
# Every 10 seconds the battery voltage is reported in 16.16 fixed point format in volts
reading = IOTileReading(self.tick_count, battery_voltage.encode(), int(self.voltage * 65536))
self.sensor_graph.process_input(battery_voltage, reading, self.rpc_executor)
now = monotonic()
# If we are trying to execute this sensor graph in realtime, wait for
# the remaining slice of this tick.
if (not accelerated) and (now < next_tick):
time.sleep(next_tick - now) | [
"def",
"run",
"(",
"self",
",",
"include_reset",
"=",
"True",
",",
"accelerated",
"=",
"True",
")",
":",
"self",
".",
"_start_tick",
"=",
"self",
".",
"tick_count",
"if",
"self",
".",
"_check_stop_conditions",
"(",
"self",
".",
"sensor_graph",
")",
":",
... | Run this sensor graph until a stop condition is hit.
Multiple calls to this function are useful only if
there has been some change in the stop conditions that would
cause the second call to not exit immediately.
Args:
include_reset (bool): Start the sensor graph run with
a reset event to match what would happen when an
actual device powers on.
accelerated (bool): Whether to run this sensor graph as
fast as possible or to delay tick events to simulate
the actual passage of wall clock time. | [
"Run",
"this",
"sensor",
"graph",
"until",
"a",
"stop",
"condition",
"is",
"hit",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L111-L183 |
23,022 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | SensorGraphSimulator._check_stop_conditions | def _check_stop_conditions(self, sensor_graph):
"""Check if any of our stop conditions are met.
Args:
sensor_graph (SensorGraph): The sensor graph we are currently simulating
Returns:
bool: True if we should stop the simulation
"""
for stop in self.stop_conditions:
if stop.should_stop(self.tick_count, self.tick_count - self._start_tick, sensor_graph):
return True
return False | python | def _check_stop_conditions(self, sensor_graph):
for stop in self.stop_conditions:
if stop.should_stop(self.tick_count, self.tick_count - self._start_tick, sensor_graph):
return True
return False | [
"def",
"_check_stop_conditions",
"(",
"self",
",",
"sensor_graph",
")",
":",
"for",
"stop",
"in",
"self",
".",
"stop_conditions",
":",
"if",
"stop",
".",
"should_stop",
"(",
"self",
".",
"tick_count",
",",
"self",
".",
"tick_count",
"-",
"self",
".",
"_sta... | Check if any of our stop conditions are met.
Args:
sensor_graph (SensorGraph): The sensor graph we are currently simulating
Returns:
bool: True if we should stop the simulation | [
"Check",
"if",
"any",
"of",
"our",
"stop",
"conditions",
"are",
"met",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L203-L217 |
23,023 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | SensorGraphSimulator.stimulus | def stimulus(self, stimulus):
"""Add a simulation stimulus at a given time.
A stimulus is a specific input given to the graph at a specific
time to a specific input stream. The format for specifying a
stimulus is:
[time: ][system ]input X = Y
where X and Y are integers.
This will cause the simulator to inject this input at the given time.
If you specify a time of 0 seconds, it will happen before the simulation
starts. Similarly, if you specify a time of 1 second it will also happen
before anything else since the simulations start with a tick value of 1.
The stimulus is injected before any other things happen at each new tick.
Args:
stimulus (str or SimulationStimulus): A prebuilt stimulus object or
a string description of the stimulus of the format:
[time: ][system ]input X = Y
where time is optional and defaults to 0 seconds if not specified.
Examples:
sim.stimulus('system input 10 = 15')
sim.stimulus('1 minute: input 1 = 5')
"""
if not isinstance(stimulus, SimulationStimulus):
stimulus = SimulationStimulus.FromString(stimulus)
self.stimuli.append(stimulus)
self.stimuli.sort(key=lambda x:x.time) | python | def stimulus(self, stimulus):
if not isinstance(stimulus, SimulationStimulus):
stimulus = SimulationStimulus.FromString(stimulus)
self.stimuli.append(stimulus)
self.stimuli.sort(key=lambda x:x.time) | [
"def",
"stimulus",
"(",
"self",
",",
"stimulus",
")",
":",
"if",
"not",
"isinstance",
"(",
"stimulus",
",",
"SimulationStimulus",
")",
":",
"stimulus",
"=",
"SimulationStimulus",
".",
"FromString",
"(",
"stimulus",
")",
"self",
".",
"stimuli",
".",
"append",... | Add a simulation stimulus at a given time.
A stimulus is a specific input given to the graph at a specific
time to a specific input stream. The format for specifying a
stimulus is:
[time: ][system ]input X = Y
where X and Y are integers.
This will cause the simulator to inject this input at the given time.
If you specify a time of 0 seconds, it will happen before the simulation
starts. Similarly, if you specify a time of 1 second it will also happen
before anything else since the simulations start with a tick value of 1.
The stimulus is injected before any other things happen at each new tick.
Args:
stimulus (str or SimulationStimulus): A prebuilt stimulus object or
a string description of the stimulus of the format:
[time: ][system ]input X = Y
where time is optional and defaults to 0 seconds if not specified.
Examples:
sim.stimulus('system input 10 = 15')
sim.stimulus('1 minute: input 1 = 5') | [
"Add",
"a",
"simulation",
"stimulus",
"at",
"a",
"given",
"time",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L219-L250 |
23,024 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | SensorGraphSimulator.stop_condition | def stop_condition(self, condition):
"""Add a stop condition to this simulation.
Stop conditions are specified as strings and parsed into
the appropriate internal structures.
Args:
condition (str): a string description of the stop condition
"""
# Try to parse this into a stop condition with each of our registered
# condition types
for cond_format in self._known_conditions:
try:
cond = cond_format.FromString(condition)
self.stop_conditions.append(cond)
return
except ArgumentError:
continue
raise ArgumentError("Stop condition could not be processed by any known StopCondition type", condition=condition, suggestion="It may be mistyped or otherwise invalid.") | python | def stop_condition(self, condition):
# Try to parse this into a stop condition with each of our registered
# condition types
for cond_format in self._known_conditions:
try:
cond = cond_format.FromString(condition)
self.stop_conditions.append(cond)
return
except ArgumentError:
continue
raise ArgumentError("Stop condition could not be processed by any known StopCondition type", condition=condition, suggestion="It may be mistyped or otherwise invalid.") | [
"def",
"stop_condition",
"(",
"self",
",",
"condition",
")",
":",
"# Try to parse this into a stop condition with each of our registered",
"# condition types",
"for",
"cond_format",
"in",
"self",
".",
"_known_conditions",
":",
"try",
":",
"cond",
"=",
"cond_format",
".",
... | Add a stop condition to this simulation.
Stop conditions are specified as strings and parsed into
the appropriate internal structures.
Args:
condition (str): a string description of the stop condition | [
"Add",
"a",
"stop",
"condition",
"to",
"this",
"simulation",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L252-L272 |
23,025 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.dump | def dump(self):
"""Serialize the state of this subsystem into a dict.
Returns:
dict: The serialized state
"""
walker = self.dump_walker
if walker is not None:
walker = walker.dump()
state = {
'storage': self.storage.dump(),
'dump_walker': walker,
'next_id': self.next_id
}
return state | python | def dump(self):
walker = self.dump_walker
if walker is not None:
walker = walker.dump()
state = {
'storage': self.storage.dump(),
'dump_walker': walker,
'next_id': self.next_id
}
return state | [
"def",
"dump",
"(",
"self",
")",
":",
"walker",
"=",
"self",
".",
"dump_walker",
"if",
"walker",
"is",
"not",
"None",
":",
"walker",
"=",
"walker",
".",
"dump",
"(",
")",
"state",
"=",
"{",
"'storage'",
":",
"self",
".",
"storage",
".",
"dump",
"("... | Serialize the state of this subsystem into a dict.
Returns:
dict: The serialized state | [
"Serialize",
"the",
"state",
"of",
"this",
"subsystem",
"into",
"a",
"dict",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L36-L53 |
23,026 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.clear | def clear(self, timestamp):
"""Clear all data from the RSL.
This pushes a single reading once we clear everything so that
we keep track of the highest ID that we have allocated to date.
This needs the current timestamp to be able to properly timestamp
the cleared storage reading that it pushes.
Args:
timestamp (int): The current timestamp to store with the
reading.
"""
self.storage.clear()
self.push(streams.DATA_CLEARED, timestamp, 1) | python | def clear(self, timestamp):
self.storage.clear()
self.push(streams.DATA_CLEARED, timestamp, 1) | [
"def",
"clear",
"(",
"self",
",",
"timestamp",
")",
":",
"self",
".",
"storage",
".",
"clear",
"(",
")",
"self",
".",
"push",
"(",
"streams",
".",
"DATA_CLEARED",
",",
"timestamp",
",",
"1",
")"
] | Clear all data from the RSL.
This pushes a single reading once we clear everything so that
we keep track of the highest ID that we have allocated to date.
This needs the current timestamp to be able to properly timestamp
the cleared storage reading that it pushes.
Args:
timestamp (int): The current timestamp to store with the
reading. | [
"Clear",
"all",
"data",
"from",
"the",
"RSL",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L86-L102 |
23,027 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.push | def push(self, stream_id, timestamp, value):
"""Push a value to a stream.
Args:
stream_id (int): The stream we want to push to.
timestamp (int): The raw timestamp of the value we want to
store.
value (int): The 32-bit integer value we want to push.
Returns:
int: Packed 32-bit error code.
"""
stream = DataStream.FromEncoded(stream_id)
reading = IOTileReading(stream_id, timestamp, value)
try:
self.storage.push(stream, reading)
return Error.NO_ERROR
except StorageFullError:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.RING_BUFFER_FULL) | python | def push(self, stream_id, timestamp, value):
stream = DataStream.FromEncoded(stream_id)
reading = IOTileReading(stream_id, timestamp, value)
try:
self.storage.push(stream, reading)
return Error.NO_ERROR
except StorageFullError:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.RING_BUFFER_FULL) | [
"def",
"push",
"(",
"self",
",",
"stream_id",
",",
"timestamp",
",",
"value",
")",
":",
"stream",
"=",
"DataStream",
".",
"FromEncoded",
"(",
"stream_id",
")",
"reading",
"=",
"IOTileReading",
"(",
"stream_id",
",",
"timestamp",
",",
"value",
")",
"try",
... | Push a value to a stream.
Args:
stream_id (int): The stream we want to push to.
timestamp (int): The raw timestamp of the value we want to
store.
value (int): The 32-bit integer value we want to push.
Returns:
int: Packed 32-bit error code. | [
"Push",
"a",
"value",
"to",
"a",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L142-L162 |
23,028 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.inspect_virtual | def inspect_virtual(self, stream_id):
"""Inspect the last value written into a virtual stream.
Args:
stream_id (int): The virtual stream was want to inspect.
Returns:
(int, int): An error code and the stream value.
"""
stream = DataStream.FromEncoded(stream_id)
if stream.buffered:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0]
try:
reading = self.storage.inspect_last(stream, only_allocated=True)
return [Error.NO_ERROR, reading.value]
except StreamEmptyError:
return [Error.NO_ERROR, 0]
except UnresolvedIdentifierError:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0] | python | def inspect_virtual(self, stream_id):
stream = DataStream.FromEncoded(stream_id)
if stream.buffered:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0]
try:
reading = self.storage.inspect_last(stream, only_allocated=True)
return [Error.NO_ERROR, reading.value]
except StreamEmptyError:
return [Error.NO_ERROR, 0]
except UnresolvedIdentifierError:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0] | [
"def",
"inspect_virtual",
"(",
"self",
",",
"stream_id",
")",
":",
"stream",
"=",
"DataStream",
".",
"FromEncoded",
"(",
"stream_id",
")",
"if",
"stream",
".",
"buffered",
":",
"return",
"[",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
... | Inspect the last value written into a virtual stream.
Args:
stream_id (int): The virtual stream was want to inspect.
Returns:
(int, int): An error code and the stream value. | [
"Inspect",
"the",
"last",
"value",
"written",
"into",
"a",
"virtual",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L164-L185 |
23,029 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.dump_begin | def dump_begin(self, selector_id):
"""Start dumping a stream.
Args:
selector_id (int): The buffered stream we want to dump.
Returns:
(int, int, int): Error code, second error code, number of available readings
"""
if self.dump_walker is not None:
self.storage.destroy_walker(self.dump_walker)
selector = DataStreamSelector.FromEncoded(selector_id)
self.dump_walker = self.storage.create_walker(selector, skip_all=False)
return Error.NO_ERROR, Error.NO_ERROR, self.dump_walker.count() | python | def dump_begin(self, selector_id):
if self.dump_walker is not None:
self.storage.destroy_walker(self.dump_walker)
selector = DataStreamSelector.FromEncoded(selector_id)
self.dump_walker = self.storage.create_walker(selector, skip_all=False)
return Error.NO_ERROR, Error.NO_ERROR, self.dump_walker.count() | [
"def",
"dump_begin",
"(",
"self",
",",
"selector_id",
")",
":",
"if",
"self",
".",
"dump_walker",
"is",
"not",
"None",
":",
"self",
".",
"storage",
".",
"destroy_walker",
"(",
"self",
".",
"dump_walker",
")",
"selector",
"=",
"DataStreamSelector",
".",
"Fr... | Start dumping a stream.
Args:
selector_id (int): The buffered stream we want to dump.
Returns:
(int, int, int): Error code, second error code, number of available readings | [
"Start",
"dumping",
"a",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L187-L203 |
23,030 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.dump_seek | def dump_seek(self, reading_id):
"""Seek the dump streamer to a given ID.
Returns:
(int, int, int): Two error codes and the count of remaining readings.
The first error code covers the seeking process.
The second error code covers the stream counting process (cannot fail)
The third item in the tuple is the number of readings left in the stream.
"""
if self.dump_walker is None:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED),
Error.NO_ERROR, 0)
try:
exact = self.dump_walker.seek(reading_id, target='id')
except UnresolvedIdentifierError:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS),
Error.NO_ERROR, 0)
error = Error.NO_ERROR
if not exact:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.ID_FOUND_FOR_ANOTHER_STREAM)
return (error, error.NO_ERROR, self.dump_walker.count()) | python | def dump_seek(self, reading_id):
if self.dump_walker is None:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED),
Error.NO_ERROR, 0)
try:
exact = self.dump_walker.seek(reading_id, target='id')
except UnresolvedIdentifierError:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS),
Error.NO_ERROR, 0)
error = Error.NO_ERROR
if not exact:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.ID_FOUND_FOR_ANOTHER_STREAM)
return (error, error.NO_ERROR, self.dump_walker.count()) | [
"def",
"dump_seek",
"(",
"self",
",",
"reading_id",
")",
":",
"if",
"self",
".",
"dump_walker",
"is",
"None",
":",
"return",
"(",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"STREAM_WALKER_NOT_INITIALIZED",
")",
",",
... | Seek the dump streamer to a given ID.
Returns:
(int, int, int): Two error codes and the count of remaining readings.
The first error code covers the seeking process.
The second error code covers the stream counting process (cannot fail)
The third item in the tuple is the number of readings left in the stream. | [
"Seek",
"the",
"dump",
"streamer",
"to",
"a",
"given",
"ID",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L205-L230 |
23,031 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.dump_next | def dump_next(self):
"""Dump the next reading from the stream.
Returns:
IOTileReading: The next reading or None if there isn't one
"""
if self.dump_walker is None:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED)
try:
return self.dump_walker.pop()
except StreamEmptyError:
return None | python | def dump_next(self):
if self.dump_walker is None:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED)
try:
return self.dump_walker.pop()
except StreamEmptyError:
return None | [
"def",
"dump_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"dump_walker",
"is",
"None",
":",
"return",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"STREAM_WALKER_NOT_INITIALIZED",
")",
"try",
":",
"return",
"self",... | Dump the next reading from the stream.
Returns:
IOTileReading: The next reading or None if there isn't one | [
"Dump",
"the",
"next",
"reading",
"from",
"the",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L232-L245 |
23,032 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | SensorLogSubsystem.highest_stored_id | def highest_stored_id(self):
"""Scan through the stored readings and report the highest stored id.
Returns:
int: The highest stored id.
"""
shared = [0]
def _keep_max(_i, reading):
if reading.reading_id > shared[0]:
shared[0] = reading.reading_id
self.engine.scan_storage('storage', _keep_max)
self.engine.scan_storage('streaming', _keep_max)
return shared[0] | python | def highest_stored_id(self):
shared = [0]
def _keep_max(_i, reading):
if reading.reading_id > shared[0]:
shared[0] = reading.reading_id
self.engine.scan_storage('storage', _keep_max)
self.engine.scan_storage('streaming', _keep_max)
return shared[0] | [
"def",
"highest_stored_id",
"(",
"self",
")",
":",
"shared",
"=",
"[",
"0",
"]",
"def",
"_keep_max",
"(",
"_i",
",",
"reading",
")",
":",
"if",
"reading",
".",
"reading_id",
">",
"shared",
"[",
"0",
"]",
":",
"shared",
"[",
"0",
"]",
"=",
"reading"... | Scan through the stored readings and report the highest stored id.
Returns:
int: The highest stored id. | [
"Scan",
"through",
"the",
"stored",
"readings",
"and",
"report",
"the",
"highest",
"stored",
"id",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L247-L262 |
23,033 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | RawSensorLogMixin.rsl_push_reading | def rsl_push_reading(self, value, stream_id):
"""Push a reading to the RSL directly."""
#FIXME: Fix this with timestamp from clock manager task
err = self.sensor_log.push(stream_id, 0, value)
return [err] | python | def rsl_push_reading(self, value, stream_id):
#FIXME: Fix this with timestamp from clock manager task
err = self.sensor_log.push(stream_id, 0, value)
return [err] | [
"def",
"rsl_push_reading",
"(",
"self",
",",
"value",
",",
"stream_id",
")",
":",
"#FIXME: Fix this with timestamp from clock manager task",
"err",
"=",
"self",
".",
"sensor_log",
".",
"push",
"(",
"stream_id",
",",
"0",
",",
"value",
")",
"return",
"[",
"err",
... | Push a reading to the RSL directly. | [
"Push",
"a",
"reading",
"to",
"the",
"RSL",
"directly",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L286-L291 |
23,034 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | RawSensorLogMixin.rsl_push_many_readings | def rsl_push_many_readings(self, value, count, stream_id):
"""Push many copies of a reading to the RSL."""
#FIXME: Fix this with timestamp from clock manager task
for i in range(1, count+1):
err = self.sensor_log.push(stream_id, 0, value)
if err != Error.NO_ERROR:
return [err, i]
return [Error.NO_ERROR, count] | python | def rsl_push_many_readings(self, value, count, stream_id):
#FIXME: Fix this with timestamp from clock manager task
for i in range(1, count+1):
err = self.sensor_log.push(stream_id, 0, value)
if err != Error.NO_ERROR:
return [err, i]
return [Error.NO_ERROR, count] | [
"def",
"rsl_push_many_readings",
"(",
"self",
",",
"value",
",",
"count",
",",
"stream_id",
")",
":",
"#FIXME: Fix this with timestamp from clock manager task",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"count",
"+",
"1",
")",
":",
"err",
"=",
"self",
".",
"... | Push many copies of a reading to the RSL. | [
"Push",
"many",
"copies",
"of",
"a",
"reading",
"to",
"the",
"RSL",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L294-L304 |
23,035 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | RawSensorLogMixin.rsl_count_readings | def rsl_count_readings(self):
"""Count how many readings are stored in the RSL."""
storage, output = self.sensor_log.count()
return [Error.NO_ERROR, storage, output] | python | def rsl_count_readings(self):
storage, output = self.sensor_log.count()
return [Error.NO_ERROR, storage, output] | [
"def",
"rsl_count_readings",
"(",
"self",
")",
":",
"storage",
",",
"output",
"=",
"self",
".",
"sensor_log",
".",
"count",
"(",
")",
"return",
"[",
"Error",
".",
"NO_ERROR",
",",
"storage",
",",
"output",
"]"
] | Count how many readings are stored in the RSL. | [
"Count",
"how",
"many",
"readings",
"are",
"stored",
"in",
"the",
"RSL",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L307-L311 |
23,036 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | RawSensorLogMixin.rsl_dump_stream_begin | def rsl_dump_stream_begin(self, stream_id):
"""Begin dumping the contents of a stream."""
err, err2, count = self.sensor_log.dump_begin(stream_id)
#FIXME: Fix this with the uptime of the clock manager task
return [err, err2, count, 0] | python | def rsl_dump_stream_begin(self, stream_id):
err, err2, count = self.sensor_log.dump_begin(stream_id)
#FIXME: Fix this with the uptime of the clock manager task
return [err, err2, count, 0] | [
"def",
"rsl_dump_stream_begin",
"(",
"self",
",",
"stream_id",
")",
":",
"err",
",",
"err2",
",",
"count",
"=",
"self",
".",
"sensor_log",
".",
"dump_begin",
"(",
"stream_id",
")",
"#FIXME: Fix this with the uptime of the clock manager task",
"return",
"[",
"err",
... | Begin dumping the contents of a stream. | [
"Begin",
"dumping",
"the",
"contents",
"of",
"a",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L328-L334 |
23,037 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | RawSensorLogMixin.rsl_dump_stream_next | def rsl_dump_stream_next(self, output_format):
"""Dump the next reading from the output stream."""
timestamp = 0
stream_id = 0
value = 0
reading_id = 0
error = Error.NO_ERROR
reading = self.sensor_log.dump_next()
if reading is not None:
timestamp = reading.raw_time
stream_id = reading.stream
value = reading.value
reading_id = reading.reading_id
else:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS)
if output_format == 0:
return [struct.pack("<LLL", error, timestamp, value)]
elif output_format != 1:
raise ValueError("Output format other than 1 not yet supported")
return [struct.pack("<LLLLH2x", error, timestamp, value, reading_id, stream_id)] | python | def rsl_dump_stream_next(self, output_format):
timestamp = 0
stream_id = 0
value = 0
reading_id = 0
error = Error.NO_ERROR
reading = self.sensor_log.dump_next()
if reading is not None:
timestamp = reading.raw_time
stream_id = reading.stream
value = reading.value
reading_id = reading.reading_id
else:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS)
if output_format == 0:
return [struct.pack("<LLL", error, timestamp, value)]
elif output_format != 1:
raise ValueError("Output format other than 1 not yet supported")
return [struct.pack("<LLLLH2x", error, timestamp, value, reading_id, stream_id)] | [
"def",
"rsl_dump_stream_next",
"(",
"self",
",",
"output_format",
")",
":",
"timestamp",
"=",
"0",
"stream_id",
"=",
"0",
"value",
"=",
"0",
"reading_id",
"=",
"0",
"error",
"=",
"Error",
".",
"NO_ERROR",
"reading",
"=",
"self",
".",
"sensor_log",
".",
"... | Dump the next reading from the output stream. | [
"Dump",
"the",
"next",
"reading",
"from",
"the",
"output",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L343-L366 |
23,038 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | parse_size_name | def parse_size_name(type_name):
"""Calculate size and encoding from a type name.
This method takes a C-style type string like uint8_t[10] and returns
- the total size in bytes
- the unit size of each member (if it's an array)
- the scruct.{pack,unpack} format code for decoding the base type
- whether it is an array.
"""
if ' ' in type_name:
raise ArgumentError("There should not be a space in config variable type specifier", specifier=type_name)
variable = False
count = 1
base_type = type_name
if type_name[-1] == ']':
variable = True
start_index = type_name.find('[')
if start_index == -1:
raise ArgumentError("Could not find matching [ for ] character", specifier=type_name)
count = int(type_name[start_index+1:-1], 0)
base_type = type_name[:start_index]
matched_type = TYPE_CODES.get(base_type)
if matched_type is None:
raise ArgumentError("Could not find base type name", base_type=base_type, type_string=type_name)
base_size = struct.calcsize("<%s" % matched_type)
total_size = base_size*count
return total_size, base_size, matched_type, variable | python | def parse_size_name(type_name):
if ' ' in type_name:
raise ArgumentError("There should not be a space in config variable type specifier", specifier=type_name)
variable = False
count = 1
base_type = type_name
if type_name[-1] == ']':
variable = True
start_index = type_name.find('[')
if start_index == -1:
raise ArgumentError("Could not find matching [ for ] character", specifier=type_name)
count = int(type_name[start_index+1:-1], 0)
base_type = type_name[:start_index]
matched_type = TYPE_CODES.get(base_type)
if matched_type is None:
raise ArgumentError("Could not find base type name", base_type=base_type, type_string=type_name)
base_size = struct.calcsize("<%s" % matched_type)
total_size = base_size*count
return total_size, base_size, matched_type, variable | [
"def",
"parse_size_name",
"(",
"type_name",
")",
":",
"if",
"' '",
"in",
"type_name",
":",
"raise",
"ArgumentError",
"(",
"\"There should not be a space in config variable type specifier\"",
",",
"specifier",
"=",
"type_name",
")",
"variable",
"=",
"False",
"count",
"... | Calculate size and encoding from a type name.
This method takes a C-style type string like uint8_t[10] and returns
- the total size in bytes
- the unit size of each member (if it's an array)
- the scruct.{pack,unpack} format code for decoding the base type
- whether it is an array. | [
"Calculate",
"size",
"and",
"encoding",
"from",
"a",
"type",
"name",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L446-L479 |
23,039 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | ConfigDescriptor._validate_python_type | def _validate_python_type(self, python_type):
"""Validate the possible combinations of python_type and type_name."""
if python_type == 'bool':
if self.variable:
raise ArgumentError("You can only specify a bool python type on a scalar (non-array) type_name", type_name=self.type_name)
return
if python_type == 'string':
if not (self.variable and self.unit_size == 1):
raise ArgumentError("You can only pass a string python type on an array of 1-byte objects", type_name=self.type_name)
return
if python_type is not None:
raise ArgumentError("You can only declare a bool or string python type. Otherwise it must be passed as None", python_type=python_type) | python | def _validate_python_type(self, python_type):
if python_type == 'bool':
if self.variable:
raise ArgumentError("You can only specify a bool python type on a scalar (non-array) type_name", type_name=self.type_name)
return
if python_type == 'string':
if not (self.variable and self.unit_size == 1):
raise ArgumentError("You can only pass a string python type on an array of 1-byte objects", type_name=self.type_name)
return
if python_type is not None:
raise ArgumentError("You can only declare a bool or string python type. Otherwise it must be passed as None", python_type=python_type) | [
"def",
"_validate_python_type",
"(",
"self",
",",
"python_type",
")",
":",
"if",
"python_type",
"==",
"'bool'",
":",
"if",
"self",
".",
"variable",
":",
"raise",
"ArgumentError",
"(",
"\"You can only specify a bool python type on a scalar (non-array) type_name\"",
",",
... | Validate the possible combinations of python_type and type_name. | [
"Validate",
"the",
"possible",
"combinations",
"of",
"python_type",
"and",
"type_name",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L34-L50 |
23,040 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | ConfigDescriptor._convert_default_value | def _convert_default_value(self, default):
"""Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
If you pass a bytes object with python_type as True, do not null terminate
it, an additional null termination will be added.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
"""
if default is None:
return None
if isinstance(default, str):
if self.special_type == 'string':
return default.encode('utf-8') + b'\0'
raise DataError("You can only pass a unicode string if you are declaring a string type config variable", default=default)
if isinstance(default, (bytes, bytearray)):
if self.special_type == 'string' and isinstance(default, bytes):
default += b'\0'
return default
if isinstance(default, int):
default = [default]
format_string = "<" + (self.base_type*len(default))
return struct.pack(format_string, *default) | python | def _convert_default_value(self, default):
if default is None:
return None
if isinstance(default, str):
if self.special_type == 'string':
return default.encode('utf-8') + b'\0'
raise DataError("You can only pass a unicode string if you are declaring a string type config variable", default=default)
if isinstance(default, (bytes, bytearray)):
if self.special_type == 'string' and isinstance(default, bytes):
default += b'\0'
return default
if isinstance(default, int):
default = [default]
format_string = "<" + (self.base_type*len(default))
return struct.pack(format_string, *default) | [
"def",
"_convert_default_value",
"(",
"self",
",",
"default",
")",
":",
"if",
"default",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"default",
",",
"str",
")",
":",
"if",
"self",
".",
"special_type",
"==",
"'string'",
":",
"return",
"d... | Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
If you pass a bytes object with python_type as True, do not null terminate
it, an additional null termination will be added.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value. | [
"Convert",
"the",
"passed",
"default",
"value",
"to",
"binary",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L52-L86 |
23,041 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | ConfigDescriptor.clear | def clear(self):
"""Clear this config variable to its reset value."""
if self.default_value is None:
self.current_value = bytearray()
else:
self.current_value = bytearray(self.default_value) | python | def clear(self):
if self.default_value is None:
self.current_value = bytearray()
else:
self.current_value = bytearray(self.default_value) | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"self",
".",
"default_value",
"is",
"None",
":",
"self",
".",
"current_value",
"=",
"bytearray",
"(",
")",
"else",
":",
"self",
".",
"current_value",
"=",
"bytearray",
"(",
"self",
".",
"default_value",
")"
] | Clear this config variable to its reset value. | [
"Clear",
"this",
"config",
"variable",
"to",
"its",
"reset",
"value",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L88-L94 |
23,042 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | ConfigDescriptor.update_value | def update_value(self, offset, value):
"""Update the binary value currently stored for this config value.
Returns:
int: An opaque error code that can be returned from a set_config rpc
"""
if offset + len(value) > self.total_size:
return Error.INPUT_BUFFER_TOO_LONG
if len(self.current_value) < offset:
self.current_value += bytearray(offset - len(self.current_value))
if len(self.current_value) > offset:
self.current_value = self.current_value[:offset]
self.current_value += bytearray(value)
return 0 | python | def update_value(self, offset, value):
if offset + len(value) > self.total_size:
return Error.INPUT_BUFFER_TOO_LONG
if len(self.current_value) < offset:
self.current_value += bytearray(offset - len(self.current_value))
if len(self.current_value) > offset:
self.current_value = self.current_value[:offset]
self.current_value += bytearray(value)
return 0 | [
"def",
"update_value",
"(",
"self",
",",
"offset",
",",
"value",
")",
":",
"if",
"offset",
"+",
"len",
"(",
"value",
")",
">",
"self",
".",
"total_size",
":",
"return",
"Error",
".",
"INPUT_BUFFER_TOO_LONG",
"if",
"len",
"(",
"self",
".",
"current_value"... | Update the binary value currently stored for this config value.
Returns:
int: An opaque error code that can be returned from a set_config rpc | [
"Update",
"the",
"binary",
"value",
"currently",
"stored",
"for",
"this",
"config",
"value",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L96-L112 |
23,043 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | ConfigDescriptor.latch | def latch(self):
"""Convert the current value inside this config descriptor to a python object.
The conversion proceeds by mapping the given type name to a native
python class and performing the conversion. You can override what
python object is used as the destination class by passing a
python_type parameter to __init__.
The default mapping is:
- char (u)int8_t, (u)int16_t, (u)int32_t: int
- char[] (u)int8_t[], (u)int16_t[]0, u(int32_t): list of int
If you want to parse a char[] or uint8_t[] as a python string, it
needs to be null terminated and you should pass python_type='string'.
If you are declaring a scalar integer type and wish it to be decoded
as a bool, you can pass python_type='bool' to the constructor.
All integers are decoded as little-endian.
Returns:
object: The corresponding python object.
This will either be an int, list of int or string based on the
type_name specified and the optional python_type keyword argument
to the constructor.
Raises:
DataError: if the object cannot be converted to the desired type.
ArgumentError: if an invalid python_type was specified during construction.
"""
if len(self.current_value) == 0:
raise DataError("There was no data in a config variable during latching", name=self.name)
# Make sure the data ends on a unit boundary. This would have happened automatically
# in an actual device by the C runtime 0 padding out the storage area.
remaining = len(self.current_value) % self.unit_size
if remaining > 0:
self.current_value += bytearray(remaining)
if self.special_type == 'string':
if self.current_value[-1] != 0:
raise DataError("String type was specified by data did not end with a null byte", data=self.current_value, name=self.name)
return bytes(self.current_value[:-1]).decode('utf-8')
fmt_code = "<" + (self.base_type * (len(self.current_value) // self.unit_size))
data = struct.unpack(fmt_code, self.current_value)
if self.variable:
data = list(data)
else:
data = data[0]
if self.special_type == 'bool':
data = bool(data)
return data | python | def latch(self):
if len(self.current_value) == 0:
raise DataError("There was no data in a config variable during latching", name=self.name)
# Make sure the data ends on a unit boundary. This would have happened automatically
# in an actual device by the C runtime 0 padding out the storage area.
remaining = len(self.current_value) % self.unit_size
if remaining > 0:
self.current_value += bytearray(remaining)
if self.special_type == 'string':
if self.current_value[-1] != 0:
raise DataError("String type was specified by data did not end with a null byte", data=self.current_value, name=self.name)
return bytes(self.current_value[:-1]).decode('utf-8')
fmt_code = "<" + (self.base_type * (len(self.current_value) // self.unit_size))
data = struct.unpack(fmt_code, self.current_value)
if self.variable:
data = list(data)
else:
data = data[0]
if self.special_type == 'bool':
data = bool(data)
return data | [
"def",
"latch",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"current_value",
")",
"==",
"0",
":",
"raise",
"DataError",
"(",
"\"There was no data in a config variable during latching\"",
",",
"name",
"=",
"self",
".",
"name",
")",
"# Make sure the data... | Convert the current value inside this config descriptor to a python object.
The conversion proceeds by mapping the given type name to a native
python class and performing the conversion. You can override what
python object is used as the destination class by passing a
python_type parameter to __init__.
The default mapping is:
- char (u)int8_t, (u)int16_t, (u)int32_t: int
- char[] (u)int8_t[], (u)int16_t[]0, u(int32_t): list of int
If you want to parse a char[] or uint8_t[] as a python string, it
needs to be null terminated and you should pass python_type='string'.
If you are declaring a scalar integer type and wish it to be decoded
as a bool, you can pass python_type='bool' to the constructor.
All integers are decoded as little-endian.
Returns:
object: The corresponding python object.
This will either be an int, list of int or string based on the
type_name specified and the optional python_type keyword argument
to the constructor.
Raises:
DataError: if the object cannot be converted to the desired type.
ArgumentError: if an invalid python_type was specified during construction. | [
"Convert",
"the",
"current",
"value",
"inside",
"this",
"config",
"descriptor",
"to",
"a",
"python",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L114-L172 |
23,044 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | EmulatedTile.declare_config_variable | def declare_config_variable(self, name, config_id, type_name, default=None, convert=None): #pylint:disable=too-many-arguments;These are all necessary with sane defaults.
"""Declare a config variable that this emulated tile accepts.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
Args:
name (str): A user friendly name for this config variable so that it can
be printed nicely.
config_id (int): A 16-bit integer id number to identify the config variable.
type_name (str): An encoded type name that will be parsed by parse_size_name()
default (object): The default value if there is one. This should be a
python object that will be converted to binary according to the rules for
the config variable type specified in type_name.
convert (str): whether this variable should be converted to a
python string or bool rather than an int or a list of ints. You can
pass either 'bool', 'string' or None
"""
config = ConfigDescriptor(config_id, type_name, default, name=name, python_type=convert)
self._config_variables[config_id] = config | python | def declare_config_variable(self, name, config_id, type_name, default=None, convert=None): #pylint:disable=too-many-arguments;These are all necessary with sane defaults.
config = ConfigDescriptor(config_id, type_name, default, name=name, python_type=convert)
self._config_variables[config_id] = config | [
"def",
"declare_config_variable",
"(",
"self",
",",
"name",
",",
"config_id",
",",
"type_name",
",",
"default",
"=",
"None",
",",
"convert",
"=",
"None",
")",
":",
"#pylint:disable=too-many-arguments;These are all necessary with sane defaults.",
"config",
"=",
"ConfigDe... | Declare a config variable that this emulated tile accepts.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
Args:
name (str): A user friendly name for this config variable so that it can
be printed nicely.
config_id (int): A 16-bit integer id number to identify the config variable.
type_name (str): An encoded type name that will be parsed by parse_size_name()
default (object): The default value if there is one. This should be a
python object that will be converted to binary according to the rules for
the config variable type specified in type_name.
convert (str): whether this variable should be converted to a
python string or bool rather than an int or a list of ints. You can
pass either 'bool', 'string' or None | [
"Declare",
"a",
"config",
"variable",
"that",
"this",
"emulated",
"tile",
"accepts",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L230-L255 |
23,045 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | EmulatedTile.latch_config_variables | def latch_config_variables(self):
"""Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default values in the config
variables have been properly set otherwise DataError will be thrown.
Conceptually this method performs the operation that happens just
before a tile executive hands control to the tile application
firmware. It latches in the value of all config variables at that
point in time.
For convenience, this method does all necessary binary -> python
native object conversion so that you just get python objects back.
Returns:
dict: A dict of str -> object with the config variable values.
The keys in the dict will be the name passed to
`declare_config_variable`.
The values will be the python objects that result from calling
latch() on each config variable. Consult ConfigDescriptor.latch()
for documentation on how that method works.
"""
return {desc.name: desc.latch() for desc in self._config_variables.values()} | python | def latch_config_variables(self):
return {desc.name: desc.latch() for desc in self._config_variables.values()} | [
"def",
"latch_config_variables",
"(",
"self",
")",
":",
"return",
"{",
"desc",
".",
"name",
":",
"desc",
".",
"latch",
"(",
")",
"for",
"desc",
"in",
"self",
".",
"_config_variables",
".",
"values",
"(",
")",
"}"
] | Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default values in the config
variables have been properly set otherwise DataError will be thrown.
Conceptually this method performs the operation that happens just
before a tile executive hands control to the tile application
firmware. It latches in the value of all config variables at that
point in time.
For convenience, this method does all necessary binary -> python
native object conversion so that you just get python objects back.
Returns:
dict: A dict of str -> object with the config variable values.
The keys in the dict will be the name passed to
`declare_config_variable`.
The values will be the python objects that result from calling
latch() on each config variable. Consult ConfigDescriptor.latch()
for documentation on how that method works. | [
"Latch",
"the",
"current",
"value",
"of",
"all",
"config",
"variables",
"as",
"python",
"objects",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L268-L295 |
23,046 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | EmulatedTile.reset | async def reset(self):
"""Synchronously reset a tile.
This method must be called from the emulation loop and will
synchronously shut down all background tasks running this tile, clear
it to reset state and then restart the initialization background task.
"""
await self._device.emulator.stop_tasks(self.address)
self._handle_reset()
self._logger.info("Tile at address %d has reset itself.", self.address)
self._logger.info("Starting main task for tile at address %d", self.address)
self._device.emulator.add_task(self.address, self._reset_vector()) | python | async def reset(self):
await self._device.emulator.stop_tasks(self.address)
self._handle_reset()
self._logger.info("Tile at address %d has reset itself.", self.address)
self._logger.info("Starting main task for tile at address %d", self.address)
self._device.emulator.add_task(self.address, self._reset_vector()) | [
"async",
"def",
"reset",
"(",
"self",
")",
":",
"await",
"self",
".",
"_device",
".",
"emulator",
".",
"stop_tasks",
"(",
"self",
".",
"address",
")",
"self",
".",
"_handle_reset",
"(",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Tile at address %d... | Synchronously reset a tile.
This method must be called from the emulation loop and will
synchronously shut down all background tasks running this tile, clear
it to reset state and then restart the initialization background task. | [
"Synchronously",
"reset",
"a",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L359-L374 |
23,047 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | EmulatedTile.list_config_variables | def list_config_variables(self, offset):
"""List defined config variables up to 9 at a time."""
names = sorted(self._config_variables)
names = names[offset:offset + 9]
count = len(names)
if len(names) < 9:
names += [0]*(9 - count)
return [count] + names | python | def list_config_variables(self, offset):
names = sorted(self._config_variables)
names = names[offset:offset + 9]
count = len(names)
if len(names) < 9:
names += [0]*(9 - count)
return [count] + names | [
"def",
"list_config_variables",
"(",
"self",
",",
"offset",
")",
":",
"names",
"=",
"sorted",
"(",
"self",
".",
"_config_variables",
")",
"names",
"=",
"names",
"[",
"offset",
":",
"offset",
"+",
"9",
"]",
"count",
"=",
"len",
"(",
"names",
")",
"if",
... | List defined config variables up to 9 at a time. | [
"List",
"defined",
"config",
"variables",
"up",
"to",
"9",
"at",
"a",
"time",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L383-L393 |
23,048 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | EmulatedTile.describe_config_variable | def describe_config_variable(self, config_id):
"""Describe the config variable by its id."""
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, 0]
packed_size = config.total_size
packed_size |= int(config.variable) << 15
return [0, 0, 0, config_id, packed_size] | python | def describe_config_variable(self, config_id):
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, 0]
packed_size = config.total_size
packed_size |= int(config.variable) << 15
return [0, 0, 0, config_id, packed_size] | [
"def",
"describe_config_variable",
"(",
"self",
",",
"config_id",
")",
":",
"config",
"=",
"self",
".",
"_config_variables",
".",
"get",
"(",
"config_id",
")",
"if",
"config",
"is",
"None",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
"0",
"... | Describe the config variable by its id. | [
"Describe",
"the",
"config",
"variable",
"by",
"its",
"id",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L396-L406 |
23,049 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | EmulatedTile.set_config_variable | def set_config_variable(self, config_id, offset, value):
"""Set a chunk of the current config value's value."""
if self.initialized.is_set():
return [Error.STATE_CHANGE_AT_INVALID_TIME]
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY]
error = config.update_value(offset, value)
return [error] | python | def set_config_variable(self, config_id, offset, value):
if self.initialized.is_set():
return [Error.STATE_CHANGE_AT_INVALID_TIME]
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY]
error = config.update_value(offset, value)
return [error] | [
"def",
"set_config_variable",
"(",
"self",
",",
"config_id",
",",
"offset",
",",
"value",
")",
":",
"if",
"self",
".",
"initialized",
".",
"is_set",
"(",
")",
":",
"return",
"[",
"Error",
".",
"STATE_CHANGE_AT_INVALID_TIME",
"]",
"config",
"=",
"self",
"."... | Set a chunk of the current config value's value. | [
"Set",
"a",
"chunk",
"of",
"the",
"current",
"config",
"value",
"s",
"value",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L409-L420 |
23,050 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_tile.py | EmulatedTile.get_config_variable | def get_config_variable(self, config_id, offset):
"""Get a chunk of a config variable's value."""
config = self._config_variables.get(config_id)
if config is None:
return [b""]
return [bytes(config.current_value[offset:offset + 20])] | python | def get_config_variable(self, config_id, offset):
config = self._config_variables.get(config_id)
if config is None:
return [b""]
return [bytes(config.current_value[offset:offset + 20])] | [
"def",
"get_config_variable",
"(",
"self",
",",
"config_id",
",",
"offset",
")",
":",
"config",
"=",
"self",
".",
"_config_variables",
".",
"get",
"(",
"config_id",
")",
"if",
"config",
"is",
"None",
":",
"return",
"[",
"b\"\"",
"]",
"return",
"[",
"byte... | Get a chunk of a config variable's value. | [
"Get",
"a",
"chunk",
"of",
"a",
"config",
"variable",
"s",
"value",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L423-L430 |
23,051 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/legacy.py | DeviceAdapter.add_callback | def add_callback(self, name, func):
"""Add a callback when Device events happen
Args:
name (str): currently support 'on_scan' and 'on_disconnect'
func (callable): the function that should be called
"""
if name not in self.callbacks:
raise ValueError("Unknown callback name: %s" % name)
self.callbacks[name].add(func) | python | def add_callback(self, name, func):
if name not in self.callbacks:
raise ValueError("Unknown callback name: %s" % name)
self.callbacks[name].add(func) | [
"def",
"add_callback",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"callbacks",
":",
"raise",
"ValueError",
"(",
"\"Unknown callback name: %s\"",
"%",
"name",
")",
"self",
".",
"callbacks",
"[",
"name",
"]",
"... | Add a callback when Device events happen
Args:
name (str): currently support 'on_scan' and 'on_disconnect'
func (callable): the function that should be called | [
"Add",
"a",
"callback",
"when",
"Device",
"events",
"happen"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L120-L131 |
23,052 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/legacy.py | DeviceAdapter.connect_sync | def connect_sync(self, connection_id, connection_string):
"""Synchronously connect to a device
Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
"""
calldone = threading.Event()
results = {}
def connect_done(callback_connid, callback_adapterid, callback_success, failure_reason):
results['success'] = callback_success
results['failure_reason'] = failure_reason
calldone.set() # Be sure to set after all operations are done to prevent race condition
self.connect_async(connection_id, connection_string, connect_done)
calldone.wait()
return results | python | def connect_sync(self, connection_id, connection_string):
calldone = threading.Event()
results = {}
def connect_done(callback_connid, callback_adapterid, callback_success, failure_reason):
results['success'] = callback_success
results['failure_reason'] = failure_reason
calldone.set() # Be sure to set after all operations are done to prevent race condition
self.connect_async(connection_id, connection_string, connect_done)
calldone.wait()
return results | [
"def",
"connect_sync",
"(",
"self",
",",
"connection_id",
",",
"connection_string",
")",
":",
"calldone",
"=",
"threading",
".",
"Event",
"(",
")",
"results",
"=",
"{",
"}",
"def",
"connect_done",
"(",
"callback_connid",
",",
"callback_adapterid",
",",
"callba... | Synchronously connect to a device
Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed | [
"Synchronously",
"connect",
"to",
"a",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L151-L176 |
23,053 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/legacy.py | DeviceAdapter.disconnect_sync | def disconnect_sync(self, conn_id):
"""Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
"""
done = threading.Event()
result = {}
def disconnect_done(conn_id, adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.disconnect_async(conn_id, disconnect_done)
done.wait()
return result | python | def disconnect_sync(self, conn_id):
done = threading.Event()
result = {}
def disconnect_done(conn_id, adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.disconnect_async(conn_id, disconnect_done)
done.wait()
return result | [
"def",
"disconnect_sync",
"(",
"self",
",",
"conn_id",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"disconnect_done",
"(",
"conn_id",
",",
"adapter_id",
",",
"status",
",",
"reason",
")",
":",
"result",
"... | Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed | [
"Synchronously",
"disconnect",
"from",
"a",
"connected",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L189-L212 |
23,054 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/legacy.py | DeviceAdapter.probe_sync | def probe_sync(self):
"""Synchronously probe for devices on this adapter."""
done = threading.Event()
result = {}
def probe_done(adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.probe_async(probe_done)
done.wait()
return result | python | def probe_sync(self):
done = threading.Event()
result = {}
def probe_done(adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.probe_async(probe_done)
done.wait()
return result | [
"def",
"probe_sync",
"(",
"self",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"probe_done",
"(",
"adapter_id",
",",
"status",
",",
"reason",
")",
":",
"result",
"[",
"'success'",
"]",
"=",
"status",
"re... | Synchronously probe for devices on this adapter. | [
"Synchronously",
"probe",
"for",
"devices",
"on",
"this",
"adapter",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L288-L302 |
23,055 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/legacy.py | DeviceAdapter.send_rpc_sync | def send_rpc_sync(self, conn_id, address, rpc_id, payload, timeout):
"""Synchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (bytearray): the payload of the command
timeout (float): the number of seconds to wait for the RPC to execute
Returns:
dict: A dictionary with four elements
'success': a bool indicating whether we received a response to our attempted RPC
'failure_reason': a string with the reason for the failure if success == False
'status': the one byte status code returned for the RPC if success == True else None
'payload': a bytearray with the payload returned by RPC if success == True else None
"""
done = threading.Event()
result = {}
def send_rpc_done(conn_id, adapter_id, status, reason, rpc_status, resp_payload):
result['success'] = status
result['failure_reason'] = reason
result['status'] = rpc_status
result['payload'] = resp_payload
done.set()
self.send_rpc_async(conn_id, address, rpc_id, payload, timeout, send_rpc_done)
done.wait()
return result | python | def send_rpc_sync(self, conn_id, address, rpc_id, payload, timeout):
done = threading.Event()
result = {}
def send_rpc_done(conn_id, adapter_id, status, reason, rpc_status, resp_payload):
result['success'] = status
result['failure_reason'] = reason
result['status'] = rpc_status
result['payload'] = resp_payload
done.set()
self.send_rpc_async(conn_id, address, rpc_id, payload, timeout, send_rpc_done)
done.wait()
return result | [
"def",
"send_rpc_sync",
"(",
"self",
",",
"conn_id",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"timeout",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"send_rpc_done",
"(",
"conn_id",
",",
"adapt... | Synchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (bytearray): the payload of the command
timeout (float): the number of seconds to wait for the RPC to execute
Returns:
dict: A dictionary with four elements
'success': a bool indicating whether we received a response to our attempted RPC
'failure_reason': a string with the reason for the failure if success == False
'status': the one byte status code returned for the RPC if success == True else None
'payload': a bytearray with the payload returned by RPC if success == True else None | [
"Synchronously",
"send",
"an",
"RPC",
"to",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L325-L357 |
23,056 | iotile/coretools | iotilecore/iotile/core/hw/auth/auth_provider.py | AuthProvider.FindByName | def FindByName(cls, name):
"""Find a specific installed auth provider by name."""
reg = ComponentRegistry()
for _, entry in reg.load_extensions('iotile.auth_provider', name_filter=name):
return entry | python | def FindByName(cls, name):
reg = ComponentRegistry()
for _, entry in reg.load_extensions('iotile.auth_provider', name_filter=name):
return entry | [
"def",
"FindByName",
"(",
"cls",
",",
"name",
")",
":",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_",
",",
"entry",
"in",
"reg",
".",
"load_extensions",
"(",
"'iotile.auth_provider'",
",",
"name_filter",
"=",
"name",
")",
":",
"return",
"entry"
] | Find a specific installed auth provider by name. | [
"Find",
"a",
"specific",
"installed",
"auth",
"provider",
"by",
"name",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/auth_provider.py#L51-L56 |
23,057 | iotile/coretools | iotilecore/iotile/core/hw/auth/auth_provider.py | AuthProvider.DeriveReportKey | def DeriveReportKey(cls, root_key, report_id, sent_timestamp):
"""Derive a standard one time use report signing key.
The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp)
where MAGIC_NUMBER is 0x00000002 and all integers are in little endian.
"""
signed_data = struct.pack("<LLL", AuthProvider.ReportKeyMagic, report_id, sent_timestamp)
hmac_calc = hmac.new(root_key, signed_data, hashlib.sha256)
return bytearray(hmac_calc.digest()) | python | def DeriveReportKey(cls, root_key, report_id, sent_timestamp):
signed_data = struct.pack("<LLL", AuthProvider.ReportKeyMagic, report_id, sent_timestamp)
hmac_calc = hmac.new(root_key, signed_data, hashlib.sha256)
return bytearray(hmac_calc.digest()) | [
"def",
"DeriveReportKey",
"(",
"cls",
",",
"root_key",
",",
"report_id",
",",
"sent_timestamp",
")",
":",
"signed_data",
"=",
"struct",
".",
"pack",
"(",
"\"<LLL\"",
",",
"AuthProvider",
".",
"ReportKeyMagic",
",",
"report_id",
",",
"sent_timestamp",
")",
"hma... | Derive a standard one time use report signing key.
The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp)
where MAGIC_NUMBER is 0x00000002 and all integers are in little endian. | [
"Derive",
"a",
"standard",
"one",
"time",
"use",
"report",
"signing",
"key",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/auth_provider.py#L72-L82 |
23,058 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py | AwaitableDict.declare | def declare(self, name):
"""Declare that a key will be set in the future.
This will create a future for the key that is used to
hold its result and allow awaiting it.
Args:
name (str): The unique key that will be used.
"""
if name in self._data:
raise KeyError("Declared name {} that already existed".format(name))
self._data[name] = self._loop.create_future() | python | def declare(self, name):
if name in self._data:
raise KeyError("Declared name {} that already existed".format(name))
self._data[name] = self._loop.create_future() | [
"def",
"declare",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_data",
":",
"raise",
"KeyError",
"(",
"\"Declared name {} that already existed\"",
".",
"format",
"(",
"name",
")",
")",
"self",
".",
"_data",
"[",
"name",
"]",
"=",... | Declare that a key will be set in the future.
This will create a future for the key that is used to
hold its result and allow awaiting it.
Args:
name (str): The unique key that will be used. | [
"Declare",
"that",
"a",
"key",
"will",
"be",
"set",
"in",
"the",
"future",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L39-L52 |
23,059 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py | AwaitableDict.get | async def get(self, name, timeout=None, autoremove=True):
"""Wait for a value to be set for a key.
This is the primary way to receive values from AwaitableDict.
You pass in the name of the key you want to wait for, the maximum
amount of time you want to wait and then you can await the result
and it will resolve to value from the call to set or an
asyncio.TimeoutError.
You should generally leave autoremove as the default True value. This
causes the key to be removed from the dictionary after get returns.
Normally you have a single user calling ``get`` and another calling
``set`` so you want to automatically clean up after the getter
returns, no matter what.
If the key has not already been declared, it will be declared
automatically inside this function so it is not necessary to call
:meth:`declare` manually in most use cases.
Args:
name (str): The name of the key to wait on.
timeout (float): The maximum timeout to wait.
autoremove (bool): Whether to automatically remove the
key when get() returns.
Returns:
object: Whatever was set in the key by :meth:`set`.
Raises:
asyncio.TimeoutError: The key was not set within the timeout.
"""
self._ensure_declared(name)
try:
await asyncio.wait_for(self._data[name], timeout, loop=self._loop.get_loop())
return self._data[name].result()
finally:
if autoremove:
self._data[name].cancel()
del self._data[name] | python | async def get(self, name, timeout=None, autoremove=True):
self._ensure_declared(name)
try:
await asyncio.wait_for(self._data[name], timeout, loop=self._loop.get_loop())
return self._data[name].result()
finally:
if autoremove:
self._data[name].cancel()
del self._data[name] | [
"async",
"def",
"get",
"(",
"self",
",",
"name",
",",
"timeout",
"=",
"None",
",",
"autoremove",
"=",
"True",
")",
":",
"self",
".",
"_ensure_declared",
"(",
"name",
")",
"try",
":",
"await",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"_data",
"["... | Wait for a value to be set for a key.
This is the primary way to receive values from AwaitableDict.
You pass in the name of the key you want to wait for, the maximum
amount of time you want to wait and then you can await the result
and it will resolve to value from the call to set or an
asyncio.TimeoutError.
You should generally leave autoremove as the default True value. This
causes the key to be removed from the dictionary after get returns.
Normally you have a single user calling ``get`` and another calling
``set`` so you want to automatically clean up after the getter
returns, no matter what.
If the key has not already been declared, it will be declared
automatically inside this function so it is not necessary to call
:meth:`declare` manually in most use cases.
Args:
name (str): The name of the key to wait on.
timeout (float): The maximum timeout to wait.
autoremove (bool): Whether to automatically remove the
key when get() returns.
Returns:
object: Whatever was set in the key by :meth:`set`.
Raises:
asyncio.TimeoutError: The key was not set within the timeout. | [
"Wait",
"for",
"a",
"value",
"to",
"be",
"set",
"for",
"a",
"key",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L54-L94 |
23,060 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py | AwaitableDict.get_nowait | def get_nowait(self, name, default=_MISSING, autoremove=False):
"""Get the value of a key if it is already set.
This method allows you to check if a key has already been set
without blocking. If the key has not been set you will get the
default value you pass in or KeyError() if no default is passed.
When this method returns the key is automatically removed unless
you pass ``autoremove=False``.
This method is not a coroutine and does not block.
Args:
name (str): The name of the key to wait on.
default (object): The default value to return if the key
has not yet been set. Defaults to raising KeyError().
autoremove (bool): Whether to automatically remove the
key when get() returns.
Returns:
object: Whatever was set in the key by :meth:`set`.
"""
self._ensure_declared(name)
try:
future = self._data[name]
if future.done():
return future.result()
if default is _MISSING:
raise KeyError("Key {} has not been assigned a value and no default given".format(name))
return default
finally:
if autoremove:
self._data[name].cancel()
del self._data[name] | python | def get_nowait(self, name, default=_MISSING, autoremove=False):
self._ensure_declared(name)
try:
future = self._data[name]
if future.done():
return future.result()
if default is _MISSING:
raise KeyError("Key {} has not been assigned a value and no default given".format(name))
return default
finally:
if autoremove:
self._data[name].cancel()
del self._data[name] | [
"def",
"get_nowait",
"(",
"self",
",",
"name",
",",
"default",
"=",
"_MISSING",
",",
"autoremove",
"=",
"False",
")",
":",
"self",
".",
"_ensure_declared",
"(",
"name",
")",
"try",
":",
"future",
"=",
"self",
".",
"_data",
"[",
"name",
"]",
"if",
"fu... | Get the value of a key if it is already set.
This method allows you to check if a key has already been set
without blocking. If the key has not been set you will get the
default value you pass in or KeyError() if no default is passed.
When this method returns the key is automatically removed unless
you pass ``autoremove=False``.
This method is not a coroutine and does not block.
Args:
name (str): The name of the key to wait on.
default (object): The default value to return if the key
has not yet been set. Defaults to raising KeyError().
autoremove (bool): Whether to automatically remove the
key when get() returns.
Returns:
object: Whatever was set in the key by :meth:`set`. | [
"Get",
"the",
"value",
"of",
"a",
"key",
"if",
"it",
"is",
"already",
"set",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L96-L133 |
23,061 | iotile/coretools | iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py | AwaitableDict.set | def set(self, name, value, autodeclare=False):
"""Set the value of a key.
This method will cause anyone waiting on a key (and any future
waiters) to unblock and be returned the value you pass here.
If the key has not been declared previously, a KeyError() is
raised unless you pass ``autodeclare=True`` which will cause
the key to be declared. Normally you don't want to autodeclare.
This method is not a coroutine and does not block.
Args:
name (str): The key to set
value (object): The value to set
autodeclare (bool): Whether to automatically declare the
key if is has not already been declared. Defaults to
False.
"""
if not autodeclare and name not in self._data:
raise KeyError("Key {} has not been declared and autodeclare=False".format(name))
self._ensure_declared(name)
self._data[name].set_result(value) | python | def set(self, name, value, autodeclare=False):
if not autodeclare and name not in self._data:
raise KeyError("Key {} has not been declared and autodeclare=False".format(name))
self._ensure_declared(name)
self._data[name].set_result(value) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"autodeclare",
"=",
"False",
")",
":",
"if",
"not",
"autodeclare",
"and",
"name",
"not",
"in",
"self",
".",
"_data",
":",
"raise",
"KeyError",
"(",
"\"Key {} has not been declared and autodeclare=False... | Set the value of a key.
This method will cause anyone waiting on a key (and any future
waiters) to unblock and be returned the value you pass here.
If the key has not been declared previously, a KeyError() is
raised unless you pass ``autodeclare=True`` which will cause
the key to be declared. Normally you don't want to autodeclare.
This method is not a coroutine and does not block.
Args:
name (str): The key to set
value (object): The value to set
autodeclare (bool): Whether to automatically declare the
key if is has not already been declared. Defaults to
False. | [
"Set",
"the",
"value",
"of",
"a",
"key",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L135-L159 |
23,062 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/parser_v1.py | SensorGraphFileParser.dump_tree | def dump_tree(self, statement=None, indent_level=0):
"""Dump the AST for this parsed file.
Args:
statement (SensorGraphStatement): the statement to print
if this function is called recursively.
indent_level (int): The number of spaces to indent this
statement. Used for recursively printing blocks of
statements.
Returns:
str: The AST for this parsed sg file as a nested
tree with one node per line and blocks indented.
"""
out = u""
indent = u" "*indent_level
if statement is None:
for root_statement in self.statements:
out += self.dump_tree(root_statement, indent_level)
else:
out += indent + str(statement) + u'\n'
if len(statement.children) > 0:
for child in statement.children:
out += self.dump_tree(child, indent_level=indent_level+4)
return out | python | def dump_tree(self, statement=None, indent_level=0):
out = u""
indent = u" "*indent_level
if statement is None:
for root_statement in self.statements:
out += self.dump_tree(root_statement, indent_level)
else:
out += indent + str(statement) + u'\n'
if len(statement.children) > 0:
for child in statement.children:
out += self.dump_tree(child, indent_level=indent_level+4)
return out | [
"def",
"dump_tree",
"(",
"self",
",",
"statement",
"=",
"None",
",",
"indent_level",
"=",
"0",
")",
":",
"out",
"=",
"u\"\"",
"indent",
"=",
"u\" \"",
"*",
"indent_level",
"if",
"statement",
"is",
"None",
":",
"for",
"root_statement",
"in",
"self",
".",
... | Dump the AST for this parsed file.
Args:
statement (SensorGraphStatement): the statement to print
if this function is called recursively.
indent_level (int): The number of spaces to indent this
statement. Used for recursively printing blocks of
statements.
Returns:
str: The AST for this parsed sg file as a nested
tree with one node per line and blocks indented. | [
"Dump",
"the",
"AST",
"for",
"this",
"parsed",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L23-L51 |
23,063 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/parser_v1.py | SensorGraphFileParser.parse_file | def parse_file(self, sg_file=None, data=None):
"""Parse a sensor graph file into an AST describing the file.
This function builds the statements list for this parser.
If you pass ``sg_file``, it will be interpreted as the path to a file
to parse. If you pass ``data`` it will be directly interpreted as the
string to parse.
"""
if sg_file is not None and data is not None:
raise ArgumentError("You must pass either a path to an sgf file or the sgf contents but not both")
if sg_file is None and data is None:
raise ArgumentError("You must pass either a path to an sgf file or the sgf contents, neither passed")
if sg_file is not None:
try:
with open(sg_file, "r") as inf:
data = inf.read()
except IOError:
raise ArgumentError("Could not read sensor graph file", path=sg_file)
# convert tabs to spaces so our line numbers match correctly
data = data.replace(u'\t', u' ')
lang = get_language()
result = lang.parseString(data)
for statement in result:
parsed = self.parse_statement(statement, orig_contents=data)
self.statements.append(parsed) | python | def parse_file(self, sg_file=None, data=None):
if sg_file is not None and data is not None:
raise ArgumentError("You must pass either a path to an sgf file or the sgf contents but not both")
if sg_file is None and data is None:
raise ArgumentError("You must pass either a path to an sgf file or the sgf contents, neither passed")
if sg_file is not None:
try:
with open(sg_file, "r") as inf:
data = inf.read()
except IOError:
raise ArgumentError("Could not read sensor graph file", path=sg_file)
# convert tabs to spaces so our line numbers match correctly
data = data.replace(u'\t', u' ')
lang = get_language()
result = lang.parseString(data)
for statement in result:
parsed = self.parse_statement(statement, orig_contents=data)
self.statements.append(parsed) | [
"def",
"parse_file",
"(",
"self",
",",
"sg_file",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"sg_file",
"is",
"not",
"None",
"and",
"data",
"is",
"not",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"You must pass either a path to an sgf file or th... | Parse a sensor graph file into an AST describing the file.
This function builds the statements list for this parser.
If you pass ``sg_file``, it will be interpreted as the path to a file
to parse. If you pass ``data`` it will be directly interpreted as the
string to parse. | [
"Parse",
"a",
"sensor",
"graph",
"file",
"into",
"an",
"AST",
"describing",
"the",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L53-L83 |
23,064 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/parser_v1.py | SensorGraphFileParser.compile | def compile(self, model):
"""Compile this file into a SensorGraph.
You must have preivously called parse_file to parse a
sensor graph file into statements that are then executed
by this command to build a sensor graph.
The results are stored in self.sensor_graph and can be
inspected before running optimization passes.
Args:
model (DeviceModel): The device model that we should compile
this sensor graph for.
"""
log = SensorLog(InMemoryStorageEngine(model), model)
self.sensor_graph = SensorGraph(log, model)
allocator = StreamAllocator(self.sensor_graph, model)
self._scope_stack = []
# Create a root scope
root = RootScope(self.sensor_graph, allocator)
self._scope_stack.append(root)
for statement in self.statements:
statement.execute(self.sensor_graph, self._scope_stack)
self.sensor_graph.initialize_remaining_constants()
self.sensor_graph.sort_nodes() | python | def compile(self, model):
log = SensorLog(InMemoryStorageEngine(model), model)
self.sensor_graph = SensorGraph(log, model)
allocator = StreamAllocator(self.sensor_graph, model)
self._scope_stack = []
# Create a root scope
root = RootScope(self.sensor_graph, allocator)
self._scope_stack.append(root)
for statement in self.statements:
statement.execute(self.sensor_graph, self._scope_stack)
self.sensor_graph.initialize_remaining_constants()
self.sensor_graph.sort_nodes() | [
"def",
"compile",
"(",
"self",
",",
"model",
")",
":",
"log",
"=",
"SensorLog",
"(",
"InMemoryStorageEngine",
"(",
"model",
")",
",",
"model",
")",
"self",
".",
"sensor_graph",
"=",
"SensorGraph",
"(",
"log",
",",
"model",
")",
"allocator",
"=",
"StreamA... | Compile this file into a SensorGraph.
You must have preivously called parse_file to parse a
sensor graph file into statements that are then executed
by this command to build a sensor graph.
The results are stored in self.sensor_graph and can be
inspected before running optimization passes.
Args:
model (DeviceModel): The device model that we should compile
this sensor graph for. | [
"Compile",
"this",
"file",
"into",
"a",
"SensorGraph",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L85-L115 |
23,065 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/parser_v1.py | SensorGraphFileParser.parse_statement | def parse_statement(self, statement, orig_contents):
"""Parse a statement, possibly called recursively.
Args:
statement (int, ParseResult): The pyparsing parse result that
contains one statement prepended with the match location
orig_contents (str): The original contents of the file that we're
parsing in case we need to convert an index into a line, column
pair.
Returns:
SensorGraphStatement: The parsed statement.
"""
children = []
is_block = False
name = statement.getName()
# Recursively parse all children statements in a block
# before parsing the block itself.
# If this is a non-block statement, parse it using the statement
# parser to figure out what specific statement it is before
# processing it further.
# This two step process produces better syntax error messsages
if name == 'block':
children_statements = statement[1]
for child in children_statements:
parsed = self.parse_statement(child, orig_contents=orig_contents)
children.append(parsed)
locn = statement[0]['location']
statement = statement[0][1]
name = statement.getName()
is_block = True
else:
stmt_language = get_statement()
locn = statement['location']
statement = statement['match']
statement_string = str(u"".join(statement.asList()))
# Try to parse this generic statement into an actual statement.
# Do this here in a separate step so we have good error messages when there
# is a problem parsing a step.
try:
statement = stmt_language.parseString(statement_string)[0]
except (pyparsing.ParseException, pyparsing.ParseSyntaxException) as exc:
raise SensorGraphSyntaxError("Error parsing statement in sensor graph file", message=exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), column=pyparsing.col(locn, orig_contents))
except SensorGraphSemanticError as exc:
# Reraise semantic errors with line information
raise SensorGraphSemanticError(exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), **exc.params)
name = statement.getName()
if name not in statement_map:
raise ArgumentError("Unknown statement in sensor graph file", parsed_statement=statement, name=name)
# Save off our location information so we can give good error and warning information
line = pyparsing.line(locn, orig_contents).strip()
line_number = pyparsing.lineno(locn, orig_contents)
column = pyparsing.col(locn, orig_contents)
location_info = LocationInfo(line, line_number, column)
if is_block:
return statement_map[name](statement, children=children, location=location_info)
return statement_map[name](statement, location_info) | python | def parse_statement(self, statement, orig_contents):
children = []
is_block = False
name = statement.getName()
# Recursively parse all children statements in a block
# before parsing the block itself.
# If this is a non-block statement, parse it using the statement
# parser to figure out what specific statement it is before
# processing it further.
# This two step process produces better syntax error messsages
if name == 'block':
children_statements = statement[1]
for child in children_statements:
parsed = self.parse_statement(child, orig_contents=orig_contents)
children.append(parsed)
locn = statement[0]['location']
statement = statement[0][1]
name = statement.getName()
is_block = True
else:
stmt_language = get_statement()
locn = statement['location']
statement = statement['match']
statement_string = str(u"".join(statement.asList()))
# Try to parse this generic statement into an actual statement.
# Do this here in a separate step so we have good error messages when there
# is a problem parsing a step.
try:
statement = stmt_language.parseString(statement_string)[0]
except (pyparsing.ParseException, pyparsing.ParseSyntaxException) as exc:
raise SensorGraphSyntaxError("Error parsing statement in sensor graph file", message=exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), column=pyparsing.col(locn, orig_contents))
except SensorGraphSemanticError as exc:
# Reraise semantic errors with line information
raise SensorGraphSemanticError(exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), **exc.params)
name = statement.getName()
if name not in statement_map:
raise ArgumentError("Unknown statement in sensor graph file", parsed_statement=statement, name=name)
# Save off our location information so we can give good error and warning information
line = pyparsing.line(locn, orig_contents).strip()
line_number = pyparsing.lineno(locn, orig_contents)
column = pyparsing.col(locn, orig_contents)
location_info = LocationInfo(line, line_number, column)
if is_block:
return statement_map[name](statement, children=children, location=location_info)
return statement_map[name](statement, location_info) | [
"def",
"parse_statement",
"(",
"self",
",",
"statement",
",",
"orig_contents",
")",
":",
"children",
"=",
"[",
"]",
"is_block",
"=",
"False",
"name",
"=",
"statement",
".",
"getName",
"(",
")",
"# Recursively parse all children statements in a block",
"# before pars... | Parse a statement, possibly called recursively.
Args:
statement (int, ParseResult): The pyparsing parse result that
contains one statement prepended with the match location
orig_contents (str): The original contents of the file that we're
parsing in case we need to convert an index into a line, column
pair.
Returns:
SensorGraphStatement: The parsed statement. | [
"Parse",
"a",
"statement",
"possibly",
"called",
"recursively",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L117-L182 |
23,066 | iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualdevice.py | VirtualIOTileDevice.stream | def stream(self, report, callback=None):
"""Stream a report asynchronously.
If no one is listening for the report, the report may be dropped,
otherwise it will be queued for sending
Args:
report (IOTileReport): The report that should be streamed
callback (callable): Optional callback to get notified when
this report is actually sent.
"""
if self._push_channel is None:
return
self._push_channel.stream(report, callback=callback) | python | def stream(self, report, callback=None):
if self._push_channel is None:
return
self._push_channel.stream(report, callback=callback) | [
"def",
"stream",
"(",
"self",
",",
"report",
",",
"callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_push_channel",
"is",
"None",
":",
"return",
"self",
".",
"_push_channel",
".",
"stream",
"(",
"report",
",",
"callback",
"=",
"callback",
")"
] | Stream a report asynchronously.
If no one is listening for the report, the report may be dropped,
otherwise it will be queued for sending
Args:
report (IOTileReport): The report that should be streamed
callback (callable): Optional callback to get notified when
this report is actually sent. | [
"Stream",
"a",
"report",
"asynchronously",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L121-L136 |
23,067 | iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualdevice.py | VirtualIOTileDevice.stream_realtime | def stream_realtime(self, stream, value):
"""Stream a realtime value as an IndividualReadingReport.
If the streaming interface of the VirtualInterface this
VirtualDevice is attached to is not opened, the realtime
reading may be dropped.
Args:
stream (int): The stream id to send
value (int): The stream value to send
"""
if not self.stream_iface_open:
return
reading = IOTileReading(0, stream, value)
report = IndividualReadingReport.FromReadings(self.iotile_id, [reading])
self.stream(report) | python | def stream_realtime(self, stream, value):
if not self.stream_iface_open:
return
reading = IOTileReading(0, stream, value)
report = IndividualReadingReport.FromReadings(self.iotile_id, [reading])
self.stream(report) | [
"def",
"stream_realtime",
"(",
"self",
",",
"stream",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"stream_iface_open",
":",
"return",
"reading",
"=",
"IOTileReading",
"(",
"0",
",",
"stream",
",",
"value",
")",
"report",
"=",
"IndividualReadingReport",... | Stream a realtime value as an IndividualReadingReport.
If the streaming interface of the VirtualInterface this
VirtualDevice is attached to is not opened, the realtime
reading may be dropped.
Args:
stream (int): The stream id to send
value (int): The stream value to send | [
"Stream",
"a",
"realtime",
"value",
"as",
"an",
"IndividualReadingReport",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L138-L156 |
23,068 | iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualdevice.py | VirtualIOTileDevice.trace | def trace(self, data, callback=None):
"""Trace data asynchronously.
If no one is listening for traced data, it will be dropped
otherwise it will be queued for sending.
Args:
data (bytearray, string): Unstructured data to trace to any
connected client.
callback (callable): Optional callback to get notified when
this data is actually sent.
"""
if self._push_channel is None:
return
self._push_channel.trace(data, callback=callback) | python | def trace(self, data, callback=None):
if self._push_channel is None:
return
self._push_channel.trace(data, callback=callback) | [
"def",
"trace",
"(",
"self",
",",
"data",
",",
"callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_push_channel",
"is",
"None",
":",
"return",
"self",
".",
"_push_channel",
".",
"trace",
"(",
"data",
",",
"callback",
"=",
"callback",
")"
] | Trace data asynchronously.
If no one is listening for traced data, it will be dropped
otherwise it will be queued for sending.
Args:
data (bytearray, string): Unstructured data to trace to any
connected client.
callback (callable): Optional callback to get notified when
this data is actually sent. | [
"Trace",
"data",
"asynchronously",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L158-L174 |
23,069 | iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualdevice.py | VirtualIOTileDevice.register_rpc | def register_rpc(self, address, rpc_id, func):
"""Register a single RPC handler with the given info.
This function can be used to directly register individual RPCs,
rather than delegating all RPCs at a given address to a virtual
Tile.
If calls to this function are mixed with calls to add_tile for
the same address, these RPCs will take precedence over what is
defined in the tiles.
Args:
address (int): The address of the mock tile this RPC is for
rpc_id (int): The number of the RPC
func (callable): The function that should be called to handle the
RPC. func is called as func(payload) and must return a single
string object of up to 20 bytes with its response
"""
if rpc_id < 0 or rpc_id > 0xFFFF:
raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id))
if address not in self._rpc_overlays:
self._rpc_overlays[address] = RPCDispatcher()
self._rpc_overlays[address].add_rpc(rpc_id, func) | python | def register_rpc(self, address, rpc_id, func):
if rpc_id < 0 or rpc_id > 0xFFFF:
raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id))
if address not in self._rpc_overlays:
self._rpc_overlays[address] = RPCDispatcher()
self._rpc_overlays[address].add_rpc(rpc_id, func) | [
"def",
"register_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"func",
")",
":",
"if",
"rpc_id",
"<",
"0",
"or",
"rpc_id",
">",
"0xFFFF",
":",
"raise",
"RPCInvalidIDError",
"(",
"\"Invalid RPC ID: {}\"",
".",
"format",
"(",
"rpc_id",
")",
")",
"... | Register a single RPC handler with the given info.
This function can be used to directly register individual RPCs,
rather than delegating all RPCs at a given address to a virtual
Tile.
If calls to this function are mixed with calls to add_tile for
the same address, these RPCs will take precedence over what is
defined in the tiles.
Args:
address (int): The address of the mock tile this RPC is for
rpc_id (int): The number of the RPC
func (callable): The function that should be called to handle the
RPC. func is called as func(payload) and must return a single
string object of up to 20 bytes with its response | [
"Register",
"a",
"single",
"RPC",
"handler",
"with",
"the",
"given",
"info",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L176-L201 |
23,070 | iotile/coretools | iotilecore/iotile/core/hw/virtual/virtualdevice.py | VirtualIOTileDevice.add_tile | def add_tile(self, address, tile):
"""Add a tile to handle all RPCs at a given address.
Args:
address (int): The address of the tile
tile (RPCDispatcher): A tile object that inherits from RPCDispatcher
"""
if address in self._tiles:
raise ArgumentError("Tried to add two tiles at the same address", address=address)
self._tiles[address] = tile | python | def add_tile(self, address, tile):
if address in self._tiles:
raise ArgumentError("Tried to add two tiles at the same address", address=address)
self._tiles[address] = tile | [
"def",
"add_tile",
"(",
"self",
",",
"address",
",",
"tile",
")",
":",
"if",
"address",
"in",
"self",
".",
"_tiles",
":",
"raise",
"ArgumentError",
"(",
"\"Tried to add two tiles at the same address\"",
",",
"address",
"=",
"address",
")",
"self",
".",
"_tiles... | Add a tile to handle all RPCs at a given address.
Args:
address (int): The address of the tile
tile (RPCDispatcher): A tile object that inherits from RPCDispatcher | [
"Add",
"a",
"tile",
"to",
"handle",
"all",
"RPCs",
"at",
"a",
"given",
"address",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L230-L241 |
23,071 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_device.py | ReferenceDevice.iter_tiles | def iter_tiles(self, include_controller=True):
"""Iterate over all tiles in this device in order.
The ordering is by tile address which places the controller tile
first in the list.
Args:
include_controller (bool): Include the controller tile in the
results.
Yields:
int, EmulatedTile: A tuple with the tile address and tile object.
"""
for address, tile in sorted(self._tiles.items()):
if address == 8 and not include_controller:
continue
yield address, tile | python | def iter_tiles(self, include_controller=True):
for address, tile in sorted(self._tiles.items()):
if address == 8 and not include_controller:
continue
yield address, tile | [
"def",
"iter_tiles",
"(",
"self",
",",
"include_controller",
"=",
"True",
")",
":",
"for",
"address",
",",
"tile",
"in",
"sorted",
"(",
"self",
".",
"_tiles",
".",
"items",
"(",
")",
")",
":",
"if",
"address",
"==",
"8",
"and",
"not",
"include_controll... | Iterate over all tiles in this device in order.
The ordering is by tile address which places the controller tile
first in the list.
Args:
include_controller (bool): Include the controller tile in the
results.
Yields:
int, EmulatedTile: A tuple with the tile address and tile object. | [
"Iterate",
"over",
"all",
"tiles",
"in",
"this",
"device",
"in",
"order",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_device.py#L69-L87 |
23,072 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_device.py | ReferenceDevice.open_streaming_interface | def open_streaming_interface(self):
"""Called when someone opens a streaming interface to the device.
This method will automatically notify sensor_graph that there is a
streaming interface opened.
Returns:
list: A list of IOTileReport objects that should be sent out
the streaming interface.
"""
super(ReferenceDevice, self).open_streaming_interface()
self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_OPEN)
return [] | python | def open_streaming_interface(self):
super(ReferenceDevice, self).open_streaming_interface()
self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_OPEN)
return [] | [
"def",
"open_streaming_interface",
"(",
"self",
")",
":",
"super",
"(",
"ReferenceDevice",
",",
"self",
")",
".",
"open_streaming_interface",
"(",
")",
"self",
".",
"rpc",
"(",
"8",
",",
"rpcs",
".",
"SG_GRAPH_INPUT",
",",
"8",
",",
"streams",
".",
"COMM_T... | Called when someone opens a streaming interface to the device.
This method will automatically notify sensor_graph that there is a
streaming interface opened.
Returns:
list: A list of IOTileReport objects that should be sent out
the streaming interface. | [
"Called",
"when",
"someone",
"opens",
"a",
"streaming",
"interface",
"to",
"the",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_device.py#L144-L158 |
23,073 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_device.py | ReferenceDevice.close_streaming_interface | def close_streaming_interface(self):
"""Called when someone closes the streaming interface to the device.
This method will automatically notify sensor_graph that there is a no
longer a streaming interface opened.
"""
super(ReferenceDevice, self).close_streaming_interface()
self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_CLOSED) | python | def close_streaming_interface(self):
super(ReferenceDevice, self).close_streaming_interface()
self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_CLOSED) | [
"def",
"close_streaming_interface",
"(",
"self",
")",
":",
"super",
"(",
"ReferenceDevice",
",",
"self",
")",
".",
"close_streaming_interface",
"(",
")",
"self",
".",
"rpc",
"(",
"8",
",",
"rpcs",
".",
"SG_GRAPH_INPUT",
",",
"8",
",",
"streams",
".",
"COMM... | Called when someone closes the streaming interface to the device.
This method will automatically notify sensor_graph that there is a no
longer a streaming interface opened. | [
"Called",
"when",
"someone",
"closes",
"the",
"streaming",
"interface",
"to",
"the",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_device.py#L160-L169 |
23,074 | iotile/coretools | iotilegateway/iotilegateway/supervisor/main.py | build_parser | def build_parser():
"""Build the script's argument parser."""
parser = argparse.ArgumentParser(description="The IOTile task supervisor")
parser.add_argument('-c', '--config', help="config json with options")
parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging verbosity")
return parser | python | def build_parser():
parser = argparse.ArgumentParser(description="The IOTile task supervisor")
parser.add_argument('-c', '--config', help="config json with options")
parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging verbosity")
return parser | [
"def",
"build_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"The IOTile task supervisor\"",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--config'",
",",
"help",
"=",
"\"config json with options\"",
... | Build the script's argument parser. | [
"Build",
"the",
"script",
"s",
"argument",
"parser",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/main.py#L20-L27 |
23,075 | iotile/coretools | iotilegateway/iotilegateway/supervisor/main.py | configure_logging | def configure_logging(verbosity):
"""Set up the global logging level.
Args:
verbosity (int): The logging verbosity
"""
root = logging.getLogger()
formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s',
'%y-%m-%d %H:%M:%S')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
if verbosity >= len(loglevels):
verbosity = len(loglevels) - 1
level = loglevels[verbosity]
root.setLevel(level)
root.addHandler(handler) | python | def configure_logging(verbosity):
root = logging.getLogger()
formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s',
'%y-%m-%d %H:%M:%S')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
if verbosity >= len(loglevels):
verbosity = len(loglevels) - 1
level = loglevels[verbosity]
root.setLevel(level)
root.addHandler(handler) | [
"def",
"configure_logging",
"(",
"verbosity",
")",
":",
"root",
"=",
"logging",
".",
"getLogger",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s'",
",",
"'%y-%m-%d %H:%M:%S'",
")",
"handler",
... | Set up the global logging level.
Args:
verbosity (int): The logging verbosity | [
"Set",
"up",
"the",
"global",
"logging",
"level",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/main.py#L30-L51 |
23,076 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | createProgBuilder | def createProgBuilder(env):
"""This is a utility function that creates the Program
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
program = env['BUILDERS']['Program']
except KeyError:
import SCons.Defaults
program = SCons.Builder.Builder(action = SCons.Defaults.LinkAction,
emitter = '$PROGEMITTER',
prefix = '$PROGPREFIX',
suffix = '$PROGSUFFIX',
src_suffix = '$OBJSUFFIX',
src_builder = 'Object',
target_scanner = ProgramScanner)
env['BUILDERS']['Program'] = program
return program | python | def createProgBuilder(env):
try:
program = env['BUILDERS']['Program']
except KeyError:
import SCons.Defaults
program = SCons.Builder.Builder(action = SCons.Defaults.LinkAction,
emitter = '$PROGEMITTER',
prefix = '$PROGPREFIX',
suffix = '$PROGSUFFIX',
src_suffix = '$OBJSUFFIX',
src_builder = 'Object',
target_scanner = ProgramScanner)
env['BUILDERS']['Program'] = program
return program | [
"def",
"createProgBuilder",
"(",
"env",
")",
":",
"try",
":",
"program",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Program'",
"]",
"except",
"KeyError",
":",
"import",
"SCons",
".",
"Defaults",
"program",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(... | This is a utility function that creates the Program
Builder in an Environment if it is not there already.
If it is already there, we return the existing one. | [
"This",
"is",
"a",
"utility",
"function",
"that",
"creates",
"the",
"Program",
"Builder",
"in",
"an",
"Environment",
"if",
"it",
"is",
"not",
"there",
"already",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L306-L326 |
23,077 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | createStaticLibBuilder | def createStaticLibBuilder(env):
"""This is a utility function that creates the StaticLibrary
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
static_lib = env['BUILDERS']['StaticLibrary']
except KeyError:
action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ]
if env.get('RANLIB',False) or env.Detect('ranlib'):
ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR")
action_list.append(ranlib_action)
static_lib = SCons.Builder.Builder(action = action_list,
emitter = '$LIBEMITTER',
prefix = '$LIBPREFIX',
suffix = '$LIBSUFFIX',
src_suffix = '$OBJSUFFIX',
src_builder = 'StaticObject')
env['BUILDERS']['StaticLibrary'] = static_lib
env['BUILDERS']['Library'] = static_lib
return static_lib | python | def createStaticLibBuilder(env):
try:
static_lib = env['BUILDERS']['StaticLibrary']
except KeyError:
action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ]
if env.get('RANLIB',False) or env.Detect('ranlib'):
ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR")
action_list.append(ranlib_action)
static_lib = SCons.Builder.Builder(action = action_list,
emitter = '$LIBEMITTER',
prefix = '$LIBPREFIX',
suffix = '$LIBSUFFIX',
src_suffix = '$OBJSUFFIX',
src_builder = 'StaticObject')
env['BUILDERS']['StaticLibrary'] = static_lib
env['BUILDERS']['Library'] = static_lib
return static_lib | [
"def",
"createStaticLibBuilder",
"(",
"env",
")",
":",
"try",
":",
"static_lib",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'StaticLibrary'",
"]",
"except",
"KeyError",
":",
"action_list",
"=",
"[",
"SCons",
".",
"Action",
".",
"Action",
"(",
"\"$ARCOM\"",
... | This is a utility function that creates the StaticLibrary
Builder in an Environment if it is not there already.
If it is already there, we return the existing one. | [
"This",
"is",
"a",
"utility",
"function",
"that",
"creates",
"the",
"StaticLibrary",
"Builder",
"in",
"an",
"Environment",
"if",
"it",
"is",
"not",
"there",
"already",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L329-L353 |
23,078 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | createSharedLibBuilder | def createSharedLibBuilder(env):
"""This is a utility function that creates the SharedLibrary
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
shared_lib = env['BUILDERS']['SharedLibrary']
except KeyError:
import SCons.Defaults
action_list = [ SCons.Defaults.SharedCheck,
SCons.Defaults.ShLinkAction,
LibSymlinksAction ]
shared_lib = SCons.Builder.Builder(action = action_list,
emitter = "$SHLIBEMITTER",
prefix = ShLibPrefixGenerator,
suffix = ShLibSuffixGenerator,
target_scanner = ProgramScanner,
src_suffix = '$SHOBJSUFFIX',
src_builder = 'SharedObject')
env['BUILDERS']['SharedLibrary'] = shared_lib
return shared_lib | python | def createSharedLibBuilder(env):
try:
shared_lib = env['BUILDERS']['SharedLibrary']
except KeyError:
import SCons.Defaults
action_list = [ SCons.Defaults.SharedCheck,
SCons.Defaults.ShLinkAction,
LibSymlinksAction ]
shared_lib = SCons.Builder.Builder(action = action_list,
emitter = "$SHLIBEMITTER",
prefix = ShLibPrefixGenerator,
suffix = ShLibSuffixGenerator,
target_scanner = ProgramScanner,
src_suffix = '$SHOBJSUFFIX',
src_builder = 'SharedObject')
env['BUILDERS']['SharedLibrary'] = shared_lib
return shared_lib | [
"def",
"createSharedLibBuilder",
"(",
"env",
")",
":",
"try",
":",
"shared_lib",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'SharedLibrary'",
"]",
"except",
"KeyError",
":",
"import",
"SCons",
".",
"Defaults",
"action_list",
"=",
"[",
"SCons",
".",
"Defaults"... | This is a utility function that creates the SharedLibrary
Builder in an Environment if it is not there already.
If it is already there, we return the existing one. | [
"This",
"is",
"a",
"utility",
"function",
"that",
"creates",
"the",
"SharedLibrary",
"Builder",
"in",
"an",
"Environment",
"if",
"it",
"is",
"not",
"there",
"already",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L787-L810 |
23,079 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | createLoadableModuleBuilder | def createLoadableModuleBuilder(env):
"""This is a utility function that creates the LoadableModule
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
ld_module = env['BUILDERS']['LoadableModule']
except KeyError:
import SCons.Defaults
action_list = [ SCons.Defaults.SharedCheck,
SCons.Defaults.LdModuleLinkAction,
LibSymlinksAction ]
ld_module = SCons.Builder.Builder(action = action_list,
emitter = "$LDMODULEEMITTER",
prefix = LdModPrefixGenerator,
suffix = LdModSuffixGenerator,
target_scanner = ProgramScanner,
src_suffix = '$SHOBJSUFFIX',
src_builder = 'SharedObject')
env['BUILDERS']['LoadableModule'] = ld_module
return ld_module | python | def createLoadableModuleBuilder(env):
try:
ld_module = env['BUILDERS']['LoadableModule']
except KeyError:
import SCons.Defaults
action_list = [ SCons.Defaults.SharedCheck,
SCons.Defaults.LdModuleLinkAction,
LibSymlinksAction ]
ld_module = SCons.Builder.Builder(action = action_list,
emitter = "$LDMODULEEMITTER",
prefix = LdModPrefixGenerator,
suffix = LdModSuffixGenerator,
target_scanner = ProgramScanner,
src_suffix = '$SHOBJSUFFIX',
src_builder = 'SharedObject')
env['BUILDERS']['LoadableModule'] = ld_module
return ld_module | [
"def",
"createLoadableModuleBuilder",
"(",
"env",
")",
":",
"try",
":",
"ld_module",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'LoadableModule'",
"]",
"except",
"KeyError",
":",
"import",
"SCons",
".",
"Defaults",
"action_list",
"=",
"[",
"SCons",
".",
"Defa... | This is a utility function that creates the LoadableModule
Builder in an Environment if it is not there already.
If it is already there, we return the existing one. | [
"This",
"is",
"a",
"utility",
"function",
"that",
"creates",
"the",
"LoadableModule",
"Builder",
"in",
"an",
"Environment",
"if",
"it",
"is",
"not",
"there",
"already",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L812-L835 |
23,080 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | createObjBuilders | def createObjBuilders(env):
"""This is a utility function that creates the StaticObject
and SharedObject Builders in an Environment if they
are not there already.
If they are there already, we return the existing ones.
This is a separate function because soooo many Tools
use this functionality.
The return is a 2-tuple of (StaticObject, SharedObject)
"""
try:
static_obj = env['BUILDERS']['StaticObject']
except KeyError:
static_obj = SCons.Builder.Builder(action = {},
emitter = {},
prefix = '$OBJPREFIX',
suffix = '$OBJSUFFIX',
src_builder = ['CFile', 'CXXFile'],
source_scanner = SourceFileScanner,
single_source = 1)
env['BUILDERS']['StaticObject'] = static_obj
env['BUILDERS']['Object'] = static_obj
try:
shared_obj = env['BUILDERS']['SharedObject']
except KeyError:
shared_obj = SCons.Builder.Builder(action = {},
emitter = {},
prefix = '$SHOBJPREFIX',
suffix = '$SHOBJSUFFIX',
src_builder = ['CFile', 'CXXFile'],
source_scanner = SourceFileScanner,
single_source = 1)
env['BUILDERS']['SharedObject'] = shared_obj
return (static_obj, shared_obj) | python | def createObjBuilders(env):
try:
static_obj = env['BUILDERS']['StaticObject']
except KeyError:
static_obj = SCons.Builder.Builder(action = {},
emitter = {},
prefix = '$OBJPREFIX',
suffix = '$OBJSUFFIX',
src_builder = ['CFile', 'CXXFile'],
source_scanner = SourceFileScanner,
single_source = 1)
env['BUILDERS']['StaticObject'] = static_obj
env['BUILDERS']['Object'] = static_obj
try:
shared_obj = env['BUILDERS']['SharedObject']
except KeyError:
shared_obj = SCons.Builder.Builder(action = {},
emitter = {},
prefix = '$SHOBJPREFIX',
suffix = '$SHOBJSUFFIX',
src_builder = ['CFile', 'CXXFile'],
source_scanner = SourceFileScanner,
single_source = 1)
env['BUILDERS']['SharedObject'] = shared_obj
return (static_obj, shared_obj) | [
"def",
"createObjBuilders",
"(",
"env",
")",
":",
"try",
":",
"static_obj",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'StaticObject'",
"]",
"except",
"KeyError",
":",
"static_obj",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(",
"action",
"=",
"{",
"}... | This is a utility function that creates the StaticObject
and SharedObject Builders in an Environment if they
are not there already.
If they are there already, we return the existing ones.
This is a separate function because soooo many Tools
use this functionality.
The return is a 2-tuple of (StaticObject, SharedObject) | [
"This",
"is",
"a",
"utility",
"function",
"that",
"creates",
"the",
"StaticObject",
"and",
"SharedObject",
"Builders",
"in",
"an",
"Environment",
"if",
"they",
"are",
"not",
"there",
"already",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L837-L876 |
23,081 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | CreateJarBuilder | def CreateJarBuilder(env):
"""The Jar builder expects a list of class files
which it can package into a jar file.
The jar tool provides an interface for passing other types
of java files such as .java, directories or swig interfaces
and will build them to class files in which it can package
into the jar.
"""
try:
java_jar = env['BUILDERS']['JarFile']
except KeyError:
fs = SCons.Node.FS.get_default_fs()
jar_com = SCons.Action.Action('$JARCOM', '$JARCOMSTR')
java_jar = SCons.Builder.Builder(action = jar_com,
suffix = '$JARSUFFIX',
src_suffix = '$JAVACLASSSUFFIX',
src_builder = 'JavaClassFile',
source_factory = fs.Entry)
env['BUILDERS']['JarFile'] = java_jar
return java_jar | python | def CreateJarBuilder(env):
try:
java_jar = env['BUILDERS']['JarFile']
except KeyError:
fs = SCons.Node.FS.get_default_fs()
jar_com = SCons.Action.Action('$JARCOM', '$JARCOMSTR')
java_jar = SCons.Builder.Builder(action = jar_com,
suffix = '$JARSUFFIX',
src_suffix = '$JAVACLASSSUFFIX',
src_builder = 'JavaClassFile',
source_factory = fs.Entry)
env['BUILDERS']['JarFile'] = java_jar
return java_jar | [
"def",
"CreateJarBuilder",
"(",
"env",
")",
":",
"try",
":",
"java_jar",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'JarFile'",
"]",
"except",
"KeyError",
":",
"fs",
"=",
"SCons",
".",
"Node",
".",
"FS",
".",
"get_default_fs",
"(",
")",
"jar_com",
"=",
... | The Jar builder expects a list of class files
which it can package into a jar file.
The jar tool provides an interface for passing other types
of java files such as .java, directories or swig interfaces
and will build them to class files in which it can package
into the jar. | [
"The",
"Jar",
"builder",
"expects",
"a",
"list",
"of",
"class",
"files",
"which",
"it",
"can",
"package",
"into",
"a",
"jar",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L915-L935 |
23,082 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | ToolInitializerMethod.get_builder | def get_builder(self, env):
"""
Returns the appropriate real Builder for this method name
after having the associated ToolInitializer object apply
the appropriate Tool module.
"""
builder = getattr(env, self.__name__)
self.initializer.apply_tools(env)
builder = getattr(env, self.__name__)
if builder is self:
# There was no Builder added, which means no valid Tool
# for this name was found (or possibly there's a mismatch
# between the name we were called by and the Builder name
# added by the Tool module).
return None
self.initializer.remove_methods(env)
return builder | python | def get_builder(self, env):
builder = getattr(env, self.__name__)
self.initializer.apply_tools(env)
builder = getattr(env, self.__name__)
if builder is self:
# There was no Builder added, which means no valid Tool
# for this name was found (or possibly there's a mismatch
# between the name we were called by and the Builder name
# added by the Tool module).
return None
self.initializer.remove_methods(env)
return builder | [
"def",
"get_builder",
"(",
"self",
",",
"env",
")",
":",
"builder",
"=",
"getattr",
"(",
"env",
",",
"self",
".",
"__name__",
")",
"self",
".",
"initializer",
".",
"apply_tools",
"(",
"env",
")",
"builder",
"=",
"getattr",
"(",
"env",
",",
"self",
".... | Returns the appropriate real Builder for this method name
after having the associated ToolInitializer object apply
the appropriate Tool module. | [
"Returns",
"the",
"appropriate",
"real",
"Builder",
"for",
"this",
"method",
"name",
"after",
"having",
"the",
"associated",
"ToolInitializer",
"object",
"apply",
"the",
"appropriate",
"Tool",
"module",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L1009-L1029 |
23,083 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | ToolInitializer.remove_methods | def remove_methods(self, env):
"""
Removes the methods that were added by the tool initialization
so we no longer copy and re-bind them when the construction
environment gets cloned.
"""
for method in list(self.methods.values()):
env.RemoveMethod(method) | python | def remove_methods(self, env):
for method in list(self.methods.values()):
env.RemoveMethod(method) | [
"def",
"remove_methods",
"(",
"self",
",",
"env",
")",
":",
"for",
"method",
"in",
"list",
"(",
"self",
".",
"methods",
".",
"values",
"(",
")",
")",
":",
"env",
".",
"RemoveMethod",
"(",
"method",
")"
] | Removes the methods that were added by the tool initialization
so we no longer copy and re-bind them when the construction
environment gets cloned. | [
"Removes",
"the",
"methods",
"that",
"were",
"added",
"by",
"the",
"tool",
"initialization",
"so",
"we",
"no",
"longer",
"copy",
"and",
"re",
"-",
"bind",
"them",
"when",
"the",
"construction",
"environment",
"gets",
"cloned",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L1064-L1071 |
23,084 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py | ToolInitializer.apply_tools | def apply_tools(self, env):
"""
Searches the list of associated Tool modules for one that
exists, and applies that to the construction environment.
"""
for t in self.tools:
tool = SCons.Tool.Tool(t)
if tool.exists(env):
env.Tool(tool)
return | python | def apply_tools(self, env):
for t in self.tools:
tool = SCons.Tool.Tool(t)
if tool.exists(env):
env.Tool(tool)
return | [
"def",
"apply_tools",
"(",
"self",
",",
"env",
")",
":",
"for",
"t",
"in",
"self",
".",
"tools",
":",
"tool",
"=",
"SCons",
".",
"Tool",
".",
"Tool",
"(",
"t",
")",
"if",
"tool",
".",
"exists",
"(",
"env",
")",
":",
"env",
".",
"Tool",
"(",
"... | Searches the list of associated Tool modules for one that
exists, and applies that to the construction environment. | [
"Searches",
"the",
"list",
"of",
"associated",
"Tool",
"modules",
"for",
"one",
"that",
"exists",
"and",
"applies",
"that",
"to",
"the",
"construction",
"environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L1073-L1082 |
23,085 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | get_contents_entry | def get_contents_entry(node):
"""Fetch the contents of the entry. Returns the exact binary
contents of the file."""
try:
node = node.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Entry, but return a null
# string so calls to get_contents() in emitters and the
# like (e.g. in qt.py) don't have to disambiguate by hand
# or catch the exception.
return ''
else:
return _get_contents_map[node._func_get_contents](node) | python | def get_contents_entry(node):
try:
node = node.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Entry, but return a null
# string so calls to get_contents() in emitters and the
# like (e.g. in qt.py) don't have to disambiguate by hand
# or catch the exception.
return ''
else:
return _get_contents_map[node._func_get_contents](node) | [
"def",
"get_contents_entry",
"(",
"node",
")",
":",
"try",
":",
"node",
"=",
"node",
".",
"disambiguate",
"(",
"must_exist",
"=",
"1",
")",
"except",
"SCons",
".",
"Errors",
".",
"UserError",
":",
"# There was nothing on disk with which to disambiguate",
"# this e... | Fetch the contents of the entry. Returns the exact binary
contents of the file. | [
"Fetch",
"the",
"contents",
"of",
"the",
"entry",
".",
"Returns",
"the",
"exact",
"binary",
"contents",
"of",
"the",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L188-L201 |
23,086 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | get_contents_dir | def get_contents_dir(node):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
for n in sorted(node.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (n.get_csig(), n.name))
return ''.join(contents) | python | def get_contents_dir(node):
contents = []
for n in sorted(node.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (n.get_csig(), n.name))
return ''.join(contents) | [
"def",
"get_contents_dir",
"(",
"node",
")",
":",
"contents",
"=",
"[",
"]",
"for",
"n",
"in",
"sorted",
"(",
"node",
".",
"children",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
".",
"name",
")",
":",
"contents",
".",
"append",
"(",
"'%s... | Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted. | [
"Return",
"content",
"signatures",
"and",
"names",
"of",
"all",
"our",
"children",
"separated",
"by",
"new",
"-",
"lines",
".",
"Ensure",
"that",
"the",
"nodes",
"are",
"sorted",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L203-L209 |
23,087 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.get_build_env | def get_build_env(self):
"""Fetch the appropriate Environment to build this node.
"""
try:
return self._memo['get_build_env']
except KeyError:
pass
result = self.get_executor().get_build_env()
self._memo['get_build_env'] = result
return result | python | def get_build_env(self):
try:
return self._memo['get_build_env']
except KeyError:
pass
result = self.get_executor().get_build_env()
self._memo['get_build_env'] = result
return result | [
"def",
"get_build_env",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'get_build_env'",
"]",
"except",
"KeyError",
":",
"pass",
"result",
"=",
"self",
".",
"get_executor",
"(",
")",
".",
"get_build_env",
"(",
")",
"self",
".",
... | Fetch the appropriate Environment to build this node. | [
"Fetch",
"the",
"appropriate",
"Environment",
"to",
"build",
"this",
"node",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L616-L625 |
23,088 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.get_executor | def get_executor(self, create=1):
"""Fetch the action executor for this node. Create one if
there isn't already one, and requested to do so."""
try:
executor = self.executor
except AttributeError:
if not create:
raise
try:
act = self.builder.action
except AttributeError:
executor = SCons.Executor.Null(targets=[self])
else:
executor = SCons.Executor.Executor(act,
self.env or self.builder.env,
[self.builder.overrides],
[self],
self.sources)
self.executor = executor
return executor | python | def get_executor(self, create=1):
try:
executor = self.executor
except AttributeError:
if not create:
raise
try:
act = self.builder.action
except AttributeError:
executor = SCons.Executor.Null(targets=[self])
else:
executor = SCons.Executor.Executor(act,
self.env or self.builder.env,
[self.builder.overrides],
[self],
self.sources)
self.executor = executor
return executor | [
"def",
"get_executor",
"(",
"self",
",",
"create",
"=",
"1",
")",
":",
"try",
":",
"executor",
"=",
"self",
".",
"executor",
"except",
"AttributeError",
":",
"if",
"not",
"create",
":",
"raise",
"try",
":",
"act",
"=",
"self",
".",
"builder",
".",
"a... | Fetch the action executor for this node. Create one if
there isn't already one, and requested to do so. | [
"Fetch",
"the",
"action",
"executor",
"for",
"this",
"node",
".",
"Create",
"one",
"if",
"there",
"isn",
"t",
"already",
"one",
"and",
"requested",
"to",
"do",
"so",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L635-L654 |
23,089 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.executor_cleanup | def executor_cleanup(self):
"""Let the executor clean up any cached information."""
try:
executor = self.get_executor(create=None)
except AttributeError:
pass
else:
if executor is not None:
executor.cleanup() | python | def executor_cleanup(self):
try:
executor = self.get_executor(create=None)
except AttributeError:
pass
else:
if executor is not None:
executor.cleanup() | [
"def",
"executor_cleanup",
"(",
"self",
")",
":",
"try",
":",
"executor",
"=",
"self",
".",
"get_executor",
"(",
"create",
"=",
"None",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"if",
"executor",
"is",
"not",
"None",
":",
"executor",
"."... | Let the executor clean up any cached information. | [
"Let",
"the",
"executor",
"clean",
"up",
"any",
"cached",
"information",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L656-L664 |
23,090 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.prepare | def prepare(self):
"""Prepare for this Node to be built.
This is called after the Taskmaster has decided that the Node
is out-of-date and must be rebuilt, but before actually calling
the method to build the Node.
This default implementation checks that explicit or implicit
dependencies either exist or are derived, and initializes the
BuildInfo structure that will hold the information about how
this node is, uh, built.
(The existence of source files is checked separately by the
Executor, which aggregates checks for all of the targets built
by a specific action.)
Overriding this method allows for for a Node subclass to remove
the underlying file from the file system. Note that subclass
methods should call this base class method to get the child
check and the BuildInfo structure.
"""
if self.depends is not None:
for d in self.depends:
if d.missing():
msg = "Explicit dependency `%s' not found, needed by target `%s'."
raise SCons.Errors.StopError(msg % (d, self))
if self.implicit is not None:
for i in self.implicit:
if i.missing():
msg = "Implicit dependency `%s' not found, needed by target `%s'."
raise SCons.Errors.StopError(msg % (i, self))
self.binfo = self.get_binfo() | python | def prepare(self):
if self.depends is not None:
for d in self.depends:
if d.missing():
msg = "Explicit dependency `%s' not found, needed by target `%s'."
raise SCons.Errors.StopError(msg % (d, self))
if self.implicit is not None:
for i in self.implicit:
if i.missing():
msg = "Implicit dependency `%s' not found, needed by target `%s'."
raise SCons.Errors.StopError(msg % (i, self))
self.binfo = self.get_binfo() | [
"def",
"prepare",
"(",
"self",
")",
":",
"if",
"self",
".",
"depends",
"is",
"not",
"None",
":",
"for",
"d",
"in",
"self",
".",
"depends",
":",
"if",
"d",
".",
"missing",
"(",
")",
":",
"msg",
"=",
"\"Explicit dependency `%s' not found, needed by target `%... | Prepare for this Node to be built.
This is called after the Taskmaster has decided that the Node
is out-of-date and must be rebuilt, but before actually calling
the method to build the Node.
This default implementation checks that explicit or implicit
dependencies either exist or are derived, and initializes the
BuildInfo structure that will hold the information about how
this node is, uh, built.
(The existence of source files is checked separately by the
Executor, which aggregates checks for all of the targets built
by a specific action.)
Overriding this method allows for for a Node subclass to remove
the underlying file from the file system. Note that subclass
methods should call this base class method to get the child
check and the BuildInfo structure. | [
"Prepare",
"for",
"this",
"Node",
"to",
"be",
"built",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L703-L734 |
23,091 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.build | def build(self, **kw):
"""Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff
in built().
"""
try:
self.get_executor()(self, **kw)
except SCons.Errors.BuildError as e:
e.node = self
raise | python | def build(self, **kw):
try:
self.get_executor()(self, **kw)
except SCons.Errors.BuildError as e:
e.node = self
raise | [
"def",
"build",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"self",
".",
"get_executor",
"(",
")",
"(",
"self",
",",
"*",
"*",
"kw",
")",
"except",
"SCons",
".",
"Errors",
".",
"BuildError",
"as",
"e",
":",
"e",
".",
"node",
"=",
... | Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff
in built(). | [
"Actually",
"build",
"the",
"node",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L736-L752 |
23,092 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.built | def built(self):
"""Called just after this node is successfully built."""
# Clear the implicit dependency caches of any Nodes
# waiting for this Node to be built.
for parent in self.waiting_parents:
parent.implicit = None
self.clear()
if self.pseudo:
if self.exists():
raise SCons.Errors.UserError("Pseudo target " + str(self) + " must not exist")
else:
if not self.exists() and do_store_info:
SCons.Warnings.warn(SCons.Warnings.TargetNotBuiltWarning,
"Cannot find target " + str(self) + " after building")
self.ninfo.update(self) | python | def built(self):
# Clear the implicit dependency caches of any Nodes
# waiting for this Node to be built.
for parent in self.waiting_parents:
parent.implicit = None
self.clear()
if self.pseudo:
if self.exists():
raise SCons.Errors.UserError("Pseudo target " + str(self) + " must not exist")
else:
if not self.exists() and do_store_info:
SCons.Warnings.warn(SCons.Warnings.TargetNotBuiltWarning,
"Cannot find target " + str(self) + " after building")
self.ninfo.update(self) | [
"def",
"built",
"(",
"self",
")",
":",
"# Clear the implicit dependency caches of any Nodes",
"# waiting for this Node to be built.",
"for",
"parent",
"in",
"self",
".",
"waiting_parents",
":",
"parent",
".",
"implicit",
"=",
"None",
"self",
".",
"clear",
"(",
")",
... | Called just after this node is successfully built. | [
"Called",
"just",
"after",
"this",
"node",
"is",
"successfully",
"built",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L754-L771 |
23,093 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.has_builder | def has_builder(self):
"""Return whether this Node has a builder or not.
In Boolean tests, this turns out to be a *lot* more efficient
than simply examining the builder attribute directly ("if
node.builder: ..."). When the builder attribute is examined
directly, it ends up calling __getattr__ for both the __len__
and __nonzero__ attributes on instances of our Builder Proxy
class(es), generating a bazillion extra calls and slowing
things down immensely.
"""
try:
b = self.builder
except AttributeError:
# There was no explicit builder for this Node, so initialize
# the self.builder attribute to None now.
b = self.builder = None
return b is not None | python | def has_builder(self):
try:
b = self.builder
except AttributeError:
# There was no explicit builder for this Node, so initialize
# the self.builder attribute to None now.
b = self.builder = None
return b is not None | [
"def",
"has_builder",
"(",
"self",
")",
":",
"try",
":",
"b",
"=",
"self",
".",
"builder",
"except",
"AttributeError",
":",
"# There was no explicit builder for this Node, so initialize",
"# the self.builder attribute to None now.",
"b",
"=",
"self",
".",
"builder",
"="... | Return whether this Node has a builder or not.
In Boolean tests, this turns out to be a *lot* more efficient
than simply examining the builder attribute directly ("if
node.builder: ..."). When the builder attribute is examined
directly, it ends up calling __getattr__ for both the __len__
and __nonzero__ attributes on instances of our Builder Proxy
class(es), generating a bazillion extra calls and slowing
things down immensely. | [
"Return",
"whether",
"this",
"Node",
"has",
"a",
"builder",
"or",
"not",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L858-L875 |
23,094 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.get_implicit_deps | def get_implicit_deps(self, env, initial_scanner, path_func, kw = {}):
"""Return a list of implicit dependencies for this node.
This method exists to handle recursive invocation of the scanner
on the implicit dependencies returned by the scanner, if the
scanner's recursive flag says that we should.
"""
nodes = [self]
seen = set(nodes)
dependencies = []
path_memo = {}
root_node_scanner = self._get_scanner(env, initial_scanner, None, kw)
while nodes:
node = nodes.pop(0)
scanner = node._get_scanner(env, initial_scanner, root_node_scanner, kw)
if not scanner:
continue
try:
path = path_memo[scanner]
except KeyError:
path = path_func(scanner)
path_memo[scanner] = path
included_deps = [x for x in node.get_found_includes(env, scanner, path) if x not in seen]
if included_deps:
dependencies.extend(included_deps)
seen.update(included_deps)
nodes.extend(scanner.recurse_nodes(included_deps))
return dependencies | python | def get_implicit_deps(self, env, initial_scanner, path_func, kw = {}):
nodes = [self]
seen = set(nodes)
dependencies = []
path_memo = {}
root_node_scanner = self._get_scanner(env, initial_scanner, None, kw)
while nodes:
node = nodes.pop(0)
scanner = node._get_scanner(env, initial_scanner, root_node_scanner, kw)
if not scanner:
continue
try:
path = path_memo[scanner]
except KeyError:
path = path_func(scanner)
path_memo[scanner] = path
included_deps = [x for x in node.get_found_includes(env, scanner, path) if x not in seen]
if included_deps:
dependencies.extend(included_deps)
seen.update(included_deps)
nodes.extend(scanner.recurse_nodes(included_deps))
return dependencies | [
"def",
"get_implicit_deps",
"(",
"self",
",",
"env",
",",
"initial_scanner",
",",
"path_func",
",",
"kw",
"=",
"{",
"}",
")",
":",
"nodes",
"=",
"[",
"self",
"]",
"seen",
"=",
"set",
"(",
"nodes",
")",
"dependencies",
"=",
"[",
"]",
"path_memo",
"=",... | Return a list of implicit dependencies for this node.
This method exists to handle recursive invocation of the scanner
on the implicit dependencies returned by the scanner, if the
scanner's recursive flag says that we should. | [
"Return",
"a",
"list",
"of",
"implicit",
"dependencies",
"for",
"this",
"node",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L929-L962 |
23,095 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.get_source_scanner | def get_source_scanner(self, node):
"""Fetch the source scanner for the specified node
NOTE: "self" is the target being built, "node" is
the source file for which we want to fetch the scanner.
Implies self.has_builder() is true; again, expect to only be
called from locations where this is already verified.
This function may be called very often; it attempts to cache
the scanner found to improve performance.
"""
scanner = None
try:
scanner = self.builder.source_scanner
except AttributeError:
pass
if not scanner:
# The builder didn't have an explicit scanner, so go look up
# a scanner from env['SCANNERS'] based on the node's scanner
# key (usually the file extension).
scanner = self.get_env_scanner(self.get_build_env())
if scanner:
scanner = scanner.select(node)
return scanner | python | def get_source_scanner(self, node):
scanner = None
try:
scanner = self.builder.source_scanner
except AttributeError:
pass
if not scanner:
# The builder didn't have an explicit scanner, so go look up
# a scanner from env['SCANNERS'] based on the node's scanner
# key (usually the file extension).
scanner = self.get_env_scanner(self.get_build_env())
if scanner:
scanner = scanner.select(node)
return scanner | [
"def",
"get_source_scanner",
"(",
"self",
",",
"node",
")",
":",
"scanner",
"=",
"None",
"try",
":",
"scanner",
"=",
"self",
".",
"builder",
".",
"source_scanner",
"except",
"AttributeError",
":",
"pass",
"if",
"not",
"scanner",
":",
"# The builder didn't have... | Fetch the source scanner for the specified node
NOTE: "self" is the target being built, "node" is
the source file for which we want to fetch the scanner.
Implies self.has_builder() is true; again, expect to only be
called from locations where this is already verified.
This function may be called very often; it attempts to cache
the scanner found to improve performance. | [
"Fetch",
"the",
"source",
"scanner",
"for",
"the",
"specified",
"node"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L987-L1011 |
23,096 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.scan | def scan(self):
"""Scan this node's dependents for implicit dependencies."""
# Don't bother scanning non-derived files, because we don't
# care what their dependencies are.
# Don't scan again, if we already have scanned.
if self.implicit is not None:
return
self.implicit = []
self.implicit_set = set()
self._children_reset()
if not self.has_builder():
return
build_env = self.get_build_env()
executor = self.get_executor()
# Here's where we implement --implicit-cache.
if implicit_cache and not implicit_deps_changed:
implicit = self.get_stored_implicit()
if implicit is not None:
# We now add the implicit dependencies returned from the
# stored .sconsign entry to have already been converted
# to Nodes for us. (We used to run them through a
# source_factory function here.)
# Update all of the targets with them. This
# essentially short-circuits an N*M scan of the
# sources for each individual target, which is a hell
# of a lot more efficient.
for tgt in executor.get_all_targets():
tgt.add_to_implicit(implicit)
if implicit_deps_unchanged or self.is_up_to_date():
return
# one of this node's sources has changed,
# so we must recalculate the implicit deps for all targets
for tgt in executor.get_all_targets():
tgt.implicit = []
tgt.implicit_set = set()
# Have the executor scan the sources.
executor.scan_sources(self.builder.source_scanner)
# If there's a target scanner, have the executor scan the target
# node itself and associated targets that might be built.
scanner = self.get_target_scanner()
if scanner:
executor.scan_targets(scanner) | python | def scan(self):
# Don't bother scanning non-derived files, because we don't
# care what their dependencies are.
# Don't scan again, if we already have scanned.
if self.implicit is not None:
return
self.implicit = []
self.implicit_set = set()
self._children_reset()
if not self.has_builder():
return
build_env = self.get_build_env()
executor = self.get_executor()
# Here's where we implement --implicit-cache.
if implicit_cache and not implicit_deps_changed:
implicit = self.get_stored_implicit()
if implicit is not None:
# We now add the implicit dependencies returned from the
# stored .sconsign entry to have already been converted
# to Nodes for us. (We used to run them through a
# source_factory function here.)
# Update all of the targets with them. This
# essentially short-circuits an N*M scan of the
# sources for each individual target, which is a hell
# of a lot more efficient.
for tgt in executor.get_all_targets():
tgt.add_to_implicit(implicit)
if implicit_deps_unchanged or self.is_up_to_date():
return
# one of this node's sources has changed,
# so we must recalculate the implicit deps for all targets
for tgt in executor.get_all_targets():
tgt.implicit = []
tgt.implicit_set = set()
# Have the executor scan the sources.
executor.scan_sources(self.builder.source_scanner)
# If there's a target scanner, have the executor scan the target
# node itself and associated targets that might be built.
scanner = self.get_target_scanner()
if scanner:
executor.scan_targets(scanner) | [
"def",
"scan",
"(",
"self",
")",
":",
"# Don't bother scanning non-derived files, because we don't",
"# care what their dependencies are.",
"# Don't scan again, if we already have scanned.",
"if",
"self",
".",
"implicit",
"is",
"not",
"None",
":",
"return",
"self",
".",
"impl... | Scan this node's dependents for implicit dependencies. | [
"Scan",
"this",
"node",
"s",
"dependents",
"for",
"implicit",
"dependencies",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1020-L1067 |
23,097 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.get_binfo | def get_binfo(self):
"""
Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's signatures. We expect that they're
already built and updated by someone else, if that's
what's wanted.
"""
try:
return self.binfo
except AttributeError:
pass
binfo = self.new_binfo()
self.binfo = binfo
executor = self.get_executor()
ignore_set = self.ignore_set
if self.has_builder():
binfo.bact = str(executor)
binfo.bactsig = SCons.Util.MD5signature(executor.get_contents())
if self._specific_sources:
sources = [ s for s in self.sources if not s in ignore_set]
else:
sources = executor.get_unignored_sources(self, self.ignore)
seen = set()
binfo.bsources = [s for s in sources if s not in seen and not seen.add(s)]
binfo.bsourcesigs = [s.get_ninfo() for s in binfo.bsources]
binfo.bdepends = self.depends
binfo.bdependsigs = [d.get_ninfo() for d in self.depends if d not in ignore_set]
binfo.bimplicit = self.implicit or []
binfo.bimplicitsigs = [i.get_ninfo() for i in binfo.bimplicit if i not in ignore_set]
return binfo | python | def get_binfo(self):
try:
return self.binfo
except AttributeError:
pass
binfo = self.new_binfo()
self.binfo = binfo
executor = self.get_executor()
ignore_set = self.ignore_set
if self.has_builder():
binfo.bact = str(executor)
binfo.bactsig = SCons.Util.MD5signature(executor.get_contents())
if self._specific_sources:
sources = [ s for s in self.sources if not s in ignore_set]
else:
sources = executor.get_unignored_sources(self, self.ignore)
seen = set()
binfo.bsources = [s for s in sources if s not in seen and not seen.add(s)]
binfo.bsourcesigs = [s.get_ninfo() for s in binfo.bsources]
binfo.bdepends = self.depends
binfo.bdependsigs = [d.get_ninfo() for d in self.depends if d not in ignore_set]
binfo.bimplicit = self.implicit or []
binfo.bimplicitsigs = [i.get_ninfo() for i in binfo.bimplicit if i not in ignore_set]
return binfo | [
"def",
"get_binfo",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"binfo",
"except",
"AttributeError",
":",
"pass",
"binfo",
"=",
"self",
".",
"new_binfo",
"(",
")",
"self",
".",
"binfo",
"=",
"binfo",
"executor",
"=",
"self",
".",
"get_exe... | Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's signatures. We expect that they're
already built and updated by someone else, if that's
what's wanted. | [
"Fetch",
"a",
"node",
"s",
"build",
"information",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1109-L1155 |
23,098 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.add_dependency | def add_dependency(self, depend):
"""Adds dependencies."""
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | python | def add_dependency(self, depend):
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | [
"def",
"add_dependency",
"(",
"self",
",",
"depend",
")",
":",
"try",
":",
"self",
".",
"_add_child",
"(",
"self",
".",
"depends",
",",
"self",
".",
"depends_set",
",",
"depend",
")",
"except",
"TypeError",
"as",
"e",
":",
"e",
"=",
"e",
".",
"args",... | Adds dependencies. | [
"Adds",
"dependencies",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1232-L1242 |
23,099 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.add_ignore | def add_ignore(self, depend):
"""Adds dependencies to ignore."""
try:
self._add_child(self.ignore, self.ignore_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | python | def add_ignore(self, depend):
try:
self._add_child(self.ignore, self.ignore_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | [
"def",
"add_ignore",
"(",
"self",
",",
"depend",
")",
":",
"try",
":",
"self",
".",
"_add_child",
"(",
"self",
".",
"ignore",
",",
"self",
".",
"ignore_set",
",",
"depend",
")",
"except",
"TypeError",
"as",
"e",
":",
"e",
"=",
"e",
".",
"args",
"["... | Adds dependencies to ignore. | [
"Adds",
"dependencies",
"to",
"ignore",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1251-L1261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.