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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,000 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py | OrderedAWSIOTClient._on_receive | def _on_receive(self, client, userdata, message):
"""Callback called whenever we receive a message on a subscribed topic
Args:
client (string): The client id of the client receiving the message
userdata (string): Any user data set with the underlying MQTT client
message (object): The mesage with a topic and payload.
"""
topic = message.topic
encoded = message.payload
try:
packet = json.loads(encoded)
except ValueError:
self._logger.warn("Could not decode json packet: %s", encoded)
return
try:
seq = packet['sequence']
message_data = packet['message']
except KeyError:
self._logger.warn("Message received did not have required sequence and message keys: %s", packet)
return
# If we received a packet that does not fit into a queue, check our wildcard
# queues
if topic not in self.queues:
found = False
for _, regex, callback, ordered in self.wildcard_queues:
if regex.match(topic):
self.queues[topic] = PacketQueue(0, callback, ordered)
found = True
break
if not found:
self._logger.warn("Received message for unknown topic: %s", topic)
return
self.queues[topic].receive(seq, [seq, topic, message_data]) | python | def _on_receive(self, client, userdata, message):
topic = message.topic
encoded = message.payload
try:
packet = json.loads(encoded)
except ValueError:
self._logger.warn("Could not decode json packet: %s", encoded)
return
try:
seq = packet['sequence']
message_data = packet['message']
except KeyError:
self._logger.warn("Message received did not have required sequence and message keys: %s", packet)
return
# If we received a packet that does not fit into a queue, check our wildcard
# queues
if topic not in self.queues:
found = False
for _, regex, callback, ordered in self.wildcard_queues:
if regex.match(topic):
self.queues[topic] = PacketQueue(0, callback, ordered)
found = True
break
if not found:
self._logger.warn("Received message for unknown topic: %s", topic)
return
self.queues[topic].receive(seq, [seq, topic, message_data]) | [
"def",
"_on_receive",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"message",
")",
":",
"topic",
"=",
"message",
".",
"topic",
"encoded",
"=",
"message",
".",
"payload",
"try",
":",
"packet",
"=",
"json",
".",
"loads",
"(",
"encoded",
")",
"except... | Callback called whenever we receive a message on a subscribed topic
Args:
client (string): The client id of the client receiving the message
userdata (string): Any user data set with the underlying MQTT client
message (object): The mesage with a topic and payload. | [
"Callback",
"called",
"whenever",
"we",
"receive",
"a",
"message",
"on",
"a",
"subscribed",
"topic"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/mqtt_client.py#L222-L261 |
24,001 | iotile/coretools | iotileship/iotile/ship/actions/sync_rtc_step.py | SyncRTCStep.run | def run(self, resources):
"""Sets the RTC timestamp to UTC.
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step.
"""
hwman = resources['connection']
con = hwman.hwman.controller()
test_interface = con.test_interface()
try:
test_interface.synchronize_clock()
print('Time currently set at %s' % test_interface.current_time_str())
except:
raise ArgumentError('Error setting RTC time, check if controller actually has RTC or if iotile-support-lib-controller-3 is updated') | python | def run(self, resources):
hwman = resources['connection']
con = hwman.hwman.controller()
test_interface = con.test_interface()
try:
test_interface.synchronize_clock()
print('Time currently set at %s' % test_interface.current_time_str())
except:
raise ArgumentError('Error setting RTC time, check if controller actually has RTC or if iotile-support-lib-controller-3 is updated') | [
"def",
"run",
"(",
"self",
",",
"resources",
")",
":",
"hwman",
"=",
"resources",
"[",
"'connection'",
"]",
"con",
"=",
"hwman",
".",
"hwman",
".",
"controller",
"(",
")",
"test_interface",
"=",
"con",
".",
"test_interface",
"(",
")",
"try",
":",
"test... | Sets the RTC timestamp to UTC.
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step. | [
"Sets",
"the",
"RTC",
"timestamp",
"to",
"UTC",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/actions/sync_rtc_step.py#L21-L35 |
24,002 | iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | CommandFile.add | def add(self, command, *args):
"""Add a command to this command file.
Args:
command (str): The command to add
*args (str): The parameters to call the command with
"""
cmd = Command(command, args)
self.commands.append(cmd) | python | def add(self, command, *args):
cmd = Command(command, args)
self.commands.append(cmd) | [
"def",
"add",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"cmd",
"=",
"Command",
"(",
"command",
",",
"args",
")",
"self",
".",
"commands",
".",
"append",
"(",
"cmd",
")"
] | Add a command to this command file.
Args:
command (str): The command to add
*args (str): The parameters to call the command with | [
"Add",
"a",
"command",
"to",
"this",
"command",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L38-L47 |
24,003 | iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | CommandFile.save | def save(self, outpath):
"""Save this command file as an ascii file.
Agrs:
outpath (str): The output path to save.
"""
with open(outpath, "w") as outfile:
outfile.write(self.dump()) | python | def save(self, outpath):
with open(outpath, "w") as outfile:
outfile.write(self.dump()) | [
"def",
"save",
"(",
"self",
",",
"outpath",
")",
":",
"with",
"open",
"(",
"outpath",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"self",
".",
"dump",
"(",
")",
")"
] | Save this command file as an ascii file.
Agrs:
outpath (str): The output path to save. | [
"Save",
"this",
"command",
"file",
"as",
"an",
"ascii",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L49-L57 |
24,004 | iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | CommandFile.dump | def dump(self):
"""Dump all commands in this object to a string.
Returns:
str: An encoded list of commands separated by
\n characters suitable for saving to a file.
"""
out = []
out.append(self.filetype)
out.append("Format: {}".format(self.version))
out.append("Type: ASCII")
out.append("")
for cmd in self.commands:
out.append(self.encode(cmd))
return "\n".join(out) + "\n" | python | def dump(self):
out = []
out.append(self.filetype)
out.append("Format: {}".format(self.version))
out.append("Type: ASCII")
out.append("")
for cmd in self.commands:
out.append(self.encode(cmd))
return "\n".join(out) + "\n" | [
"def",
"dump",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"out",
".",
"append",
"(",
"self",
".",
"filetype",
")",
"out",
".",
"append",
"(",
"\"Format: {}\"",
".",
"format",
"(",
"self",
".",
"version",
")",
")",
"out",
".",
"append",
"(",
"\"... | Dump all commands in this object to a string.
Returns:
str: An encoded list of commands separated by
\n characters suitable for saving to a file. | [
"Dump",
"all",
"commands",
"in",
"this",
"object",
"to",
"a",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L59-L77 |
24,005 | iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | CommandFile.FromString | def FromString(cls, indata):
"""Load a CommandFile from a string.
The string should be produced from a previous call to
encode.
Args:
indata (str): The encoded input data.
Returns:
CommandFile: The decoded CommandFile object.
"""
lines = [x.strip() for x in indata.split("\n") if not x.startswith('#') and not x.strip() == ""]
if len(lines) < 3:
raise DataError("Invalid CommandFile string that did not contain 3 header lines", lines=lines)
fmt_line, version_line, ascii_line = lines[:3]
if not version_line.startswith("Format: "):
raise DataError("Invalid format version that did not start with 'Format: '", line=version_line)
version = version_line[8:]
if ascii_line != "Type: ASCII":
raise DataError("Unknown file type line (expected Type: ASCII)", line=ascii_line)
cmds = [cls.decode(x) for x in lines[3:]]
return CommandFile(fmt_line, version, cmds) | python | def FromString(cls, indata):
lines = [x.strip() for x in indata.split("\n") if not x.startswith('#') and not x.strip() == ""]
if len(lines) < 3:
raise DataError("Invalid CommandFile string that did not contain 3 header lines", lines=lines)
fmt_line, version_line, ascii_line = lines[:3]
if not version_line.startswith("Format: "):
raise DataError("Invalid format version that did not start with 'Format: '", line=version_line)
version = version_line[8:]
if ascii_line != "Type: ASCII":
raise DataError("Unknown file type line (expected Type: ASCII)", line=ascii_line)
cmds = [cls.decode(x) for x in lines[3:]]
return CommandFile(fmt_line, version, cmds) | [
"def",
"FromString",
"(",
"cls",
",",
"indata",
")",
":",
"lines",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"indata",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"not",
"x",
".",
"startswith",
"(",
"'#'",
")",
"and",
"not",
"x",
".... | Load a CommandFile from a string.
The string should be produced from a previous call to
encode.
Args:
indata (str): The encoded input data.
Returns:
CommandFile: The decoded CommandFile object. | [
"Load",
"a",
"CommandFile",
"from",
"a",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L80-L109 |
24,006 | iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | CommandFile.FromFile | def FromFile(cls, inpath):
"""Load a CommandFile from a path.
Args:
inpath (str): The path to the file to load
Returns:
CommandFile: The decoded CommandFile object.
"""
with open(inpath, "r") as infile:
indata = infile.read()
return cls.FromString(indata) | python | def FromFile(cls, inpath):
with open(inpath, "r") as infile:
indata = infile.read()
return cls.FromString(indata) | [
"def",
"FromFile",
"(",
"cls",
",",
"inpath",
")",
":",
"with",
"open",
"(",
"inpath",
",",
"\"r\"",
")",
"as",
"infile",
":",
"indata",
"=",
"infile",
".",
"read",
"(",
")",
"return",
"cls",
".",
"FromString",
"(",
"indata",
")"
] | Load a CommandFile from a path.
Args:
inpath (str): The path to the file to load
Returns:
CommandFile: The decoded CommandFile object. | [
"Load",
"a",
"CommandFile",
"from",
"a",
"path",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L112-L125 |
24,007 | iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | CommandFile.encode | def encode(cls, command):
"""Encode a command as an unambiguous string.
Args:
command (Command): The command to encode.
Returns:
str: The encoded command
"""
args = []
for arg in command.args:
if not isinstance(arg, str):
arg = str(arg)
if "," in arg or arg.startswith(" ") or arg.endswith(" ") or arg.startswith("hex:"):
arg = "hex:{}".format(hexlify(arg.encode('utf-8')).decode('utf-8'))
args.append(arg)
argstr = ""
if len(args) > 0:
argstr = " {" + ",".join(args) + "}"
return command.name + argstr | python | def encode(cls, command):
args = []
for arg in command.args:
if not isinstance(arg, str):
arg = str(arg)
if "," in arg or arg.startswith(" ") or arg.endswith(" ") or arg.startswith("hex:"):
arg = "hex:{}".format(hexlify(arg.encode('utf-8')).decode('utf-8'))
args.append(arg)
argstr = ""
if len(args) > 0:
argstr = " {" + ",".join(args) + "}"
return command.name + argstr | [
"def",
"encode",
"(",
"cls",
",",
"command",
")",
":",
"args",
"=",
"[",
"]",
"for",
"arg",
"in",
"command",
".",
"args",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
"if",
"\",\"",
"in",... | Encode a command as an unambiguous string.
Args:
command (Command): The command to encode.
Returns:
str: The encoded command | [
"Encode",
"a",
"command",
"as",
"an",
"unambiguous",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L128-L153 |
24,008 | iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | CommandFile.decode | def decode(cls, command_str):
"""Decode a string encoded command back into a Command object.
Args:
command_str (str): The encoded command string output from a
previous call to encode.
Returns:
Command: The decoded Command object.
"""
name, _, arg = command_str.partition(" ")
args = []
if len(arg) > 0:
if arg[0] != '{' or arg[-1] != '}':
raise DataError("Invalid command, argument is not contained in { and }", arg=arg, cmd=name)
arg = arg[1:-1]
args = arg.split(",")
proc = []
for arg in args:
if arg.startswith("hex:"):
arg = unhexlify(arg[4:]).decode('utf-8')
proc.append(arg)
return Command(name, proc) | python | def decode(cls, command_str):
name, _, arg = command_str.partition(" ")
args = []
if len(arg) > 0:
if arg[0] != '{' or arg[-1] != '}':
raise DataError("Invalid command, argument is not contained in { and }", arg=arg, cmd=name)
arg = arg[1:-1]
args = arg.split(",")
proc = []
for arg in args:
if arg.startswith("hex:"):
arg = unhexlify(arg[4:]).decode('utf-8')
proc.append(arg)
return Command(name, proc) | [
"def",
"decode",
"(",
"cls",
",",
"command_str",
")",
":",
"name",
",",
"_",
",",
"arg",
"=",
"command_str",
".",
"partition",
"(",
"\" \"",
")",
"args",
"=",
"[",
"]",
"if",
"len",
"(",
"arg",
")",
">",
"0",
":",
"if",
"arg",
"[",
"0",
"]",
... | Decode a string encoded command back into a Command object.
Args:
command_str (str): The encoded command string output from a
previous call to encode.
Returns:
Command: The decoded Command object. | [
"Decode",
"a",
"string",
"encoded",
"command",
"back",
"into",
"a",
"Command",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L156-L186 |
24,009 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/packet_queue.py | PacketQueue.receive | def receive(self, sequence, args):
"""Receive one packet
If the sequence number is one we've already seen before, it is dropped.
If it is not the next expected sequence number, it is put into the
_out_of_order queue to be processed once the holes in sequence number
are filled in.
Args:
sequence (int): The sequence number of the received packet
args (list): The list of packet contents that will be passed to callback
as callback(*args)
"""
# If we are told to ignore sequence numbers, just pass the packet on
if not self._reorder:
self._callback(*args)
return
# If this packet is in the past, drop it
if self._next_expected is not None and sequence < self._next_expected:
print("Dropping out of order packet, seq=%d" % sequence)
return
self._out_of_order.append((sequence, args))
self._out_of_order.sort(key=lambda x: x[0])
# If we have received packets, attempt to process them in order
while len(self._out_of_order) > 0:
seq, args = self._out_of_order[0]
if self._next_expected is not None and seq != self._next_expected:
return
self._callback(*args)
self._out_of_order.pop(0)
self._next_expected = seq+1 | python | def receive(self, sequence, args):
# If we are told to ignore sequence numbers, just pass the packet on
if not self._reorder:
self._callback(*args)
return
# If this packet is in the past, drop it
if self._next_expected is not None and sequence < self._next_expected:
print("Dropping out of order packet, seq=%d" % sequence)
return
self._out_of_order.append((sequence, args))
self._out_of_order.sort(key=lambda x: x[0])
# If we have received packets, attempt to process them in order
while len(self._out_of_order) > 0:
seq, args = self._out_of_order[0]
if self._next_expected is not None and seq != self._next_expected:
return
self._callback(*args)
self._out_of_order.pop(0)
self._next_expected = seq+1 | [
"def",
"receive",
"(",
"self",
",",
"sequence",
",",
"args",
")",
":",
"# If we are told to ignore sequence numbers, just pass the packet on",
"if",
"not",
"self",
".",
"_reorder",
":",
"self",
".",
"_callback",
"(",
"*",
"args",
")",
"return",
"# If this packet is ... | Receive one packet
If the sequence number is one we've already seen before, it is dropped.
If it is not the next expected sequence number, it is put into the
_out_of_order queue to be processed once the holes in sequence number
are filled in.
Args:
sequence (int): The sequence number of the received packet
args (list): The list of packet contents that will be passed to callback
as callback(*args) | [
"Receive",
"one",
"packet"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/packet_queue.py#L33-L70 |
24,010 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mwcc.py | set_vars | def set_vars(env):
"""Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars
MWCW_VERSIONS is set to a list of objects representing installed versions
MWCW_VERSION is set to the version object that will be used for building.
MWCW_VERSION can be set to a string during Environment
construction to influence which version is chosen, otherwise
the latest one from MWCW_VERSIONS is used.
Returns true if at least one version is found, false otherwise
"""
desired = env.get('MWCW_VERSION', '')
# return right away if the variables are already set
if isinstance(desired, MWVersion):
return 1
elif desired is None:
return 0
versions = find_versions()
version = None
if desired:
for v in versions:
if str(v) == desired:
version = v
elif versions:
version = versions[-1]
env['MWCW_VERSIONS'] = versions
env['MWCW_VERSION'] = version
if version is None:
return 0
env.PrependENVPath('PATH', version.clpath)
env.PrependENVPath('PATH', version.dllpath)
ENV = env['ENV']
ENV['CWFolder'] = version.path
ENV['LM_LICENSE_FILE'] = version.license
plus = lambda x: '+%s' % x
ENV['MWCIncludes'] = os.pathsep.join(map(plus, version.includes))
ENV['MWLibraries'] = os.pathsep.join(map(plus, version.libs))
return 1 | python | def set_vars(env):
desired = env.get('MWCW_VERSION', '')
# return right away if the variables are already set
if isinstance(desired, MWVersion):
return 1
elif desired is None:
return 0
versions = find_versions()
version = None
if desired:
for v in versions:
if str(v) == desired:
version = v
elif versions:
version = versions[-1]
env['MWCW_VERSIONS'] = versions
env['MWCW_VERSION'] = version
if version is None:
return 0
env.PrependENVPath('PATH', version.clpath)
env.PrependENVPath('PATH', version.dllpath)
ENV = env['ENV']
ENV['CWFolder'] = version.path
ENV['LM_LICENSE_FILE'] = version.license
plus = lambda x: '+%s' % x
ENV['MWCIncludes'] = os.pathsep.join(map(plus, version.includes))
ENV['MWLibraries'] = os.pathsep.join(map(plus, version.libs))
return 1 | [
"def",
"set_vars",
"(",
"env",
")",
":",
"desired",
"=",
"env",
".",
"get",
"(",
"'MWCW_VERSION'",
",",
"''",
")",
"# return right away if the variables are already set",
"if",
"isinstance",
"(",
"desired",
",",
"MWVersion",
")",
":",
"return",
"1",
"elif",
"d... | Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars
MWCW_VERSIONS is set to a list of objects representing installed versions
MWCW_VERSION is set to the version object that will be used for building.
MWCW_VERSION can be set to a string during Environment
construction to influence which version is chosen, otherwise
the latest one from MWCW_VERSIONS is used.
Returns true if at least one version is found, false otherwise | [
"Set",
"MWCW_VERSION",
"MWCW_VERSIONS",
"and",
"some",
"codewarrior",
"environment",
"vars"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mwcc.py#L40-L84 |
24,011 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mwcc.py | find_versions | def find_versions():
"""Return a list of MWVersion objects representing installed versions"""
versions = []
### This function finds CodeWarrior by reading from the registry on
### Windows. Some other method needs to be implemented for other
### platforms, maybe something that calls env.WhereIs('mwcc')
if SCons.Util.can_read_reg:
try:
HLM = SCons.Util.HKEY_LOCAL_MACHINE
product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions'
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
while True:
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
try:
version = SCons.Util.RegQueryValueEx(name_key, 'VERSION')
path = SCons.Util.RegQueryValueEx(name_key, 'PATH')
mwv = MWVersion(version[0], path[0], 'Win32-X86')
versions.append(mwv)
except SCons.Util.RegError:
pass
i = i + 1
except SCons.Util.RegError:
pass
return versions | python | def find_versions():
versions = []
### This function finds CodeWarrior by reading from the registry on
### Windows. Some other method needs to be implemented for other
### platforms, maybe something that calls env.WhereIs('mwcc')
if SCons.Util.can_read_reg:
try:
HLM = SCons.Util.HKEY_LOCAL_MACHINE
product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions'
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
while True:
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
try:
version = SCons.Util.RegQueryValueEx(name_key, 'VERSION')
path = SCons.Util.RegQueryValueEx(name_key, 'PATH')
mwv = MWVersion(version[0], path[0], 'Win32-X86')
versions.append(mwv)
except SCons.Util.RegError:
pass
i = i + 1
except SCons.Util.RegError:
pass
return versions | [
"def",
"find_versions",
"(",
")",
":",
"versions",
"=",
"[",
"]",
"### This function finds CodeWarrior by reading from the registry on",
"### Windows. Some other method needs to be implemented for other",
"### platforms, maybe something that calls env.WhereIs('mwcc')",
"if",
"SCons",
"."... | Return a list of MWVersion objects representing installed versions | [
"Return",
"a",
"list",
"of",
"MWVersion",
"objects",
"representing",
"installed",
"versions"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mwcc.py#L87-L119 |
24,012 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mwcc.py | generate | def generate(env):
"""Add Builders and construction variables for the mwcc to an Environment."""
import SCons.Defaults
import SCons.Tool
set_vars(env)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
for suffix in CXXSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CXXAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction)
env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -nolink -o $TARGET $SOURCES'
env['CC'] = 'mwcc'
env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CCCOMFLAGS'
env['CXX'] = 'mwcc'
env['CXXCOM'] = '$CXX $CXXFLAGS $CCCOMFLAGS'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = '$CCFLAGS'
env['SHCFLAGS'] = '$CFLAGS'
env['SHCCCOM'] = '$SHCC $SHCFLAGS $SHCCFLAGS $CCCOMFLAGS'
env['SHCXX'] = '$CXX'
env['SHCXXFLAGS'] = '$CXXFLAGS'
env['SHCXXCOM'] = '$SHCXX $SHCXXFLAGS $CCCOMFLAGS'
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cpp'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = '' | python | def generate(env):
import SCons.Defaults
import SCons.Tool
set_vars(env)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
for suffix in CXXSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CXXAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction)
env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -nolink -o $TARGET $SOURCES'
env['CC'] = 'mwcc'
env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CCCOMFLAGS'
env['CXX'] = 'mwcc'
env['CXXCOM'] = '$CXX $CXXFLAGS $CCCOMFLAGS'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = '$CCFLAGS'
env['SHCFLAGS'] = '$CFLAGS'
env['SHCCCOM'] = '$SHCC $SHCFLAGS $SHCCFLAGS $CCCOMFLAGS'
env['SHCXX'] = '$CXX'
env['SHCXXFLAGS'] = '$CXXFLAGS'
env['SHCXXCOM'] = '$SHCXX $SHCXXFLAGS $CCCOMFLAGS'
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cpp'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = '' | [
"def",
"generate",
"(",
"env",
")",
":",
"import",
"SCons",
".",
"Defaults",
"import",
"SCons",
".",
"Tool",
"set_vars",
"(",
"env",
")",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"for",
"suffi... | Add Builders and construction variables for the mwcc to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"the",
"mwcc",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mwcc.py#L155-L194 |
24,013 | iotile/coretools | iotilecore/iotile/core/hw/debug/flash_board_step.py | FlashBoardStep.run | def run(self, resources):
"""Runs the flash step
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step.
"""
if not resources['connection']._port.startswith('jlink'):
raise ArgumentError("FlashBoardStep is currently only possible through jlink", invalid_port=args['port'])
hwman = resources['connection']
debug = hwman.hwman.debug(self._debug_string)
debug.flash(self._file) | python | def run(self, resources):
if not resources['connection']._port.startswith('jlink'):
raise ArgumentError("FlashBoardStep is currently only possible through jlink", invalid_port=args['port'])
hwman = resources['connection']
debug = hwman.hwman.debug(self._debug_string)
debug.flash(self._file) | [
"def",
"run",
"(",
"self",
",",
"resources",
")",
":",
"if",
"not",
"resources",
"[",
"'connection'",
"]",
".",
"_port",
".",
"startswith",
"(",
"'jlink'",
")",
":",
"raise",
"ArgumentError",
"(",
"\"FlashBoardStep is currently only possible through jlink\"",
",",... | Runs the flash step
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step. | [
"Runs",
"the",
"flash",
"step"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/debug/flash_board_step.py#L26-L38 |
24,014 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/filesystem.py | copyto_emitter | def copyto_emitter(target, source, env):
""" changes the path of the source to be under the target (which
are assumed to be directories.
"""
n_target = []
for t in target:
n_target = n_target + [t.File( str( s ) ) for s in source]
return (n_target, source) | python | def copyto_emitter(target, source, env):
n_target = []
for t in target:
n_target = n_target + [t.File( str( s ) ) for s in source]
return (n_target, source) | [
"def",
"copyto_emitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"n_target",
"=",
"[",
"]",
"for",
"t",
"in",
"target",
":",
"n_target",
"=",
"n_target",
"+",
"[",
"t",
".",
"File",
"(",
"str",
"(",
"s",
")",
")",
"for",
"s",
"in",
... | changes the path of the source to be under the target (which
are assumed to be directories. | [
"changes",
"the",
"path",
"of",
"the",
"source",
"to",
"be",
"under",
"the",
"target",
"(",
"which",
"are",
"assumed",
"to",
"be",
"directories",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/filesystem.py#L40-L49 |
24,015 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/PharLapCommon.py | getPharLapPath | def getPharLapPath():
"""Reads the registry to find the installed path of the Phar Lap ETS
development kit.
Raises UserError if no installed version of Phar Lap can
be found."""
if not SCons.Util.can_read_reg:
raise SCons.Errors.InternalError("No Windows registry module was found")
try:
k=SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Pharlap\\ETS')
val, type = SCons.Util.RegQueryValueEx(k, 'BaseDir')
# The following is a hack...there is (not surprisingly)
# an odd issue in the Phar Lap plug in that inserts
# a bunch of junk data after the phar lap path in the
# registry. We must trim it.
idx=val.find('\0')
if idx >= 0:
val = val[:idx]
return os.path.normpath(val)
except SCons.Util.RegError:
raise SCons.Errors.UserError("Cannot find Phar Lap ETS path in the registry. Is it installed properly?") | python | def getPharLapPath():
if not SCons.Util.can_read_reg:
raise SCons.Errors.InternalError("No Windows registry module was found")
try:
k=SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Pharlap\\ETS')
val, type = SCons.Util.RegQueryValueEx(k, 'BaseDir')
# The following is a hack...there is (not surprisingly)
# an odd issue in the Phar Lap plug in that inserts
# a bunch of junk data after the phar lap path in the
# registry. We must trim it.
idx=val.find('\0')
if idx >= 0:
val = val[:idx]
return os.path.normpath(val)
except SCons.Util.RegError:
raise SCons.Errors.UserError("Cannot find Phar Lap ETS path in the registry. Is it installed properly?") | [
"def",
"getPharLapPath",
"(",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"can_read_reg",
":",
"raise",
"SCons",
".",
"Errors",
".",
"InternalError",
"(",
"\"No Windows registry module was found\"",
")",
"try",
":",
"k",
"=",
"SCons",
".",
"Util",
".",... | Reads the registry to find the installed path of the Phar Lap ETS
development kit.
Raises UserError if no installed version of Phar Lap can
be found. | [
"Reads",
"the",
"registry",
"to",
"find",
"the",
"installed",
"path",
"of",
"the",
"Phar",
"Lap",
"ETS",
"development",
"kit",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/PharLapCommon.py#L40-L64 |
24,016 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/PharLapCommon.py | addPharLapPaths | def addPharLapPaths(env):
"""This function adds the path to the Phar Lap binaries, includes,
and libraries, if they are not already there."""
ph_path = getPharLapPath()
try:
env_dict = env['ENV']
except KeyError:
env_dict = {}
env['ENV'] = env_dict
SCons.Util.AddPathIfNotExists(env_dict, 'PATH',
os.path.join(ph_path, 'bin'))
SCons.Util.AddPathIfNotExists(env_dict, 'INCLUDE',
os.path.join(ph_path, 'include'))
SCons.Util.AddPathIfNotExists(env_dict, 'LIB',
os.path.join(ph_path, 'lib'))
SCons.Util.AddPathIfNotExists(env_dict, 'LIB',
os.path.join(ph_path, os.path.normpath('lib/vclib')))
env['PHARLAP_PATH'] = getPharLapPath()
env['PHARLAP_VERSION'] = str(getPharLapVersion()) | python | def addPharLapPaths(env):
ph_path = getPharLapPath()
try:
env_dict = env['ENV']
except KeyError:
env_dict = {}
env['ENV'] = env_dict
SCons.Util.AddPathIfNotExists(env_dict, 'PATH',
os.path.join(ph_path, 'bin'))
SCons.Util.AddPathIfNotExists(env_dict, 'INCLUDE',
os.path.join(ph_path, 'include'))
SCons.Util.AddPathIfNotExists(env_dict, 'LIB',
os.path.join(ph_path, 'lib'))
SCons.Util.AddPathIfNotExists(env_dict, 'LIB',
os.path.join(ph_path, os.path.normpath('lib/vclib')))
env['PHARLAP_PATH'] = getPharLapPath()
env['PHARLAP_VERSION'] = str(getPharLapVersion()) | [
"def",
"addPharLapPaths",
"(",
"env",
")",
":",
"ph_path",
"=",
"getPharLapPath",
"(",
")",
"try",
":",
"env_dict",
"=",
"env",
"[",
"'ENV'",
"]",
"except",
"KeyError",
":",
"env_dict",
"=",
"{",
"}",
"env",
"[",
"'ENV'",
"]",
"=",
"env_dict",
"SCons",... | This function adds the path to the Phar Lap binaries, includes,
and libraries, if they are not already there. | [
"This",
"function",
"adds",
"the",
"path",
"to",
"the",
"Phar",
"Lap",
"binaries",
"includes",
"and",
"libraries",
"if",
"they",
"are",
"not",
"already",
"there",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/PharLapCommon.py#L88-L108 |
24,017 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py | _update_or_init_po_files | def _update_or_init_po_files(target, source, env):
""" Action function for `POUpdate` builder """
import SCons.Action
from SCons.Tool.GettextCommon import _init_po_files
for tgt in target:
if tgt.rexists():
action = SCons.Action.Action('$MSGMERGECOM', '$MSGMERGECOMSTR')
else:
action = _init_po_files
status = action([tgt], source, env)
if status : return status
return 0 | python | def _update_or_init_po_files(target, source, env):
import SCons.Action
from SCons.Tool.GettextCommon import _init_po_files
for tgt in target:
if tgt.rexists():
action = SCons.Action.Action('$MSGMERGECOM', '$MSGMERGECOMSTR')
else:
action = _init_po_files
status = action([tgt], source, env)
if status : return status
return 0 | [
"def",
"_update_or_init_po_files",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"import",
"SCons",
".",
"Action",
"from",
"SCons",
".",
"Tool",
".",
"GettextCommon",
"import",
"_init_po_files",
"for",
"tgt",
"in",
"target",
":",
"if",
"tgt",
".",
"r... | Action function for `POUpdate` builder | [
"Action",
"function",
"for",
"POUpdate",
"builder"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py#L30-L41 |
24,018 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py | _POUpdateBuilder | def _POUpdateBuilder(env, **kw):
""" Create an object of `POUpdate` builder """
import SCons.Action
from SCons.Tool.GettextCommon import _POFileBuilder
action = SCons.Action.Action(_update_or_init_po_files, None)
return _POFileBuilder(env, action=action, target_alias='$POUPDATE_ALIAS') | python | def _POUpdateBuilder(env, **kw):
import SCons.Action
from SCons.Tool.GettextCommon import _POFileBuilder
action = SCons.Action.Action(_update_or_init_po_files, None)
return _POFileBuilder(env, action=action, target_alias='$POUPDATE_ALIAS') | [
"def",
"_POUpdateBuilder",
"(",
"env",
",",
"*",
"*",
"kw",
")",
":",
"import",
"SCons",
".",
"Action",
"from",
"SCons",
".",
"Tool",
".",
"GettextCommon",
"import",
"_POFileBuilder",
"action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"_update_or_i... | Create an object of `POUpdate` builder | [
"Create",
"an",
"object",
"of",
"POUpdate",
"builder"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py#L45-L50 |
24,019 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py | _POUpdateBuilderWrapper | def _POUpdateBuilderWrapper(env, target=None, source=_null, **kw):
""" Wrapper for `POUpdate` builder - make user's life easier """
if source is _null:
if 'POTDOMAIN' in kw:
domain = kw['POTDOMAIN']
elif 'POTDOMAIN' in env and env['POTDOMAIN']:
domain = env['POTDOMAIN']
else:
domain = 'messages'
source = [ domain ] # NOTE: Suffix shall be appended automatically
return env._POUpdateBuilder(target, source, **kw) | python | def _POUpdateBuilderWrapper(env, target=None, source=_null, **kw):
if source is _null:
if 'POTDOMAIN' in kw:
domain = kw['POTDOMAIN']
elif 'POTDOMAIN' in env and env['POTDOMAIN']:
domain = env['POTDOMAIN']
else:
domain = 'messages'
source = [ domain ] # NOTE: Suffix shall be appended automatically
return env._POUpdateBuilder(target, source, **kw) | [
"def",
"_POUpdateBuilderWrapper",
"(",
"env",
",",
"target",
"=",
"None",
",",
"source",
"=",
"_null",
",",
"*",
"*",
"kw",
")",
":",
"if",
"source",
"is",
"_null",
":",
"if",
"'POTDOMAIN'",
"in",
"kw",
":",
"domain",
"=",
"kw",
"[",
"'POTDOMAIN'",
"... | Wrapper for `POUpdate` builder - make user's life easier | [
"Wrapper",
"for",
"POUpdate",
"builder",
"-",
"make",
"user",
"s",
"life",
"easier"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py#L56-L66 |
24,020 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py | generate | def generate(env,**kw):
""" Generate the `xgettext` tool """
from SCons.Tool.GettextCommon import _detect_msgmerge
try:
env['MSGMERGE'] = _detect_msgmerge(env)
except:
env['MSGMERGE'] = 'msgmerge'
env.SetDefault(
POTSUFFIX = ['.pot'],
POSUFFIX = ['.po'],
MSGMERGECOM = '$MSGMERGE $MSGMERGEFLAGS --update $TARGET $SOURCE',
MSGMERGECOMSTR = '',
MSGMERGEFLAGS = [ ],
POUPDATE_ALIAS = 'po-update'
)
env.Append(BUILDERS = { '_POUpdateBuilder':_POUpdateBuilder(env) })
env.AddMethod(_POUpdateBuilderWrapper, 'POUpdate')
env.AlwaysBuild(env.Alias('$POUPDATE_ALIAS')) | python | def generate(env,**kw):
from SCons.Tool.GettextCommon import _detect_msgmerge
try:
env['MSGMERGE'] = _detect_msgmerge(env)
except:
env['MSGMERGE'] = 'msgmerge'
env.SetDefault(
POTSUFFIX = ['.pot'],
POSUFFIX = ['.po'],
MSGMERGECOM = '$MSGMERGE $MSGMERGEFLAGS --update $TARGET $SOURCE',
MSGMERGECOMSTR = '',
MSGMERGEFLAGS = [ ],
POUPDATE_ALIAS = 'po-update'
)
env.Append(BUILDERS = { '_POUpdateBuilder':_POUpdateBuilder(env) })
env.AddMethod(_POUpdateBuilderWrapper, 'POUpdate')
env.AlwaysBuild(env.Alias('$POUPDATE_ALIAS')) | [
"def",
"generate",
"(",
"env",
",",
"*",
"*",
"kw",
")",
":",
"from",
"SCons",
".",
"Tool",
".",
"GettextCommon",
"import",
"_detect_msgmerge",
"try",
":",
"env",
"[",
"'MSGMERGE'",
"]",
"=",
"_detect_msgmerge",
"(",
"env",
")",
"except",
":",
"env",
"... | Generate the `xgettext` tool | [
"Generate",
"the",
"xgettext",
"tool"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgmerge.py#L70-L87 |
24,021 | iotile/coretools | iotilebuild/iotile/build/build/depends.py | ProductResolver._create_filter | def _create_filter(self):
"""Create a filter of all of the dependency products that we have selected."""
self._product_filter = {}
for chip in itertools.chain(iter(self._family.targets(self._tile.short_name)),
iter([self._family.platform_independent_target()])):
for key, prods in chip.property('depends', {}).items():
name, _, _ = key.partition(',')
for prod in prods:
if prod not in self._product_filter:
self._product_filter[prod] = set()
self._product_filter[prod].add(name) | python | def _create_filter(self):
self._product_filter = {}
for chip in itertools.chain(iter(self._family.targets(self._tile.short_name)),
iter([self._family.platform_independent_target()])):
for key, prods in chip.property('depends', {}).items():
name, _, _ = key.partition(',')
for prod in prods:
if prod not in self._product_filter:
self._product_filter[prod] = set()
self._product_filter[prod].add(name) | [
"def",
"_create_filter",
"(",
"self",
")",
":",
"self",
".",
"_product_filter",
"=",
"{",
"}",
"for",
"chip",
"in",
"itertools",
".",
"chain",
"(",
"iter",
"(",
"self",
".",
"_family",
".",
"targets",
"(",
"self",
".",
"_tile",
".",
"short_name",
")",
... | Create a filter of all of the dependency products that we have selected. | [
"Create",
"a",
"filter",
"of",
"all",
"of",
"the",
"dependency",
"products",
"that",
"we",
"have",
"selected",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/depends.py#L38-L52 |
24,022 | iotile/coretools | iotilebuild/iotile/build/build/depends.py | ProductResolver._create_product_map | def _create_product_map(self):
"""Create a map of all products produced by this or a dependency."""
self._product_map = {}
for dep in self._tile.dependencies:
try:
dep_tile = IOTile(os.path.join('build', 'deps', dep['unique_id']))
except (ArgumentError, EnvironmentError):
raise BuildError("Could not find required dependency", name=dep['name'])
self._add_products(dep_tile)
self._add_products(self._tile, show_all=True) | python | def _create_product_map(self):
self._product_map = {}
for dep in self._tile.dependencies:
try:
dep_tile = IOTile(os.path.join('build', 'deps', dep['unique_id']))
except (ArgumentError, EnvironmentError):
raise BuildError("Could not find required dependency", name=dep['name'])
self._add_products(dep_tile)
self._add_products(self._tile, show_all=True) | [
"def",
"_create_product_map",
"(",
"self",
")",
":",
"self",
".",
"_product_map",
"=",
"{",
"}",
"for",
"dep",
"in",
"self",
".",
"_tile",
".",
"dependencies",
":",
"try",
":",
"dep_tile",
"=",
"IOTile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'bu... | Create a map of all products produced by this or a dependency. | [
"Create",
"a",
"map",
"of",
"all",
"products",
"produced",
"by",
"this",
"or",
"a",
"dependency",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/depends.py#L63-L76 |
24,023 | iotile/coretools | iotilebuild/iotile/build/build/depends.py | ProductResolver._add_products | def _add_products(self, tile, show_all=False):
"""Add all products from a tile into our product map."""
products = tile.products
unique_id = tile.unique_id
base_path = tile.output_folder
for prod_path, prod_type in products.items():
# We need to handle include_directories and tilebus_definitions
# specially since those are stored reversed in module_settings.json
# for historical reasons. Currently we don't support resolving
# tilebus_definitions or include_directories in ProductResolver
if prod_path == 'tilebus_definitions' or prod_path == 'include_directories':
continue
if prod_type in self.IGNORED_PRODUCTS:
continue
prod_base = os.path.basename(prod_path)
if prod_type not in self._product_map:
self._product_map[prod_type] = {}
prod_map = self._product_map[prod_type]
if prod_base not in prod_map:
prod_map[prod_base] = []
full_path = os.path.normpath(os.path.join(base_path, prod_path))
info = ProductInfo(prod_base, full_path, unique_id, not show_all and prod_base not in self._product_filter)
prod_map[prod_base].append(info) | python | def _add_products(self, tile, show_all=False):
products = tile.products
unique_id = tile.unique_id
base_path = tile.output_folder
for prod_path, prod_type in products.items():
# We need to handle include_directories and tilebus_definitions
# specially since those are stored reversed in module_settings.json
# for historical reasons. Currently we don't support resolving
# tilebus_definitions or include_directories in ProductResolver
if prod_path == 'tilebus_definitions' or prod_path == 'include_directories':
continue
if prod_type in self.IGNORED_PRODUCTS:
continue
prod_base = os.path.basename(prod_path)
if prod_type not in self._product_map:
self._product_map[prod_type] = {}
prod_map = self._product_map[prod_type]
if prod_base not in prod_map:
prod_map[prod_base] = []
full_path = os.path.normpath(os.path.join(base_path, prod_path))
info = ProductInfo(prod_base, full_path, unique_id, not show_all and prod_base not in self._product_filter)
prod_map[prod_base].append(info) | [
"def",
"_add_products",
"(",
"self",
",",
"tile",
",",
"show_all",
"=",
"False",
")",
":",
"products",
"=",
"tile",
".",
"products",
"unique_id",
"=",
"tile",
".",
"unique_id",
"base_path",
"=",
"tile",
".",
"output_folder",
"for",
"prod_path",
",",
"prod_... | Add all products from a tile into our product map. | [
"Add",
"all",
"products",
"from",
"a",
"tile",
"into",
"our",
"product",
"map",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/depends.py#L78-L106 |
24,024 | iotile/coretools | iotilebuild/iotile/build/build/depends.py | ProductResolver.find_all | def find_all(self, product_type, short_name, include_hidden=False):
"""Find all providers of a given product by its short name.
This function will return all providers of a given product. If you
want to ensure that a product's name is unique among all dependencies,
you should use find_unique.
Args:
product_type (str): The type of product that we are looking for, like
firmware_image, library etc.
short_name (str): The short name of the product that we wish to find,
usually its os.path.basename()
include_hidden (bool): Return products that are hidden and not selected
as visible in the depends section of this tile's module settings.
This defaults to False.
Returns:
list of ProductInfo: A list of all of the matching products. If no matching
products are found, an empty list is returned. If you want to raise
a BuildError in that case use find_unique.
"""
all_prods = []
# If product_type is not return products of all types
if product_type is None:
for prod_dict in self._product_map.values():
all_prods.extend([prod for prod in prod_dict.get(short_name, []) if include_hidden or not prod.hidden])
return all_prods
all_prods = self._product_map.get(product_type, {})
return [prod for prod in all_prods.get(short_name, []) if include_hidden or not prod.hidden] | python | def find_all(self, product_type, short_name, include_hidden=False):
all_prods = []
# If product_type is not return products of all types
if product_type is None:
for prod_dict in self._product_map.values():
all_prods.extend([prod for prod in prod_dict.get(short_name, []) if include_hidden or not prod.hidden])
return all_prods
all_prods = self._product_map.get(product_type, {})
return [prod for prod in all_prods.get(short_name, []) if include_hidden or not prod.hidden] | [
"def",
"find_all",
"(",
"self",
",",
"product_type",
",",
"short_name",
",",
"include_hidden",
"=",
"False",
")",
":",
"all_prods",
"=",
"[",
"]",
"# If product_type is not return products of all types",
"if",
"product_type",
"is",
"None",
":",
"for",
"prod_dict",
... | Find all providers of a given product by its short name.
This function will return all providers of a given product. If you
want to ensure that a product's name is unique among all dependencies,
you should use find_unique.
Args:
product_type (str): The type of product that we are looking for, like
firmware_image, library etc.
short_name (str): The short name of the product that we wish to find,
usually its os.path.basename()
include_hidden (bool): Return products that are hidden and not selected
as visible in the depends section of this tile's module settings.
This defaults to False.
Returns:
list of ProductInfo: A list of all of the matching products. If no matching
products are found, an empty list is returned. If you want to raise
a BuildError in that case use find_unique. | [
"Find",
"all",
"providers",
"of",
"a",
"given",
"product",
"by",
"its",
"short",
"name",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/depends.py#L108-L140 |
24,025 | iotile/coretools | iotilebuild/iotile/build/build/depends.py | ProductResolver.find_unique | def find_unique(self, product_type, short_name, include_hidden=False):
"""Find the unique provider of a given product by its short name.
This function will ensure that the product is only provided by exactly
one tile (either this tile or one of its dependencies and raise a
BuildError if not.
Args:
product_type (str): The type of product that we are looking for, like
firmware_image, library etc.
short_name (str): The short name of the product that we wish to find,
usually its os.path.basename()
include_hidden (bool): Return products that are hidden and not selected
as visible in the depends section of this tile's module settings.
This defaults to False.
Returns:
ProductInfo: The information of the one unique provider of this product.
"""
prods = self.find_all(product_type, short_name, include_hidden)
if len(prods) == 0:
raise BuildError("Could not find product by name in find_unique", name=short_name, type=product_type)
if len(prods) > 1:
raise BuildError("Multiple providers of the same product in find_unique", name=short_name, type=product_type, products=prods)
if self._tracking:
self._resolved_products.append(prods[0])
return prods[0] | python | def find_unique(self, product_type, short_name, include_hidden=False):
prods = self.find_all(product_type, short_name, include_hidden)
if len(prods) == 0:
raise BuildError("Could not find product by name in find_unique", name=short_name, type=product_type)
if len(prods) > 1:
raise BuildError("Multiple providers of the same product in find_unique", name=short_name, type=product_type, products=prods)
if self._tracking:
self._resolved_products.append(prods[0])
return prods[0] | [
"def",
"find_unique",
"(",
"self",
",",
"product_type",
",",
"short_name",
",",
"include_hidden",
"=",
"False",
")",
":",
"prods",
"=",
"self",
".",
"find_all",
"(",
"product_type",
",",
"short_name",
",",
"include_hidden",
")",
"if",
"len",
"(",
"prods",
... | Find the unique provider of a given product by its short name.
This function will ensure that the product is only provided by exactly
one tile (either this tile or one of its dependencies and raise a
BuildError if not.
Args:
product_type (str): The type of product that we are looking for, like
firmware_image, library etc.
short_name (str): The short name of the product that we wish to find,
usually its os.path.basename()
include_hidden (bool): Return products that are hidden and not selected
as visible in the depends section of this tile's module settings.
This defaults to False.
Returns:
ProductInfo: The information of the one unique provider of this product. | [
"Find",
"the",
"unique",
"provider",
"of",
"a",
"given",
"product",
"by",
"its",
"short",
"name",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/depends.py#L142-L173 |
24,026 | iotile/coretools | iotilebuild/iotile/build/scripts/iotile_tbcompile.py | main | def main(raw_args=None):
"""Run the iotile-tbcompile script.
Args:
raw_args (list): Optional list of command line arguments. If not
passed these are pulled from sys.argv.
"""
multifile_choices = frozenset(['c_files'])
if raw_args is None:
raw_args = sys.argv[1:]
parser = build_parser()
args = parser.parse_args(raw_args)
if args.output is None and args.format in multifile_choices:
print("You must specify an output file with -o, --output when "
"using a format that produces multiple files (-f %s)" % args.format)
return 1
desc = TBDescriptor(args.bus_definition)
if args.format == 'json':
print("JSON output is not yet supported")
return 1
block = desc.get_block()
template_map = {
'command_map_c': 'command_map_c.c.tpl',
'command_map_h': 'command_map_c.h.tpl',
'config_map_c': 'config_variables_c.c.tpl',
'config_map_h': 'config_variables_c.h.tpl'
}
template_name = template_map.get(args.format)
data = block.render_template(template_name)
print(data)
return 0 | python | def main(raw_args=None):
multifile_choices = frozenset(['c_files'])
if raw_args is None:
raw_args = sys.argv[1:]
parser = build_parser()
args = parser.parse_args(raw_args)
if args.output is None and args.format in multifile_choices:
print("You must specify an output file with -o, --output when "
"using a format that produces multiple files (-f %s)" % args.format)
return 1
desc = TBDescriptor(args.bus_definition)
if args.format == 'json':
print("JSON output is not yet supported")
return 1
block = desc.get_block()
template_map = {
'command_map_c': 'command_map_c.c.tpl',
'command_map_h': 'command_map_c.h.tpl',
'config_map_c': 'config_variables_c.c.tpl',
'config_map_h': 'config_variables_c.h.tpl'
}
template_name = template_map.get(args.format)
data = block.render_template(template_name)
print(data)
return 0 | [
"def",
"main",
"(",
"raw_args",
"=",
"None",
")",
":",
"multifile_choices",
"=",
"frozenset",
"(",
"[",
"'c_files'",
"]",
")",
"if",
"raw_args",
"is",
"None",
":",
"raw_args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"build_parser",
... | Run the iotile-tbcompile script.
Args:
raw_args (list): Optional list of command line arguments. If not
passed these are pulled from sys.argv. | [
"Run",
"the",
"iotile",
"-",
"tbcompile",
"script",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/scripts/iotile_tbcompile.py#L37-L77 |
24,027 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rpcgen.py | generate | def generate(env):
"Add RPCGEN Builders and construction variables for an Environment."
client = Builder(action=rpcgen_client, suffix='_clnt.c', src_suffix='.x')
header = Builder(action=rpcgen_header, suffix='.h', src_suffix='.x')
service = Builder(action=rpcgen_service, suffix='_svc.c', src_suffix='.x')
xdr = Builder(action=rpcgen_xdr, suffix='_xdr.c', src_suffix='.x')
env.Append(BUILDERS={'RPCGenClient' : client,
'RPCGenHeader' : header,
'RPCGenService' : service,
'RPCGenXDR' : xdr})
env['RPCGEN'] = 'rpcgen'
env['RPCGENFLAGS'] = SCons.Util.CLVar('')
env['RPCGENCLIENTFLAGS'] = SCons.Util.CLVar('')
env['RPCGENHEADERFLAGS'] = SCons.Util.CLVar('')
env['RPCGENSERVICEFLAGS'] = SCons.Util.CLVar('')
env['RPCGENXDRFLAGS'] = SCons.Util.CLVar('') | python | def generate(env):
"Add RPCGEN Builders and construction variables for an Environment."
client = Builder(action=rpcgen_client, suffix='_clnt.c', src_suffix='.x')
header = Builder(action=rpcgen_header, suffix='.h', src_suffix='.x')
service = Builder(action=rpcgen_service, suffix='_svc.c', src_suffix='.x')
xdr = Builder(action=rpcgen_xdr, suffix='_xdr.c', src_suffix='.x')
env.Append(BUILDERS={'RPCGenClient' : client,
'RPCGenHeader' : header,
'RPCGenService' : service,
'RPCGenXDR' : xdr})
env['RPCGEN'] = 'rpcgen'
env['RPCGENFLAGS'] = SCons.Util.CLVar('')
env['RPCGENCLIENTFLAGS'] = SCons.Util.CLVar('')
env['RPCGENHEADERFLAGS'] = SCons.Util.CLVar('')
env['RPCGENSERVICEFLAGS'] = SCons.Util.CLVar('')
env['RPCGENXDRFLAGS'] = SCons.Util.CLVar('') | [
"def",
"generate",
"(",
"env",
")",
":",
"client",
"=",
"Builder",
"(",
"action",
"=",
"rpcgen_client",
",",
"suffix",
"=",
"'_clnt.c'",
",",
"src_suffix",
"=",
"'.x'",
")",
"header",
"=",
"Builder",
"(",
"action",
"=",
"rpcgen_header",
",",
"suffix",
"=... | Add RPCGEN Builders and construction variables for an Environment. | [
"Add",
"RPCGEN",
"Builders",
"and",
"construction",
"variables",
"for",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rpcgen.py#L45-L61 |
24,028 | iotile/coretools | scripts/release.py | build_parser | def build_parser():
"""Build argument parsers."""
parser = argparse.ArgumentParser("Release packages to pypi")
parser.add_argument('--check', '-c', action="store_true", help="Do a dry run without uploading")
parser.add_argument('component', help="The component to release as component-version")
return parser | python | def build_parser():
parser = argparse.ArgumentParser("Release packages to pypi")
parser.add_argument('--check', '-c', action="store_true", help="Do a dry run without uploading")
parser.add_argument('component', help="The component to release as component-version")
return parser | [
"def",
"build_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"\"Release packages to pypi\"",
")",
"parser",
".",
"add_argument",
"(",
"'--check'",
",",
"'-c'",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Do a dry ru... | Build argument parsers. | [
"Build",
"argument",
"parsers",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/scripts/release.py#L21-L27 |
24,029 | iotile/coretools | scripts/release.py | get_release_component | def get_release_component(comp):
"""Split the argument passed on the command line into a component name and expected version"""
name, vers = comp.split("-")
if name not in comp_names:
print("Known components:")
for comp in comp_names:
print("- %s" % comp)
raise EnvironmentError("Unknown release component name '%s'" % name)
return name, vers | python | def get_release_component(comp):
name, vers = comp.split("-")
if name not in comp_names:
print("Known components:")
for comp in comp_names:
print("- %s" % comp)
raise EnvironmentError("Unknown release component name '%s'" % name)
return name, vers | [
"def",
"get_release_component",
"(",
"comp",
")",
":",
"name",
",",
"vers",
"=",
"comp",
".",
"split",
"(",
"\"-\"",
")",
"if",
"name",
"not",
"in",
"comp_names",
":",
"print",
"(",
"\"Known components:\"",
")",
"for",
"comp",
"in",
"comp_names",
":",
"p... | Split the argument passed on the command line into a component name and expected version | [
"Split",
"the",
"argument",
"passed",
"on",
"the",
"command",
"line",
"into",
"a",
"component",
"name",
"and",
"expected",
"version"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/scripts/release.py#L43-L55 |
24,030 | iotile/coretools | scripts/release.py | check_compatibility | def check_compatibility(name):
"""Verify if we can release this component on the running interpreter.
All components are released from python 2.7 by default unless they specify
that they are python 3 only, in which case they are released from python 3.6
"""
comp = comp_names[name]
if sys.version_info.major < 3 and comp.compat == "python3":
return False
if sys.version_info.major >= 3 and comp.compat != "python3":
return False
return True | python | def check_compatibility(name):
comp = comp_names[name]
if sys.version_info.major < 3 and comp.compat == "python3":
return False
if sys.version_info.major >= 3 and comp.compat != "python3":
return False
return True | [
"def",
"check_compatibility",
"(",
"name",
")",
":",
"comp",
"=",
"comp_names",
"[",
"name",
"]",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
"and",
"comp",
".",
"compat",
"==",
"\"python3\"",
":",
"return",
"False",
"if",
"sys",
".",
"ve... | Verify if we can release this component on the running interpreter.
All components are released from python 2.7 by default unless they specify
that they are python 3 only, in which case they are released from python 3.6 | [
"Verify",
"if",
"we",
"can",
"release",
"this",
"component",
"on",
"the",
"running",
"interpreter",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/scripts/release.py#L58-L73 |
24,031 | iotile/coretools | scripts/release.py | build_component | def build_component(component):
"""Create an sdist and a wheel for the desired component"""
comp = comp_names[component]
curr = os.getcwd()
os.chdir(comp.path)
args = ['-q', 'clean', 'sdist', 'bdist_wheel']
if comp.compat == 'universal':
args.append('--universal')
try:
setuptools.sandbox.run_setup('setup.py', args)
finally:
os.chdir(curr) | python | def build_component(component):
comp = comp_names[component]
curr = os.getcwd()
os.chdir(comp.path)
args = ['-q', 'clean', 'sdist', 'bdist_wheel']
if comp.compat == 'universal':
args.append('--universal')
try:
setuptools.sandbox.run_setup('setup.py', args)
finally:
os.chdir(curr) | [
"def",
"build_component",
"(",
"component",
")",
":",
"comp",
"=",
"comp_names",
"[",
"component",
"]",
"curr",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"comp",
".",
"path",
")",
"args",
"=",
"[",
"'-q'",
",",
"'clean'",
",",
"'... | Create an sdist and a wheel for the desired component | [
"Create",
"an",
"sdist",
"and",
"a",
"wheel",
"for",
"the",
"desired",
"component"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/scripts/release.py#L90-L105 |
24,032 | iotile/coretools | iotilecore/iotile/core/utilities/gid.py | uuid_to_slug | def uuid_to_slug(uuid):
"""
Return IOTile Cloud compatible Device Slug
:param uuid: UUID
:return: string in the form of d--0000-0000-0000-0001
"""
if not isinstance(uuid, int):
raise ArgumentError("Invalid id that is not an integer", id=uuid)
if uuid < 0 or uuid > 0x7fffffff:
# For now, limiting support to a signed integer (which on some platforms, can be 32bits)
raise ArgumentError("Integer should be a positive number and smaller than 0x7fffffff", id=uuid)
return '--'.join(['d', int64gid(uuid)]) | python | def uuid_to_slug(uuid):
if not isinstance(uuid, int):
raise ArgumentError("Invalid id that is not an integer", id=uuid)
if uuid < 0 or uuid > 0x7fffffff:
# For now, limiting support to a signed integer (which on some platforms, can be 32bits)
raise ArgumentError("Integer should be a positive number and smaller than 0x7fffffff", id=uuid)
return '--'.join(['d', int64gid(uuid)]) | [
"def",
"uuid_to_slug",
"(",
"uuid",
")",
":",
"if",
"not",
"isinstance",
"(",
"uuid",
",",
"int",
")",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid id that is not an integer\"",
",",
"id",
"=",
"uuid",
")",
"if",
"uuid",
"<",
"0",
"or",
"uuid",
">",
"0... | Return IOTile Cloud compatible Device Slug
:param uuid: UUID
:return: string in the form of d--0000-0000-0000-0001 | [
"Return",
"IOTile",
"Cloud",
"compatible",
"Device",
"Slug"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/gid.py#L7-L21 |
24,033 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/ipk.py | package | def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION,
SUMMARY, X_IPK_PRIORITY, X_IPK_SECTION, SOURCE_URL,
X_IPK_MAINTAINER, X_IPK_DEPENDS, **kw):
""" This function prepares the packageroot directory for packaging with the
ipkg builder.
"""
SCons.Tool.Tool('ipkg').generate(env)
# setup the Ipkg builder
bld = env['BUILDERS']['Ipkg']
target, source = stripinstallbuilder(target, source, env)
target, source = putintopackageroot(target, source, env, PACKAGEROOT)
# This should be overrideable from the construction environment,
# which it is by using ARCHITECTURE=.
# Guessing based on what os.uname() returns at least allows it
# to work for both i386 and x86_64 Linux systems.
archmap = {
'i686' : 'i386',
'i586' : 'i386',
'i486' : 'i386',
}
buildarchitecture = os.uname()[4]
buildarchitecture = archmap.get(buildarchitecture, buildarchitecture)
if 'ARCHITECTURE' in kw:
buildarchitecture = kw['ARCHITECTURE']
# setup the kw to contain the mandatory arguments to this function.
# do this before calling any builder or setup function
loc=locals()
del loc['kw']
kw.update(loc)
del kw['source'], kw['target'], kw['env']
# generate the specfile
specfile = gen_ipk_dir(PACKAGEROOT, source, env, kw)
# override the default target.
if str(target[0])=="%s-%s"%(NAME, VERSION):
target=[ "%s_%s_%s.ipk"%(NAME, VERSION, buildarchitecture) ]
# now apply the Ipkg builder
return bld(env, target, specfile, **kw) | python | def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION,
SUMMARY, X_IPK_PRIORITY, X_IPK_SECTION, SOURCE_URL,
X_IPK_MAINTAINER, X_IPK_DEPENDS, **kw):
SCons.Tool.Tool('ipkg').generate(env)
# setup the Ipkg builder
bld = env['BUILDERS']['Ipkg']
target, source = stripinstallbuilder(target, source, env)
target, source = putintopackageroot(target, source, env, PACKAGEROOT)
# This should be overrideable from the construction environment,
# which it is by using ARCHITECTURE=.
# Guessing based on what os.uname() returns at least allows it
# to work for both i386 and x86_64 Linux systems.
archmap = {
'i686' : 'i386',
'i586' : 'i386',
'i486' : 'i386',
}
buildarchitecture = os.uname()[4]
buildarchitecture = archmap.get(buildarchitecture, buildarchitecture)
if 'ARCHITECTURE' in kw:
buildarchitecture = kw['ARCHITECTURE']
# setup the kw to contain the mandatory arguments to this function.
# do this before calling any builder or setup function
loc=locals()
del loc['kw']
kw.update(loc)
del kw['source'], kw['target'], kw['env']
# generate the specfile
specfile = gen_ipk_dir(PACKAGEROOT, source, env, kw)
# override the default target.
if str(target[0])=="%s-%s"%(NAME, VERSION):
target=[ "%s_%s_%s.ipk"%(NAME, VERSION, buildarchitecture) ]
# now apply the Ipkg builder
return bld(env, target, specfile, **kw) | [
"def",
"package",
"(",
"env",
",",
"target",
",",
"source",
",",
"PACKAGEROOT",
",",
"NAME",
",",
"VERSION",
",",
"DESCRIPTION",
",",
"SUMMARY",
",",
"X_IPK_PRIORITY",
",",
"X_IPK_SECTION",
",",
"SOURCE_URL",
",",
"X_IPK_MAINTAINER",
",",
"X_IPK_DEPENDS",
",",... | This function prepares the packageroot directory for packaging with the
ipkg builder. | [
"This",
"function",
"prepares",
"the",
"packageroot",
"directory",
"for",
"packaging",
"with",
"the",
"ipkg",
"builder",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/ipk.py#L35-L79 |
24,034 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/ipk.py | build_specfiles | def build_specfiles(source, target, env):
""" Filter the targets for the needed files and use the variables in env
to create the specfile.
"""
#
# At first we care for the CONTROL/control file, which is the main file for ipk.
#
# For this we need to open multiple files in random order, so we store into
# a dict so they can be easily accessed.
#
#
opened_files={}
def open_file(needle, haystack):
try:
return opened_files[needle]
except KeyError:
file=filter(lambda x: x.get_path().rfind(needle)!=-1, haystack)[0]
opened_files[needle]=open(file.get_abspath(), 'w')
return opened_files[needle]
control_file=open_file('control', target)
if 'X_IPK_DESCRIPTION' not in env:
env['X_IPK_DESCRIPTION']="%s\n %s"%(env['SUMMARY'],
env['DESCRIPTION'].replace('\n', '\n '))
content = """
Package: $NAME
Version: $VERSION
Priority: $X_IPK_PRIORITY
Section: $X_IPK_SECTION
Source: $SOURCE_URL
Architecture: $ARCHITECTURE
Maintainer: $X_IPK_MAINTAINER
Depends: $X_IPK_DEPENDS
Description: $X_IPK_DESCRIPTION
"""
control_file.write(env.subst(content))
#
# now handle the various other files, which purpose it is to set post-,
# pre-scripts and mark files as config files.
#
# We do so by filtering the source files for files which are marked with
# the "config" tag and afterwards we do the same for x_ipk_postrm,
# x_ipk_prerm, x_ipk_postinst and x_ipk_preinst tags.
#
# The first one will write the name of the file into the file
# CONTROL/configfiles, the latter add the content of the x_ipk_* variable
# into the same named file.
#
for f in [x for x in source if 'PACKAGING_CONFIG' in dir(x)]:
config=open_file('conffiles')
config.write(f.PACKAGING_INSTALL_LOCATION)
config.write('\n')
for str in 'POSTRM PRERM POSTINST PREINST'.split():
name="PACKAGING_X_IPK_%s"%str
for f in [x for x in source if name in dir(x)]:
file=open_file(name)
file.write(env[str])
#
# close all opened files
for f in list(opened_files.values()):
f.close()
# call a user specified function
if 'CHANGE_SPECFILE' in env:
content += env['CHANGE_SPECFILE'](target)
return 0 | python | def build_specfiles(source, target, env):
#
# At first we care for the CONTROL/control file, which is the main file for ipk.
#
# For this we need to open multiple files in random order, so we store into
# a dict so they can be easily accessed.
#
#
opened_files={}
def open_file(needle, haystack):
try:
return opened_files[needle]
except KeyError:
file=filter(lambda x: x.get_path().rfind(needle)!=-1, haystack)[0]
opened_files[needle]=open(file.get_abspath(), 'w')
return opened_files[needle]
control_file=open_file('control', target)
if 'X_IPK_DESCRIPTION' not in env:
env['X_IPK_DESCRIPTION']="%s\n %s"%(env['SUMMARY'],
env['DESCRIPTION'].replace('\n', '\n '))
content = """
Package: $NAME
Version: $VERSION
Priority: $X_IPK_PRIORITY
Section: $X_IPK_SECTION
Source: $SOURCE_URL
Architecture: $ARCHITECTURE
Maintainer: $X_IPK_MAINTAINER
Depends: $X_IPK_DEPENDS
Description: $X_IPK_DESCRIPTION
"""
control_file.write(env.subst(content))
#
# now handle the various other files, which purpose it is to set post-,
# pre-scripts and mark files as config files.
#
# We do so by filtering the source files for files which are marked with
# the "config" tag and afterwards we do the same for x_ipk_postrm,
# x_ipk_prerm, x_ipk_postinst and x_ipk_preinst tags.
#
# The first one will write the name of the file into the file
# CONTROL/configfiles, the latter add the content of the x_ipk_* variable
# into the same named file.
#
for f in [x for x in source if 'PACKAGING_CONFIG' in dir(x)]:
config=open_file('conffiles')
config.write(f.PACKAGING_INSTALL_LOCATION)
config.write('\n')
for str in 'POSTRM PRERM POSTINST PREINST'.split():
name="PACKAGING_X_IPK_%s"%str
for f in [x for x in source if name in dir(x)]:
file=open_file(name)
file.write(env[str])
#
# close all opened files
for f in list(opened_files.values()):
f.close()
# call a user specified function
if 'CHANGE_SPECFILE' in env:
content += env['CHANGE_SPECFILE'](target)
return 0 | [
"def",
"build_specfiles",
"(",
"source",
",",
"target",
",",
"env",
")",
":",
"#",
"# At first we care for the CONTROL/control file, which is the main file for ipk.",
"#",
"# For this we need to open multiple files in random order, so we store into",
"# a dict so they can be easily acces... | Filter the targets for the needed files and use the variables in env
to create the specfile. | [
"Filter",
"the",
"targets",
"for",
"the",
"needed",
"files",
"and",
"use",
"the",
"variables",
"in",
"env",
"to",
"create",
"the",
"specfile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/ipk.py#L106-L179 |
24,035 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javah.py | emit_java_headers | def emit_java_headers(target, source, env):
"""Create and return lists of Java stub header files that will
be created from a set of class files.
"""
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
classdir = env.get('JAVACLASSDIR')
if not classdir:
try:
s = source[0]
except IndexError:
classdir = '.'
else:
try:
classdir = s.attributes.java_classdir
except AttributeError:
classdir = '.'
classdir = env.Dir(classdir).rdir()
if str(classdir) == '.':
c_ = None
else:
c_ = str(classdir) + os.sep
slist = []
for src in source:
try:
classname = src.attributes.java_classname
except AttributeError:
classname = str(src)
if c_ and classname[:len(c_)] == c_:
classname = classname[len(c_):]
if class_suffix and classname[-len(class_suffix):] == class_suffix:
classname = classname[:-len(class_suffix)]
classname = SCons.Tool.javac.classname(classname)
s = src.rfile()
s.attributes.java_classname = classname
slist.append(s)
s = source[0].rfile()
if not hasattr(s.attributes, 'java_classdir'):
s.attributes.java_classdir = classdir
if target[0].__class__ is SCons.Node.FS.File:
tlist = target
else:
if not isinstance(target[0], SCons.Node.FS.Dir):
target[0].__class__ = SCons.Node.FS.Dir
target[0]._morph()
tlist = []
for s in source:
fname = s.attributes.java_classname.replace('.', '_') + '.h'
t = target[0].File(fname)
t.attributes.java_lookupdir = target[0]
tlist.append(t)
return tlist, source | python | def emit_java_headers(target, source, env):
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
classdir = env.get('JAVACLASSDIR')
if not classdir:
try:
s = source[0]
except IndexError:
classdir = '.'
else:
try:
classdir = s.attributes.java_classdir
except AttributeError:
classdir = '.'
classdir = env.Dir(classdir).rdir()
if str(classdir) == '.':
c_ = None
else:
c_ = str(classdir) + os.sep
slist = []
for src in source:
try:
classname = src.attributes.java_classname
except AttributeError:
classname = str(src)
if c_ and classname[:len(c_)] == c_:
classname = classname[len(c_):]
if class_suffix and classname[-len(class_suffix):] == class_suffix:
classname = classname[:-len(class_suffix)]
classname = SCons.Tool.javac.classname(classname)
s = src.rfile()
s.attributes.java_classname = classname
slist.append(s)
s = source[0].rfile()
if not hasattr(s.attributes, 'java_classdir'):
s.attributes.java_classdir = classdir
if target[0].__class__ is SCons.Node.FS.File:
tlist = target
else:
if not isinstance(target[0], SCons.Node.FS.Dir):
target[0].__class__ = SCons.Node.FS.Dir
target[0]._morph()
tlist = []
for s in source:
fname = s.attributes.java_classname.replace('.', '_') + '.h'
t = target[0].File(fname)
t.attributes.java_lookupdir = target[0]
tlist.append(t)
return tlist, source | [
"def",
"emit_java_headers",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"class_suffix",
"=",
"env",
".",
"get",
"(",
"'JAVACLASSSUFFIX'",
",",
"'.class'",
")",
"classdir",
"=",
"env",
".",
"get",
"(",
"'JAVACLASSDIR'",
")",
"if",
"not",
"classdir",... | Create and return lists of Java stub header files that will
be created from a set of class files. | [
"Create",
"and",
"return",
"lists",
"of",
"Java",
"stub",
"header",
"files",
"that",
"will",
"be",
"created",
"from",
"a",
"set",
"of",
"class",
"files",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javah.py#L44-L100 |
24,036 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javah.py | generate | def generate(env):
"""Add Builders and construction variables for javah to an Environment."""
java_javah = SCons.Tool.CreateJavaHBuilder(env)
java_javah.emitter = emit_java_headers
env['_JAVAHOUTFLAG'] = JavaHOutFlagGenerator
env['JAVAH'] = 'javah'
env['JAVAHFLAGS'] = SCons.Util.CLVar('')
env['_JAVAHCLASSPATH'] = getJavaHClassPath
env['JAVAHCOM'] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}'
env['JAVACLASSSUFFIX'] = '.class' | python | def generate(env):
java_javah = SCons.Tool.CreateJavaHBuilder(env)
java_javah.emitter = emit_java_headers
env['_JAVAHOUTFLAG'] = JavaHOutFlagGenerator
env['JAVAH'] = 'javah'
env['JAVAHFLAGS'] = SCons.Util.CLVar('')
env['_JAVAHCLASSPATH'] = getJavaHClassPath
env['JAVAHCOM'] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}'
env['JAVACLASSSUFFIX'] = '.class' | [
"def",
"generate",
"(",
"env",
")",
":",
"java_javah",
"=",
"SCons",
".",
"Tool",
".",
"CreateJavaHBuilder",
"(",
"env",
")",
"java_javah",
".",
"emitter",
"=",
"emit_java_headers",
"env",
"[",
"'_JAVAHOUTFLAG'",
"]",
"=",
"JavaHOutFlagGenerator",
"env",
"[",
... | Add Builders and construction variables for javah to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"javah",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javah.py#L118-L128 |
24,037 | iotile/coretools | iotilesensorgraph/iotile/sg/engine/in_memory.py | InMemoryStorageEngine.dump | def dump(self):
"""Serialize the state of this InMemoryStorageEngine to a dict.
Returns:
dict: The serialized data.
"""
return {
u'storage_data': [x.asdict() for x in self.storage_data],
u'streaming_data': [x.asdict() for x in self.streaming_data]
} | python | def dump(self):
return {
u'storage_data': [x.asdict() for x in self.storage_data],
u'streaming_data': [x.asdict() for x in self.streaming_data]
} | [
"def",
"dump",
"(",
"self",
")",
":",
"return",
"{",
"u'storage_data'",
":",
"[",
"x",
".",
"asdict",
"(",
")",
"for",
"x",
"in",
"self",
".",
"storage_data",
"]",
",",
"u'streaming_data'",
":",
"[",
"x",
".",
"asdict",
"(",
")",
"for",
"x",
"in",
... | Serialize the state of this InMemoryStorageEngine to a dict.
Returns:
dict: The serialized data. | [
"Serialize",
"the",
"state",
"of",
"this",
"InMemoryStorageEngine",
"to",
"a",
"dict",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L26-L36 |
24,038 | iotile/coretools | iotilesensorgraph/iotile/sg/engine/in_memory.py | InMemoryStorageEngine.restore | def restore(self, state):
"""Restore the state of this InMemoryStorageEngine from a dict."""
storage_data = state.get(u'storage_data', [])
streaming_data = state.get(u'streaming_data', [])
if len(storage_data) > self.storage_length or len(streaming_data) > self.streaming_length:
raise ArgumentError("Cannot restore InMemoryStorageEngine, too many readings",
storage_size=len(storage_data), storage_max=self.storage_length,
streaming_size=len(streaming_data), streaming_max=self.streaming_length)
self.storage_data = [IOTileReading.FromDict(x) for x in storage_data]
self.streaming_data = [IOTileReading.FromDict(x) for x in streaming_data] | python | def restore(self, state):
storage_data = state.get(u'storage_data', [])
streaming_data = state.get(u'streaming_data', [])
if len(storage_data) > self.storage_length or len(streaming_data) > self.streaming_length:
raise ArgumentError("Cannot restore InMemoryStorageEngine, too many readings",
storage_size=len(storage_data), storage_max=self.storage_length,
streaming_size=len(streaming_data), streaming_max=self.streaming_length)
self.storage_data = [IOTileReading.FromDict(x) for x in storage_data]
self.streaming_data = [IOTileReading.FromDict(x) for x in streaming_data] | [
"def",
"restore",
"(",
"self",
",",
"state",
")",
":",
"storage_data",
"=",
"state",
".",
"get",
"(",
"u'storage_data'",
",",
"[",
"]",
")",
"streaming_data",
"=",
"state",
".",
"get",
"(",
"u'streaming_data'",
",",
"[",
"]",
")",
"if",
"len",
"(",
"... | Restore the state of this InMemoryStorageEngine from a dict. | [
"Restore",
"the",
"state",
"of",
"this",
"InMemoryStorageEngine",
"from",
"a",
"dict",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L38-L50 |
24,039 | iotile/coretools | iotilesensorgraph/iotile/sg/engine/in_memory.py | InMemoryStorageEngine.count_matching | def count_matching(self, selector, offset=0):
"""Count the number of readings matching selector.
Args:
selector (DataStreamSelector): The selector that we want to
count matching readings for.
offset (int): The starting offset that we should begin counting at.
Returns:
int: The number of matching readings.
"""
if selector.output:
data = self.streaming_data
elif selector.buffered:
data = self.storage_data
else:
raise ArgumentError("You can only pass a buffered selector to count_matching", selector=selector)
count = 0
for i in range(offset, len(data)):
reading = data[i]
stream = DataStream.FromEncoded(reading.stream)
if selector.matches(stream):
count += 1
return count | python | def count_matching(self, selector, offset=0):
if selector.output:
data = self.streaming_data
elif selector.buffered:
data = self.storage_data
else:
raise ArgumentError("You can only pass a buffered selector to count_matching", selector=selector)
count = 0
for i in range(offset, len(data)):
reading = data[i]
stream = DataStream.FromEncoded(reading.stream)
if selector.matches(stream):
count += 1
return count | [
"def",
"count_matching",
"(",
"self",
",",
"selector",
",",
"offset",
"=",
"0",
")",
":",
"if",
"selector",
".",
"output",
":",
"data",
"=",
"self",
".",
"streaming_data",
"elif",
"selector",
".",
"buffered",
":",
"data",
"=",
"self",
".",
"storage_data"... | Count the number of readings matching selector.
Args:
selector (DataStreamSelector): The selector that we want to
count matching readings for.
offset (int): The starting offset that we should begin counting at.
Returns:
int: The number of matching readings. | [
"Count",
"the",
"number",
"of",
"readings",
"matching",
"selector",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L61-L88 |
24,040 | iotile/coretools | iotilesensorgraph/iotile/sg/engine/in_memory.py | InMemoryStorageEngine.scan_storage | def scan_storage(self, area_name, callable, start=0, stop=None):
"""Iterate over streaming or storage areas, calling callable.
Args:
area_name (str): Either 'storage' or 'streaming' to indicate which
storage area to scan.
callable (callable): A function that will be called as (offset, reading)
for each reading between start_offset and end_offset (inclusive). If
the scan function wants to stop early it can return True. If it returns
anything else (including False or None), scanning will continue.
start (int): Optional offset to start at (included in scan).
stop (int): Optional offset to end at (included in scan).
Returns:
int: The number of entries scanned.
"""
if area_name == u'storage':
data = self.storage_data
elif area_name == u'streaming':
data = self.streaming_data
else:
raise ArgumentError("Unknown area name in scan_storage (%s) should be storage or streaming" % area_name)
if len(data) == 0:
return 0
if stop is None:
stop = len(data) - 1
elif stop >= len(data):
raise ArgumentError("Given stop offset is greater than the highest offset supported", length=len(data), stop_offset=stop)
scanned = 0
for i in range(start, stop + 1):
scanned += 1
should_break = callable(i, data[i])
if should_break is True:
break
return scanned | python | def scan_storage(self, area_name, callable, start=0, stop=None):
if area_name == u'storage':
data = self.storage_data
elif area_name == u'streaming':
data = self.streaming_data
else:
raise ArgumentError("Unknown area name in scan_storage (%s) should be storage or streaming" % area_name)
if len(data) == 0:
return 0
if stop is None:
stop = len(data) - 1
elif stop >= len(data):
raise ArgumentError("Given stop offset is greater than the highest offset supported", length=len(data), stop_offset=stop)
scanned = 0
for i in range(start, stop + 1):
scanned += 1
should_break = callable(i, data[i])
if should_break is True:
break
return scanned | [
"def",
"scan_storage",
"(",
"self",
",",
"area_name",
",",
"callable",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
")",
":",
"if",
"area_name",
"==",
"u'storage'",
":",
"data",
"=",
"self",
".",
"storage_data",
"elif",
"area_name",
"==",
"u'streami... | Iterate over streaming or storage areas, calling callable.
Args:
area_name (str): Either 'storage' or 'streaming' to indicate which
storage area to scan.
callable (callable): A function that will be called as (offset, reading)
for each reading between start_offset and end_offset (inclusive). If
the scan function wants to stop early it can return True. If it returns
anything else (including False or None), scanning will continue.
start (int): Optional offset to start at (included in scan).
stop (int): Optional offset to end at (included in scan).
Returns:
int: The number of entries scanned. | [
"Iterate",
"over",
"streaming",
"or",
"storage",
"areas",
"calling",
"callable",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L90-L130 |
24,041 | iotile/coretools | iotilesensorgraph/iotile/sg/engine/in_memory.py | InMemoryStorageEngine.push | def push(self, value):
"""Store a new value for the given stream.
Args:
value (IOTileReading): The value to store. The stream
parameter must have the correct value
"""
stream = DataStream.FromEncoded(value.stream)
if stream.stream_type == DataStream.OutputType:
if len(self.streaming_data) == self.streaming_length:
raise StorageFullError('Streaming buffer full')
self.streaming_data.append(value)
else:
if len(self.storage_data) == self.storage_length:
raise StorageFullError('Storage buffer full')
self.storage_data.append(value) | python | def push(self, value):
stream = DataStream.FromEncoded(value.stream)
if stream.stream_type == DataStream.OutputType:
if len(self.streaming_data) == self.streaming_length:
raise StorageFullError('Streaming buffer full')
self.streaming_data.append(value)
else:
if len(self.storage_data) == self.storage_length:
raise StorageFullError('Storage buffer full')
self.storage_data.append(value) | [
"def",
"push",
"(",
"self",
",",
"value",
")",
":",
"stream",
"=",
"DataStream",
".",
"FromEncoded",
"(",
"value",
".",
"stream",
")",
"if",
"stream",
".",
"stream_type",
"==",
"DataStream",
".",
"OutputType",
":",
"if",
"len",
"(",
"self",
".",
"strea... | Store a new value for the given stream.
Args:
value (IOTileReading): The value to store. The stream
parameter must have the correct value | [
"Store",
"a",
"new",
"value",
"for",
"the",
"given",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L138-L157 |
24,042 | iotile/coretools | iotilesensorgraph/iotile/sg/engine/in_memory.py | InMemoryStorageEngine.get | def get(self, buffer_type, offset):
"""Get a reading from the buffer at offset.
Offset is specified relative to the start of the data buffer.
This means that if the buffer rolls over, the offset for a given
item will appear to change. Anyone holding an offset outside of this
engine object will need to be notified when rollovers happen (i.e.
popn is called so that they can update their offset indices)
Args:
buffer_type (str): The buffer to pop from (either u"storage" or u"streaming")
offset (int): The offset of the reading to get
"""
if buffer_type == u'streaming':
chosen_buffer = self.streaming_data
else:
chosen_buffer = self.storage_data
if offset >= len(chosen_buffer):
raise StreamEmptyError("Invalid index given in get command", requested=offset, stored=len(chosen_buffer), buffer=buffer_type)
return chosen_buffer[offset] | python | def get(self, buffer_type, offset):
if buffer_type == u'streaming':
chosen_buffer = self.streaming_data
else:
chosen_buffer = self.storage_data
if offset >= len(chosen_buffer):
raise StreamEmptyError("Invalid index given in get command", requested=offset, stored=len(chosen_buffer), buffer=buffer_type)
return chosen_buffer[offset] | [
"def",
"get",
"(",
"self",
",",
"buffer_type",
",",
"offset",
")",
":",
"if",
"buffer_type",
"==",
"u'streaming'",
":",
"chosen_buffer",
"=",
"self",
".",
"streaming_data",
"else",
":",
"chosen_buffer",
"=",
"self",
".",
"storage_data",
"if",
"offset",
">=",... | Get a reading from the buffer at offset.
Offset is specified relative to the start of the data buffer.
This means that if the buffer rolls over, the offset for a given
item will appear to change. Anyone holding an offset outside of this
engine object will need to be notified when rollovers happen (i.e.
popn is called so that they can update their offset indices)
Args:
buffer_type (str): The buffer to pop from (either u"storage" or u"streaming")
offset (int): The offset of the reading to get | [
"Get",
"a",
"reading",
"from",
"the",
"buffer",
"at",
"offset",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L159-L181 |
24,043 | iotile/coretools | iotilesensorgraph/iotile/sg/engine/in_memory.py | InMemoryStorageEngine.popn | def popn(self, buffer_type, count):
"""Remove and return the oldest count values from the named buffer
Args:
buffer_type (str): The buffer to pop from (either u"storage" or u"streaming")
count (int): The number of readings to pop
Returns:
list(IOTileReading): The values popped from the buffer
"""
buffer_type = str(buffer_type)
if buffer_type == u'streaming':
chosen_buffer = self.streaming_data
else:
chosen_buffer = self.storage_data
if count > len(chosen_buffer):
raise StreamEmptyError("Not enough data in buffer for popn command", requested=count, stored=len(chosen_buffer), buffer=buffer_type)
popped = chosen_buffer[:count]
remaining = chosen_buffer[count:]
if buffer_type == u'streaming':
self.streaming_data = remaining
else:
self.storage_data = remaining
return popped | python | def popn(self, buffer_type, count):
buffer_type = str(buffer_type)
if buffer_type == u'streaming':
chosen_buffer = self.streaming_data
else:
chosen_buffer = self.storage_data
if count > len(chosen_buffer):
raise StreamEmptyError("Not enough data in buffer for popn command", requested=count, stored=len(chosen_buffer), buffer=buffer_type)
popped = chosen_buffer[:count]
remaining = chosen_buffer[count:]
if buffer_type == u'streaming':
self.streaming_data = remaining
else:
self.storage_data = remaining
return popped | [
"def",
"popn",
"(",
"self",
",",
"buffer_type",
",",
"count",
")",
":",
"buffer_type",
"=",
"str",
"(",
"buffer_type",
")",
"if",
"buffer_type",
"==",
"u'streaming'",
":",
"chosen_buffer",
"=",
"self",
".",
"streaming_data",
"else",
":",
"chosen_buffer",
"="... | Remove and return the oldest count values from the named buffer
Args:
buffer_type (str): The buffer to pop from (either u"storage" or u"streaming")
count (int): The number of readings to pop
Returns:
list(IOTileReading): The values popped from the buffer | [
"Remove",
"and",
"return",
"the",
"oldest",
"count",
"values",
"from",
"the",
"named",
"buffer"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L183-L212 |
24,044 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_adapter.py | WebSocketDeviceAdapter.send_script | async def send_script(self, conn_id, data):
"""Send a a script to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
data (bytes): the script to send to the device
"""
self._ensure_connection(conn_id, True)
connection_string = self._get_property(conn_id, "connection_string")
msg = dict(connection_string=connection_string, fragment_count=1, fragment_index=0,
script=base64.b64encode(data))
await self._send_command(OPERATIONS.SEND_SCRIPT, msg, COMMANDS.SendScriptResponse) | python | async def send_script(self, conn_id, data):
self._ensure_connection(conn_id, True)
connection_string = self._get_property(conn_id, "connection_string")
msg = dict(connection_string=connection_string, fragment_count=1, fragment_index=0,
script=base64.b64encode(data))
await self._send_command(OPERATIONS.SEND_SCRIPT, msg, COMMANDS.SendScriptResponse) | [
"async",
"def",
"send_script",
"(",
"self",
",",
"conn_id",
",",
"data",
")",
":",
"self",
".",
"_ensure_connection",
"(",
"conn_id",
",",
"True",
")",
"connection_string",
"=",
"self",
".",
"_get_property",
"(",
"conn_id",
",",
"\"connection_string\"",
")",
... | Send a a script to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
data (bytes): the script to send to the device | [
"Send",
"a",
"a",
"script",
"to",
"this",
"IOTile",
"device"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_adapter.py#L154-L167 |
24,045 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_adapter.py | WebSocketDeviceAdapter._on_report_notification | async def _on_report_notification(self, event):
"""Callback function called when a report event is received.
Args:
event (dict): The report_event
"""
conn_string = event.get('connection_string')
report = self._report_parser.deserialize_report(event.get('serialized_report'))
self.notify_event(conn_string, 'report', report) | python | async def _on_report_notification(self, event):
conn_string = event.get('connection_string')
report = self._report_parser.deserialize_report(event.get('serialized_report'))
self.notify_event(conn_string, 'report', report) | [
"async",
"def",
"_on_report_notification",
"(",
"self",
",",
"event",
")",
":",
"conn_string",
"=",
"event",
".",
"get",
"(",
"'connection_string'",
")",
"report",
"=",
"self",
".",
"_report_parser",
".",
"deserialize_report",
"(",
"event",
".",
"get",
"(",
... | Callback function called when a report event is received.
Args:
event (dict): The report_event | [
"Callback",
"function",
"called",
"when",
"a",
"report",
"event",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_adapter.py#L178-L188 |
24,046 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_adapter.py | WebSocketDeviceAdapter._on_trace_notification | async def _on_trace_notification(self, trace_event):
"""Callback function called when a trace chunk is received.
Args:
trace_chunk (dict): The received trace chunk information
"""
conn_string = trace_event.get('connection_string')
payload = trace_event.get('payload')
await self.notify_event(conn_string, 'trace', payload) | python | async def _on_trace_notification(self, trace_event):
conn_string = trace_event.get('connection_string')
payload = trace_event.get('payload')
await self.notify_event(conn_string, 'trace', payload) | [
"async",
"def",
"_on_trace_notification",
"(",
"self",
",",
"trace_event",
")",
":",
"conn_string",
"=",
"trace_event",
".",
"get",
"(",
"'connection_string'",
")",
"payload",
"=",
"trace_event",
".",
"get",
"(",
"'payload'",
")",
"await",
"self",
".",
"notify... | Callback function called when a trace chunk is received.
Args:
trace_chunk (dict): The received trace chunk information | [
"Callback",
"function",
"called",
"when",
"a",
"trace",
"chunk",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_adapter.py#L202-L212 |
24,047 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_adapter.py | WebSocketDeviceAdapter._on_progress_notification | async def _on_progress_notification(self, progress):
"""Callback function called when a progress notification is received.
Args:
progress (dict): The received notification containing the progress information
"""
conn_string = progress.get('connection_string')
done = progress.get('done_count')
total = progress.get('total_count')
operation = progress.get('operation')
await self.notify_progress(conn_string, operation, done, total, wait=True) | python | async def _on_progress_notification(self, progress):
conn_string = progress.get('connection_string')
done = progress.get('done_count')
total = progress.get('total_count')
operation = progress.get('operation')
await self.notify_progress(conn_string, operation, done, total, wait=True) | [
"async",
"def",
"_on_progress_notification",
"(",
"self",
",",
"progress",
")",
":",
"conn_string",
"=",
"progress",
".",
"get",
"(",
"'connection_string'",
")",
"done",
"=",
"progress",
".",
"get",
"(",
"'done_count'",
")",
"total",
"=",
"progress",
".",
"g... | Callback function called when a progress notification is received.
Args:
progress (dict): The received notification containing the progress information | [
"Callback",
"function",
"called",
"when",
"a",
"progress",
"notification",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_adapter.py#L214-L226 |
24,048 | iotile/coretools | iotileship/iotile/ship/recipe.py | _extract_variables | def _extract_variables(param):
"""Find all template variables in args."""
variables = set()
if isinstance(param, list):
variables.update(*[_extract_variables(x) for x in param])
elif isinstance(param, dict):
variables.update(*[_extract_variables(x) for x in param.values()])
elif isinstance(param, str):
for match in re.finditer(TEMPLATE_REGEX, param):
if match.group('short_id') is not None:
variables.add(match.group('short_id'))
else:
variables.add(match.group('long_id'))
return variables | python | def _extract_variables(param):
variables = set()
if isinstance(param, list):
variables.update(*[_extract_variables(x) for x in param])
elif isinstance(param, dict):
variables.update(*[_extract_variables(x) for x in param.values()])
elif isinstance(param, str):
for match in re.finditer(TEMPLATE_REGEX, param):
if match.group('short_id') is not None:
variables.add(match.group('short_id'))
else:
variables.add(match.group('long_id'))
return variables | [
"def",
"_extract_variables",
"(",
"param",
")",
":",
"variables",
"=",
"set",
"(",
")",
"if",
"isinstance",
"(",
"param",
",",
"list",
")",
":",
"variables",
".",
"update",
"(",
"*",
"[",
"_extract_variables",
"(",
"x",
")",
"for",
"x",
"in",
"param",
... | Find all template variables in args. | [
"Find",
"all",
"template",
"variables",
"in",
"args",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L506-L522 |
24,049 | iotile/coretools | iotileship/iotile/ship/recipe.py | _run_step | def _run_step(step_obj, step_declaration, initialized_resources):
"""Actually run a step."""
start_time = time.time()
# Open any resources that need to be opened before we run this step
for res_name in step_declaration.resources.opened:
initialized_resources[res_name].open()
# Create a dictionary of all of the resources that are required for this step
used_resources = {local_name: initialized_resources[global_name] for local_name, global_name in step_declaration.resources.used.items()}
# Allow steps with no resources to not need a resources keyword parameter
if len(used_resources) > 0:
out = step_obj.run(resources=used_resources)
else:
out = step_obj.run()
# Close any resources that need to be closed before we run this step
for res_name in step_declaration.resources.closed:
initialized_resources[res_name].close()
end_time = time.time()
return (end_time - start_time, out) | python | def _run_step(step_obj, step_declaration, initialized_resources):
start_time = time.time()
# Open any resources that need to be opened before we run this step
for res_name in step_declaration.resources.opened:
initialized_resources[res_name].open()
# Create a dictionary of all of the resources that are required for this step
used_resources = {local_name: initialized_resources[global_name] for local_name, global_name in step_declaration.resources.used.items()}
# Allow steps with no resources to not need a resources keyword parameter
if len(used_resources) > 0:
out = step_obj.run(resources=used_resources)
else:
out = step_obj.run()
# Close any resources that need to be closed before we run this step
for res_name in step_declaration.resources.closed:
initialized_resources[res_name].close()
end_time = time.time()
return (end_time - start_time, out) | [
"def",
"_run_step",
"(",
"step_obj",
",",
"step_declaration",
",",
"initialized_resources",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"# Open any resources that need to be opened before we run this step",
"for",
"res_name",
"in",
"step_declaration",
".",... | Actually run a step. | [
"Actually",
"run",
"a",
"step",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L525-L549 |
24,050 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject.archive | def archive(self, output_path):
"""Archive this recipe and all associated files into a .ship archive.
Args:
output_path (str): The path where the .ship file should be saved.
"""
if self.path is None:
raise ArgumentError("Cannot archive a recipe yet without a reference to its original yaml file in self.path")
outfile = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
outfile.write(self.path, arcname="recipe_script.yaml")
written_files = set()
for _factory, args, _resources, files in self.steps:
for arg_name in files:
file_path = args[arg_name]
if file_path in written_files:
continue
if os.path.basename(file_path) != file_path:
raise ArgumentError("Cannot archive a recipe yet that references file not in the same directory as the recipe")
full_path = os.path.join(os.path.dirname(self.path), file_path)
outfile.write(full_path, arcname=file_path)
written_files.add(file_path) | python | def archive(self, output_path):
if self.path is None:
raise ArgumentError("Cannot archive a recipe yet without a reference to its original yaml file in self.path")
outfile = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
outfile.write(self.path, arcname="recipe_script.yaml")
written_files = set()
for _factory, args, _resources, files in self.steps:
for arg_name in files:
file_path = args[arg_name]
if file_path in written_files:
continue
if os.path.basename(file_path) != file_path:
raise ArgumentError("Cannot archive a recipe yet that references file not in the same directory as the recipe")
full_path = os.path.join(os.path.dirname(self.path), file_path)
outfile.write(full_path, arcname=file_path)
written_files.add(file_path) | [
"def",
"archive",
"(",
"self",
",",
"output_path",
")",
":",
"if",
"self",
".",
"path",
"is",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"Cannot archive a recipe yet without a reference to its original yaml file in self.path\"",
")",
"outfile",
"=",
"zipfile",
".",
... | Archive this recipe and all associated files into a .ship archive.
Args:
output_path (str): The path where the .ship file should be saved. | [
"Archive",
"this",
"recipe",
"and",
"all",
"associated",
"files",
"into",
"a",
".",
"ship",
"archive",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L86-L114 |
24,051 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject.FromArchive | def FromArchive(cls, path, actions_dict, resources_dict, temp_dir=None):
"""Create a RecipeObject from a .ship archive.
This archive should have been generated from a previous call to
iotile-ship -a <path to yaml file>
or via iotile-build using autobuild_shiparchive().
Args:
path (str): The path to the recipe file that we wish to load
actions_dict (dict): A dictionary of named RecipeActionObject
types that is used to look up all of the steps listed in
the recipe file.
resources_dict (dict): A dictionary of named RecipeResource types
that is used to look up all of the shared resources listed in
the recipe file.
file_format (str): The file format of the recipe file. Currently
we only support yaml.
temp_dir (str): An optional temporary directory where this archive
should be unpacked. Otherwise a system wide temporary directory
is used.
"""
if not path.endswith(".ship"):
raise ArgumentError("Attempted to unpack a recipe archive from a file that did not end in .ship", path=path)
name = os.path.basename(path)[:-5]
if temp_dir is None:
temp_dir = tempfile.mkdtemp()
extract_path = os.path.join(temp_dir, name)
archive = zipfile.ZipFile(path, "r")
archive.extractall(extract_path)
recipe_yaml = os.path.join(extract_path, 'recipe_script.yaml')
return cls.FromFile(recipe_yaml, actions_dict, resources_dict, name=name) | python | def FromArchive(cls, path, actions_dict, resources_dict, temp_dir=None):
if not path.endswith(".ship"):
raise ArgumentError("Attempted to unpack a recipe archive from a file that did not end in .ship", path=path)
name = os.path.basename(path)[:-5]
if temp_dir is None:
temp_dir = tempfile.mkdtemp()
extract_path = os.path.join(temp_dir, name)
archive = zipfile.ZipFile(path, "r")
archive.extractall(extract_path)
recipe_yaml = os.path.join(extract_path, 'recipe_script.yaml')
return cls.FromFile(recipe_yaml, actions_dict, resources_dict, name=name) | [
"def",
"FromArchive",
"(",
"cls",
",",
"path",
",",
"actions_dict",
",",
"resources_dict",
",",
"temp_dir",
"=",
"None",
")",
":",
"if",
"not",
"path",
".",
"endswith",
"(",
"\".ship\"",
")",
":",
"raise",
"ArgumentError",
"(",
"\"Attempted to unpack a recipe ... | Create a RecipeObject from a .ship archive.
This archive should have been generated from a previous call to
iotile-ship -a <path to yaml file>
or via iotile-build using autobuild_shiparchive().
Args:
path (str): The path to the recipe file that we wish to load
actions_dict (dict): A dictionary of named RecipeActionObject
types that is used to look up all of the steps listed in
the recipe file.
resources_dict (dict): A dictionary of named RecipeResource types
that is used to look up all of the shared resources listed in
the recipe file.
file_format (str): The file format of the recipe file. Currently
we only support yaml.
temp_dir (str): An optional temporary directory where this archive
should be unpacked. Otherwise a system wide temporary directory
is used. | [
"Create",
"a",
"RecipeObject",
"from",
"a",
".",
"ship",
"archive",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L117-L153 |
24,052 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject.FromFile | def FromFile(cls, path, actions_dict, resources_dict, file_format="yaml", name=None):
"""Create a RecipeObject from a file.
The file should be a specially constructed yaml file that describes
the recipe as well as the actions that it performs.
Args:
path (str): The path to the recipe file that we wish to load
actions_dict (dict): A dictionary of named RecipeActionObject
types that is used to look up all of the steps listed in
the recipe file.
resources_dict (dict): A dictionary of named RecipeResource types
that is used to look up all of the shared resources listed in
the recipe file.
file_format (str): The file format of the recipe file. Currently
we only support yaml.
name (str): The name of this recipe if we created it originally from an
archive.
"""
format_map = {
"yaml": cls._process_yaml
}
format_handler = format_map.get(file_format)
if format_handler is None:
raise ArgumentError("Unknown file format or file extension", file_format=file_format, \
known_formats=[x for x in format_map if format_map[x] is not None])
recipe_info = format_handler(path)
if name is None:
name, _ext = os.path.splitext(os.path.basename(path))
# Validate that the recipe file is correctly formatted
try:
recipe_info = RecipeSchema.verify(recipe_info)
except ValidationError as exc:
raise RecipeFileInvalid("Recipe file does not match expected schema", file=path, error_message=exc.msg, **exc.params)
description = recipe_info.get('description')
# Parse out global default and shared resource information
try:
resources = cls._parse_resource_declarations(recipe_info.get('resources', []), resources_dict)
defaults = cls._parse_variable_defaults(recipe_info.get("defaults", []))
steps = []
for i, action in enumerate(recipe_info.get('actions', [])):
action_name = action.pop('name')
if action_name is None:
raise RecipeFileInvalid("Action is missing required name parameter", \
parameters=action, path=path)
action_class = actions_dict.get(action_name)
if action_class is None:
raise UnknownRecipeActionType("Unknown step specified in recipe", \
action=action_name, step=i + 1, path=path)
# Parse out any resource usage in this step and make sure we only
# use named resources
step_resources = cls._parse_resource_usage(action, declarations=resources)
fixed_files, _variable_files = cls._parse_file_usage(action_class, action)
step = RecipeStep(action_class, action, step_resources, fixed_files)
steps.append(step)
return RecipeObject(name, description, steps, resources, defaults, path)
except RecipeFileInvalid as exc:
cls._future_raise(RecipeFileInvalid, RecipeFileInvalid(exc.msg, recipe=name, **exc.params),
sys.exc_info()[2]) | python | def FromFile(cls, path, actions_dict, resources_dict, file_format="yaml", name=None):
format_map = {
"yaml": cls._process_yaml
}
format_handler = format_map.get(file_format)
if format_handler is None:
raise ArgumentError("Unknown file format or file extension", file_format=file_format, \
known_formats=[x for x in format_map if format_map[x] is not None])
recipe_info = format_handler(path)
if name is None:
name, _ext = os.path.splitext(os.path.basename(path))
# Validate that the recipe file is correctly formatted
try:
recipe_info = RecipeSchema.verify(recipe_info)
except ValidationError as exc:
raise RecipeFileInvalid("Recipe file does not match expected schema", file=path, error_message=exc.msg, **exc.params)
description = recipe_info.get('description')
# Parse out global default and shared resource information
try:
resources = cls._parse_resource_declarations(recipe_info.get('resources', []), resources_dict)
defaults = cls._parse_variable_defaults(recipe_info.get("defaults", []))
steps = []
for i, action in enumerate(recipe_info.get('actions', [])):
action_name = action.pop('name')
if action_name is None:
raise RecipeFileInvalid("Action is missing required name parameter", \
parameters=action, path=path)
action_class = actions_dict.get(action_name)
if action_class is None:
raise UnknownRecipeActionType("Unknown step specified in recipe", \
action=action_name, step=i + 1, path=path)
# Parse out any resource usage in this step and make sure we only
# use named resources
step_resources = cls._parse_resource_usage(action, declarations=resources)
fixed_files, _variable_files = cls._parse_file_usage(action_class, action)
step = RecipeStep(action_class, action, step_resources, fixed_files)
steps.append(step)
return RecipeObject(name, description, steps, resources, defaults, path)
except RecipeFileInvalid as exc:
cls._future_raise(RecipeFileInvalid, RecipeFileInvalid(exc.msg, recipe=name, **exc.params),
sys.exc_info()[2]) | [
"def",
"FromFile",
"(",
"cls",
",",
"path",
",",
"actions_dict",
",",
"resources_dict",
",",
"file_format",
"=",
"\"yaml\"",
",",
"name",
"=",
"None",
")",
":",
"format_map",
"=",
"{",
"\"yaml\"",
":",
"cls",
".",
"_process_yaml",
"}",
"format_handler",
"=... | Create a RecipeObject from a file.
The file should be a specially constructed yaml file that describes
the recipe as well as the actions that it performs.
Args:
path (str): The path to the recipe file that we wish to load
actions_dict (dict): A dictionary of named RecipeActionObject
types that is used to look up all of the steps listed in
the recipe file.
resources_dict (dict): A dictionary of named RecipeResource types
that is used to look up all of the shared resources listed in
the recipe file.
file_format (str): The file format of the recipe file. Currently
we only support yaml.
name (str): The name of this recipe if we created it originally from an
archive. | [
"Create",
"a",
"RecipeObject",
"from",
"a",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L156-L225 |
24,053 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject._parse_file_usage | def _parse_file_usage(cls, action_class, args):
"""Find all external files referenced by an action."""
fixed_files = {}
variable_files = []
if not hasattr(action_class, 'FILES'):
return fixed_files, variable_files
for file_arg in action_class.FILES:
arg_value = args.get(file_arg)
if arg_value is None:
raise RecipeFileInvalid("Action lists a file argument but none was given", declared_argument=file_arg, passed_arguments=args)
variables = _extract_variables(arg_value)
if len(variables) == 0:
fixed_files[file_arg] = arg_value
else:
variable_files.append(arg_value)
return fixed_files, variable_files | python | def _parse_file_usage(cls, action_class, args):
fixed_files = {}
variable_files = []
if not hasattr(action_class, 'FILES'):
return fixed_files, variable_files
for file_arg in action_class.FILES:
arg_value = args.get(file_arg)
if arg_value is None:
raise RecipeFileInvalid("Action lists a file argument but none was given", declared_argument=file_arg, passed_arguments=args)
variables = _extract_variables(arg_value)
if len(variables) == 0:
fixed_files[file_arg] = arg_value
else:
variable_files.append(arg_value)
return fixed_files, variable_files | [
"def",
"_parse_file_usage",
"(",
"cls",
",",
"action_class",
",",
"args",
")",
":",
"fixed_files",
"=",
"{",
"}",
"variable_files",
"=",
"[",
"]",
"if",
"not",
"hasattr",
"(",
"action_class",
",",
"'FILES'",
")",
":",
"return",
"fixed_files",
",",
"variabl... | Find all external files referenced by an action. | [
"Find",
"all",
"external",
"files",
"referenced",
"by",
"an",
"action",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L240-L260 |
24,054 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject._parse_resource_declarations | def _parse_resource_declarations(cls, declarations, resource_map):
"""Parse out what resources are declared as shared for this recipe."""
resources = {}
for decl in declarations:
name = decl.pop('name')
typename = decl.pop('type')
desc = decl.pop('description', None)
autocreate = decl.pop('autocreate', False)
args = decl
res_type = resource_map.get(typename)
if res_type is None:
raise UnknownRecipeResourceType("Could not find shared resource type", type=typename, name=name)
# If the resource defines an argument schema, make sure we enforce it.
if hasattr(res_type, "ARG_SCHEMA"):
try:
args = res_type.ARG_SCHEMA.verify(args)
except ValidationError as exc:
raise RecipeFileInvalid("Recipe file resource declarttion has invalid parameters", resource=name, error_message=exc.msg, **exc.params)
if name in resources:
raise RecipeFileInvalid("Attempted to add two shared resources with the same name", name=name)
res = ResourceDeclaration(name, resource_map.get(typename), args, autocreate, desc, typename)
resources[name] = res
return resources | python | def _parse_resource_declarations(cls, declarations, resource_map):
resources = {}
for decl in declarations:
name = decl.pop('name')
typename = decl.pop('type')
desc = decl.pop('description', None)
autocreate = decl.pop('autocreate', False)
args = decl
res_type = resource_map.get(typename)
if res_type is None:
raise UnknownRecipeResourceType("Could not find shared resource type", type=typename, name=name)
# If the resource defines an argument schema, make sure we enforce it.
if hasattr(res_type, "ARG_SCHEMA"):
try:
args = res_type.ARG_SCHEMA.verify(args)
except ValidationError as exc:
raise RecipeFileInvalid("Recipe file resource declarttion has invalid parameters", resource=name, error_message=exc.msg, **exc.params)
if name in resources:
raise RecipeFileInvalid("Attempted to add two shared resources with the same name", name=name)
res = ResourceDeclaration(name, resource_map.get(typename), args, autocreate, desc, typename)
resources[name] = res
return resources | [
"def",
"_parse_resource_declarations",
"(",
"cls",
",",
"declarations",
",",
"resource_map",
")",
":",
"resources",
"=",
"{",
"}",
"for",
"decl",
"in",
"declarations",
":",
"name",
"=",
"decl",
".",
"pop",
"(",
"'name'",
")",
"typename",
"=",
"decl",
".",
... | Parse out what resources are declared as shared for this recipe. | [
"Parse",
"out",
"what",
"resources",
"are",
"declared",
"as",
"shared",
"for",
"this",
"recipe",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L263-L293 |
24,055 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject._parse_variable_defaults | def _parse_variable_defaults(cls, defaults):
"""Parse out all of the variable defaults."""
default_dict = {}
for item in defaults:
key = next(iter(item))
value = item[key]
if key in default_dict:
raise RecipeFileInvalid("Default variable value specified twice", name=key, old_value=default_dict[key], new_value=value)
default_dict[key] = value
return default_dict | python | def _parse_variable_defaults(cls, defaults):
default_dict = {}
for item in defaults:
key = next(iter(item))
value = item[key]
if key in default_dict:
raise RecipeFileInvalid("Default variable value specified twice", name=key, old_value=default_dict[key], new_value=value)
default_dict[key] = value
return default_dict | [
"def",
"_parse_variable_defaults",
"(",
"cls",
",",
"defaults",
")",
":",
"default_dict",
"=",
"{",
"}",
"for",
"item",
"in",
"defaults",
":",
"key",
"=",
"next",
"(",
"iter",
"(",
"item",
")",
")",
"value",
"=",
"item",
"[",
"key",
"]",
"if",
"key",... | Parse out all of the variable defaults. | [
"Parse",
"out",
"all",
"of",
"the",
"variable",
"defaults",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L296-L310 |
24,056 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject._parse_resource_usage | def _parse_resource_usage(cls, action_dict, declarations):
"""Parse out what resources are used, opened and closed in an action step."""
raw_used = action_dict.pop('use', [])
opened = [x.strip() for x in action_dict.pop('open_before', [])]
closed = [x.strip() for x in action_dict.pop('close_after', [])]
used = {}
for resource in raw_used:
if 'as' in resource:
global_name, _, local_name = resource.partition('as')
global_name = global_name.strip()
local_name = local_name.strip()
if len(global_name) == 0 or len(local_name) == 0:
raise RecipeFileInvalid("Resource usage specified in action with invalid name using 'as' statement", global_name=global_name, local_name=local_name, statement=resource)
else:
global_name = resource.strip()
local_name = global_name
if local_name in used:
raise RecipeFileInvalid("Resource specified twice for action", args=action_dict, resource=local_name, used_resources=used)
used[local_name] = global_name
# Make sure we only use, open and close declared resources
for name in (x for x in used.values() if x not in declarations):
raise RecipeFileInvalid("Action makes use of non-declared shared resource", name=name)
for name in (x for x in opened if x not in declarations):
raise RecipeFileInvalid("Action specified a non-declared shared resource in open_before", name=name)
for name in (x for x in closed if x not in declarations):
raise RecipeFileInvalid("Action specified a non-declared shared resource in close_after", name=name)
return ResourceUsage(used, opened, closed) | python | def _parse_resource_usage(cls, action_dict, declarations):
raw_used = action_dict.pop('use', [])
opened = [x.strip() for x in action_dict.pop('open_before', [])]
closed = [x.strip() for x in action_dict.pop('close_after', [])]
used = {}
for resource in raw_used:
if 'as' in resource:
global_name, _, local_name = resource.partition('as')
global_name = global_name.strip()
local_name = local_name.strip()
if len(global_name) == 0 or len(local_name) == 0:
raise RecipeFileInvalid("Resource usage specified in action with invalid name using 'as' statement", global_name=global_name, local_name=local_name, statement=resource)
else:
global_name = resource.strip()
local_name = global_name
if local_name in used:
raise RecipeFileInvalid("Resource specified twice for action", args=action_dict, resource=local_name, used_resources=used)
used[local_name] = global_name
# Make sure we only use, open and close declared resources
for name in (x for x in used.values() if x not in declarations):
raise RecipeFileInvalid("Action makes use of non-declared shared resource", name=name)
for name in (x for x in opened if x not in declarations):
raise RecipeFileInvalid("Action specified a non-declared shared resource in open_before", name=name)
for name in (x for x in closed if x not in declarations):
raise RecipeFileInvalid("Action specified a non-declared shared resource in close_after", name=name)
return ResourceUsage(used, opened, closed) | [
"def",
"_parse_resource_usage",
"(",
"cls",
",",
"action_dict",
",",
"declarations",
")",
":",
"raw_used",
"=",
"action_dict",
".",
"pop",
"(",
"'use'",
",",
"[",
"]",
")",
"opened",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"action_dict... | Parse out what resources are used, opened and closed in an action step. | [
"Parse",
"out",
"what",
"resources",
"are",
"used",
"opened",
"and",
"closed",
"in",
"an",
"action",
"step",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L313-L349 |
24,057 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject.prepare | def prepare(self, variables):
"""Initialize all steps in this recipe using their parameters.
Args:
variables (dict): A dictionary of global variable definitions
that may be used to replace or augment the parameters given
to each step.
Returns:
list of RecipeActionObject like instances: The list of instantiated
steps that can be used to execute this recipe.
"""
initializedsteps = []
if variables is None:
variables = dict()
for step, params, _resources, _files in self.steps:
new_params = _complete_parameters(params, variables)
initializedsteps.append(step(new_params))
return initializedsteps | python | def prepare(self, variables):
initializedsteps = []
if variables is None:
variables = dict()
for step, params, _resources, _files in self.steps:
new_params = _complete_parameters(params, variables)
initializedsteps.append(step(new_params))
return initializedsteps | [
"def",
"prepare",
"(",
"self",
",",
"variables",
")",
":",
"initializedsteps",
"=",
"[",
"]",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"dict",
"(",
")",
"for",
"step",
",",
"params",
",",
"_resources",
",",
"_files",
"in",
"self",
".",
... | Initialize all steps in this recipe using their parameters.
Args:
variables (dict): A dictionary of global variable definitions
that may be used to replace or augment the parameters given
to each step.
Returns:
list of RecipeActionObject like instances: The list of instantiated
steps that can be used to execute this recipe. | [
"Initialize",
"all",
"steps",
"in",
"this",
"recipe",
"using",
"their",
"parameters",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L358-L376 |
24,058 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject._prepare_resources | def _prepare_resources(self, variables, overrides=None):
"""Create and optionally open all shared resources."""
if overrides is None:
overrides = {}
res_map = {}
own_map = {}
for decl in self.resources.values():
resource = overrides.get(decl.name)
if resource is None:
args = _complete_parameters(decl.args, variables)
resource = decl.type(args)
own_map[decl.name] = resource
if decl.autocreate:
resource.open()
res_map[decl.name] = resource
return res_map, own_map | python | def _prepare_resources(self, variables, overrides=None):
if overrides is None:
overrides = {}
res_map = {}
own_map = {}
for decl in self.resources.values():
resource = overrides.get(decl.name)
if resource is None:
args = _complete_parameters(decl.args, variables)
resource = decl.type(args)
own_map[decl.name] = resource
if decl.autocreate:
resource.open()
res_map[decl.name] = resource
return res_map, own_map | [
"def",
"_prepare_resources",
"(",
"self",
",",
"variables",
",",
"overrides",
"=",
"None",
")",
":",
"if",
"overrides",
"is",
"None",
":",
"overrides",
"=",
"{",
"}",
"res_map",
"=",
"{",
"}",
"own_map",
"=",
"{",
"}",
"for",
"decl",
"in",
"self",
".... | Create and optionally open all shared resources. | [
"Create",
"and",
"optionally",
"open",
"all",
"shared",
"resources",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L378-L400 |
24,059 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject._cleanup_resources | def _cleanup_resources(self, initialized_resources):
"""Cleanup all resources that we own that are open."""
cleanup_errors = []
# Make sure we clean up all resources that we can and don't error out at the
# first one.
for name, res in initialized_resources.items():
try:
if res.opened:
res.close()
except Exception:
_type, value, traceback = sys.exc_info()
cleanup_errors.append((name, value, traceback))
if len(cleanup_errors) > 0:
raise RecipeResourceManagementError(operation="resource cleanup", errors=cleanup_errors) | python | def _cleanup_resources(self, initialized_resources):
cleanup_errors = []
# Make sure we clean up all resources that we can and don't error out at the
# first one.
for name, res in initialized_resources.items():
try:
if res.opened:
res.close()
except Exception:
_type, value, traceback = sys.exc_info()
cleanup_errors.append((name, value, traceback))
if len(cleanup_errors) > 0:
raise RecipeResourceManagementError(operation="resource cleanup", errors=cleanup_errors) | [
"def",
"_cleanup_resources",
"(",
"self",
",",
"initialized_resources",
")",
":",
"cleanup_errors",
"=",
"[",
"]",
"# Make sure we clean up all resources that we can and don't error out at the",
"# first one.",
"for",
"name",
",",
"res",
"in",
"initialized_resources",
".",
... | Cleanup all resources that we own that are open. | [
"Cleanup",
"all",
"resources",
"that",
"we",
"own",
"that",
"are",
"open",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L402-L418 |
24,060 | iotile/coretools | iotileship/iotile/ship/recipe.py | RecipeObject.run | def run(self, variables=None, overrides=None):
"""Initialize and run this recipe.
By default all necessary shared resources are created and destroyed in
this function unless you pass them preinitizlied in overrides, in
which case they are used as is. The overrides parameter is designed
to allow testability of iotile-ship recipes by inspecting the shared
resources after the recipe has finished to ensure that it was properly
set up.
Args:
variables (dict): An optional dictionary of variable assignments.
There must be a single assignment for all free variables that
do not have a default value, otherwise the recipe will not
run.
overrides (dict): An optional dictionary of shared resource
objects that should be used instead of creating that resource
and destroying it inside this function.
"""
old_dir = os.getcwd()
try:
os.chdir(self.run_directory)
initialized_steps = self.prepare(variables)
owned_resources = {}
try:
print("Running in %s" % self.run_directory)
initialized_resources, owned_resources = self._prepare_resources(variables, overrides)
for i, (step, decl) in enumerate(zip(initialized_steps, self.steps)):
print("===> Step %d: %s\t Description: %s" % (i+1, self.steps[i][0].__name__, \
self.steps[i][1].get('description', '')))
runtime, out = _run_step(step, decl, initialized_resources)
print("======> Time Elapsed: %.2f seconds" % runtime)
if out is not None:
print(out[1])
finally:
self._cleanup_resources(owned_resources)
finally:
os.chdir(old_dir) | python | def run(self, variables=None, overrides=None):
old_dir = os.getcwd()
try:
os.chdir(self.run_directory)
initialized_steps = self.prepare(variables)
owned_resources = {}
try:
print("Running in %s" % self.run_directory)
initialized_resources, owned_resources = self._prepare_resources(variables, overrides)
for i, (step, decl) in enumerate(zip(initialized_steps, self.steps)):
print("===> Step %d: %s\t Description: %s" % (i+1, self.steps[i][0].__name__, \
self.steps[i][1].get('description', '')))
runtime, out = _run_step(step, decl, initialized_resources)
print("======> Time Elapsed: %.2f seconds" % runtime)
if out is not None:
print(out[1])
finally:
self._cleanup_resources(owned_resources)
finally:
os.chdir(old_dir) | [
"def",
"run",
"(",
"self",
",",
"variables",
"=",
"None",
",",
"overrides",
"=",
"None",
")",
":",
"old_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"os",
".",
"chdir",
"(",
"self",
".",
"run_directory",
")",
"initialized_steps",
"=",
"self"... | Initialize and run this recipe.
By default all necessary shared resources are created and destroyed in
this function unless you pass them preinitizlied in overrides, in
which case they are used as is. The overrides parameter is designed
to allow testability of iotile-ship recipes by inspecting the shared
resources after the recipe has finished to ensure that it was properly
set up.
Args:
variables (dict): An optional dictionary of variable assignments.
There must be a single assignment for all free variables that
do not have a default value, otherwise the recipe will not
run.
overrides (dict): An optional dictionary of shared resource
objects that should be used instead of creating that resource
and destroying it inside this function. | [
"Initialize",
"and",
"run",
"this",
"recipe",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe.py#L420-L463 |
24,061 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/yacc.py | generate | def generate(env):
"""Add Builders and construction variables for yacc to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
# C
c_file.add_action('.y', YaccAction)
c_file.add_emitter('.y', yEmitter)
c_file.add_action('.yacc', YaccAction)
c_file.add_emitter('.yacc', yEmitter)
# Objective-C
c_file.add_action('.ym', YaccAction)
c_file.add_emitter('.ym', ymEmitter)
# C++
cxx_file.add_action('.yy', YaccAction)
cxx_file.add_emitter('.yy', yyEmitter)
env['YACC'] = env.Detect('bison') or 'yacc'
env['YACCFLAGS'] = SCons.Util.CLVar('')
env['YACCCOM'] = '$YACC $YACCFLAGS -o $TARGET $SOURCES'
env['YACCHFILESUFFIX'] = '.h'
env['YACCHXXFILESUFFIX'] = '.hpp'
env['YACCVCGFILESUFFIX'] = '.vcg' | python | def generate(env):
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
# C
c_file.add_action('.y', YaccAction)
c_file.add_emitter('.y', yEmitter)
c_file.add_action('.yacc', YaccAction)
c_file.add_emitter('.yacc', yEmitter)
# Objective-C
c_file.add_action('.ym', YaccAction)
c_file.add_emitter('.ym', ymEmitter)
# C++
cxx_file.add_action('.yy', YaccAction)
cxx_file.add_emitter('.yy', yyEmitter)
env['YACC'] = env.Detect('bison') or 'yacc'
env['YACCFLAGS'] = SCons.Util.CLVar('')
env['YACCCOM'] = '$YACC $YACCFLAGS -o $TARGET $SOURCES'
env['YACCHFILESUFFIX'] = '.h'
env['YACCHXXFILESUFFIX'] = '.hpp'
env['YACCVCGFILESUFFIX'] = '.vcg' | [
"def",
"generate",
"(",
"env",
")",
":",
"c_file",
",",
"cxx_file",
"=",
"SCons",
".",
"Tool",
".",
"createCFileBuilders",
"(",
"env",
")",
"# C",
"c_file",
".",
"add_action",
"(",
"'.y'",
",",
"YaccAction",
")",
"c_file",
".",
"add_emitter",
"(",
"'.y'"... | Add Builders and construction variables for yacc to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"yacc",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/yacc.py#L97-L123 |
24,062 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ilink32.py | generate | def generate(env):
"""Add Builders and construction variables for Borland ilink to an
Environment."""
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['LINK'] = '$CC'
env['LINKFLAGS'] = SCons.Util.CLVar('')
env['LINKCOM'] = '$LINK -q $LINKFLAGS -e$TARGET $SOURCES $LIBS'
env['LIBDIRPREFIX']=''
env['LIBDIRSUFFIX']=''
env['LIBLINKPREFIX']=''
env['LIBLINKSUFFIX']='$LIBSUFFIX' | python | def generate(env):
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['LINK'] = '$CC'
env['LINKFLAGS'] = SCons.Util.CLVar('')
env['LINKCOM'] = '$LINK -q $LINKFLAGS -e$TARGET $SOURCES $LIBS'
env['LIBDIRPREFIX']=''
env['LIBDIRSUFFIX']=''
env['LIBLINKPREFIX']=''
env['LIBLINKSUFFIX']='$LIBSUFFIX' | [
"def",
"generate",
"(",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"createSharedLibBuilder",
"(",
"env",
")",
"SCons",
".",
"Tool",
".",
"createProgBuilder",
"(",
"env",
")",
"env",
"[",
"'LINK'",
"]",
"=",
"'$CC'",
"env",
"[",
"'LINKFLAGS'",
"]",
"="... | Add Builders and construction variables for Borland ilink to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Borland",
"ilink",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ilink32.py#L36-L48 |
24,063 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/sdk.py | SDKDefinition.find_sdk_dir | def find_sdk_dir(self):
"""Try to find the MS SDK from the registry.
Return None if failed or the directory does not exist.
"""
if not SCons.Util.can_read_reg:
debug('find_sdk_dir(): can not read registry')
return None
hkey = self.HKEY_FMT % self.hkey_data
debug('find_sdk_dir(): checking registry:{}'.format(hkey))
try:
sdk_dir = common.read_reg(hkey)
except SCons.Util.WinError as e:
debug('find_sdk_dir(): no SDK registry key {}'.format(repr(hkey)))
return None
debug('find_sdk_dir(): Trying SDK Dir: {}'.format(sdk_dir))
if not os.path.exists(sdk_dir):
debug('find_sdk_dir(): {} not on file system'.format(sdk_dir))
return None
ftc = os.path.join(sdk_dir, self.sanity_check_file)
if not os.path.exists(ftc):
debug("find_sdk_dir(): sanity check {} not found".format(ftc))
return None
return sdk_dir | python | def find_sdk_dir(self):
if not SCons.Util.can_read_reg:
debug('find_sdk_dir(): can not read registry')
return None
hkey = self.HKEY_FMT % self.hkey_data
debug('find_sdk_dir(): checking registry:{}'.format(hkey))
try:
sdk_dir = common.read_reg(hkey)
except SCons.Util.WinError as e:
debug('find_sdk_dir(): no SDK registry key {}'.format(repr(hkey)))
return None
debug('find_sdk_dir(): Trying SDK Dir: {}'.format(sdk_dir))
if not os.path.exists(sdk_dir):
debug('find_sdk_dir(): {} not on file system'.format(sdk_dir))
return None
ftc = os.path.join(sdk_dir, self.sanity_check_file)
if not os.path.exists(ftc):
debug("find_sdk_dir(): sanity check {} not found".format(ftc))
return None
return sdk_dir | [
"def",
"find_sdk_dir",
"(",
"self",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"can_read_reg",
":",
"debug",
"(",
"'find_sdk_dir(): can not read registry'",
")",
"return",
"None",
"hkey",
"=",
"self",
".",
"HKEY_FMT",
"%",
"self",
".",
"hkey_data",
"d... | Try to find the MS SDK from the registry.
Return None if failed or the directory does not exist. | [
"Try",
"to",
"find",
"the",
"MS",
"SDK",
"from",
"the",
"registry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/sdk.py#L69-L98 |
24,064 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/sdk.py | SDKDefinition.get_sdk_dir | def get_sdk_dir(self):
"""Return the MSSSDK given the version string."""
try:
return self._sdk_dir
except AttributeError:
sdk_dir = self.find_sdk_dir()
self._sdk_dir = sdk_dir
return sdk_dir | python | def get_sdk_dir(self):
try:
return self._sdk_dir
except AttributeError:
sdk_dir = self.find_sdk_dir()
self._sdk_dir = sdk_dir
return sdk_dir | [
"def",
"get_sdk_dir",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_sdk_dir",
"except",
"AttributeError",
":",
"sdk_dir",
"=",
"self",
".",
"find_sdk_dir",
"(",
")",
"self",
".",
"_sdk_dir",
"=",
"sdk_dir",
"return",
"sdk_dir"
] | Return the MSSSDK given the version string. | [
"Return",
"the",
"MSSSDK",
"given",
"the",
"version",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/sdk.py#L100-L107 |
24,065 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/sdk.py | SDKDefinition.get_sdk_vc_script | def get_sdk_vc_script(self,host_arch, target_arch):
""" Return the script to initialize the VC compiler installed by SDK
"""
if (host_arch == 'amd64' and target_arch == 'x86'):
# No cross tools needed compiling 32 bits on 64 bit machine
host_arch=target_arch
arch_string=target_arch
if (host_arch != target_arch):
arch_string='%s_%s'%(host_arch,target_arch)
debug("sdk.py: get_sdk_vc_script():arch_string:%s host_arch:%s target_arch:%s"%(arch_string,
host_arch,
target_arch))
file=self.vc_setup_scripts.get(arch_string,None)
debug("sdk.py: get_sdk_vc_script():file:%s"%file)
return file | python | def get_sdk_vc_script(self,host_arch, target_arch):
if (host_arch == 'amd64' and target_arch == 'x86'):
# No cross tools needed compiling 32 bits on 64 bit machine
host_arch=target_arch
arch_string=target_arch
if (host_arch != target_arch):
arch_string='%s_%s'%(host_arch,target_arch)
debug("sdk.py: get_sdk_vc_script():arch_string:%s host_arch:%s target_arch:%s"%(arch_string,
host_arch,
target_arch))
file=self.vc_setup_scripts.get(arch_string,None)
debug("sdk.py: get_sdk_vc_script():file:%s"%file)
return file | [
"def",
"get_sdk_vc_script",
"(",
"self",
",",
"host_arch",
",",
"target_arch",
")",
":",
"if",
"(",
"host_arch",
"==",
"'amd64'",
"and",
"target_arch",
"==",
"'x86'",
")",
":",
"# No cross tools needed compiling 32 bits on 64 bit machine",
"host_arch",
"=",
"target_ar... | Return the script to initialize the VC compiler installed by SDK | [
"Return",
"the",
"script",
"to",
"initialize",
"the",
"VC",
"compiler",
"installed",
"by",
"SDK"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/sdk.py#L109-L126 |
24,066 | iotile/coretools | iotileemulate/iotile/emulate/utilities/format_rpc.py | format_rpc | def format_rpc(data):
"""Format an RPC call and response.
Args:
data (tuple): A tuple containing the address, rpc_id, argument and
response payloads and any error code.
Returns:
str: The formated RPC string.
"""
address, rpc_id, args, resp, _status = data
name = rpc_name(rpc_id)
if isinstance(args, (bytes, bytearray)):
arg_str = hexlify(args)
else:
arg_str = repr(args)
if isinstance(resp, (bytes, bytearray)):
resp_str = hexlify(resp)
else:
resp_str = repr(resp)
#FIXME: Check and print status as well
return "%s called on address %d, payload=%s, response=%s" % (name, address, arg_str, resp_str) | python | def format_rpc(data):
address, rpc_id, args, resp, _status = data
name = rpc_name(rpc_id)
if isinstance(args, (bytes, bytearray)):
arg_str = hexlify(args)
else:
arg_str = repr(args)
if isinstance(resp, (bytes, bytearray)):
resp_str = hexlify(resp)
else:
resp_str = repr(resp)
#FIXME: Check and print status as well
return "%s called on address %d, payload=%s, response=%s" % (name, address, arg_str, resp_str) | [
"def",
"format_rpc",
"(",
"data",
")",
":",
"address",
",",
"rpc_id",
",",
"args",
",",
"resp",
",",
"_status",
"=",
"data",
"name",
"=",
"rpc_name",
"(",
"rpc_id",
")",
"if",
"isinstance",
"(",
"args",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
... | Format an RPC call and response.
Args:
data (tuple): A tuple containing the address, rpc_id, argument and
response payloads and any error code.
Returns:
str: The formated RPC string. | [
"Format",
"an",
"RPC",
"call",
"and",
"response",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/utilities/format_rpc.py#L6-L32 |
24,067 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/server_bled112.py | BLED112Server.start | async def start(self):
"""Start serving access to devices over bluetooth."""
self._command_task.start()
try:
await self._cleanup_old_connections()
except Exception:
await self.stop()
raise
#FIXME: This is a temporary hack, get the actual device we are serving.
iotile_id = next(iter(self.adapter.devices))
self.device = self.adapter.devices[iotile_id]
self._logger.info("Serving device 0x%04X over BLED112", iotile_id)
await self._update_advertisement()
self.setup_client(self.CLIENT_ID, scan=False, broadcast=True) | python | async def start(self):
self._command_task.start()
try:
await self._cleanup_old_connections()
except Exception:
await self.stop()
raise
#FIXME: This is a temporary hack, get the actual device we are serving.
iotile_id = next(iter(self.adapter.devices))
self.device = self.adapter.devices[iotile_id]
self._logger.info("Serving device 0x%04X over BLED112", iotile_id)
await self._update_advertisement()
self.setup_client(self.CLIENT_ID, scan=False, broadcast=True) | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_command_task",
".",
"start",
"(",
")",
"try",
":",
"await",
"self",
".",
"_cleanup_old_connections",
"(",
")",
"except",
"Exception",
":",
"await",
"self",
".",
"stop",
"(",
")",
"raise",
"... | Start serving access to devices over bluetooth. | [
"Start",
"serving",
"access",
"to",
"devices",
"over",
"bluetooth",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/server_bled112.py#L126-L144 |
24,068 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/server_bled112.py | BLED112Server.stop | async def stop(self):
"""Safely shut down this interface"""
await self._command_task.future_command(['_set_mode', 0, 0]) # Disable advertising
await self._cleanup_old_connections()
self._command_task.stop()
self._stream.stop()
self._serial_port.close()
await super(BLED112Server, self).stop() | python | async def stop(self):
await self._command_task.future_command(['_set_mode', 0, 0]) # Disable advertising
await self._cleanup_old_connections()
self._command_task.stop()
self._stream.stop()
self._serial_port.close()
await super(BLED112Server, self).stop() | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"await",
"self",
".",
"_command_task",
".",
"future_command",
"(",
"[",
"'_set_mode'",
",",
"0",
",",
"0",
"]",
")",
"# Disable advertising",
"await",
"self",
".",
"_cleanup_old_connections",
"(",
")",
"self",
... | Safely shut down this interface | [
"Safely",
"shut",
"down",
"this",
"interface"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/server_bled112.py#L146-L155 |
24,069 | iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/server_bled112.py | BLED112Server._call_rpc | async def _call_rpc(self, header):
"""Call an RPC given a header and possibly a previously sent payload
Args:
header (bytearray): The RPC header we should call
"""
length, _, cmd, feature, address = struct.unpack("<BBBBB", bytes(header))
rpc_id = (feature << 8) | cmd
payload = self.rpc_payload[:length]
self._logger.debug("Calling RPC %d:%04X with %s", address, rpc_id, binascii.hexlify(payload))
exception = None
response = None
try:
response = await self.send_rpc(self.CLIENT_ID, str(self.device.iotile_id), address, rpc_id, bytes(payload), timeout=30.0)
except VALID_RPC_EXCEPTIONS as err:
exception = err
except Exception as err:
self._logger.exception("Error calling RPC %d:%04X", address, rpc_id)
exception = err
status, response = pack_rpc_response(response, exception)
resp_header = struct.pack("<BBBB", status, 0, 0, len(response))
await self._send_notification(self.ReceiveHeaderHandle, resp_header)
if len(response) > 0:
await self._send_notification(self.ReceivePayloadHandle, response) | python | async def _call_rpc(self, header):
length, _, cmd, feature, address = struct.unpack("<BBBBB", bytes(header))
rpc_id = (feature << 8) | cmd
payload = self.rpc_payload[:length]
self._logger.debug("Calling RPC %d:%04X with %s", address, rpc_id, binascii.hexlify(payload))
exception = None
response = None
try:
response = await self.send_rpc(self.CLIENT_ID, str(self.device.iotile_id), address, rpc_id, bytes(payload), timeout=30.0)
except VALID_RPC_EXCEPTIONS as err:
exception = err
except Exception as err:
self._logger.exception("Error calling RPC %d:%04X", address, rpc_id)
exception = err
status, response = pack_rpc_response(response, exception)
resp_header = struct.pack("<BBBB", status, 0, 0, len(response))
await self._send_notification(self.ReceiveHeaderHandle, resp_header)
if len(response) > 0:
await self._send_notification(self.ReceivePayloadHandle, response) | [
"async",
"def",
"_call_rpc",
"(",
"self",
",",
"header",
")",
":",
"length",
",",
"_",
",",
"cmd",
",",
"feature",
",",
"address",
"=",
"struct",
".",
"unpack",
"(",
"\"<BBBBB\"",
",",
"bytes",
"(",
"header",
")",
")",
"rpc_id",
"=",
"(",
"feature",
... | Call an RPC given a header and possibly a previously sent payload
Args:
header (bytearray): The RPC header we should call | [
"Call",
"an",
"RPC",
"given",
"a",
"header",
"and",
"possibly",
"a",
"previously",
"sent",
"payload"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/server_bled112.py#L308-L339 |
24,070 | iotile/coretools | iotilesensorgraph/iotile/sg/output_formats/script.py | format_script | def format_script(sensor_graph):
"""Create a binary script containing this sensor graph.
This function produces a repeatable script by applying a known sorting
order to all constants and config variables when iterating over those
dictionaries.
Args:
sensor_graph (SensorGraph): the sensor graph that we want to format
Returns:
bytearray: The binary script data.
"""
records = []
records.append(SetGraphOnlineRecord(False, address=8))
records.append(ClearDataRecord(address=8))
records.append(ResetGraphRecord(address=8))
for node in sensor_graph.nodes:
records.append(AddNodeRecord(str(node), address=8))
for streamer in sensor_graph.streamers:
records.append(AddStreamerRecord(streamer, address=8))
for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()):
records.append(SetConstantRecord(stream, value, address=8))
records.append(PersistGraphRecord(address=8))
records.append(ClearConfigVariablesRecord())
for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()):
for config_id in sorted(sensor_graph.config_database[slot]):
config_type, value = sensor_graph.config_database[slot][config_id]
byte_value = _convert_to_bytes(config_type, value)
records.append(SetConfigRecord(slot, config_id, byte_value))
# If we have an app tag and version set program them in
app_tag = sensor_graph.metadata_database.get('app_tag')
app_version = sensor_graph.metadata_database.get('app_version')
if app_tag is not None:
records.append(SetDeviceTagRecord(app_tag=app_tag, app_version=app_version))
script = UpdateScript(records)
return script.encode() | python | def format_script(sensor_graph):
records = []
records.append(SetGraphOnlineRecord(False, address=8))
records.append(ClearDataRecord(address=8))
records.append(ResetGraphRecord(address=8))
for node in sensor_graph.nodes:
records.append(AddNodeRecord(str(node), address=8))
for streamer in sensor_graph.streamers:
records.append(AddStreamerRecord(streamer, address=8))
for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()):
records.append(SetConstantRecord(stream, value, address=8))
records.append(PersistGraphRecord(address=8))
records.append(ClearConfigVariablesRecord())
for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()):
for config_id in sorted(sensor_graph.config_database[slot]):
config_type, value = sensor_graph.config_database[slot][config_id]
byte_value = _convert_to_bytes(config_type, value)
records.append(SetConfigRecord(slot, config_id, byte_value))
# If we have an app tag and version set program them in
app_tag = sensor_graph.metadata_database.get('app_tag')
app_version = sensor_graph.metadata_database.get('app_version')
if app_tag is not None:
records.append(SetDeviceTagRecord(app_tag=app_tag, app_version=app_version))
script = UpdateScript(records)
return script.encode() | [
"def",
"format_script",
"(",
"sensor_graph",
")",
":",
"records",
"=",
"[",
"]",
"records",
".",
"append",
"(",
"SetGraphOnlineRecord",
"(",
"False",
",",
"address",
"=",
"8",
")",
")",
"records",
".",
"append",
"(",
"ClearDataRecord",
"(",
"address",
"=",... | Create a binary script containing this sensor graph.
This function produces a repeatable script by applying a known sorting
order to all constants and config variables when iterating over those
dictionaries.
Args:
sensor_graph (SensorGraph): the sensor graph that we want to format
Returns:
bytearray: The binary script data. | [
"Create",
"a",
"binary",
"script",
"containing",
"this",
"sensor",
"graph",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/output_formats/script.py#L12-L60 |
24,071 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.dump | def dump(self):
"""Dump the state of this SensorLog.
The purpose of this method is to be able to restore the same state
later. However there are links in the SensorLog for stream walkers.
So the dump process saves the state of each stream walker and upon
restore, it looks through the current set of stream walkers and
restores each one that existed when dump() was called to its state.
Returns:
dict: The serialized state of this SensorLog.
"""
walkers = {}
walkers.update({str(walker.selector): walker.dump() for walker in self._queue_walkers})
walkers.update({str(walker.selector): walker.dump() for walker in self._virtual_walkers})
return {
u'engine': self._engine.dump(),
u'rollover_storage': self._rollover_storage,
u'rollover_streaming': self._rollover_streaming,
u'last_values': {str(stream): reading.asdict() for stream, reading in self._last_values.items()},
u'walkers': walkers
} | python | def dump(self):
walkers = {}
walkers.update({str(walker.selector): walker.dump() for walker in self._queue_walkers})
walkers.update({str(walker.selector): walker.dump() for walker in self._virtual_walkers})
return {
u'engine': self._engine.dump(),
u'rollover_storage': self._rollover_storage,
u'rollover_streaming': self._rollover_streaming,
u'last_values': {str(stream): reading.asdict() for stream, reading in self._last_values.items()},
u'walkers': walkers
} | [
"def",
"dump",
"(",
"self",
")",
":",
"walkers",
"=",
"{",
"}",
"walkers",
".",
"update",
"(",
"{",
"str",
"(",
"walker",
".",
"selector",
")",
":",
"walker",
".",
"dump",
"(",
")",
"for",
"walker",
"in",
"self",
".",
"_queue_walkers",
"}",
")",
... | Dump the state of this SensorLog.
The purpose of this method is to be able to restore the same state
later. However there are links in the SensorLog for stream walkers.
So the dump process saves the state of each stream walker and upon
restore, it looks through the current set of stream walkers and
restores each one that existed when dump() was called to its state.
Returns:
dict: The serialized state of this SensorLog. | [
"Dump",
"the",
"state",
"of",
"this",
"SensorLog",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L74-L98 |
24,072 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.set_rollover | def set_rollover(self, area, enabled):
"""Configure whether rollover is enabled for streaming or storage streams.
Normally a SensorLog is used in ring-buffer mode which means that old
readings are automatically overwritten as needed when new data is saved.
However, you can configure it into fill-stop mode by using:
set_rollover("streaming"|"storage", True|False)
By default rollover is set to True for both streaming and storage and can
be controlled individually for each one.
Args:
area (str): Either streaming or storage.
enabled (bool): Whether to enable or disable rollover.
"""
if area == u'streaming':
self._rollover_streaming = enabled
elif area == u'storage':
self._rollover_storage = enabled
else:
raise ArgumentError("You must pass one of 'storage' or 'streaming' to set_rollover", area=area) | python | def set_rollover(self, area, enabled):
if area == u'streaming':
self._rollover_streaming = enabled
elif area == u'storage':
self._rollover_storage = enabled
else:
raise ArgumentError("You must pass one of 'storage' or 'streaming' to set_rollover", area=area) | [
"def",
"set_rollover",
"(",
"self",
",",
"area",
",",
"enabled",
")",
":",
"if",
"area",
"==",
"u'streaming'",
":",
"self",
".",
"_rollover_streaming",
"=",
"enabled",
"elif",
"area",
"==",
"u'storage'",
":",
"self",
".",
"_rollover_storage",
"=",
"enabled",... | Configure whether rollover is enabled for streaming or storage streams.
Normally a SensorLog is used in ring-buffer mode which means that old
readings are automatically overwritten as needed when new data is saved.
However, you can configure it into fill-stop mode by using:
set_rollover("streaming"|"storage", True|False)
By default rollover is set to True for both streaming and storage and can
be controlled individually for each one.
Args:
area (str): Either streaming or storage.
enabled (bool): Whether to enable or disable rollover. | [
"Configure",
"whether",
"rollover",
"is",
"enabled",
"for",
"streaming",
"or",
"storage",
"streams",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L146-L168 |
24,073 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.watch | def watch(self, selector, callback):
"""Call a function whenever a stream changes.
Args:
selector (DataStreamSelector): The selector to watch.
If this is None, it is treated as a wildcard selector
that matches every stream.
callback (callable): The function to call when a new
reading is pushed. Callback is called as:
callback(stream, value)
"""
if selector not in self._monitors:
self._monitors[selector] = set()
self._monitors[selector].add(callback) | python | def watch(self, selector, callback):
if selector not in self._monitors:
self._monitors[selector] = set()
self._monitors[selector].add(callback) | [
"def",
"watch",
"(",
"self",
",",
"selector",
",",
"callback",
")",
":",
"if",
"selector",
"not",
"in",
"self",
".",
"_monitors",
":",
"self",
".",
"_monitors",
"[",
"selector",
"]",
"=",
"set",
"(",
")",
"self",
".",
"_monitors",
"[",
"selector",
"]... | Call a function whenever a stream changes.
Args:
selector (DataStreamSelector): The selector to watch.
If this is None, it is treated as a wildcard selector
that matches every stream.
callback (callable): The function to call when a new
reading is pushed. Callback is called as:
callback(stream, value) | [
"Call",
"a",
"function",
"whenever",
"a",
"stream",
"changes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L190-L205 |
24,074 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.create_walker | def create_walker(self, selector, skip_all=True):
"""Create a stream walker based on the given selector.
This function returns a StreamWalker subclass that will
remain up to date and allow iterating over and popping readings
from the stream(s) specified by the selector.
When the stream walker is done, it should be passed to
destroy_walker so that it is removed from internal lists that
are used to always keep it in sync.
Args:
selector (DataStreamSelector): The selector describing the
streams that we want to iterate over.
skip_all (bool): Whether to start at the beginning of the data
or to skip everything and start at the end. Defaults
to skipping everything. This parameter only has any
effect on buffered stream selectors.
Returns:
StreamWalker: A properly updating stream walker with the given selector.
"""
if selector.buffered:
walker = BufferedStreamWalker(selector, self._engine, skip_all=skip_all)
self._queue_walkers.append(walker)
return walker
if selector.match_type == DataStream.CounterType:
walker = CounterStreamWalker(selector)
else:
walker = VirtualStreamWalker(selector)
self._virtual_walkers.append(walker)
return walker | python | def create_walker(self, selector, skip_all=True):
if selector.buffered:
walker = BufferedStreamWalker(selector, self._engine, skip_all=skip_all)
self._queue_walkers.append(walker)
return walker
if selector.match_type == DataStream.CounterType:
walker = CounterStreamWalker(selector)
else:
walker = VirtualStreamWalker(selector)
self._virtual_walkers.append(walker)
return walker | [
"def",
"create_walker",
"(",
"self",
",",
"selector",
",",
"skip_all",
"=",
"True",
")",
":",
"if",
"selector",
".",
"buffered",
":",
"walker",
"=",
"BufferedStreamWalker",
"(",
"selector",
",",
"self",
".",
"_engine",
",",
"skip_all",
"=",
"skip_all",
")"... | Create a stream walker based on the given selector.
This function returns a StreamWalker subclass that will
remain up to date and allow iterating over and popping readings
from the stream(s) specified by the selector.
When the stream walker is done, it should be passed to
destroy_walker so that it is removed from internal lists that
are used to always keep it in sync.
Args:
selector (DataStreamSelector): The selector describing the
streams that we want to iterate over.
skip_all (bool): Whether to start at the beginning of the data
or to skip everything and start at the end. Defaults
to skipping everything. This parameter only has any
effect on buffered stream selectors.
Returns:
StreamWalker: A properly updating stream walker with the given selector. | [
"Create",
"a",
"stream",
"walker",
"based",
"on",
"the",
"given",
"selector",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L207-L242 |
24,075 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.destroy_walker | def destroy_walker(self, walker):
"""Destroy a previously created stream walker.
Args:
walker (StreamWalker): The walker to remove from internal updating
lists.
"""
if walker.buffered:
self._queue_walkers.remove(walker)
else:
self._virtual_walkers.remove(walker) | python | def destroy_walker(self, walker):
if walker.buffered:
self._queue_walkers.remove(walker)
else:
self._virtual_walkers.remove(walker) | [
"def",
"destroy_walker",
"(",
"self",
",",
"walker",
")",
":",
"if",
"walker",
".",
"buffered",
":",
"self",
".",
"_queue_walkers",
".",
"remove",
"(",
"walker",
")",
"else",
":",
"self",
".",
"_virtual_walkers",
".",
"remove",
"(",
"walker",
")"
] | Destroy a previously created stream walker.
Args:
walker (StreamWalker): The walker to remove from internal updating
lists. | [
"Destroy",
"a",
"previously",
"created",
"stream",
"walker",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L244-L255 |
24,076 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.restore_walker | def restore_walker(self, dumped_state):
"""Restore a stream walker that was previously serialized.
Since stream walkers need to be tracked in an internal list for
notification purposes, we need to be careful with how we restore
them to make sure they remain part of the right list.
Args:
dumped_state (dict): The dumped state of a stream walker
from a previous call to StreamWalker.dump()
Returns:
StreamWalker: The correctly restored StreamWalker subclass.
"""
selector_string = dumped_state.get(u'selector')
if selector_string is None:
raise ArgumentError("Invalid stream walker state in restore_walker, missing 'selector' key", state=dumped_state)
selector = DataStreamSelector.FromString(selector_string)
walker = self.create_walker(selector)
walker.restore(dumped_state)
return walker | python | def restore_walker(self, dumped_state):
selector_string = dumped_state.get(u'selector')
if selector_string is None:
raise ArgumentError("Invalid stream walker state in restore_walker, missing 'selector' key", state=dumped_state)
selector = DataStreamSelector.FromString(selector_string)
walker = self.create_walker(selector)
walker.restore(dumped_state)
return walker | [
"def",
"restore_walker",
"(",
"self",
",",
"dumped_state",
")",
":",
"selector_string",
"=",
"dumped_state",
".",
"get",
"(",
"u'selector'",
")",
"if",
"selector_string",
"is",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid stream walker state in restore_walke... | Restore a stream walker that was previously serialized.
Since stream walkers need to be tracked in an internal list for
notification purposes, we need to be careful with how we restore
them to make sure they remain part of the right list.
Args:
dumped_state (dict): The dumped state of a stream walker
from a previous call to StreamWalker.dump()
Returns:
StreamWalker: The correctly restored StreamWalker subclass. | [
"Restore",
"a",
"stream",
"walker",
"that",
"was",
"previously",
"serialized",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L257-L280 |
24,077 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.clear | def clear(self):
"""Clear all data from this sensor_log.
All readings in all walkers are skipped and buffered data is
destroyed.
"""
for walker in self._virtual_walkers:
walker.skip_all()
self._engine.clear()
for walker in self._queue_walkers:
walker.skip_all()
self._last_values = {} | python | def clear(self):
for walker in self._virtual_walkers:
walker.skip_all()
self._engine.clear()
for walker in self._queue_walkers:
walker.skip_all()
self._last_values = {} | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"walker",
"in",
"self",
".",
"_virtual_walkers",
":",
"walker",
".",
"skip_all",
"(",
")",
"self",
".",
"_engine",
".",
"clear",
"(",
")",
"for",
"walker",
"in",
"self",
".",
"_queue_walkers",
":",
"walker"... | Clear all data from this sensor_log.
All readings in all walkers are skipped and buffered data is
destroyed. | [
"Clear",
"all",
"data",
"from",
"this",
"sensor_log",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L297-L312 |
24,078 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.push | def push(self, stream, reading):
"""Push a reading into a stream, updating any associated stream walkers.
Args:
stream (DataStream): the stream to push the reading into
reading (IOTileReading): the reading to push
"""
# Make sure the stream is correct
reading = copy.copy(reading)
reading.stream = stream.encode()
if stream.buffered:
output_buffer = stream.output
if self.id_assigner is not None:
reading.reading_id = self.id_assigner(stream, reading)
try:
self._engine.push(reading)
except StorageFullError:
# If we are in fill-stop mode, don't auto erase old data.
if (stream.output and not self._rollover_streaming) or (not stream.output and not self._rollover_storage):
raise
self._erase_buffer(stream.output)
self._engine.push(reading)
for walker in self._queue_walkers:
# Only notify the walkers that are on this queue
if walker.selector.output == output_buffer:
walker.notify_added(stream)
# Activate any monitors we have for this stream
for selector in self._monitors:
if selector is None or selector.matches(stream):
for callback in self._monitors[selector]:
callback(stream, reading)
# Virtual streams live only in their walkers, so update each walker
# that contains this stream.
for walker in self._virtual_walkers:
if walker.matches(stream):
walker.push(stream, reading)
self._last_values[stream] = reading | python | def push(self, stream, reading):
# Make sure the stream is correct
reading = copy.copy(reading)
reading.stream = stream.encode()
if stream.buffered:
output_buffer = stream.output
if self.id_assigner is not None:
reading.reading_id = self.id_assigner(stream, reading)
try:
self._engine.push(reading)
except StorageFullError:
# If we are in fill-stop mode, don't auto erase old data.
if (stream.output and not self._rollover_streaming) or (not stream.output and not self._rollover_storage):
raise
self._erase_buffer(stream.output)
self._engine.push(reading)
for walker in self._queue_walkers:
# Only notify the walkers that are on this queue
if walker.selector.output == output_buffer:
walker.notify_added(stream)
# Activate any monitors we have for this stream
for selector in self._monitors:
if selector is None or selector.matches(stream):
for callback in self._monitors[selector]:
callback(stream, reading)
# Virtual streams live only in their walkers, so update each walker
# that contains this stream.
for walker in self._virtual_walkers:
if walker.matches(stream):
walker.push(stream, reading)
self._last_values[stream] = reading | [
"def",
"push",
"(",
"self",
",",
"stream",
",",
"reading",
")",
":",
"# Make sure the stream is correct",
"reading",
"=",
"copy",
".",
"copy",
"(",
"reading",
")",
"reading",
".",
"stream",
"=",
"stream",
".",
"encode",
"(",
")",
"if",
"stream",
".",
"bu... | Push a reading into a stream, updating any associated stream walkers.
Args:
stream (DataStream): the stream to push the reading into
reading (IOTileReading): the reading to push | [
"Push",
"a",
"reading",
"into",
"a",
"stream",
"updating",
"any",
"associated",
"stream",
"walkers",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L314-L359 |
24,079 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog._erase_buffer | def _erase_buffer(self, output_buffer):
"""Erase readings in the specified buffer to make space."""
erase_size = self._model.get(u'buffer_erase_size')
buffer_type = u'storage'
if output_buffer:
buffer_type = u'streaming'
old_readings = self._engine.popn(buffer_type, erase_size)
# Now go through all of our walkers that could match and
# update their availability counts and data buffer pointers
for reading in old_readings:
stream = DataStream.FromEncoded(reading.stream)
for walker in self._queue_walkers:
# Only notify the walkers that are on this queue
if walker.selector.output == output_buffer:
walker.notify_rollover(stream) | python | def _erase_buffer(self, output_buffer):
erase_size = self._model.get(u'buffer_erase_size')
buffer_type = u'storage'
if output_buffer:
buffer_type = u'streaming'
old_readings = self._engine.popn(buffer_type, erase_size)
# Now go through all of our walkers that could match and
# update their availability counts and data buffer pointers
for reading in old_readings:
stream = DataStream.FromEncoded(reading.stream)
for walker in self._queue_walkers:
# Only notify the walkers that are on this queue
if walker.selector.output == output_buffer:
walker.notify_rollover(stream) | [
"def",
"_erase_buffer",
"(",
"self",
",",
"output_buffer",
")",
":",
"erase_size",
"=",
"self",
".",
"_model",
".",
"get",
"(",
"u'buffer_erase_size'",
")",
"buffer_type",
"=",
"u'storage'",
"if",
"output_buffer",
":",
"buffer_type",
"=",
"u'streaming'",
"old_re... | Erase readings in the specified buffer to make space. | [
"Erase",
"readings",
"in",
"the",
"specified",
"buffer",
"to",
"make",
"space",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L361-L380 |
24,080 | iotile/coretools | iotilesensorgraph/iotile/sg/sensor_log.py | SensorLog.inspect_last | def inspect_last(self, stream, only_allocated=False):
"""Return the last value pushed into a stream.
This function works even if the stream is virtual and no
virtual walker has been created for it. It is primarily
useful to aid in debugging sensor graphs.
Args:
stream (DataStream): The stream to inspect.
only_allocated (bool): Optional parameter to only allow inspection
of allocated virtual streams. This is useful for mimicking the
behavior of an embedded device that does not have a _last_values
array.
Returns:
IOTileReading: The data in the stream
Raises:
StreamEmptyError: if there has never been data written to
the stream.
UnresolvedIdentifierError: if only_allocated is True and there has not
been a virtual stream walker allocated to listen to this stream.
"""
if only_allocated:
found = False
for walker in self._virtual_walkers:
if walker.matches(stream):
found = True
break
if not found:
raise UnresolvedIdentifierError("inspect_last could not find an allocated virtual streamer for the desired stream", stream=stream)
if stream in self._last_values:
return self._last_values[stream]
raise StreamEmptyError(u"inspect_last called on stream that has never been written to", stream=stream) | python | def inspect_last(self, stream, only_allocated=False):
if only_allocated:
found = False
for walker in self._virtual_walkers:
if walker.matches(stream):
found = True
break
if not found:
raise UnresolvedIdentifierError("inspect_last could not find an allocated virtual streamer for the desired stream", stream=stream)
if stream in self._last_values:
return self._last_values[stream]
raise StreamEmptyError(u"inspect_last called on stream that has never been written to", stream=stream) | [
"def",
"inspect_last",
"(",
"self",
",",
"stream",
",",
"only_allocated",
"=",
"False",
")",
":",
"if",
"only_allocated",
":",
"found",
"=",
"False",
"for",
"walker",
"in",
"self",
".",
"_virtual_walkers",
":",
"if",
"walker",
".",
"matches",
"(",
"stream"... | Return the last value pushed into a stream.
This function works even if the stream is virtual and no
virtual walker has been created for it. It is primarily
useful to aid in debugging sensor graphs.
Args:
stream (DataStream): The stream to inspect.
only_allocated (bool): Optional parameter to only allow inspection
of allocated virtual streams. This is useful for mimicking the
behavior of an embedded device that does not have a _last_values
array.
Returns:
IOTileReading: The data in the stream
Raises:
StreamEmptyError: if there has never been data written to
the stream.
UnresolvedIdentifierError: if only_allocated is True and there has not
been a virtual stream walker allocated to listen to this stream. | [
"Return",
"the",
"last",
"value",
"pushed",
"into",
"a",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sensor_log.py#L382-L419 |
24,081 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/exitfuncs.py | _run_exitfuncs | def _run_exitfuncs():
"""run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out.
"""
while _exithandlers:
func, targs, kargs = _exithandlers.pop()
func(*targs, **kargs) | python | def _run_exitfuncs():
while _exithandlers:
func, targs, kargs = _exithandlers.pop()
func(*targs, **kargs) | [
"def",
"_run_exitfuncs",
"(",
")",
":",
"while",
"_exithandlers",
":",
"func",
",",
"targs",
",",
"kargs",
"=",
"_exithandlers",
".",
"pop",
"(",
")",
"func",
"(",
"*",
"targs",
",",
"*",
"*",
"kargs",
")"
] | run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out. | [
"run",
"any",
"registered",
"exit",
"functions"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/exitfuncs.py#L36-L45 |
24,082 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py | _windowsLdmodTargets | def _windowsLdmodTargets(target, source, env, for_signature):
"""Get targets for loadable modules."""
return _dllTargets(target, source, env, for_signature, 'LDMODULE') | python | def _windowsLdmodTargets(target, source, env, for_signature):
return _dllTargets(target, source, env, for_signature, 'LDMODULE') | [
"def",
"_windowsLdmodTargets",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"return",
"_dllTargets",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
",",
"'LDMODULE'",
")"
] | Get targets for loadable modules. | [
"Get",
"targets",
"for",
"loadable",
"modules",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py#L87-L89 |
24,083 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py | _windowsLdmodSources | def _windowsLdmodSources(target, source, env, for_signature):
"""Get sources for loadable modules."""
return _dllSources(target, source, env, for_signature, 'LDMODULE') | python | def _windowsLdmodSources(target, source, env, for_signature):
return _dllSources(target, source, env, for_signature, 'LDMODULE') | [
"def",
"_windowsLdmodSources",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"return",
"_dllSources",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
",",
"'LDMODULE'",
")"
] | Get sources for loadable modules. | [
"Get",
"sources",
"for",
"loadable",
"modules",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py#L91-L93 |
24,084 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py | _dllEmitter | def _dllEmitter(target, source, env, paramtp):
"""Common implementation of dll emitter."""
SCons.Tool.msvc.validate_vars(env)
extratargets = []
extrasources = []
dll = env.FindIxes(target, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp)
no_import_lib = env.get('no_import_lib', 0)
if not dll:
raise SCons.Errors.UserError('A shared library should have exactly one target with the suffix: %s' % env.subst('$%sSUFFIX' % paramtp))
insert_def = env.subst("$WINDOWS_INSERT_DEF")
if not insert_def in ['', '0', 0] and \
not env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"):
# append a def file to the list of sources
extrasources.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"))
version_num, suite = SCons.Tool.msvs.msvs_parse_version(env.get('MSVS_VERSION', '6.0'))
if version_num >= 8.0 and \
(env.get('WINDOWS_INSERT_MANIFEST', 0) or env.get('WINDOWS_EMBED_MANIFEST', 0)):
# MSVC 8 and above automatically generate .manifest files that must be installed
extratargets.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"WINDOWSSHLIBMANIFESTPREFIX", "WINDOWSSHLIBMANIFESTSUFFIX"))
if 'PDB' in env and env['PDB']:
pdb = env.arg2nodes('$PDB', target=target, source=source)[0]
extratargets.append(pdb)
target[0].attributes.pdb = pdb
if version_num >= 11.0 and env.get('PCH', 0):
# MSVC 11 and above need the PCH object file to be added to the link line,
# otherwise you get link error LNK2011.
pchobj = SCons.Util.splitext(str(env['PCH']))[0] + '.obj'
# print "prog_emitter, version %s, appending pchobj %s"%(version_num, pchobj)
if pchobj not in extrasources:
extrasources.append(pchobj)
if not no_import_lib and \
not env.FindIxes(target, "LIBPREFIX", "LIBSUFFIX"):
# Append an import library to the list of targets.
extratargets.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"LIBPREFIX", "LIBSUFFIX"))
# and .exp file is created if there are exports from a DLL
extratargets.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"WINDOWSEXPPREFIX", "WINDOWSEXPSUFFIX"))
return (target+extratargets, source+extrasources) | python | def _dllEmitter(target, source, env, paramtp):
SCons.Tool.msvc.validate_vars(env)
extratargets = []
extrasources = []
dll = env.FindIxes(target, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp)
no_import_lib = env.get('no_import_lib', 0)
if not dll:
raise SCons.Errors.UserError('A shared library should have exactly one target with the suffix: %s' % env.subst('$%sSUFFIX' % paramtp))
insert_def = env.subst("$WINDOWS_INSERT_DEF")
if not insert_def in ['', '0', 0] and \
not env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"):
# append a def file to the list of sources
extrasources.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"))
version_num, suite = SCons.Tool.msvs.msvs_parse_version(env.get('MSVS_VERSION', '6.0'))
if version_num >= 8.0 and \
(env.get('WINDOWS_INSERT_MANIFEST', 0) or env.get('WINDOWS_EMBED_MANIFEST', 0)):
# MSVC 8 and above automatically generate .manifest files that must be installed
extratargets.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"WINDOWSSHLIBMANIFESTPREFIX", "WINDOWSSHLIBMANIFESTSUFFIX"))
if 'PDB' in env and env['PDB']:
pdb = env.arg2nodes('$PDB', target=target, source=source)[0]
extratargets.append(pdb)
target[0].attributes.pdb = pdb
if version_num >= 11.0 and env.get('PCH', 0):
# MSVC 11 and above need the PCH object file to be added to the link line,
# otherwise you get link error LNK2011.
pchobj = SCons.Util.splitext(str(env['PCH']))[0] + '.obj'
# print "prog_emitter, version %s, appending pchobj %s"%(version_num, pchobj)
if pchobj not in extrasources:
extrasources.append(pchobj)
if not no_import_lib and \
not env.FindIxes(target, "LIBPREFIX", "LIBSUFFIX"):
# Append an import library to the list of targets.
extratargets.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"LIBPREFIX", "LIBSUFFIX"))
# and .exp file is created if there are exports from a DLL
extratargets.append(
env.ReplaceIxes(dll,
'%sPREFIX' % paramtp, '%sSUFFIX' % paramtp,
"WINDOWSEXPPREFIX", "WINDOWSEXPSUFFIX"))
return (target+extratargets, source+extrasources) | [
"def",
"_dllEmitter",
"(",
"target",
",",
"source",
",",
"env",
",",
"paramtp",
")",
":",
"SCons",
".",
"Tool",
".",
"msvc",
".",
"validate_vars",
"(",
"env",
")",
"extratargets",
"=",
"[",
"]",
"extrasources",
"=",
"[",
"]",
"dll",
"=",
"env",
".",
... | Common implementation of dll emitter. | [
"Common",
"implementation",
"of",
"dll",
"emitter",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py#L95-L153 |
24,085 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py | embedManifestDllCheck | def embedManifestDllCheck(target, source, env):
"""Function run by embedManifestDllCheckAction to check for existence of manifest
and other conditions, and embed the manifest by calling embedManifestDllAction if so."""
if env.get('WINDOWS_EMBED_MANIFEST', 0):
manifestSrc = target[0].get_abspath() + '.manifest'
if os.path.exists(manifestSrc):
ret = (embedManifestDllAction) ([target[0]],None,env)
if ret:
raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
return ret
else:
print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
return 0 | python | def embedManifestDllCheck(target, source, env):
if env.get('WINDOWS_EMBED_MANIFEST', 0):
manifestSrc = target[0].get_abspath() + '.manifest'
if os.path.exists(manifestSrc):
ret = (embedManifestDllAction) ([target[0]],None,env)
if ret:
raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
return ret
else:
print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
return 0 | [
"def",
"embedManifestDllCheck",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"if",
"env",
".",
"get",
"(",
"'WINDOWS_EMBED_MANIFEST'",
",",
"0",
")",
":",
"manifestSrc",
"=",
"target",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
"+",
"'.manifest'... | Function run by embedManifestDllCheckAction to check for existence of manifest
and other conditions, and embed the manifest by calling embedManifestDllAction if so. | [
"Function",
"run",
"by",
"embedManifestDllCheckAction",
"to",
"check",
"for",
"existence",
"of",
"manifest",
"and",
"other",
"conditions",
"and",
"embed",
"the",
"manifest",
"by",
"calling",
"embedManifestDllAction",
"if",
"so",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py#L215-L227 |
24,086 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py | embedManifestExeCheck | def embedManifestExeCheck(target, source, env):
"""Function run by embedManifestExeCheckAction to check for existence of manifest
and other conditions, and embed the manifest by calling embedManifestExeAction if so."""
if env.get('WINDOWS_EMBED_MANIFEST', 0):
manifestSrc = target[0].get_abspath() + '.manifest'
if os.path.exists(manifestSrc):
ret = (embedManifestExeAction) ([target[0]],None,env)
if ret:
raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
return ret
else:
print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
return 0 | python | def embedManifestExeCheck(target, source, env):
if env.get('WINDOWS_EMBED_MANIFEST', 0):
manifestSrc = target[0].get_abspath() + '.manifest'
if os.path.exists(manifestSrc):
ret = (embedManifestExeAction) ([target[0]],None,env)
if ret:
raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
return ret
else:
print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
return 0 | [
"def",
"embedManifestExeCheck",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"if",
"env",
".",
"get",
"(",
"'WINDOWS_EMBED_MANIFEST'",
",",
"0",
")",
":",
"manifestSrc",
"=",
"target",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
"+",
"'.manifest'... | Function run by embedManifestExeCheckAction to check for existence of manifest
and other conditions, and embed the manifest by calling embedManifestExeAction if so. | [
"Function",
"run",
"by",
"embedManifestExeCheckAction",
"to",
"check",
"for",
"existence",
"of",
"manifest",
"and",
"other",
"conditions",
"and",
"embed",
"the",
"manifest",
"by",
"calling",
"embedManifestExeAction",
"if",
"so",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslink.py#L229-L241 |
24,087 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvips.py | generate | def generate(env):
"""Add Builders and construction variables for dvips to an Environment."""
global PSAction
if PSAction is None:
PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR')
global DVIPSAction
if DVIPSAction is None:
DVIPSAction = SCons.Action.Action(DviPsFunction, strfunction = DviPsStrFunction)
global PSBuilder
if PSBuilder is None:
PSBuilder = SCons.Builder.Builder(action = PSAction,
prefix = '$PSPREFIX',
suffix = '$PSSUFFIX',
src_suffix = '.dvi',
src_builder = 'DVI',
single_source=True)
env['BUILDERS']['PostScript'] = PSBuilder
env['DVIPS'] = 'dvips'
env['DVIPSFLAGS'] = SCons.Util.CLVar('')
# I'm not quite sure I got the directories and filenames right for variant_dir
# We need to be in the correct directory for the sake of latex \includegraphics eps included files.
env['PSCOM'] = 'cd ${TARGET.dir} && $DVIPS $DVIPSFLAGS -o ${TARGET.file} ${SOURCE.file}'
env['PSPREFIX'] = ''
env['PSSUFFIX'] = '.ps' | python | def generate(env):
global PSAction
if PSAction is None:
PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR')
global DVIPSAction
if DVIPSAction is None:
DVIPSAction = SCons.Action.Action(DviPsFunction, strfunction = DviPsStrFunction)
global PSBuilder
if PSBuilder is None:
PSBuilder = SCons.Builder.Builder(action = PSAction,
prefix = '$PSPREFIX',
suffix = '$PSSUFFIX',
src_suffix = '.dvi',
src_builder = 'DVI',
single_source=True)
env['BUILDERS']['PostScript'] = PSBuilder
env['DVIPS'] = 'dvips'
env['DVIPSFLAGS'] = SCons.Util.CLVar('')
# I'm not quite sure I got the directories and filenames right for variant_dir
# We need to be in the correct directory for the sake of latex \includegraphics eps included files.
env['PSCOM'] = 'cd ${TARGET.dir} && $DVIPS $DVIPSFLAGS -o ${TARGET.file} ${SOURCE.file}'
env['PSPREFIX'] = ''
env['PSSUFFIX'] = '.ps' | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"PSAction",
"if",
"PSAction",
"is",
"None",
":",
"PSAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$PSCOM'",
",",
"'$PSCOMSTR'",
")",
"global",
"DVIPSAction",
"if",
"DVIPSAction",
"is",
"None"... | Add Builders and construction variables for dvips to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"dvips",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvips.py#L58-L85 |
24,088 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/arm.py | build_library | def build_library(tile, libname, chip):
"""Build a static ARM cortex library"""
dirs = chip.build_dirs()
output_name = '%s_%s.a' % (libname, chip.arch_name())
# Support both firmware/src and just src locations for source code
if os.path.exists('firmware'):
VariantDir(dirs['build'], os.path.join('firmware', 'src'), duplicate=0)
else:
VariantDir(dirs['build'], 'src', duplicate=0)
library_env = setup_environment(chip)
library_env['OUTPUT'] = output_name
library_env['OUTPUT_PATH'] = os.path.join(dirs['build'], output_name)
library_env['BUILD_DIR'] = dirs['build']
# Check for any dependencies this library has
tilebus_defs = setup_dependencies(tile, library_env)
# Create header files for all tilebus config variables and commands that are defined in ourselves
# or in our dependencies
tilebus_defs += tile.find_products('tilebus_definitions')
compile_tilebus(tilebus_defs, library_env, header_only=True)
SConscript(os.path.join(dirs['build'], 'SConscript'), exports='library_env')
library_env.InstallAs(os.path.join(dirs['output'], output_name), os.path.join(dirs['build'], output_name))
# See if we should copy any files over to the output:
for src, dst in chip.property('copy_files', []):
srcpath = os.path.join(*src)
destpath = os.path.join(dirs['output'], dst)
library_env.InstallAs(destpath, srcpath)
return os.path.join(dirs['output'], output_name) | python | def build_library(tile, libname, chip):
dirs = chip.build_dirs()
output_name = '%s_%s.a' % (libname, chip.arch_name())
# Support both firmware/src and just src locations for source code
if os.path.exists('firmware'):
VariantDir(dirs['build'], os.path.join('firmware', 'src'), duplicate=0)
else:
VariantDir(dirs['build'], 'src', duplicate=0)
library_env = setup_environment(chip)
library_env['OUTPUT'] = output_name
library_env['OUTPUT_PATH'] = os.path.join(dirs['build'], output_name)
library_env['BUILD_DIR'] = dirs['build']
# Check for any dependencies this library has
tilebus_defs = setup_dependencies(tile, library_env)
# Create header files for all tilebus config variables and commands that are defined in ourselves
# or in our dependencies
tilebus_defs += tile.find_products('tilebus_definitions')
compile_tilebus(tilebus_defs, library_env, header_only=True)
SConscript(os.path.join(dirs['build'], 'SConscript'), exports='library_env')
library_env.InstallAs(os.path.join(dirs['output'], output_name), os.path.join(dirs['build'], output_name))
# See if we should copy any files over to the output:
for src, dst in chip.property('copy_files', []):
srcpath = os.path.join(*src)
destpath = os.path.join(dirs['output'], dst)
library_env.InstallAs(destpath, srcpath)
return os.path.join(dirs['output'], output_name) | [
"def",
"build_library",
"(",
"tile",
",",
"libname",
",",
"chip",
")",
":",
"dirs",
"=",
"chip",
".",
"build_dirs",
"(",
")",
"output_name",
"=",
"'%s_%s.a'",
"%",
"(",
"libname",
",",
"chip",
".",
"arch_name",
"(",
")",
")",
"# Support both firmware/src a... | Build a static ARM cortex library | [
"Build",
"a",
"static",
"ARM",
"cortex",
"library"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L129-L165 |
24,089 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/arm.py | setup_environment | def setup_environment(chip, args_file=None):
"""Setup the SCons environment for compiling arm cortex code.
This will return an env that has all of the correct settings and create a
command line arguments file for GCC that contains all of the required
flags. The use of a command line argument file passed with @./file_path is
important since there can be many flags that exceed the maximum allowed length
of a command line on Windows.
"""
config = ConfigManager()
# Make sure we never get MSVC settings for windows since that has the wrong command line flags for gcc
if platform.system() == 'Windows':
env = Environment(tools=['mingw'], ENV=os.environ)
else:
env = Environment(tools=['default'], ENV=os.environ)
env['INCPREFIX'] = '-I"'
env['INCSUFFIX'] = '"'
env['CPPDEFPREFIX'] = ''
env['CPPDEFSUFFIX'] = ''
env['CPPPATH'] = chip.includes()
env['ARCH'] = chip
# Setup Cross Compiler
env['CC'] = 'arm-none-eabi-gcc'
env['AS'] = 'arm-none-eabi-gcc'
env['LINK'] = 'arm-none-eabi-gcc'
env['AR'] = 'arm-none-eabi-ar'
env['RANLIB'] = 'arm-none-eabi-ranlib'
# AS command line is by default setup for call as directly so we need
# to modify it to call via *-gcc to allow for preprocessing
env['ASCOM'] = "$AS $ASFLAGS -o $TARGET -c $SOURCES"
# Setup nice display strings unless we're asked to show raw commands
if not config.get('build:show-commands'):
env['CCCOMSTR'] = "Compiling $TARGET"
env['ARCOMSTR'] = "Building static library $TARGET"
env['RANLIBCOMSTR'] = "Indexing static library $TARGET"
env['LINKCOMSTR'] = "Linking $TARGET"
# Setup Compiler Flags
env['CCFLAGS'] = chip.combined_properties('cflags')
env['LINKFLAGS'] = chip.combined_properties('ldflags')
env['ARFLAGS'].append(chip.combined_properties('arflags')) # There are default ARFLAGS that are necessary to keep
env['ASFLAGS'].append(chip.combined_properties('asflags'))
# Add in compile tile definitions
defines = utilities.build_defines(chip.property('defines', {}))
env['CPPDEFINES'] = defines
if args_file is not None:
env['CCCOM'] = "$CC $CCFLAGS $CPPFLAGS @{} -c -o $TARGET $SOURCES".format(args_file)
# Setup Target Architecture
env['CCFLAGS'].append('-mcpu=%s' % chip.property('cpu'))
env['ASFLAGS'].append('-mcpu=%s' % chip.property('cpu'))
env['LINKFLAGS'].append('-mcpu=%s' % chip.property('cpu'))
# Initialize library paths (all libraries are added via dependencies)
env['LIBPATH'] = []
env['LIBS'] = []
return env | python | def setup_environment(chip, args_file=None):
config = ConfigManager()
# Make sure we never get MSVC settings for windows since that has the wrong command line flags for gcc
if platform.system() == 'Windows':
env = Environment(tools=['mingw'], ENV=os.environ)
else:
env = Environment(tools=['default'], ENV=os.environ)
env['INCPREFIX'] = '-I"'
env['INCSUFFIX'] = '"'
env['CPPDEFPREFIX'] = ''
env['CPPDEFSUFFIX'] = ''
env['CPPPATH'] = chip.includes()
env['ARCH'] = chip
# Setup Cross Compiler
env['CC'] = 'arm-none-eabi-gcc'
env['AS'] = 'arm-none-eabi-gcc'
env['LINK'] = 'arm-none-eabi-gcc'
env['AR'] = 'arm-none-eabi-ar'
env['RANLIB'] = 'arm-none-eabi-ranlib'
# AS command line is by default setup for call as directly so we need
# to modify it to call via *-gcc to allow for preprocessing
env['ASCOM'] = "$AS $ASFLAGS -o $TARGET -c $SOURCES"
# Setup nice display strings unless we're asked to show raw commands
if not config.get('build:show-commands'):
env['CCCOMSTR'] = "Compiling $TARGET"
env['ARCOMSTR'] = "Building static library $TARGET"
env['RANLIBCOMSTR'] = "Indexing static library $TARGET"
env['LINKCOMSTR'] = "Linking $TARGET"
# Setup Compiler Flags
env['CCFLAGS'] = chip.combined_properties('cflags')
env['LINKFLAGS'] = chip.combined_properties('ldflags')
env['ARFLAGS'].append(chip.combined_properties('arflags')) # There are default ARFLAGS that are necessary to keep
env['ASFLAGS'].append(chip.combined_properties('asflags'))
# Add in compile tile definitions
defines = utilities.build_defines(chip.property('defines', {}))
env['CPPDEFINES'] = defines
if args_file is not None:
env['CCCOM'] = "$CC $CCFLAGS $CPPFLAGS @{} -c -o $TARGET $SOURCES".format(args_file)
# Setup Target Architecture
env['CCFLAGS'].append('-mcpu=%s' % chip.property('cpu'))
env['ASFLAGS'].append('-mcpu=%s' % chip.property('cpu'))
env['LINKFLAGS'].append('-mcpu=%s' % chip.property('cpu'))
# Initialize library paths (all libraries are added via dependencies)
env['LIBPATH'] = []
env['LIBS'] = []
return env | [
"def",
"setup_environment",
"(",
"chip",
",",
"args_file",
"=",
"None",
")",
":",
"config",
"=",
"ConfigManager",
"(",
")",
"# Make sure we never get MSVC settings for windows since that has the wrong command line flags for gcc",
"if",
"platform",
".",
"system",
"(",
")",
... | Setup the SCons environment for compiling arm cortex code.
This will return an env that has all of the correct settings and create a
command line arguments file for GCC that contains all of the required
flags. The use of a command line argument file passed with @./file_path is
important since there can be many flags that exceed the maximum allowed length
of a command line on Windows. | [
"Setup",
"the",
"SCons",
"environment",
"for",
"compiling",
"arm",
"cortex",
"code",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L168-L234 |
24,090 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/arm.py | tb_h_file_creation | def tb_h_file_creation(target, source, env):
"""Compile tilebus file into only .h files corresponding to config variables for inclusion in a library"""
files = [str(x) for x in source]
try:
desc = TBDescriptor(files)
except pyparsing.ParseException as e:
raise BuildError("Could not parse tilebus file", parsing_exception=e)
block = desc.get_block(config_only=True)
block.render_template(block.CommandHeaderTemplate, out_path=str(target[0]))
block.render_template(block.ConfigHeaderTemplate, out_path=str(target[1])) | python | def tb_h_file_creation(target, source, env):
files = [str(x) for x in source]
try:
desc = TBDescriptor(files)
except pyparsing.ParseException as e:
raise BuildError("Could not parse tilebus file", parsing_exception=e)
block = desc.get_block(config_only=True)
block.render_template(block.CommandHeaderTemplate, out_path=str(target[0]))
block.render_template(block.ConfigHeaderTemplate, out_path=str(target[1])) | [
"def",
"tb_h_file_creation",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"files",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"source",
"]",
"try",
":",
"desc",
"=",
"TBDescriptor",
"(",
"files",
")",
"except",
"pyparsing",
".",
"ParseE... | Compile tilebus file into only .h files corresponding to config variables for inclusion in a library | [
"Compile",
"tilebus",
"file",
"into",
"only",
".",
"h",
"files",
"corresponding",
"to",
"config",
"variables",
"for",
"inclusion",
"in",
"a",
"library"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L316-L328 |
24,091 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/arm.py | checksum_creation_action | def checksum_creation_action(target, source, env):
"""Create a linker command file for patching an application checksum into a firmware image"""
# Important Notes:
# There are apparently many ways to calculate a CRC-32 checksum, we use the following options
# Initial seed value prepended to the input: 0xFFFFFFFF
# Whether the input is fed into the shift register least-significant bit or most-significant bit first: LSB
# Whether each data word is inverted: No
# Whether the final CRC value is inverted: No
# *These settings must agree between the executive and this function*
import crcmod
crc32_func = crcmod.mkCrcFun(0x104C11DB7, initCrc=0xFFFFFFFF, rev=False, xorOut=0)
with open(str(source[0]), 'rb') as f:
data = f.read()
# Ignore the last four bytes of the file since that is where the checksum will go
data = data[:-4]
# Make sure the magic number is correct so that we're dealing with an actual firmware image
magicbin = data[-4:]
magic, = struct.unpack('<L', magicbin)
if magic != 0xBAADDAAD:
raise BuildError("Attempting to patch a file that is not a CDB binary or has the wrong size", reason="invalid magic number found", actual_magic=magic, desired_magic=0xBAADDAAD)
# Calculate CRC32 in the same way as its done in the target microcontroller
checksum = crc32_func(data) & 0xFFFFFFFF
with open(str(target[0]), 'w') as f:
# hex strings end with L on windows and possibly some other systems
checkhex = hex(checksum)
if checkhex[-1] == 'L':
checkhex = checkhex[:-1]
f.write("--defsym=__image_checksum=%s\n" % checkhex) | python | def checksum_creation_action(target, source, env):
# Important Notes:
# There are apparently many ways to calculate a CRC-32 checksum, we use the following options
# Initial seed value prepended to the input: 0xFFFFFFFF
# Whether the input is fed into the shift register least-significant bit or most-significant bit first: LSB
# Whether each data word is inverted: No
# Whether the final CRC value is inverted: No
# *These settings must agree between the executive and this function*
import crcmod
crc32_func = crcmod.mkCrcFun(0x104C11DB7, initCrc=0xFFFFFFFF, rev=False, xorOut=0)
with open(str(source[0]), 'rb') as f:
data = f.read()
# Ignore the last four bytes of the file since that is where the checksum will go
data = data[:-4]
# Make sure the magic number is correct so that we're dealing with an actual firmware image
magicbin = data[-4:]
magic, = struct.unpack('<L', magicbin)
if magic != 0xBAADDAAD:
raise BuildError("Attempting to patch a file that is not a CDB binary or has the wrong size", reason="invalid magic number found", actual_magic=magic, desired_magic=0xBAADDAAD)
# Calculate CRC32 in the same way as its done in the target microcontroller
checksum = crc32_func(data) & 0xFFFFFFFF
with open(str(target[0]), 'w') as f:
# hex strings end with L on windows and possibly some other systems
checkhex = hex(checksum)
if checkhex[-1] == 'L':
checkhex = checkhex[:-1]
f.write("--defsym=__image_checksum=%s\n" % checkhex) | [
"def",
"checksum_creation_action",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"# Important Notes:",
"# There are apparently many ways to calculate a CRC-32 checksum, we use the following options",
"# Initial seed value prepended to the input: 0xFFFFFFFF",
"# Whether the input is f... | Create a linker command file for patching an application checksum into a firmware image | [
"Create",
"a",
"linker",
"command",
"file",
"for",
"patching",
"an",
"application",
"checksum",
"into",
"a",
"firmware",
"image"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L331-L367 |
24,092 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/arm.py | create_arg_file | def create_arg_file(target, source, env):
"""Create an argument file containing -I and -D arguments to gcc.
This file will be passed to gcc using @<path>.
"""
output_name = str(target[0])
with open(output_name, "w") as outfile:
for define in env.get('CPPDEFINES', []):
outfile.write(define + '\n')
include_folders = target[0].RDirs(tuple(env.get('CPPPATH', [])))
include_folders.append('.')
for include_folder in include_folders:
include_folder = str(include_folder)
if not include_folder.startswith('build'):
include_folder = os.path.join('firmware', 'src', include_folder)
outfile.write('"-I{}"\n'.format(include_folder.replace('\\', '\\\\'))) | python | def create_arg_file(target, source, env):
output_name = str(target[0])
with open(output_name, "w") as outfile:
for define in env.get('CPPDEFINES', []):
outfile.write(define + '\n')
include_folders = target[0].RDirs(tuple(env.get('CPPPATH', [])))
include_folders.append('.')
for include_folder in include_folders:
include_folder = str(include_folder)
if not include_folder.startswith('build'):
include_folder = os.path.join('firmware', 'src', include_folder)
outfile.write('"-I{}"\n'.format(include_folder.replace('\\', '\\\\'))) | [
"def",
"create_arg_file",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"output_name",
"=",
"str",
"(",
"target",
"[",
"0",
"]",
")",
"with",
"open",
"(",
"output_name",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"for",
"define",
"in",
"env",
"."... | Create an argument file containing -I and -D arguments to gcc.
This file will be passed to gcc using @<path>. | [
"Create",
"an",
"argument",
"file",
"containing",
"-",
"I",
"and",
"-",
"D",
"arguments",
"to",
"gcc",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L370-L391 |
24,093 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/arm.py | merge_hex_executables | def merge_hex_executables(target, source, env):
"""Combine all hex files into a singular executable file."""
output_name = str(target[0])
hex_final = IntelHex()
for image in source:
file = str(image)
root, ext = os.path.splitext(file)
file_format = ext[1:]
if file_format == 'elf':
file = root + '.hex'
hex_data = IntelHex(file)
# merge will throw errors on mismatched Start Segment Addresses, which we don't need
# See <https://stackoverflow.com/questions/26295776/what-are-the-intel-hex-records-type-03-or-05-doing-in-ihex-program-for-arm>
hex_data.start_addr = None
hex_final.merge(hex_data, overlap='error')
with open(output_name, 'w') as outfile:
hex_final.write_hex_file(outfile) | python | def merge_hex_executables(target, source, env):
output_name = str(target[0])
hex_final = IntelHex()
for image in source:
file = str(image)
root, ext = os.path.splitext(file)
file_format = ext[1:]
if file_format == 'elf':
file = root + '.hex'
hex_data = IntelHex(file)
# merge will throw errors on mismatched Start Segment Addresses, which we don't need
# See <https://stackoverflow.com/questions/26295776/what-are-the-intel-hex-records-type-03-or-05-doing-in-ihex-program-for-arm>
hex_data.start_addr = None
hex_final.merge(hex_data, overlap='error')
with open(output_name, 'w') as outfile:
hex_final.write_hex_file(outfile) | [
"def",
"merge_hex_executables",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"output_name",
"=",
"str",
"(",
"target",
"[",
"0",
"]",
")",
"hex_final",
"=",
"IntelHex",
"(",
")",
"for",
"image",
"in",
"source",
":",
"file",
"=",
"str",
"(",
"i... | Combine all hex files into a singular executable file. | [
"Combine",
"all",
"hex",
"files",
"into",
"a",
"singular",
"executable",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L394-L413 |
24,094 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/arm.py | ensure_image_is_hex | def ensure_image_is_hex(input_path):
"""Return a path to a hex version of a firmware image.
If the input file is already in hex format then input_path
is returned and nothing is done. If it is not in hex format
then an SCons action is added to convert it to hex and the
target output file path is returned.
A cache is kept so that each file is only converted once.
Args:
input_path (str): A path to a firmware image.
Returns:
str: The path to a hex version of input_path, this may
be equal to input_path if it is already in hex format.
"""
family = utilities.get_family('module_settings.json')
target = family.platform_independent_target()
build_dir = target.build_dirs()['build']
if platform.system() == 'Windows':
env = Environment(tools=['mingw'], ENV=os.environ)
else:
env = Environment(tools=['default'], ENV=os.environ)
input_path = str(input_path)
image_name = os.path.basename(input_path)
root, ext = os.path.splitext(image_name)
if len(ext) == 0:
raise BuildError("Unknown file format or missing file extension in ensure_image_is_hex", file_name=input_path)
file_format = ext[1:]
if file_format == 'hex':
return input_path
if file_format == 'elf':
new_file = os.path.join(build_dir, root + '.hex')
if new_file not in CONVERTED_HEX_FILES:
env.Command(new_file, input_path, action=Action("arm-none-eabi-objcopy -O ihex $SOURCE $TARGET",
"Creating intel hex file from: $SOURCE"))
CONVERTED_HEX_FILES.add(new_file)
return new_file
raise BuildError("Unknown file format extension in ensure_image_is_hex",
file_name=input_path, extension=file_format) | python | def ensure_image_is_hex(input_path):
family = utilities.get_family('module_settings.json')
target = family.platform_independent_target()
build_dir = target.build_dirs()['build']
if platform.system() == 'Windows':
env = Environment(tools=['mingw'], ENV=os.environ)
else:
env = Environment(tools=['default'], ENV=os.environ)
input_path = str(input_path)
image_name = os.path.basename(input_path)
root, ext = os.path.splitext(image_name)
if len(ext) == 0:
raise BuildError("Unknown file format or missing file extension in ensure_image_is_hex", file_name=input_path)
file_format = ext[1:]
if file_format == 'hex':
return input_path
if file_format == 'elf':
new_file = os.path.join(build_dir, root + '.hex')
if new_file not in CONVERTED_HEX_FILES:
env.Command(new_file, input_path, action=Action("arm-none-eabi-objcopy -O ihex $SOURCE $TARGET",
"Creating intel hex file from: $SOURCE"))
CONVERTED_HEX_FILES.add(new_file)
return new_file
raise BuildError("Unknown file format extension in ensure_image_is_hex",
file_name=input_path, extension=file_format) | [
"def",
"ensure_image_is_hex",
"(",
"input_path",
")",
":",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_settings.json'",
")",
"target",
"=",
"family",
".",
"platform_independent_target",
"(",
")",
"build_dir",
"=",
"target",
".",
"build_dirs",
"(",... | Return a path to a hex version of a firmware image.
If the input file is already in hex format then input_path
is returned and nothing is done. If it is not in hex format
then an SCons action is added to convert it to hex and the
target output file path is returned.
A cache is kept so that each file is only converted once.
Args:
input_path (str): A path to a firmware image.
Returns:
str: The path to a hex version of input_path, this may
be equal to input_path if it is already in hex format. | [
"Return",
"a",
"path",
"to",
"a",
"hex",
"version",
"of",
"a",
"firmware",
"image",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L419-L469 |
24,095 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_device.py | EmulatedDevice._dispatch_rpc | def _dispatch_rpc(self, address, rpc_id, arg_payload):
"""Background work queue handler to dispatch RPCs."""
if self.emulator.is_tile_busy(address):
self._track_change('device.rpc_busy_response', (address, rpc_id, arg_payload, None, None), formatter=format_rpc)
raise BusyRPCResponse()
try:
# Send the RPC immediately and wait for the response
resp = super(EmulatedDevice, self).call_rpc(address, rpc_id, arg_payload)
self._track_change('device.rpc_sent', (address, rpc_id, arg_payload, resp, None), formatter=format_rpc)
return resp
except AsynchronousRPCResponse:
self._track_change('device.rpc_started', (address, rpc_id, arg_payload, None, None), formatter=format_rpc)
raise
except Exception as exc:
self._track_change('device.rpc_exception', (address, rpc_id, arg_payload, None, exc), formatter=format_rpc)
raise | python | def _dispatch_rpc(self, address, rpc_id, arg_payload):
if self.emulator.is_tile_busy(address):
self._track_change('device.rpc_busy_response', (address, rpc_id, arg_payload, None, None), formatter=format_rpc)
raise BusyRPCResponse()
try:
# Send the RPC immediately and wait for the response
resp = super(EmulatedDevice, self).call_rpc(address, rpc_id, arg_payload)
self._track_change('device.rpc_sent', (address, rpc_id, arg_payload, resp, None), formatter=format_rpc)
return resp
except AsynchronousRPCResponse:
self._track_change('device.rpc_started', (address, rpc_id, arg_payload, None, None), formatter=format_rpc)
raise
except Exception as exc:
self._track_change('device.rpc_exception', (address, rpc_id, arg_payload, None, exc), formatter=format_rpc)
raise | [
"def",
"_dispatch_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"arg_payload",
")",
":",
"if",
"self",
".",
"emulator",
".",
"is_tile_busy",
"(",
"address",
")",
":",
"self",
".",
"_track_change",
"(",
"'device.rpc_busy_response'",
",",
"(",
"addres... | Background work queue handler to dispatch RPCs. | [
"Background",
"work",
"queue",
"handler",
"to",
"dispatch",
"RPCs",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_device.py#L46-L64 |
24,096 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_device.py | EmulatedDevice.rpc | def rpc(self, address, rpc_id, *args, **kwargs):
"""Immediately dispatch an RPC inside this EmulatedDevice.
This function is meant to be used for testing purposes as well as by
tiles inside a complex EmulatedDevice subclass that need to
communicate with each other. It should only be called from the main
virtual device thread where start() was called from.
**Background workers may not call this method since it may cause them to deadlock.**
Args:
address (int): The address of the tile that has the RPC.
rpc_id (int): The 16-bit id of the rpc we want to call
*args: Any required arguments for the RPC as python objects.
**kwargs: Only two keyword arguments are supported:
- arg_format: A format specifier for the argument list
- result_format: A format specifier for the result
Returns:
list: A list of the decoded response members from the RPC.
"""
if isinstance(rpc_id, RPCDeclaration):
arg_format = rpc_id.arg_format
resp_format = rpc_id.resp_format
rpc_id = rpc_id.rpc_id
else:
arg_format = kwargs.get('arg_format', None)
resp_format = kwargs.get('resp_format', None)
arg_payload = b''
if arg_format is not None:
arg_payload = pack_rpc_payload(arg_format, args)
self._logger.debug("Sending rpc to %d:%04X, payload=%s", address, rpc_id, args)
resp_payload = self.call_rpc(address, rpc_id, arg_payload)
if resp_format is None:
return []
resp = unpack_rpc_payload(resp_format, resp_payload)
return resp | python | def rpc(self, address, rpc_id, *args, **kwargs):
if isinstance(rpc_id, RPCDeclaration):
arg_format = rpc_id.arg_format
resp_format = rpc_id.resp_format
rpc_id = rpc_id.rpc_id
else:
arg_format = kwargs.get('arg_format', None)
resp_format = kwargs.get('resp_format', None)
arg_payload = b''
if arg_format is not None:
arg_payload = pack_rpc_payload(arg_format, args)
self._logger.debug("Sending rpc to %d:%04X, payload=%s", address, rpc_id, args)
resp_payload = self.call_rpc(address, rpc_id, arg_payload)
if resp_format is None:
return []
resp = unpack_rpc_payload(resp_format, resp_payload)
return resp | [
"def",
"rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"rpc_id",
",",
"RPCDeclaration",
")",
":",
"arg_format",
"=",
"rpc_id",
".",
"arg_format",
"resp_format",
"=",
"rpc_... | Immediately dispatch an RPC inside this EmulatedDevice.
This function is meant to be used for testing purposes as well as by
tiles inside a complex EmulatedDevice subclass that need to
communicate with each other. It should only be called from the main
virtual device thread where start() was called from.
**Background workers may not call this method since it may cause them to deadlock.**
Args:
address (int): The address of the tile that has the RPC.
rpc_id (int): The 16-bit id of the rpc we want to call
*args: Any required arguments for the RPC as python objects.
**kwargs: Only two keyword arguments are supported:
- arg_format: A format specifier for the argument list
- result_format: A format specifier for the result
Returns:
list: A list of the decoded response members from the RPC. | [
"Immediately",
"dispatch",
"an",
"RPC",
"inside",
"this",
"EmulatedDevice",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_device.py#L133-L175 |
24,097 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_device.py | EmulatedDevice.trace_sync | def trace_sync(self, data, timeout=5.0):
"""Send tracing data and wait for it to finish.
This awaitable coroutine wraps VirtualIOTileDevice.trace() and turns
the callback into an awaitable object. The appropriate usage of this
method is by calling it inside the event loop as:
await device.trace_sync(data)
Args:
data (bytes): The raw data that should be traced.
timeout (float): The maximum number of seconds to wait before
timing out.
Returns:
awaitable: An awaitable object with the result.
The result will be True if the data was sent successfully
or False if the data could not be sent in its entirety.
When False is returned, there is no guarantee about how much of
the data was sent, if any, just that it was not known to be
successfully sent.
"""
done = AwaitableResponse()
self.trace(data, callback=done.set_result)
return done.wait(timeout) | python | def trace_sync(self, data, timeout=5.0):
done = AwaitableResponse()
self.trace(data, callback=done.set_result)
return done.wait(timeout) | [
"def",
"trace_sync",
"(",
"self",
",",
"data",
",",
"timeout",
"=",
"5.0",
")",
":",
"done",
"=",
"AwaitableResponse",
"(",
")",
"self",
".",
"trace",
"(",
"data",
",",
"callback",
"=",
"done",
".",
"set_result",
")",
"return",
"done",
".",
"wait",
"... | Send tracing data and wait for it to finish.
This awaitable coroutine wraps VirtualIOTileDevice.trace() and turns
the callback into an awaitable object. The appropriate usage of this
method is by calling it inside the event loop as:
await device.trace_sync(data)
Args:
data (bytes): The raw data that should be traced.
timeout (float): The maximum number of seconds to wait before
timing out.
Returns:
awaitable: An awaitable object with the result.
The result will be True if the data was sent successfully
or False if the data could not be sent in its entirety.
When False is returned, there is no guarantee about how much of
the data was sent, if any, just that it was not known to be
successfully sent. | [
"Send",
"tracing",
"data",
"and",
"wait",
"for",
"it",
"to",
"finish",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_device.py#L194-L221 |
24,098 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_device.py | EmulatedDevice.stream_sync | def stream_sync(self, report, timeout=120.0):
"""Send a report and wait for it to finish.
This awaitable coroutine wraps VirtualIOTileDevice.stream() and turns
the callback into an awaitable object. The appropriate usage of this
method is by calling it inside the event loop as:
await device.stream_sync(data)
Args:
report (IOTileReport): The report that should be streamed.
timeout (float): The maximum number of seconds to wait before
timing out.
Returns:
awaitable: An awaitable object with the result.
The result will be True if the data was sent successfully
or False if the data could not be sent in its entirety.
When False is returned, there is no guarantee about how much of
the data was sent, if any, just that it was not known to be
successfully sent.
"""
done = AwaitableResponse()
self.stream(report, callback=done.set_result)
return done.wait(timeout) | python | def stream_sync(self, report, timeout=120.0):
done = AwaitableResponse()
self.stream(report, callback=done.set_result)
return done.wait(timeout) | [
"def",
"stream_sync",
"(",
"self",
",",
"report",
",",
"timeout",
"=",
"120.0",
")",
":",
"done",
"=",
"AwaitableResponse",
"(",
")",
"self",
".",
"stream",
"(",
"report",
",",
"callback",
"=",
"done",
".",
"set_result",
")",
"return",
"done",
".",
"wa... | Send a report and wait for it to finish.
This awaitable coroutine wraps VirtualIOTileDevice.stream() and turns
the callback into an awaitable object. The appropriate usage of this
method is by calling it inside the event loop as:
await device.stream_sync(data)
Args:
report (IOTileReport): The report that should be streamed.
timeout (float): The maximum number of seconds to wait before
timing out.
Returns:
awaitable: An awaitable object with the result.
The result will be True if the data was sent successfully
or False if the data could not be sent in its entirety.
When False is returned, there is no guarantee about how much of
the data was sent, if any, just that it was not known to be
successfully sent. | [
"Send",
"a",
"report",
"and",
"wait",
"for",
"it",
"to",
"finish",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_device.py#L223-L250 |
24,099 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_device.py | EmulatedDevice.synchronize_task | def synchronize_task(self, func, *args, **kwargs):
"""Run callable in the rpc thread and wait for it to finish.
The callable ``func`` will be passed into the EmulationLoop and run
there. This method will block until ``func`` is finished and
return/raise whatever that callable returns/raises.
This method is mainly useful for performing an activity that needs to
be synchronized with the rpc thread for safety reasons.
If this method is called from the rpc thread itself, it will just
run the task and return its result.
Args:
func (callable): A method with signature callable(*args, **kwargs),
that will be called with the optional *args and **kwargs passed
to this method.
*args: Arguments that will be passed to callable.
**kwargs: Keyword arguments that will be passed to callable.
Returns:
object: Whatever callable returns after it runs.
"""
async def _runner():
return func(*args, **kwargs)
return self.emulator.run_task_external(_runner()) | python | def synchronize_task(self, func, *args, **kwargs):
async def _runner():
return func(*args, **kwargs)
return self.emulator.run_task_external(_runner()) | [
"def",
"synchronize_task",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"async",
"def",
"_runner",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"emulator",... | Run callable in the rpc thread and wait for it to finish.
The callable ``func`` will be passed into the EmulationLoop and run
there. This method will block until ``func`` is finished and
return/raise whatever that callable returns/raises.
This method is mainly useful for performing an activity that needs to
be synchronized with the rpc thread for safety reasons.
If this method is called from the rpc thread itself, it will just
run the task and return its result.
Args:
func (callable): A method with signature callable(*args, **kwargs),
that will be called with the optional *args and **kwargs passed
to this method.
*args: Arguments that will be passed to callable.
**kwargs: Keyword arguments that will be passed to callable.
Returns:
object: Whatever callable returns after it runs. | [
"Run",
"callable",
"in",
"the",
"rpc",
"thread",
"and",
"wait",
"for",
"it",
"to",
"finish",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_device.py#L252-L279 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.