repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex._tobinarray_really
|
def _tobinarray_really(self, start, end, pad, size):
"""Return binary array."""
if pad is None:
pad = self.padding
bin = array('B')
if self._buf == {} and None in (start, end):
return bin
if size is not None and size <= 0:
raise ValueError("tobinarray: wrong value for size")
start, end = self._get_start_end(start, end, size)
for i in range_g(start, end+1):
bin.append(self._buf.get(i, pad))
return bin
|
python
|
def _tobinarray_really(self, start, end, pad, size):
"""Return binary array."""
if pad is None:
pad = self.padding
bin = array('B')
if self._buf == {} and None in (start, end):
return bin
if size is not None and size <= 0:
raise ValueError("tobinarray: wrong value for size")
start, end = self._get_start_end(start, end, size)
for i in range_g(start, end+1):
bin.append(self._buf.get(i, pad))
return bin
|
[
"def",
"_tobinarray_really",
"(",
"self",
",",
"start",
",",
"end",
",",
"pad",
",",
"size",
")",
":",
"if",
"pad",
"is",
"None",
":",
"pad",
"=",
"self",
".",
"padding",
"bin",
"=",
"array",
"(",
"'B'",
")",
"if",
"self",
".",
"_buf",
"==",
"{",
"}",
"and",
"None",
"in",
"(",
"start",
",",
"end",
")",
":",
"return",
"bin",
"if",
"size",
"is",
"not",
"None",
"and",
"size",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"tobinarray: wrong value for size\"",
")",
"start",
",",
"end",
"=",
"self",
".",
"_get_start_end",
"(",
"start",
",",
"end",
",",
"size",
")",
"for",
"i",
"in",
"range_g",
"(",
"start",
",",
"end",
"+",
"1",
")",
":",
"bin",
".",
"append",
"(",
"self",
".",
"_buf",
".",
"get",
"(",
"i",
",",
"pad",
")",
")",
"return",
"bin"
] |
Return binary array.
|
[
"Return",
"binary",
"array",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L348-L360
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.tobinstr
|
def tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None):
''' Convert to binary form and return as binary string.
@param start start address of output bytes.
@param end end address of output bytes (inclusive).
@param pad [DEPRECATED PARAMETER, please use self.padding instead]
fill empty spaces with this value
(if pad is None then this method uses self.padding).
@param size size of the block, used with start or end parameter.
@return bytes string of binary data.
'''
if not isinstance(pad, _DeprecatedParam):
print ("IntelHex.tobinstr: 'pad' parameter is deprecated.")
if pad is not None:
print ("Please, use IntelHex.padding attribute instead.")
else:
print ("Please, don't pass it explicitly.")
print ("Use syntax like this: ih.tobinstr(start=xxx, end=yyy, size=zzz)")
else:
pad = None
return self._tobinstr_really(start, end, pad, size)
|
python
|
def tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None):
''' Convert to binary form and return as binary string.
@param start start address of output bytes.
@param end end address of output bytes (inclusive).
@param pad [DEPRECATED PARAMETER, please use self.padding instead]
fill empty spaces with this value
(if pad is None then this method uses self.padding).
@param size size of the block, used with start or end parameter.
@return bytes string of binary data.
'''
if not isinstance(pad, _DeprecatedParam):
print ("IntelHex.tobinstr: 'pad' parameter is deprecated.")
if pad is not None:
print ("Please, use IntelHex.padding attribute instead.")
else:
print ("Please, don't pass it explicitly.")
print ("Use syntax like this: ih.tobinstr(start=xxx, end=yyy, size=zzz)")
else:
pad = None
return self._tobinstr_really(start, end, pad, size)
|
[
"def",
"tobinstr",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"pad",
"=",
"_DEPRECATED",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"pad",
",",
"_DeprecatedParam",
")",
":",
"print",
"(",
"\"IntelHex.tobinstr: 'pad' parameter is deprecated.\"",
")",
"if",
"pad",
"is",
"not",
"None",
":",
"print",
"(",
"\"Please, use IntelHex.padding attribute instead.\"",
")",
"else",
":",
"print",
"(",
"\"Please, don't pass it explicitly.\"",
")",
"print",
"(",
"\"Use syntax like this: ih.tobinstr(start=xxx, end=yyy, size=zzz)\"",
")",
"else",
":",
"pad",
"=",
"None",
"return",
"self",
".",
"_tobinstr_really",
"(",
"start",
",",
"end",
",",
"pad",
",",
"size",
")"
] |
Convert to binary form and return as binary string.
@param start start address of output bytes.
@param end end address of output bytes (inclusive).
@param pad [DEPRECATED PARAMETER, please use self.padding instead]
fill empty spaces with this value
(if pad is None then this method uses self.padding).
@param size size of the block, used with start or end parameter.
@return bytes string of binary data.
|
[
"Convert",
"to",
"binary",
"form",
"and",
"return",
"as",
"binary",
"string",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L362-L381
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.tobinfile
|
def tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None):
'''Convert to binary and write to file.
@param fobj file name or file object for writing output bytes.
@param start start address of output bytes.
@param end end address of output bytes (inclusive).
@param pad [DEPRECATED PARAMETER, please use self.padding instead]
fill empty spaces with this value
(if pad is None then this method uses self.padding).
@param size size of the block, used with start or end parameter.
'''
if not isinstance(pad, _DeprecatedParam):
print ("IntelHex.tobinfile: 'pad' parameter is deprecated.")
if pad is not None:
print ("Please, use IntelHex.padding attribute instead.")
else:
print ("Please, don't pass it explicitly.")
print ("Use syntax like this: ih.tobinfile(start=xxx, end=yyy, size=zzz)")
else:
pad = None
if getattr(fobj, "write", None) is None:
fobj = open(fobj, "wb")
close_fd = True
else:
close_fd = False
fobj.write(self._tobinstr_really(start, end, pad, size))
if close_fd:
fobj.close()
|
python
|
def tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None):
'''Convert to binary and write to file.
@param fobj file name or file object for writing output bytes.
@param start start address of output bytes.
@param end end address of output bytes (inclusive).
@param pad [DEPRECATED PARAMETER, please use self.padding instead]
fill empty spaces with this value
(if pad is None then this method uses self.padding).
@param size size of the block, used with start or end parameter.
'''
if not isinstance(pad, _DeprecatedParam):
print ("IntelHex.tobinfile: 'pad' parameter is deprecated.")
if pad is not None:
print ("Please, use IntelHex.padding attribute instead.")
else:
print ("Please, don't pass it explicitly.")
print ("Use syntax like this: ih.tobinfile(start=xxx, end=yyy, size=zzz)")
else:
pad = None
if getattr(fobj, "write", None) is None:
fobj = open(fobj, "wb")
close_fd = True
else:
close_fd = False
fobj.write(self._tobinstr_really(start, end, pad, size))
if close_fd:
fobj.close()
|
[
"def",
"tobinfile",
"(",
"self",
",",
"fobj",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"pad",
"=",
"_DEPRECATED",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"pad",
",",
"_DeprecatedParam",
")",
":",
"print",
"(",
"\"IntelHex.tobinfile: 'pad' parameter is deprecated.\"",
")",
"if",
"pad",
"is",
"not",
"None",
":",
"print",
"(",
"\"Please, use IntelHex.padding attribute instead.\"",
")",
"else",
":",
"print",
"(",
"\"Please, don't pass it explicitly.\"",
")",
"print",
"(",
"\"Use syntax like this: ih.tobinfile(start=xxx, end=yyy, size=zzz)\"",
")",
"else",
":",
"pad",
"=",
"None",
"if",
"getattr",
"(",
"fobj",
",",
"\"write\"",
",",
"None",
")",
"is",
"None",
":",
"fobj",
"=",
"open",
"(",
"fobj",
",",
"\"wb\"",
")",
"close_fd",
"=",
"True",
"else",
":",
"close_fd",
"=",
"False",
"fobj",
".",
"write",
"(",
"self",
".",
"_tobinstr_really",
"(",
"start",
",",
"end",
",",
"pad",
",",
"size",
")",
")",
"if",
"close_fd",
":",
"fobj",
".",
"close",
"(",
")"
] |
Convert to binary and write to file.
@param fobj file name or file object for writing output bytes.
@param start start address of output bytes.
@param end end address of output bytes (inclusive).
@param pad [DEPRECATED PARAMETER, please use self.padding instead]
fill empty spaces with this value
(if pad is None then this method uses self.padding).
@param size size of the block, used with start or end parameter.
|
[
"Convert",
"to",
"binary",
"and",
"write",
"to",
"file",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L386-L415
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.todict
|
def todict(self):
'''Convert to python dictionary.
@return dict suitable for initializing another IntelHex object.
'''
r = {}
r.update(self._buf)
if self.start_addr:
r['start_addr'] = self.start_addr
return r
|
python
|
def todict(self):
'''Convert to python dictionary.
@return dict suitable for initializing another IntelHex object.
'''
r = {}
r.update(self._buf)
if self.start_addr:
r['start_addr'] = self.start_addr
return r
|
[
"def",
"todict",
"(",
"self",
")",
":",
"r",
"=",
"{",
"}",
"r",
".",
"update",
"(",
"self",
".",
"_buf",
")",
"if",
"self",
".",
"start_addr",
":",
"r",
"[",
"'start_addr'",
"]",
"=",
"self",
".",
"start_addr",
"return",
"r"
] |
Convert to python dictionary.
@return dict suitable for initializing another IntelHex object.
|
[
"Convert",
"to",
"python",
"dictionary",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L417-L426
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.tofile
|
def tofile(self, fobj, format):
"""Write data to hex or bin file. Preferred method over tobin or tohex.
@param fobj file name or file-like object
@param format file format ("hex" or "bin")
"""
if format == 'hex':
self.write_hex_file(fobj)
elif format == 'bin':
self.tobinfile(fobj)
else:
raise ValueError('format should be either "hex" or "bin";'
' got %r instead' % format)
|
python
|
def tofile(self, fobj, format):
"""Write data to hex or bin file. Preferred method over tobin or tohex.
@param fobj file name or file-like object
@param format file format ("hex" or "bin")
"""
if format == 'hex':
self.write_hex_file(fobj)
elif format == 'bin':
self.tobinfile(fobj)
else:
raise ValueError('format should be either "hex" or "bin";'
' got %r instead' % format)
|
[
"def",
"tofile",
"(",
"self",
",",
"fobj",
",",
"format",
")",
":",
"if",
"format",
"==",
"'hex'",
":",
"self",
".",
"write_hex_file",
"(",
"fobj",
")",
"elif",
"format",
"==",
"'bin'",
":",
"self",
".",
"tobinfile",
"(",
"fobj",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'format should be either \"hex\" or \"bin\";'",
"' got %r instead'",
"%",
"format",
")"
] |
Write data to hex or bin file. Preferred method over tobin or tohex.
@param fobj file name or file-like object
@param format file format ("hex" or "bin")
|
[
"Write",
"data",
"to",
"hex",
"or",
"bin",
"file",
".",
"Preferred",
"method",
"over",
"tobin",
"or",
"tohex",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L720-L732
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.gets
|
def gets(self, addr, length):
"""Get string of bytes from given address. If any entries are blank
from addr through addr+length, a NotEnoughDataError exception will
be raised. Padding is not used.
"""
a = array('B', asbytes('\0'*length))
try:
for i in range_g(length):
a[i] = self._buf[addr+i]
except KeyError:
raise NotEnoughDataError(address=addr, length=length)
return array_tobytes(a)
|
python
|
def gets(self, addr, length):
"""Get string of bytes from given address. If any entries are blank
from addr through addr+length, a NotEnoughDataError exception will
be raised. Padding is not used.
"""
a = array('B', asbytes('\0'*length))
try:
for i in range_g(length):
a[i] = self._buf[addr+i]
except KeyError:
raise NotEnoughDataError(address=addr, length=length)
return array_tobytes(a)
|
[
"def",
"gets",
"(",
"self",
",",
"addr",
",",
"length",
")",
":",
"a",
"=",
"array",
"(",
"'B'",
",",
"asbytes",
"(",
"'\\0'",
"*",
"length",
")",
")",
"try",
":",
"for",
"i",
"in",
"range_g",
"(",
"length",
")",
":",
"a",
"[",
"i",
"]",
"=",
"self",
".",
"_buf",
"[",
"addr",
"+",
"i",
"]",
"except",
"KeyError",
":",
"raise",
"NotEnoughDataError",
"(",
"address",
"=",
"addr",
",",
"length",
"=",
"length",
")",
"return",
"array_tobytes",
"(",
"a",
")"
] |
Get string of bytes from given address. If any entries are blank
from addr through addr+length, a NotEnoughDataError exception will
be raised. Padding is not used.
|
[
"Get",
"string",
"of",
"bytes",
"from",
"given",
"address",
".",
"If",
"any",
"entries",
"are",
"blank",
"from",
"addr",
"through",
"addr",
"+",
"length",
"a",
"NotEnoughDataError",
"exception",
"will",
"be",
"raised",
".",
"Padding",
"is",
"not",
"used",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L734-L745
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.puts
|
def puts(self, addr, s):
"""Put string of bytes at given address. Will overwrite any previous
entries.
"""
a = array('B', asbytes(s))
for i in range_g(len(a)):
self._buf[addr+i] = a[i]
|
python
|
def puts(self, addr, s):
"""Put string of bytes at given address. Will overwrite any previous
entries.
"""
a = array('B', asbytes(s))
for i in range_g(len(a)):
self._buf[addr+i] = a[i]
|
[
"def",
"puts",
"(",
"self",
",",
"addr",
",",
"s",
")",
":",
"a",
"=",
"array",
"(",
"'B'",
",",
"asbytes",
"(",
"s",
")",
")",
"for",
"i",
"in",
"range_g",
"(",
"len",
"(",
"a",
")",
")",
":",
"self",
".",
"_buf",
"[",
"addr",
"+",
"i",
"]",
"=",
"a",
"[",
"i",
"]"
] |
Put string of bytes at given address. Will overwrite any previous
entries.
|
[
"Put",
"string",
"of",
"bytes",
"at",
"given",
"address",
".",
"Will",
"overwrite",
"any",
"previous",
"entries",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L747-L753
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.getsz
|
def getsz(self, addr):
"""Get zero-terminated bytes string from given address. Will raise
NotEnoughDataError exception if a hole is encountered before a 0.
"""
i = 0
try:
while True:
if self._buf[addr+i] == 0:
break
i += 1
except KeyError:
raise NotEnoughDataError(msg=('Bad access at 0x%X: '
'not enough data to read zero-terminated string') % addr)
return self.gets(addr, i)
|
python
|
def getsz(self, addr):
"""Get zero-terminated bytes string from given address. Will raise
NotEnoughDataError exception if a hole is encountered before a 0.
"""
i = 0
try:
while True:
if self._buf[addr+i] == 0:
break
i += 1
except KeyError:
raise NotEnoughDataError(msg=('Bad access at 0x%X: '
'not enough data to read zero-terminated string') % addr)
return self.gets(addr, i)
|
[
"def",
"getsz",
"(",
"self",
",",
"addr",
")",
":",
"i",
"=",
"0",
"try",
":",
"while",
"True",
":",
"if",
"self",
".",
"_buf",
"[",
"addr",
"+",
"i",
"]",
"==",
"0",
":",
"break",
"i",
"+=",
"1",
"except",
"KeyError",
":",
"raise",
"NotEnoughDataError",
"(",
"msg",
"=",
"(",
"'Bad access at 0x%X: '",
"'not enough data to read zero-terminated string'",
")",
"%",
"addr",
")",
"return",
"self",
".",
"gets",
"(",
"addr",
",",
"i",
")"
] |
Get zero-terminated bytes string from given address. Will raise
NotEnoughDataError exception if a hole is encountered before a 0.
|
[
"Get",
"zero",
"-",
"terminated",
"bytes",
"string",
"from",
"given",
"address",
".",
"Will",
"raise",
"NotEnoughDataError",
"exception",
"if",
"a",
"hole",
"is",
"encountered",
"before",
"a",
"0",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L755-L768
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.putsz
|
def putsz(self, addr, s):
"""Put bytes string in object at addr and append terminating zero at end."""
self.puts(addr, s)
self._buf[addr+len(s)] = 0
|
python
|
def putsz(self, addr, s):
"""Put bytes string in object at addr and append terminating zero at end."""
self.puts(addr, s)
self._buf[addr+len(s)] = 0
|
[
"def",
"putsz",
"(",
"self",
",",
"addr",
",",
"s",
")",
":",
"self",
".",
"puts",
"(",
"addr",
",",
"s",
")",
"self",
".",
"_buf",
"[",
"addr",
"+",
"len",
"(",
"s",
")",
"]",
"=",
"0"
] |
Put bytes string in object at addr and append terminating zero at end.
|
[
"Put",
"bytes",
"string",
"in",
"object",
"at",
"addr",
"and",
"append",
"terminating",
"zero",
"at",
"end",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L770-L773
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.dump
|
def dump(self, tofile=None, width=16, withpadding=False):
"""Dump object content to specified file object or to stdout if None.
Format is a hexdump with some header information at the beginning,
addresses on the left, and data on right.
@param tofile file-like object to dump to
@param width number of bytes per line (i.e. columns)
@param withpadding print padding character instead of '--'
@raise ValueError if width is not a positive integer
"""
if not isinstance(width,int) or width < 1:
raise ValueError('width must be a positive integer.')
# The integer can be of float type - does not work with bit operations
width = int(width)
if tofile is None:
tofile = sys.stdout
# start addr possibly
if self.start_addr is not None:
cs = self.start_addr.get('CS')
ip = self.start_addr.get('IP')
eip = self.start_addr.get('EIP')
if eip is not None and cs is None and ip is None:
tofile.write('EIP = 0x%08X\n' % eip)
elif eip is None and cs is not None and ip is not None:
tofile.write('CS = 0x%04X, IP = 0x%04X\n' % (cs, ip))
else:
tofile.write('start_addr = %r\n' % start_addr)
# actual data
addresses = dict_keys(self._buf)
if addresses:
addresses.sort()
minaddr = addresses[0]
maxaddr = addresses[-1]
startaddr = (minaddr // width) * width
endaddr = ((maxaddr // width) + 1) * width
maxdigits = max(len(hex(endaddr)) - 2, 4) # Less 2 to exclude '0x'
templa = '%%0%dX' % maxdigits
rangewidth = range_l(width)
if withpadding:
pad = self.padding
else:
pad = None
for i in range_g(startaddr, endaddr, width):
tofile.write(templa % i)
tofile.write(' ')
s = []
for j in rangewidth:
x = self._buf.get(i+j, pad)
if x is not None:
tofile.write(' %02X' % x)
if 32 <= x < 127: # GNU less does not like 0x7F (128 decimal) so we'd better show it as dot
s.append(chr(x))
else:
s.append('.')
else:
tofile.write(' --')
s.append(' ')
tofile.write(' |' + ''.join(s) + '|\n')
|
python
|
def dump(self, tofile=None, width=16, withpadding=False):
"""Dump object content to specified file object or to stdout if None.
Format is a hexdump with some header information at the beginning,
addresses on the left, and data on right.
@param tofile file-like object to dump to
@param width number of bytes per line (i.e. columns)
@param withpadding print padding character instead of '--'
@raise ValueError if width is not a positive integer
"""
if not isinstance(width,int) or width < 1:
raise ValueError('width must be a positive integer.')
# The integer can be of float type - does not work with bit operations
width = int(width)
if tofile is None:
tofile = sys.stdout
# start addr possibly
if self.start_addr is not None:
cs = self.start_addr.get('CS')
ip = self.start_addr.get('IP')
eip = self.start_addr.get('EIP')
if eip is not None and cs is None and ip is None:
tofile.write('EIP = 0x%08X\n' % eip)
elif eip is None and cs is not None and ip is not None:
tofile.write('CS = 0x%04X, IP = 0x%04X\n' % (cs, ip))
else:
tofile.write('start_addr = %r\n' % start_addr)
# actual data
addresses = dict_keys(self._buf)
if addresses:
addresses.sort()
minaddr = addresses[0]
maxaddr = addresses[-1]
startaddr = (minaddr // width) * width
endaddr = ((maxaddr // width) + 1) * width
maxdigits = max(len(hex(endaddr)) - 2, 4) # Less 2 to exclude '0x'
templa = '%%0%dX' % maxdigits
rangewidth = range_l(width)
if withpadding:
pad = self.padding
else:
pad = None
for i in range_g(startaddr, endaddr, width):
tofile.write(templa % i)
tofile.write(' ')
s = []
for j in rangewidth:
x = self._buf.get(i+j, pad)
if x is not None:
tofile.write(' %02X' % x)
if 32 <= x < 127: # GNU less does not like 0x7F (128 decimal) so we'd better show it as dot
s.append(chr(x))
else:
s.append('.')
else:
tofile.write(' --')
s.append(' ')
tofile.write(' |' + ''.join(s) + '|\n')
|
[
"def",
"dump",
"(",
"self",
",",
"tofile",
"=",
"None",
",",
"width",
"=",
"16",
",",
"withpadding",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"width",
",",
"int",
")",
"or",
"width",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'width must be a positive integer.'",
")",
"# The integer can be of float type - does not work with bit operations",
"width",
"=",
"int",
"(",
"width",
")",
"if",
"tofile",
"is",
"None",
":",
"tofile",
"=",
"sys",
".",
"stdout",
"# start addr possibly",
"if",
"self",
".",
"start_addr",
"is",
"not",
"None",
":",
"cs",
"=",
"self",
".",
"start_addr",
".",
"get",
"(",
"'CS'",
")",
"ip",
"=",
"self",
".",
"start_addr",
".",
"get",
"(",
"'IP'",
")",
"eip",
"=",
"self",
".",
"start_addr",
".",
"get",
"(",
"'EIP'",
")",
"if",
"eip",
"is",
"not",
"None",
"and",
"cs",
"is",
"None",
"and",
"ip",
"is",
"None",
":",
"tofile",
".",
"write",
"(",
"'EIP = 0x%08X\\n'",
"%",
"eip",
")",
"elif",
"eip",
"is",
"None",
"and",
"cs",
"is",
"not",
"None",
"and",
"ip",
"is",
"not",
"None",
":",
"tofile",
".",
"write",
"(",
"'CS = 0x%04X, IP = 0x%04X\\n'",
"%",
"(",
"cs",
",",
"ip",
")",
")",
"else",
":",
"tofile",
".",
"write",
"(",
"'start_addr = %r\\n'",
"%",
"start_addr",
")",
"# actual data",
"addresses",
"=",
"dict_keys",
"(",
"self",
".",
"_buf",
")",
"if",
"addresses",
":",
"addresses",
".",
"sort",
"(",
")",
"minaddr",
"=",
"addresses",
"[",
"0",
"]",
"maxaddr",
"=",
"addresses",
"[",
"-",
"1",
"]",
"startaddr",
"=",
"(",
"minaddr",
"//",
"width",
")",
"*",
"width",
"endaddr",
"=",
"(",
"(",
"maxaddr",
"//",
"width",
")",
"+",
"1",
")",
"*",
"width",
"maxdigits",
"=",
"max",
"(",
"len",
"(",
"hex",
"(",
"endaddr",
")",
")",
"-",
"2",
",",
"4",
")",
"# Less 2 to exclude '0x'",
"templa",
"=",
"'%%0%dX'",
"%",
"maxdigits",
"rangewidth",
"=",
"range_l",
"(",
"width",
")",
"if",
"withpadding",
":",
"pad",
"=",
"self",
".",
"padding",
"else",
":",
"pad",
"=",
"None",
"for",
"i",
"in",
"range_g",
"(",
"startaddr",
",",
"endaddr",
",",
"width",
")",
":",
"tofile",
".",
"write",
"(",
"templa",
"%",
"i",
")",
"tofile",
".",
"write",
"(",
"' '",
")",
"s",
"=",
"[",
"]",
"for",
"j",
"in",
"rangewidth",
":",
"x",
"=",
"self",
".",
"_buf",
".",
"get",
"(",
"i",
"+",
"j",
",",
"pad",
")",
"if",
"x",
"is",
"not",
"None",
":",
"tofile",
".",
"write",
"(",
"' %02X'",
"%",
"x",
")",
"if",
"32",
"<=",
"x",
"<",
"127",
":",
"# GNU less does not like 0x7F (128 decimal) so we'd better show it as dot",
"s",
".",
"append",
"(",
"chr",
"(",
"x",
")",
")",
"else",
":",
"s",
".",
"append",
"(",
"'.'",
")",
"else",
":",
"tofile",
".",
"write",
"(",
"' --'",
")",
"s",
".",
"append",
"(",
"' '",
")",
"tofile",
".",
"write",
"(",
"' |'",
"+",
"''",
".",
"join",
"(",
"s",
")",
"+",
"'|\\n'",
")"
] |
Dump object content to specified file object or to stdout if None.
Format is a hexdump with some header information at the beginning,
addresses on the left, and data on right.
@param tofile file-like object to dump to
@param width number of bytes per line (i.e. columns)
@param withpadding print padding character instead of '--'
@raise ValueError if width is not a positive integer
|
[
"Dump",
"object",
"content",
"to",
"specified",
"file",
"object",
"or",
"to",
"stdout",
"if",
"None",
".",
"Format",
"is",
"a",
"hexdump",
"with",
"some",
"header",
"information",
"at",
"the",
"beginning",
"addresses",
"on",
"the",
"left",
"and",
"data",
"on",
"right",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L775-L834
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.segments
|
def segments(self):
"""Return a list of ordered tuple objects, representing contiguous occupied data addresses.
Each tuple has a length of two and follows the semantics of the range and xrange objects.
The second entry of the tuple is always an integer greater than the first entry.
"""
addresses = self.addresses()
if not addresses:
return []
elif len(addresses) == 1:
return([(addresses[0], addresses[0]+1)])
adjacent_differences = [(b - a) for (a, b) in zip(addresses[:-1], addresses[1:])]
breaks = [i for (i, x) in enumerate(adjacent_differences) if x > 1]
endings = [addresses[b] for b in breaks]
endings.append(addresses[-1])
beginings = [addresses[b+1] for b in breaks]
beginings.insert(0, addresses[0])
return [(a, b+1) for (a, b) in zip(beginings, endings)]
|
python
|
def segments(self):
"""Return a list of ordered tuple objects, representing contiguous occupied data addresses.
Each tuple has a length of two and follows the semantics of the range and xrange objects.
The second entry of the tuple is always an integer greater than the first entry.
"""
addresses = self.addresses()
if not addresses:
return []
elif len(addresses) == 1:
return([(addresses[0], addresses[0]+1)])
adjacent_differences = [(b - a) for (a, b) in zip(addresses[:-1], addresses[1:])]
breaks = [i for (i, x) in enumerate(adjacent_differences) if x > 1]
endings = [addresses[b] for b in breaks]
endings.append(addresses[-1])
beginings = [addresses[b+1] for b in breaks]
beginings.insert(0, addresses[0])
return [(a, b+1) for (a, b) in zip(beginings, endings)]
|
[
"def",
"segments",
"(",
"self",
")",
":",
"addresses",
"=",
"self",
".",
"addresses",
"(",
")",
"if",
"not",
"addresses",
":",
"return",
"[",
"]",
"elif",
"len",
"(",
"addresses",
")",
"==",
"1",
":",
"return",
"(",
"[",
"(",
"addresses",
"[",
"0",
"]",
",",
"addresses",
"[",
"0",
"]",
"+",
"1",
")",
"]",
")",
"adjacent_differences",
"=",
"[",
"(",
"b",
"-",
"a",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"zip",
"(",
"addresses",
"[",
":",
"-",
"1",
"]",
",",
"addresses",
"[",
"1",
":",
"]",
")",
"]",
"breaks",
"=",
"[",
"i",
"for",
"(",
"i",
",",
"x",
")",
"in",
"enumerate",
"(",
"adjacent_differences",
")",
"if",
"x",
">",
"1",
"]",
"endings",
"=",
"[",
"addresses",
"[",
"b",
"]",
"for",
"b",
"in",
"breaks",
"]",
"endings",
".",
"append",
"(",
"addresses",
"[",
"-",
"1",
"]",
")",
"beginings",
"=",
"[",
"addresses",
"[",
"b",
"+",
"1",
"]",
"for",
"b",
"in",
"breaks",
"]",
"beginings",
".",
"insert",
"(",
"0",
",",
"addresses",
"[",
"0",
"]",
")",
"return",
"[",
"(",
"a",
",",
"b",
"+",
"1",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"zip",
"(",
"beginings",
",",
"endings",
")",
"]"
] |
Return a list of ordered tuple objects, representing contiguous occupied data addresses.
Each tuple has a length of two and follows the semantics of the range and xrange objects.
The second entry of the tuple is always an integer greater than the first entry.
|
[
"Return",
"a",
"list",
"of",
"ordered",
"tuple",
"objects",
"representing",
"contiguous",
"occupied",
"data",
"addresses",
".",
"Each",
"tuple",
"has",
"a",
"length",
"of",
"two",
"and",
"follows",
"the",
"semantics",
"of",
"the",
"range",
"and",
"xrange",
"objects",
".",
"The",
"second",
"entry",
"of",
"the",
"tuple",
"is",
"always",
"an",
"integer",
"greater",
"than",
"the",
"first",
"entry",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L884-L900
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
IntelHex.get_memory_size
|
def get_memory_size(self):
"""Returns the approximate memory footprint for data."""
n = sys.getsizeof(self)
n += sys.getsizeof(self.padding)
n += total_size(self.start_addr)
n += total_size(self._buf)
n += sys.getsizeof(self._offset)
return n
|
python
|
def get_memory_size(self):
"""Returns the approximate memory footprint for data."""
n = sys.getsizeof(self)
n += sys.getsizeof(self.padding)
n += total_size(self.start_addr)
n += total_size(self._buf)
n += sys.getsizeof(self._offset)
return n
|
[
"def",
"get_memory_size",
"(",
"self",
")",
":",
"n",
"=",
"sys",
".",
"getsizeof",
"(",
"self",
")",
"n",
"+=",
"sys",
".",
"getsizeof",
"(",
"self",
".",
"padding",
")",
"n",
"+=",
"total_size",
"(",
"self",
".",
"start_addr",
")",
"n",
"+=",
"total_size",
"(",
"self",
".",
"_buf",
")",
"n",
"+=",
"sys",
".",
"getsizeof",
"(",
"self",
".",
"_offset",
")",
"return",
"n"
] |
Returns the approximate memory footprint for data.
|
[
"Returns",
"the",
"approximate",
"memory",
"footprint",
"for",
"data",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L902-L909
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/__init__.py
|
Record._from_bytes
|
def _from_bytes(bytes):
"""Takes a list of bytes, computes the checksum, and outputs the entire
record as a string. bytes should be the hex record without the colon
or final checksum.
@param bytes list of byte values so far to pack into record.
@return String representation of one HEX record
"""
assert len(bytes) >= 4
# calculate checksum
s = (-sum(bytes)) & 0x0FF
bin = array('B', bytes + [s])
return ':' + asstr(hexlify(array_tobytes(bin))).upper()
|
python
|
def _from_bytes(bytes):
"""Takes a list of bytes, computes the checksum, and outputs the entire
record as a string. bytes should be the hex record without the colon
or final checksum.
@param bytes list of byte values so far to pack into record.
@return String representation of one HEX record
"""
assert len(bytes) >= 4
# calculate checksum
s = (-sum(bytes)) & 0x0FF
bin = array('B', bytes + [s])
return ':' + asstr(hexlify(array_tobytes(bin))).upper()
|
[
"def",
"_from_bytes",
"(",
"bytes",
")",
":",
"assert",
"len",
"(",
"bytes",
")",
">=",
"4",
"# calculate checksum",
"s",
"=",
"(",
"-",
"sum",
"(",
"bytes",
")",
")",
"&",
"0x0FF",
"bin",
"=",
"array",
"(",
"'B'",
",",
"bytes",
"+",
"[",
"s",
"]",
")",
"return",
"':'",
"+",
"asstr",
"(",
"hexlify",
"(",
"array_tobytes",
"(",
"bin",
")",
")",
")",
".",
"upper",
"(",
")"
] |
Takes a list of bytes, computes the checksum, and outputs the entire
record as a string. bytes should be the hex record without the colon
or final checksum.
@param bytes list of byte values so far to pack into record.
@return String representation of one HEX record
|
[
"Takes",
"a",
"list",
"of",
"bytes",
"computes",
"the",
"checksum",
"and",
"outputs",
"the",
"entire",
"record",
"as",
"a",
"string",
".",
"bytes",
"should",
"be",
"the",
"hex",
"record",
"without",
"the",
"colon",
"or",
"final",
"checksum",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L1130-L1142
|
train
|
iotile/coretools
|
iotilebuild/iotile/build/config/site_scons/release.py
|
create_release_settings_action
|
def create_release_settings_action(target, source, env):
"""Copy module_settings.json and add release and build information
"""
with open(str(source[0]), "r") as fileobj:
settings = json.load(fileobj)
settings['release'] = True
settings['release_date'] = datetime.datetime.utcnow().isoformat()
settings['dependency_versions'] = {}
#Also insert the versions of every dependency that we used to build this component
for dep in env['TILE'].dependencies:
tile = IOTile(os.path.join('build', 'deps', dep['unique_id']))
settings['dependency_versions'][dep['unique_id']] = str(tile.parsed_version)
with open(str(target[0]), "w") as fileobj:
json.dump(settings, fileobj, indent=4)
|
python
|
def create_release_settings_action(target, source, env):
"""Copy module_settings.json and add release and build information
"""
with open(str(source[0]), "r") as fileobj:
settings = json.load(fileobj)
settings['release'] = True
settings['release_date'] = datetime.datetime.utcnow().isoformat()
settings['dependency_versions'] = {}
#Also insert the versions of every dependency that we used to build this component
for dep in env['TILE'].dependencies:
tile = IOTile(os.path.join('build', 'deps', dep['unique_id']))
settings['dependency_versions'][dep['unique_id']] = str(tile.parsed_version)
with open(str(target[0]), "w") as fileobj:
json.dump(settings, fileobj, indent=4)
|
[
"def",
"create_release_settings_action",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"with",
"open",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
",",
"\"r\"",
")",
"as",
"fileobj",
":",
"settings",
"=",
"json",
".",
"load",
"(",
"fileobj",
")",
"settings",
"[",
"'release'",
"]",
"=",
"True",
"settings",
"[",
"'release_date'",
"]",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"settings",
"[",
"'dependency_versions'",
"]",
"=",
"{",
"}",
"#Also insert the versions of every dependency that we used to build this component",
"for",
"dep",
"in",
"env",
"[",
"'TILE'",
"]",
".",
"dependencies",
":",
"tile",
"=",
"IOTile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'build'",
",",
"'deps'",
",",
"dep",
"[",
"'unique_id'",
"]",
")",
")",
"settings",
"[",
"'dependency_versions'",
"]",
"[",
"dep",
"[",
"'unique_id'",
"]",
"]",
"=",
"str",
"(",
"tile",
".",
"parsed_version",
")",
"with",
"open",
"(",
"str",
"(",
"target",
"[",
"0",
"]",
")",
",",
"\"w\"",
")",
"as",
"fileobj",
":",
"json",
".",
"dump",
"(",
"settings",
",",
"fileobj",
",",
"indent",
"=",
"4",
")"
] |
Copy module_settings.json and add release and build information
|
[
"Copy",
"module_settings",
".",
"json",
"and",
"add",
"release",
"and",
"build",
"information"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/release.py#L16-L34
|
train
|
iotile/coretools
|
iotilebuild/iotile/build/config/site_scons/release.py
|
copy_extra_files
|
def copy_extra_files(tile):
"""Copy all files listed in a copy_files and copy_products section.
Files listed in copy_files will be copied from the specified location
in the current component to the specified path under the output
folder.
Files listed in copy_products will be looked up with a ProductResolver
and copied copied to the specified path in the output folder. There
is not currently a way to specify what type of product is being resolved.
The `short_name` given must be unique across all products from this
component and its direct dependencies.
"""
env = Environment(tools=[])
outputbase = os.path.join('build', 'output')
for src, dest in tile.settings.get('copy_files', {}).items():
outputfile = os.path.join(outputbase, dest)
env.Command([outputfile], [src], Copy("$TARGET", "$SOURCE"))
resolver = ProductResolver.Create()
for src, dest in tile.settings.get('copy_products', {}).items():
prod = resolver.find_unique(None, src)
outputfile = os.path.join(outputbase, dest)
env.Command([outputfile], [prod.full_path], Copy("$TARGET", "$SOURCE"))
|
python
|
def copy_extra_files(tile):
"""Copy all files listed in a copy_files and copy_products section.
Files listed in copy_files will be copied from the specified location
in the current component to the specified path under the output
folder.
Files listed in copy_products will be looked up with a ProductResolver
and copied copied to the specified path in the output folder. There
is not currently a way to specify what type of product is being resolved.
The `short_name` given must be unique across all products from this
component and its direct dependencies.
"""
env = Environment(tools=[])
outputbase = os.path.join('build', 'output')
for src, dest in tile.settings.get('copy_files', {}).items():
outputfile = os.path.join(outputbase, dest)
env.Command([outputfile], [src], Copy("$TARGET", "$SOURCE"))
resolver = ProductResolver.Create()
for src, dest in tile.settings.get('copy_products', {}).items():
prod = resolver.find_unique(None, src)
outputfile = os.path.join(outputbase, dest)
env.Command([outputfile], [prod.full_path], Copy("$TARGET", "$SOURCE"))
|
[
"def",
"copy_extra_files",
"(",
"tile",
")",
":",
"env",
"=",
"Environment",
"(",
"tools",
"=",
"[",
"]",
")",
"outputbase",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'build'",
",",
"'output'",
")",
"for",
"src",
",",
"dest",
"in",
"tile",
".",
"settings",
".",
"get",
"(",
"'copy_files'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"outputfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outputbase",
",",
"dest",
")",
"env",
".",
"Command",
"(",
"[",
"outputfile",
"]",
",",
"[",
"src",
"]",
",",
"Copy",
"(",
"\"$TARGET\"",
",",
"\"$SOURCE\"",
")",
")",
"resolver",
"=",
"ProductResolver",
".",
"Create",
"(",
")",
"for",
"src",
",",
"dest",
"in",
"tile",
".",
"settings",
".",
"get",
"(",
"'copy_products'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"prod",
"=",
"resolver",
".",
"find_unique",
"(",
"None",
",",
"src",
")",
"outputfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outputbase",
",",
"dest",
")",
"env",
".",
"Command",
"(",
"[",
"outputfile",
"]",
",",
"[",
"prod",
".",
"full_path",
"]",
",",
"Copy",
"(",
"\"$TARGET\"",
",",
"\"$SOURCE\"",
")",
")"
] |
Copy all files listed in a copy_files and copy_products section.
Files listed in copy_files will be copied from the specified location
in the current component to the specified path under the output
folder.
Files listed in copy_products will be looked up with a ProductResolver
and copied copied to the specified path in the output folder. There
is not currently a way to specify what type of product is being resolved.
The `short_name` given must be unique across all products from this
component and its direct dependencies.
|
[
"Copy",
"all",
"files",
"listed",
"in",
"a",
"copy_files",
"and",
"copy_products",
"section",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/release.py#L99-L125
|
train
|
iotile/coretools
|
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/masm.py
|
generate
|
def generate(env):
"""Add Builders and construction variables for masm to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
shared_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
for suffix in ASPPSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
shared_obj.add_action(suffix, SCons.Defaults.ASPPAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['AS'] = 'ml'
env['ASFLAGS'] = SCons.Util.CLVar('/nologo')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
|
python
|
def generate(env):
"""Add Builders and construction variables for masm to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
shared_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
for suffix in ASPPSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
shared_obj.add_action(suffix, SCons.Defaults.ASPPAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['AS'] = 'ml'
env['ASFLAGS'] = SCons.Util.CLVar('/nologo')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
|
[
"def",
"generate",
"(",
"env",
")",
":",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"for",
"suffix",
"in",
"ASSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASAction",
")",
"shared_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASAction",
")",
"static_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"StaticObjectEmitter",
")",
"shared_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"SharedObjectEmitter",
")",
"for",
"suffix",
"in",
"ASPPSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASPPAction",
")",
"shared_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASPPAction",
")",
"static_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"StaticObjectEmitter",
")",
"shared_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"SharedObjectEmitter",
")",
"env",
"[",
"'AS'",
"]",
"=",
"'ml'",
"env",
"[",
"'ASFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'/nologo'",
")",
"env",
"[",
"'ASPPFLAGS'",
"]",
"=",
"'$ASFLAGS'",
"env",
"[",
"'ASCOM'",
"]",
"=",
"'$AS $ASFLAGS /c /Fo$TARGET $SOURCES'",
"env",
"[",
"'ASPPCOM'",
"]",
"=",
"'$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES'",
"env",
"[",
"'STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'",
"]",
"=",
"1"
] |
Add Builders and construction variables for masm to an Environment.
|
[
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"masm",
"to",
"an",
"Environment",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/masm.py#L47-L68
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/bench.py
|
median
|
def median(values):
"""Return median value for the list of values.
@param values: list of values for processing.
@return: median value.
"""
values.sort()
n = int(len(values) / 2)
return values[n]
|
python
|
def median(values):
"""Return median value for the list of values.
@param values: list of values for processing.
@return: median value.
"""
values.sort()
n = int(len(values) / 2)
return values[n]
|
[
"def",
"median",
"(",
"values",
")",
":",
"values",
".",
"sort",
"(",
")",
"n",
"=",
"int",
"(",
"len",
"(",
"values",
")",
"/",
"2",
")",
"return",
"values",
"[",
"n",
"]"
] |
Return median value for the list of values.
@param values: list of values for processing.
@return: median value.
|
[
"Return",
"median",
"value",
"for",
"the",
"list",
"of",
"values",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L45-L52
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/bench.py
|
time_coef
|
def time_coef(tc, nc, tb, nb):
"""Return time coefficient relative to base numbers.
@param tc: current test time
@param nc: current test data size
@param tb: base test time
@param nb: base test data size
@return: time coef.
"""
tc = float(tc)
nc = float(nc)
tb = float(tb)
nb = float(nb)
q = (tc * nb) / (tb * nc)
return q
|
python
|
def time_coef(tc, nc, tb, nb):
"""Return time coefficient relative to base numbers.
@param tc: current test time
@param nc: current test data size
@param tb: base test time
@param nb: base test data size
@return: time coef.
"""
tc = float(tc)
nc = float(nc)
tb = float(tb)
nb = float(nb)
q = (tc * nb) / (tb * nc)
return q
|
[
"def",
"time_coef",
"(",
"tc",
",",
"nc",
",",
"tb",
",",
"nb",
")",
":",
"tc",
"=",
"float",
"(",
"tc",
")",
"nc",
"=",
"float",
"(",
"nc",
")",
"tb",
"=",
"float",
"(",
"tb",
")",
"nb",
"=",
"float",
"(",
"nb",
")",
"q",
"=",
"(",
"tc",
"*",
"nb",
")",
"/",
"(",
"tb",
"*",
"nc",
")",
"return",
"q"
] |
Return time coefficient relative to base numbers.
@param tc: current test time
@param nc: current test data size
@param tb: base test time
@param nb: base test data size
@return: time coef.
|
[
"Return",
"time",
"coefficient",
"relative",
"to",
"base",
"numbers",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L100-L113
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/bench.py
|
main
|
def main(argv=None):
"""Main function to run benchmarks.
@param argv: command-line arguments.
@return: exit code (0 is OK).
"""
import getopt
# default values
test_read = None
test_write = None
n = 3 # number of repeat
if argv is None:
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, 'hn:rw', [])
for o,a in opts:
if o == '-h':
print(HELP)
return 0
elif o == '-n':
n = int(a)
elif o == '-r':
test_read = True
elif o == '-w':
test_write = True
if args:
raise getopt.GetoptError('Arguments are not used.')
except getopt.GetoptError:
msg = sys.exc_info()[1] # current exception
txt = str(msg)
print(txt)
return 1
if (test_read, test_write) == (None, None):
test_read = test_write = True
m = Measure(n, test_read, test_write)
m.measure_all()
m.print_report()
return 0
|
python
|
def main(argv=None):
"""Main function to run benchmarks.
@param argv: command-line arguments.
@return: exit code (0 is OK).
"""
import getopt
# default values
test_read = None
test_write = None
n = 3 # number of repeat
if argv is None:
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, 'hn:rw', [])
for o,a in opts:
if o == '-h':
print(HELP)
return 0
elif o == '-n':
n = int(a)
elif o == '-r':
test_read = True
elif o == '-w':
test_write = True
if args:
raise getopt.GetoptError('Arguments are not used.')
except getopt.GetoptError:
msg = sys.exc_info()[1] # current exception
txt = str(msg)
print(txt)
return 1
if (test_read, test_write) == (None, None):
test_read = test_write = True
m = Measure(n, test_read, test_write)
m.measure_all()
m.print_report()
return 0
|
[
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"import",
"getopt",
"# default values",
"test_read",
"=",
"None",
"test_write",
"=",
"None",
"n",
"=",
"3",
"# number of repeat",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"argv",
",",
"'hn:rw'",
",",
"[",
"]",
")",
"for",
"o",
",",
"a",
"in",
"opts",
":",
"if",
"o",
"==",
"'-h'",
":",
"print",
"(",
"HELP",
")",
"return",
"0",
"elif",
"o",
"==",
"'-n'",
":",
"n",
"=",
"int",
"(",
"a",
")",
"elif",
"o",
"==",
"'-r'",
":",
"test_read",
"=",
"True",
"elif",
"o",
"==",
"'-w'",
":",
"test_write",
"=",
"True",
"if",
"args",
":",
"raise",
"getopt",
".",
"GetoptError",
"(",
"'Arguments are not used.'",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"msg",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"# current exception",
"txt",
"=",
"str",
"(",
"msg",
")",
"print",
"(",
"txt",
")",
"return",
"1",
"if",
"(",
"test_read",
",",
"test_write",
")",
"==",
"(",
"None",
",",
"None",
")",
":",
"test_read",
"=",
"test_write",
"=",
"True",
"m",
"=",
"Measure",
"(",
"n",
",",
"test_read",
",",
"test_write",
")",
"m",
".",
"measure_all",
"(",
")",
"m",
".",
"print_report",
"(",
")",
"return",
"0"
] |
Main function to run benchmarks.
@param argv: command-line arguments.
@return: exit code (0 is OK).
|
[
"Main",
"function",
"to",
"run",
"benchmarks",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L240-L284
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/intelhex/bench.py
|
Measure.measure_one
|
def measure_one(self, data):
"""Do measuring of read and write operations.
@param data: 3-tuple from get_test_data
@return: (time readhex, time writehex)
"""
_unused, hexstr, ih = data
tread, twrite = 0.0, 0.0
if self.read:
tread = run_readtest_N_times(intelhex.IntelHex, hexstr, self.n)[0]
if self.write:
twrite = run_writetest_N_times(ih.write_hex_file, self.n)[0]
return tread, twrite
|
python
|
def measure_one(self, data):
"""Do measuring of read and write operations.
@param data: 3-tuple from get_test_data
@return: (time readhex, time writehex)
"""
_unused, hexstr, ih = data
tread, twrite = 0.0, 0.0
if self.read:
tread = run_readtest_N_times(intelhex.IntelHex, hexstr, self.n)[0]
if self.write:
twrite = run_writetest_N_times(ih.write_hex_file, self.n)[0]
return tread, twrite
|
[
"def",
"measure_one",
"(",
"self",
",",
"data",
")",
":",
"_unused",
",",
"hexstr",
",",
"ih",
"=",
"data",
"tread",
",",
"twrite",
"=",
"0.0",
",",
"0.0",
"if",
"self",
".",
"read",
":",
"tread",
"=",
"run_readtest_N_times",
"(",
"intelhex",
".",
"IntelHex",
",",
"hexstr",
",",
"self",
".",
"n",
")",
"[",
"0",
"]",
"if",
"self",
".",
"write",
":",
"twrite",
"=",
"run_writetest_N_times",
"(",
"ih",
".",
"write_hex_file",
",",
"self",
".",
"n",
")",
"[",
"0",
"]",
"return",
"tread",
",",
"twrite"
] |
Do measuring of read and write operations.
@param data: 3-tuple from get_test_data
@return: (time readhex, time writehex)
|
[
"Do",
"measuring",
"of",
"read",
"and",
"write",
"operations",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L174-L185
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/auth/env_auth_provider.py
|
EnvAuthProvider._get_key
|
def _get_key(cls, device_id):
"""Attempt to get a user key from an environment variable
"""
var_name = "USER_KEY_{0:08X}".format(device_id)
if var_name not in os.environ:
raise NotFoundError("No user key could be found for devices", device_id=device_id,
expected_variable_name=var_name)
key_var = os.environ[var_name]
if len(key_var) != 64:
raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters",
device_id=device_id, key_value=key_var)
try:
key = binascii.unhexlify(key_var)
except ValueError:
raise NotFoundError("User key in variable could not be decoded from hex", device_id=device_id,
key_value=key_var)
if len(key) != 32:
raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters",
device_id=device_id, key_value=key_var)
return key
|
python
|
def _get_key(cls, device_id):
"""Attempt to get a user key from an environment variable
"""
var_name = "USER_KEY_{0:08X}".format(device_id)
if var_name not in os.environ:
raise NotFoundError("No user key could be found for devices", device_id=device_id,
expected_variable_name=var_name)
key_var = os.environ[var_name]
if len(key_var) != 64:
raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters",
device_id=device_id, key_value=key_var)
try:
key = binascii.unhexlify(key_var)
except ValueError:
raise NotFoundError("User key in variable could not be decoded from hex", device_id=device_id,
key_value=key_var)
if len(key) != 32:
raise NotFoundError("User key in variable is not the correct length, should be 64 hex characters",
device_id=device_id, key_value=key_var)
return key
|
[
"def",
"_get_key",
"(",
"cls",
",",
"device_id",
")",
":",
"var_name",
"=",
"\"USER_KEY_{0:08X}\"",
".",
"format",
"(",
"device_id",
")",
"if",
"var_name",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"NotFoundError",
"(",
"\"No user key could be found for devices\"",
",",
"device_id",
"=",
"device_id",
",",
"expected_variable_name",
"=",
"var_name",
")",
"key_var",
"=",
"os",
".",
"environ",
"[",
"var_name",
"]",
"if",
"len",
"(",
"key_var",
")",
"!=",
"64",
":",
"raise",
"NotFoundError",
"(",
"\"User key in variable is not the correct length, should be 64 hex characters\"",
",",
"device_id",
"=",
"device_id",
",",
"key_value",
"=",
"key_var",
")",
"try",
":",
"key",
"=",
"binascii",
".",
"unhexlify",
"(",
"key_var",
")",
"except",
"ValueError",
":",
"raise",
"NotFoundError",
"(",
"\"User key in variable could not be decoded from hex\"",
",",
"device_id",
"=",
"device_id",
",",
"key_value",
"=",
"key_var",
")",
"if",
"len",
"(",
"key",
")",
"!=",
"32",
":",
"raise",
"NotFoundError",
"(",
"\"User key in variable is not the correct length, should be 64 hex characters\"",
",",
"device_id",
"=",
"device_id",
",",
"key_value",
"=",
"key_var",
")",
"return",
"key"
] |
Attempt to get a user key from an environment variable
|
[
"Attempt",
"to",
"get",
"a",
"user",
"key",
"from",
"an",
"environment",
"variable"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/env_auth_provider.py#L23-L48
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/auth/env_auth_provider.py
|
EnvAuthProvider.decrypt_report
|
def decrypt_report(self, device_id, root, data, **kwargs):
"""Decrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (bytearray): The data that we should decrypt
**kwargs: There are additional specific keyword args that are required
depending on the root key used. Typically, you must specify
- report_id (int): The report id
- sent_timestamp (int): The sent timestamp of the report
These two bits of information are used to construct the per report
signing and encryption key from the specific root key type.
Returns:
dict: The decrypted data and any associated metadata about the data.
The data itself must always be a bytearray stored under the 'data'
key, however additional keys may be present depending on the encryption method
used.
Raises:
NotFoundError: If the auth provider is not able to decrypt the data.
"""
report_key = self._verify_derive_key(device_id, root, **kwargs)
try:
from Crypto.Cipher import AES
import Crypto.Util.Counter
except ImportError:
raise NotFoundError
ctr = Crypto.Util.Counter.new(128)
# We use AES-128 for encryption
encryptor = AES.new(bytes(report_key[:16]), AES.MODE_CTR, counter=ctr)
decrypted = encryptor.decrypt(bytes(data))
return {'data': decrypted}
|
python
|
def decrypt_report(self, device_id, root, data, **kwargs):
"""Decrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (bytearray): The data that we should decrypt
**kwargs: There are additional specific keyword args that are required
depending on the root key used. Typically, you must specify
- report_id (int): The report id
- sent_timestamp (int): The sent timestamp of the report
These two bits of information are used to construct the per report
signing and encryption key from the specific root key type.
Returns:
dict: The decrypted data and any associated metadata about the data.
The data itself must always be a bytearray stored under the 'data'
key, however additional keys may be present depending on the encryption method
used.
Raises:
NotFoundError: If the auth provider is not able to decrypt the data.
"""
report_key = self._verify_derive_key(device_id, root, **kwargs)
try:
from Crypto.Cipher import AES
import Crypto.Util.Counter
except ImportError:
raise NotFoundError
ctr = Crypto.Util.Counter.new(128)
# We use AES-128 for encryption
encryptor = AES.new(bytes(report_key[:16]), AES.MODE_CTR, counter=ctr)
decrypted = encryptor.decrypt(bytes(data))
return {'data': decrypted}
|
[
"def",
"decrypt_report",
"(",
"self",
",",
"device_id",
",",
"root",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"report_key",
"=",
"self",
".",
"_verify_derive_key",
"(",
"device_id",
",",
"root",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"from",
"Crypto",
".",
"Cipher",
"import",
"AES",
"import",
"Crypto",
".",
"Util",
".",
"Counter",
"except",
"ImportError",
":",
"raise",
"NotFoundError",
"ctr",
"=",
"Crypto",
".",
"Util",
".",
"Counter",
".",
"new",
"(",
"128",
")",
"# We use AES-128 for encryption",
"encryptor",
"=",
"AES",
".",
"new",
"(",
"bytes",
"(",
"report_key",
"[",
":",
"16",
"]",
")",
",",
"AES",
".",
"MODE_CTR",
",",
"counter",
"=",
"ctr",
")",
"decrypted",
"=",
"encryptor",
".",
"decrypt",
"(",
"bytes",
"(",
"data",
")",
")",
"return",
"{",
"'data'",
":",
"decrypted",
"}"
] |
Decrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (bytearray): The data that we should decrypt
**kwargs: There are additional specific keyword args that are required
depending on the root key used. Typically, you must specify
- report_id (int): The report id
- sent_timestamp (int): The sent timestamp of the report
These two bits of information are used to construct the per report
signing and encryption key from the specific root key type.
Returns:
dict: The decrypted data and any associated metadata about the data.
The data itself must always be a bytearray stored under the 'data'
key, however additional keys may be present depending on the encryption method
used.
Raises:
NotFoundError: If the auth provider is not able to decrypt the data.
|
[
"Decrypt",
"a",
"buffer",
"of",
"report",
"data",
"on",
"behalf",
"of",
"a",
"device",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/env_auth_provider.py#L147-L186
|
train
|
iotile/coretools
|
iotilebuild/iotile/build/config/site_scons/utilities.py
|
join_path
|
def join_path(path):
"""If given a string, return it, otherwise combine a list into a string using os.path.join"""
if isinstance(path, str):
return path
return os.path.join(*path)
|
python
|
def join_path(path):
"""If given a string, return it, otherwise combine a list into a string using os.path.join"""
if isinstance(path, str):
return path
return os.path.join(*path)
|
[
"def",
"join_path",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"path",
")"
] |
If given a string, return it, otherwise combine a list into a string using os.path.join
|
[
"If",
"given",
"a",
"string",
"return",
"it",
"otherwise",
"combine",
"a",
"list",
"into",
"a",
"string",
"using",
"os",
".",
"path",
".",
"join"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/utilities.py#L49-L55
|
train
|
iotile/coretools
|
iotilebuild/iotile/build/config/site_scons/utilities.py
|
build_defines
|
def build_defines(defines):
"""Build a list of `-D` directives to pass to the compiler.
This will drop any definitions whose value is None so that
you can get rid of a define from another architecture by
setting its value to null in the `module_settings.json`.
"""
return ['-D"%s=%s"' % (x, str(y)) for x, y in defines.items() if y is not None]
|
python
|
def build_defines(defines):
"""Build a list of `-D` directives to pass to the compiler.
This will drop any definitions whose value is None so that
you can get rid of a define from another architecture by
setting its value to null in the `module_settings.json`.
"""
return ['-D"%s=%s"' % (x, str(y)) for x, y in defines.items() if y is not None]
|
[
"def",
"build_defines",
"(",
"defines",
")",
":",
"return",
"[",
"'-D\"%s=%s\"'",
"%",
"(",
"x",
",",
"str",
"(",
"y",
")",
")",
"for",
"x",
",",
"y",
"in",
"defines",
".",
"items",
"(",
")",
"if",
"y",
"is",
"not",
"None",
"]"
] |
Build a list of `-D` directives to pass to the compiler.
This will drop any definitions whose value is None so that
you can get rid of a define from another architecture by
setting its value to null in the `module_settings.json`.
|
[
"Build",
"a",
"list",
"of",
"-",
"D",
"directives",
"to",
"pass",
"to",
"the",
"compiler",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/utilities.py#L58-L66
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._open_interface
|
def _open_interface(self, conn_id, iface, callback):
"""Open an interface on this device
Args:
conn_id (int): the unique identifier for the connection
iface (string): the interface name to open
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
return
self.conns.begin_operation(conn_id, 'open_interface', callback, self.get_config('default_timeout'))
topics = context['topics']
open_iface_message = {'key': context['key'], 'type': 'command', 'operation': 'open_interface', 'client': self.name, 'interface': iface}
self.client.publish(topics.action, open_iface_message)
|
python
|
def _open_interface(self, conn_id, iface, callback):
"""Open an interface on this device
Args:
conn_id (int): the unique identifier for the connection
iface (string): the interface name to open
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
"""
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
return
self.conns.begin_operation(conn_id, 'open_interface', callback, self.get_config('default_timeout'))
topics = context['topics']
open_iface_message = {'key': context['key'], 'type': 'command', 'operation': 'open_interface', 'client': self.name, 'interface': iface}
self.client.publish(topics.action, open_iface_message)
|
[
"def",
"_open_interface",
"(",
"self",
",",
"conn_id",
",",
"iface",
",",
"callback",
")",
":",
"try",
":",
"context",
"=",
"self",
".",
"conns",
".",
"get_context",
"(",
"conn_id",
")",
"except",
"ArgumentError",
":",
"callback",
"(",
"conn_id",
",",
"self",
".",
"id",
",",
"False",
",",
"\"Could not find connection information\"",
")",
"return",
"self",
".",
"conns",
".",
"begin_operation",
"(",
"conn_id",
",",
"'open_interface'",
",",
"callback",
",",
"self",
".",
"get_config",
"(",
"'default_timeout'",
")",
")",
"topics",
"=",
"context",
"[",
"'topics'",
"]",
"open_iface_message",
"=",
"{",
"'key'",
":",
"context",
"[",
"'key'",
"]",
",",
"'type'",
":",
"'command'",
",",
"'operation'",
":",
"'open_interface'",
",",
"'client'",
":",
"self",
".",
"name",
",",
"'interface'",
":",
"iface",
"}",
"self",
".",
"client",
".",
"publish",
"(",
"topics",
".",
"action",
",",
"open_iface_message",
")"
] |
Open an interface on this device
Args:
conn_id (int): the unique identifier for the connection
iface (string): the interface name to open
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)
|
[
"Open",
"an",
"interface",
"on",
"this",
"device"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L259-L280
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter.stop_sync
|
def stop_sync(self):
"""Synchronously stop this adapter
"""
conn_ids = self.conns.get_connections()
# If we have any open connections, try to close them here before shutting down
for conn in list(conn_ids):
try:
self.disconnect_sync(conn)
except HardwareError:
pass
self.client.disconnect()
self.conns.stop()
|
python
|
def stop_sync(self):
"""Synchronously stop this adapter
"""
conn_ids = self.conns.get_connections()
# If we have any open connections, try to close them here before shutting down
for conn in list(conn_ids):
try:
self.disconnect_sync(conn)
except HardwareError:
pass
self.client.disconnect()
self.conns.stop()
|
[
"def",
"stop_sync",
"(",
"self",
")",
":",
"conn_ids",
"=",
"self",
".",
"conns",
".",
"get_connections",
"(",
")",
"# If we have any open connections, try to close them here before shutting down",
"for",
"conn",
"in",
"list",
"(",
"conn_ids",
")",
":",
"try",
":",
"self",
".",
"disconnect_sync",
"(",
"conn",
")",
"except",
"HardwareError",
":",
"pass",
"self",
".",
"client",
".",
"disconnect",
"(",
")",
"self",
".",
"conns",
".",
"stop",
"(",
")"
] |
Synchronously stop this adapter
|
[
"Synchronously",
"stop",
"this",
"adapter"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L282-L296
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter.probe_async
|
def probe_async(self, callback):
"""Probe for visible devices connected to this DeviceAdapter.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
success: bool
failure_reason: None if success is True, otherwise a reason for why we could not probe
"""
topics = MQTTTopicValidator(self.prefix)
self.client.publish(topics.probe, {'type': 'command', 'operation': 'probe', 'client': self.name})
callback(self.id, True, None)
|
python
|
def probe_async(self, callback):
"""Probe for visible devices connected to this DeviceAdapter.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
success: bool
failure_reason: None if success is True, otherwise a reason for why we could not probe
"""
topics = MQTTTopicValidator(self.prefix)
self.client.publish(topics.probe, {'type': 'command', 'operation': 'probe', 'client': self.name})
callback(self.id, True, None)
|
[
"def",
"probe_async",
"(",
"self",
",",
"callback",
")",
":",
"topics",
"=",
"MQTTTopicValidator",
"(",
"self",
".",
"prefix",
")",
"self",
".",
"client",
".",
"publish",
"(",
"topics",
".",
"probe",
",",
"{",
"'type'",
":",
"'command'",
",",
"'operation'",
":",
"'probe'",
",",
"'client'",
":",
"self",
".",
"name",
"}",
")",
"callback",
"(",
"self",
".",
"id",
",",
"True",
",",
"None",
")"
] |
Probe for visible devices connected to this DeviceAdapter.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
success: bool
failure_reason: None if success is True, otherwise a reason for why we could not probe
|
[
"Probe",
"for",
"visible",
"devices",
"connected",
"to",
"this",
"DeviceAdapter",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L298-L310
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter.periodic_callback
|
def periodic_callback(self):
"""Periodically help maintain adapter internal state
"""
while True:
try:
action = self._deferred.get(False)
action()
except queue.Empty:
break
except Exception:
self._logger.exception('Exception in periodic callback')
|
python
|
def periodic_callback(self):
"""Periodically help maintain adapter internal state
"""
while True:
try:
action = self._deferred.get(False)
action()
except queue.Empty:
break
except Exception:
self._logger.exception('Exception in periodic callback')
|
[
"def",
"periodic_callback",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"action",
"=",
"self",
".",
"_deferred",
".",
"get",
"(",
"False",
")",
"action",
"(",
")",
"except",
"queue",
".",
"Empty",
":",
"break",
"except",
"Exception",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Exception in periodic callback'",
")"
] |
Periodically help maintain adapter internal state
|
[
"Periodically",
"help",
"maintain",
"adapter",
"internal",
"state"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L312-L323
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._bind_topics
|
def _bind_topics(self, topics):
"""Subscribe to all the topics we need to communication with this device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we are connecting to.
"""
# FIXME: Allow for these subscriptions to fail and clean up the previous ones
# so that this function is atomic
self.client.subscribe(topics.status, self._on_status_message)
self.client.subscribe(topics.tracing, self._on_trace)
self.client.subscribe(topics.streaming, self._on_report)
self.client.subscribe(topics.response, self._on_response_message)
|
python
|
def _bind_topics(self, topics):
"""Subscribe to all the topics we need to communication with this device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we are connecting to.
"""
# FIXME: Allow for these subscriptions to fail and clean up the previous ones
# so that this function is atomic
self.client.subscribe(topics.status, self._on_status_message)
self.client.subscribe(topics.tracing, self._on_trace)
self.client.subscribe(topics.streaming, self._on_report)
self.client.subscribe(topics.response, self._on_response_message)
|
[
"def",
"_bind_topics",
"(",
"self",
",",
"topics",
")",
":",
"# FIXME: Allow for these subscriptions to fail and clean up the previous ones",
"# so that this function is atomic",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"status",
",",
"self",
".",
"_on_status_message",
")",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"tracing",
",",
"self",
".",
"_on_trace",
")",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"streaming",
",",
"self",
".",
"_on_report",
")",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"response",
",",
"self",
".",
"_on_response_message",
")"
] |
Subscribe to all the topics we need to communication with this device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we are connecting to.
|
[
"Subscribe",
"to",
"all",
"the",
"topics",
"we",
"need",
"to",
"communication",
"with",
"this",
"device"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L325-L339
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._unbind_topics
|
def _unbind_topics(self, topics):
"""Unsubscribe to all of the topics we needed for communication with device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we have connected to.
"""
self.client.unsubscribe(topics.status)
self.client.unsubscribe(topics.tracing)
self.client.unsubscribe(topics.streaming)
self.client.unsubscribe(topics.response)
|
python
|
def _unbind_topics(self, topics):
"""Unsubscribe to all of the topics we needed for communication with device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we have connected to.
"""
self.client.unsubscribe(topics.status)
self.client.unsubscribe(topics.tracing)
self.client.unsubscribe(topics.streaming)
self.client.unsubscribe(topics.response)
|
[
"def",
"_unbind_topics",
"(",
"self",
",",
"topics",
")",
":",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"status",
")",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"tracing",
")",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"streaming",
")",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"response",
")"
] |
Unsubscribe to all of the topics we needed for communication with device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we have connected to.
|
[
"Unsubscribe",
"to",
"all",
"of",
"the",
"topics",
"we",
"needed",
"for",
"communication",
"with",
"device"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L341-L352
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._find_connection
|
def _find_connection(self, topic):
"""Attempt to find a connection id corresponding with a topic
The device is found by assuming the topic ends in <slug>/[control|data]/channel
Args:
topic (string): The topic we received a message on
Returns:
int: The internal connect id (device slug) associated with this topic
"""
parts = topic.split('/')
if len(parts) < 3:
return None
slug = parts[-3]
return slug
|
python
|
def _find_connection(self, topic):
"""Attempt to find a connection id corresponding with a topic
The device is found by assuming the topic ends in <slug>/[control|data]/channel
Args:
topic (string): The topic we received a message on
Returns:
int: The internal connect id (device slug) associated with this topic
"""
parts = topic.split('/')
if len(parts) < 3:
return None
slug = parts[-3]
return slug
|
[
"def",
"_find_connection",
"(",
"self",
",",
"topic",
")",
":",
"parts",
"=",
"topic",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"parts",
")",
"<",
"3",
":",
"return",
"None",
"slug",
"=",
"parts",
"[",
"-",
"3",
"]",
"return",
"slug"
] |
Attempt to find a connection id corresponding with a topic
The device is found by assuming the topic ends in <slug>/[control|data]/channel
Args:
topic (string): The topic we received a message on
Returns:
int: The internal connect id (device slug) associated with this topic
|
[
"Attempt",
"to",
"find",
"a",
"connection",
"id",
"corresponding",
"with",
"a",
"topic"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L364-L381
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._on_report
|
def _on_report(self, sequence, topic, message):
"""Process a report received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping report message that does not correspond with a known connection, topic=%s", topic)
return
try:
rep_msg = messages.ReportNotification.verify(message)
serialized_report = {}
serialized_report['report_format'] = rep_msg['report_format']
serialized_report['encoded_report'] = rep_msg['report']
serialized_report['received_time'] = datetime.datetime.strptime(rep_msg['received_time'].encode().decode(), "%Y%m%dT%H:%M:%S.%fZ")
report = self.report_parser.deserialize_report(serialized_report)
self._trigger_callback('on_report', conn_id, report)
except Exception:
self._logger.exception("Error processing report conn_id=%d", conn_id)
|
python
|
def _on_report(self, sequence, topic, message):
"""Process a report received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping report message that does not correspond with a known connection, topic=%s", topic)
return
try:
rep_msg = messages.ReportNotification.verify(message)
serialized_report = {}
serialized_report['report_format'] = rep_msg['report_format']
serialized_report['encoded_report'] = rep_msg['report']
serialized_report['received_time'] = datetime.datetime.strptime(rep_msg['received_time'].encode().decode(), "%Y%m%dT%H:%M:%S.%fZ")
report = self.report_parser.deserialize_report(serialized_report)
self._trigger_callback('on_report', conn_id, report)
except Exception:
self._logger.exception("Error processing report conn_id=%d", conn_id)
|
[
"def",
"_on_report",
"(",
"self",
",",
"sequence",
",",
"topic",
",",
"message",
")",
":",
"try",
":",
"conn_key",
"=",
"self",
".",
"_find_connection",
"(",
"topic",
")",
"conn_id",
"=",
"self",
".",
"conns",
".",
"get_connection_id",
"(",
"conn_key",
")",
"except",
"ArgumentError",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Dropping report message that does not correspond with a known connection, topic=%s\"",
",",
"topic",
")",
"return",
"try",
":",
"rep_msg",
"=",
"messages",
".",
"ReportNotification",
".",
"verify",
"(",
"message",
")",
"serialized_report",
"=",
"{",
"}",
"serialized_report",
"[",
"'report_format'",
"]",
"=",
"rep_msg",
"[",
"'report_format'",
"]",
"serialized_report",
"[",
"'encoded_report'",
"]",
"=",
"rep_msg",
"[",
"'report'",
"]",
"serialized_report",
"[",
"'received_time'",
"]",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"rep_msg",
"[",
"'received_time'",
"]",
".",
"encode",
"(",
")",
".",
"decode",
"(",
")",
",",
"\"%Y%m%dT%H:%M:%S.%fZ\"",
")",
"report",
"=",
"self",
".",
"report_parser",
".",
"deserialize_report",
"(",
"serialized_report",
")",
"self",
".",
"_trigger_callback",
"(",
"'on_report'",
",",
"conn_id",
",",
"report",
")",
"except",
"Exception",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"\"Error processing report conn_id=%d\"",
",",
"conn_id",
")"
] |
Process a report received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
|
[
"Process",
"a",
"report",
"received",
"from",
"a",
"device",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L394-L421
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._on_trace
|
def _on_trace(self, sequence, topic, message):
"""Process a trace received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping trace message that does not correspond with a known connection, topic=%s", topic)
return
try:
tracing = messages.TracingNotification.verify(message)
self._trigger_callback('on_trace', conn_id, tracing['trace'])
except Exception:
self._logger.exception("Error processing trace conn_id=%d", conn_id)
|
python
|
def _on_trace(self, sequence, topic, message):
"""Process a trace received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping trace message that does not correspond with a known connection, topic=%s", topic)
return
try:
tracing = messages.TracingNotification.verify(message)
self._trigger_callback('on_trace', conn_id, tracing['trace'])
except Exception:
self._logger.exception("Error processing trace conn_id=%d", conn_id)
|
[
"def",
"_on_trace",
"(",
"self",
",",
"sequence",
",",
"topic",
",",
"message",
")",
":",
"try",
":",
"conn_key",
"=",
"self",
".",
"_find_connection",
"(",
"topic",
")",
"conn_id",
"=",
"self",
".",
"conns",
".",
"get_connection_id",
"(",
"conn_key",
")",
"except",
"ArgumentError",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Dropping trace message that does not correspond with a known connection, topic=%s\"",
",",
"topic",
")",
"return",
"try",
":",
"tracing",
"=",
"messages",
".",
"TracingNotification",
".",
"verify",
"(",
"message",
")",
"self",
".",
"_trigger_callback",
"(",
"'on_trace'",
",",
"conn_id",
",",
"tracing",
"[",
"'trace'",
"]",
")",
"except",
"Exception",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"\"Error processing trace conn_id=%d\"",
",",
"conn_id",
")"
] |
Process a trace received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
|
[
"Process",
"a",
"trace",
"received",
"from",
"a",
"device",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L423-L443
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._on_status_message
|
def _on_status_message(self, sequence, topic, message):
"""Process a status message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
self._logger.debug("Received message on (topic=%s): %s" % (topic, message))
try:
conn_key = self._find_connection(topic)
except ArgumentError:
self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message)
return
if messages.ConnectionResponse.matches(message):
if self.name != message['client']:
self._logger.debug("Connection response received for a different client, client=%s, name=%s", message['client'], self.name)
return
self.conns.finish_connection(conn_key, message['success'], message.get('failure_reason', None))
else:
self._logger.warn("Dropping message that did not correspond with a known schema, message=%s", message)
|
python
|
def _on_status_message(self, sequence, topic, message):
"""Process a status message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
self._logger.debug("Received message on (topic=%s): %s" % (topic, message))
try:
conn_key = self._find_connection(topic)
except ArgumentError:
self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message)
return
if messages.ConnectionResponse.matches(message):
if self.name != message['client']:
self._logger.debug("Connection response received for a different client, client=%s, name=%s", message['client'], self.name)
return
self.conns.finish_connection(conn_key, message['success'], message.get('failure_reason', None))
else:
self._logger.warn("Dropping message that did not correspond with a known schema, message=%s", message)
|
[
"def",
"_on_status_message",
"(",
"self",
",",
"sequence",
",",
"topic",
",",
"message",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Received message on (topic=%s): %s\"",
"%",
"(",
"topic",
",",
"message",
")",
")",
"try",
":",
"conn_key",
"=",
"self",
".",
"_find_connection",
"(",
"topic",
")",
"except",
"ArgumentError",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Dropping message that does not correspond with a known connection, message=%s\"",
",",
"message",
")",
"return",
"if",
"messages",
".",
"ConnectionResponse",
".",
"matches",
"(",
"message",
")",
":",
"if",
"self",
".",
"name",
"!=",
"message",
"[",
"'client'",
"]",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Connection response received for a different client, client=%s, name=%s\"",
",",
"message",
"[",
"'client'",
"]",
",",
"self",
".",
"name",
")",
"return",
"self",
".",
"conns",
".",
"finish_connection",
"(",
"conn_key",
",",
"message",
"[",
"'success'",
"]",
",",
"message",
".",
"get",
"(",
"'failure_reason'",
",",
"None",
")",
")",
"else",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Dropping message that did not correspond with a known schema, message=%s\"",
",",
"message",
")"
] |
Process a status message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
|
[
"Process",
"a",
"status",
"message",
"received"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L445-L469
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
|
AWSIOTDeviceAdapter._on_response_message
|
def _on_response_message(self, sequence, topic, message):
"""Process a response message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
try:
conn_key = self._find_connection(topic)
context = self.conns.get_context(conn_key)
except ArgumentError:
self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message)
return
if 'client' in message and message['client'] != self.name:
self._logger.debug("Dropping message that is for another client %s, we are %s", message['client'], self.name)
if messages.DisconnectionResponse.matches(message):
self.conns.finish_disconnection(conn_key, message['success'], message.get('failure_reason', None))
elif messages.OpenInterfaceResponse.matches(message):
self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None))
elif messages.RPCResponse.matches(message):
rpc_message = messages.RPCResponse.verify(message)
self.conns.finish_operation(conn_key, rpc_message['success'], rpc_message.get('failure_reason', None), rpc_message.get('status', None), rpc_message.get('payload', None))
elif messages.ProgressNotification.matches(message):
progress_callback = context.get('progress_callback', None)
if progress_callback is not None:
progress_callback(message['done_count'], message['total_count'])
elif messages.ScriptResponse.matches(message):
if 'progress_callback' in context:
del context['progress_callback']
self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None))
elif messages.DisconnectionNotification.matches(message):
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping disconnect notification that does not correspond with a known connection, topic=%s", topic)
return
self.conns.unexpected_disconnect(conn_key)
self._trigger_callback('on_disconnect', self.id, conn_id)
else:
self._logger.warn("Invalid response message received, message=%s", message)
|
python
|
def _on_response_message(self, sequence, topic, message):
"""Process a response message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
try:
conn_key = self._find_connection(topic)
context = self.conns.get_context(conn_key)
except ArgumentError:
self._logger.warn("Dropping message that does not correspond with a known connection, message=%s", message)
return
if 'client' in message and message['client'] != self.name:
self._logger.debug("Dropping message that is for another client %s, we are %s", message['client'], self.name)
if messages.DisconnectionResponse.matches(message):
self.conns.finish_disconnection(conn_key, message['success'], message.get('failure_reason', None))
elif messages.OpenInterfaceResponse.matches(message):
self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None))
elif messages.RPCResponse.matches(message):
rpc_message = messages.RPCResponse.verify(message)
self.conns.finish_operation(conn_key, rpc_message['success'], rpc_message.get('failure_reason', None), rpc_message.get('status', None), rpc_message.get('payload', None))
elif messages.ProgressNotification.matches(message):
progress_callback = context.get('progress_callback', None)
if progress_callback is not None:
progress_callback(message['done_count'], message['total_count'])
elif messages.ScriptResponse.matches(message):
if 'progress_callback' in context:
del context['progress_callback']
self.conns.finish_operation(conn_key, message['success'], message.get('failure_reason', None))
elif messages.DisconnectionNotification.matches(message):
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping disconnect notification that does not correspond with a known connection, topic=%s", topic)
return
self.conns.unexpected_disconnect(conn_key)
self._trigger_callback('on_disconnect', self.id, conn_id)
else:
self._logger.warn("Invalid response message received, message=%s", message)
|
[
"def",
"_on_response_message",
"(",
"self",
",",
"sequence",
",",
"topic",
",",
"message",
")",
":",
"try",
":",
"conn_key",
"=",
"self",
".",
"_find_connection",
"(",
"topic",
")",
"context",
"=",
"self",
".",
"conns",
".",
"get_context",
"(",
"conn_key",
")",
"except",
"ArgumentError",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Dropping message that does not correspond with a known connection, message=%s\"",
",",
"message",
")",
"return",
"if",
"'client'",
"in",
"message",
"and",
"message",
"[",
"'client'",
"]",
"!=",
"self",
".",
"name",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Dropping message that is for another client %s, we are %s\"",
",",
"message",
"[",
"'client'",
"]",
",",
"self",
".",
"name",
")",
"if",
"messages",
".",
"DisconnectionResponse",
".",
"matches",
"(",
"message",
")",
":",
"self",
".",
"conns",
".",
"finish_disconnection",
"(",
"conn_key",
",",
"message",
"[",
"'success'",
"]",
",",
"message",
".",
"get",
"(",
"'failure_reason'",
",",
"None",
")",
")",
"elif",
"messages",
".",
"OpenInterfaceResponse",
".",
"matches",
"(",
"message",
")",
":",
"self",
".",
"conns",
".",
"finish_operation",
"(",
"conn_key",
",",
"message",
"[",
"'success'",
"]",
",",
"message",
".",
"get",
"(",
"'failure_reason'",
",",
"None",
")",
")",
"elif",
"messages",
".",
"RPCResponse",
".",
"matches",
"(",
"message",
")",
":",
"rpc_message",
"=",
"messages",
".",
"RPCResponse",
".",
"verify",
"(",
"message",
")",
"self",
".",
"conns",
".",
"finish_operation",
"(",
"conn_key",
",",
"rpc_message",
"[",
"'success'",
"]",
",",
"rpc_message",
".",
"get",
"(",
"'failure_reason'",
",",
"None",
")",
",",
"rpc_message",
".",
"get",
"(",
"'status'",
",",
"None",
")",
",",
"rpc_message",
".",
"get",
"(",
"'payload'",
",",
"None",
")",
")",
"elif",
"messages",
".",
"ProgressNotification",
".",
"matches",
"(",
"message",
")",
":",
"progress_callback",
"=",
"context",
".",
"get",
"(",
"'progress_callback'",
",",
"None",
")",
"if",
"progress_callback",
"is",
"not",
"None",
":",
"progress_callback",
"(",
"message",
"[",
"'done_count'",
"]",
",",
"message",
"[",
"'total_count'",
"]",
")",
"elif",
"messages",
".",
"ScriptResponse",
".",
"matches",
"(",
"message",
")",
":",
"if",
"'progress_callback'",
"in",
"context",
":",
"del",
"context",
"[",
"'progress_callback'",
"]",
"self",
".",
"conns",
".",
"finish_operation",
"(",
"conn_key",
",",
"message",
"[",
"'success'",
"]",
",",
"message",
".",
"get",
"(",
"'failure_reason'",
",",
"None",
")",
")",
"elif",
"messages",
".",
"DisconnectionNotification",
".",
"matches",
"(",
"message",
")",
":",
"try",
":",
"conn_key",
"=",
"self",
".",
"_find_connection",
"(",
"topic",
")",
"conn_id",
"=",
"self",
".",
"conns",
".",
"get_connection_id",
"(",
"conn_key",
")",
"except",
"ArgumentError",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Dropping disconnect notification that does not correspond with a known connection, topic=%s\"",
",",
"topic",
")",
"return",
"self",
".",
"conns",
".",
"unexpected_disconnect",
"(",
"conn_key",
")",
"self",
".",
"_trigger_callback",
"(",
"'on_disconnect'",
",",
"self",
".",
"id",
",",
"conn_id",
")",
"else",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"Invalid response message received, message=%s\"",
",",
"message",
")"
] |
Process a response message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
|
[
"Process",
"a",
"response",
"message",
"received"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L471-L517
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py
|
write_output
|
def write_output(output, text=True, output_path=None):
"""Write binary or text output to a file or stdout."""
if output_path is None and text is False:
print("ERROR: You must specify an output file using -o/--output for binary output formats")
sys.exit(1)
if output_path is not None:
if text:
outfile = open(output_path, "w", encoding="utf-8")
else:
outfile = open(output_path, "wb")
else:
outfile = sys.stdout
try:
if text and isinstance(output, bytes):
output = output.decode('utf-8')
outfile.write(output)
finally:
if outfile is not sys.stdout:
outfile.close()
|
python
|
def write_output(output, text=True, output_path=None):
"""Write binary or text output to a file or stdout."""
if output_path is None and text is False:
print("ERROR: You must specify an output file using -o/--output for binary output formats")
sys.exit(1)
if output_path is not None:
if text:
outfile = open(output_path, "w", encoding="utf-8")
else:
outfile = open(output_path, "wb")
else:
outfile = sys.stdout
try:
if text and isinstance(output, bytes):
output = output.decode('utf-8')
outfile.write(output)
finally:
if outfile is not sys.stdout:
outfile.close()
|
[
"def",
"write_output",
"(",
"output",
",",
"text",
"=",
"True",
",",
"output_path",
"=",
"None",
")",
":",
"if",
"output_path",
"is",
"None",
"and",
"text",
"is",
"False",
":",
"print",
"(",
"\"ERROR: You must specify an output file using -o/--output for binary output formats\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"output_path",
"is",
"not",
"None",
":",
"if",
"text",
":",
"outfile",
"=",
"open",
"(",
"output_path",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"else",
":",
"outfile",
"=",
"open",
"(",
"output_path",
",",
"\"wb\"",
")",
"else",
":",
"outfile",
"=",
"sys",
".",
"stdout",
"try",
":",
"if",
"text",
"and",
"isinstance",
"(",
"output",
",",
"bytes",
")",
":",
"output",
"=",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
"outfile",
".",
"write",
"(",
"output",
")",
"finally",
":",
"if",
"outfile",
"is",
"not",
"sys",
".",
"stdout",
":",
"outfile",
".",
"close",
"(",
")"
] |
Write binary or text output to a file or stdout.
|
[
"Write",
"binary",
"or",
"text",
"output",
"to",
"a",
"file",
"or",
"stdout",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py#L23-L45
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py
|
main
|
def main():
"""Main entry point for iotile-sgcompile."""
arg_parser = build_args()
args = arg_parser.parse_args()
model = DeviceModel()
parser = SensorGraphFileParser()
parser.parse_file(args.sensor_graph)
if args.format == u'ast':
write_output(parser.dump_tree(), True, args.output)
sys.exit(0)
parser.compile(model)
if not args.disable_optimizer:
opt = SensorGraphOptimizer()
opt.optimize(parser.sensor_graph, model=model)
if args.format == u'nodes':
output = u'\n'.join(parser.sensor_graph.dump_nodes()) + u'\n'
write_output(output, True, args.output)
else:
if args.format not in KNOWN_FORMATS:
print("Unknown output format: {}".format(args.format))
sys.exit(1)
output_format = KNOWN_FORMATS[args.format]
output = output_format.format(parser.sensor_graph)
write_output(output, output_format.text, args.output)
|
python
|
def main():
"""Main entry point for iotile-sgcompile."""
arg_parser = build_args()
args = arg_parser.parse_args()
model = DeviceModel()
parser = SensorGraphFileParser()
parser.parse_file(args.sensor_graph)
if args.format == u'ast':
write_output(parser.dump_tree(), True, args.output)
sys.exit(0)
parser.compile(model)
if not args.disable_optimizer:
opt = SensorGraphOptimizer()
opt.optimize(parser.sensor_graph, model=model)
if args.format == u'nodes':
output = u'\n'.join(parser.sensor_graph.dump_nodes()) + u'\n'
write_output(output, True, args.output)
else:
if args.format not in KNOWN_FORMATS:
print("Unknown output format: {}".format(args.format))
sys.exit(1)
output_format = KNOWN_FORMATS[args.format]
output = output_format.format(parser.sensor_graph)
write_output(output, output_format.text, args.output)
|
[
"def",
"main",
"(",
")",
":",
"arg_parser",
"=",
"build_args",
"(",
")",
"args",
"=",
"arg_parser",
".",
"parse_args",
"(",
")",
"model",
"=",
"DeviceModel",
"(",
")",
"parser",
"=",
"SensorGraphFileParser",
"(",
")",
"parser",
".",
"parse_file",
"(",
"args",
".",
"sensor_graph",
")",
"if",
"args",
".",
"format",
"==",
"u'ast'",
":",
"write_output",
"(",
"parser",
".",
"dump_tree",
"(",
")",
",",
"True",
",",
"args",
".",
"output",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"parser",
".",
"compile",
"(",
"model",
")",
"if",
"not",
"args",
".",
"disable_optimizer",
":",
"opt",
"=",
"SensorGraphOptimizer",
"(",
")",
"opt",
".",
"optimize",
"(",
"parser",
".",
"sensor_graph",
",",
"model",
"=",
"model",
")",
"if",
"args",
".",
"format",
"==",
"u'nodes'",
":",
"output",
"=",
"u'\\n'",
".",
"join",
"(",
"parser",
".",
"sensor_graph",
".",
"dump_nodes",
"(",
")",
")",
"+",
"u'\\n'",
"write_output",
"(",
"output",
",",
"True",
",",
"args",
".",
"output",
")",
"else",
":",
"if",
"args",
".",
"format",
"not",
"in",
"KNOWN_FORMATS",
":",
"print",
"(",
"\"Unknown output format: {}\"",
".",
"format",
"(",
"args",
".",
"format",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"output_format",
"=",
"KNOWN_FORMATS",
"[",
"args",
".",
"format",
"]",
"output",
"=",
"output_format",
".",
"format",
"(",
"parser",
".",
"sensor_graph",
")",
"write_output",
"(",
"output",
",",
"output_format",
".",
"text",
",",
"args",
".",
"output",
")"
] |
Main entry point for iotile-sgcompile.
|
[
"Main",
"entry",
"point",
"for",
"iotile",
"-",
"sgcompile",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py#L48-L80
|
train
|
iotile/coretools
|
iotilecore/iotile/core/utilities/typedargs/__init__.py
|
load_external_components
|
def load_external_components(typesys):
"""Load all external types defined by iotile plugins.
This allows plugins to register their own types for type annotations and
allows all registered iotile components that have associated type libraries to
add themselves to the global type system.
"""
# Find all of the registered IOTile components and see if we need to add any type libraries for them
from iotile.core.dev.registry import ComponentRegistry
reg = ComponentRegistry()
modules = reg.list_components()
typelibs = reduce(lambda x, y: x+y, [reg.find_component(x).find_products('type_package') for x in modules], [])
for lib in typelibs:
if lib.endswith('.py'):
lib = lib[:-3]
typesys.load_external_types(lib)
|
python
|
def load_external_components(typesys):
"""Load all external types defined by iotile plugins.
This allows plugins to register their own types for type annotations and
allows all registered iotile components that have associated type libraries to
add themselves to the global type system.
"""
# Find all of the registered IOTile components and see if we need to add any type libraries for them
from iotile.core.dev.registry import ComponentRegistry
reg = ComponentRegistry()
modules = reg.list_components()
typelibs = reduce(lambda x, y: x+y, [reg.find_component(x).find_products('type_package') for x in modules], [])
for lib in typelibs:
if lib.endswith('.py'):
lib = lib[:-3]
typesys.load_external_types(lib)
|
[
"def",
"load_external_components",
"(",
"typesys",
")",
":",
"# Find all of the registered IOTile components and see if we need to add any type libraries for them",
"from",
"iotile",
".",
"core",
".",
"dev",
".",
"registry",
"import",
"ComponentRegistry",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"modules",
"=",
"reg",
".",
"list_components",
"(",
")",
"typelibs",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"[",
"reg",
".",
"find_component",
"(",
"x",
")",
".",
"find_products",
"(",
"'type_package'",
")",
"for",
"x",
"in",
"modules",
"]",
",",
"[",
"]",
")",
"for",
"lib",
"in",
"typelibs",
":",
"if",
"lib",
".",
"endswith",
"(",
"'.py'",
")",
":",
"lib",
"=",
"lib",
"[",
":",
"-",
"3",
"]",
"typesys",
".",
"load_external_types",
"(",
"lib",
")"
] |
Load all external types defined by iotile plugins.
This allows plugins to register their own types for type annotations and
allows all registered iotile components that have associated type libraries to
add themselves to the global type system.
|
[
"Load",
"all",
"external",
"types",
"defined",
"by",
"iotile",
"plugins",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/typedargs/__init__.py#L10-L29
|
train
|
iotile/coretools
|
iotileship/iotile/ship/recipe_manager.py
|
RecipeManager.add_recipe_folder
|
def add_recipe_folder(self, recipe_folder, whitelist=None):
"""Add all recipes inside a folder to this RecipeManager with an optional whitelist.
Args:
recipe_folder (str): The path to the folder of recipes to add.
whitelist (list): Only include files whose os.basename() matches something
on the whitelist
"""
if whitelist is not None:
whitelist = set(whitelist)
if recipe_folder == '':
recipe_folder = '.'
for yaml_file in [x for x in os.listdir(recipe_folder) if x.endswith('.yaml')]:
if whitelist is not None and yaml_file not in whitelist:
continue
recipe = RecipeObject.FromFile(os.path.join(recipe_folder, yaml_file), self._recipe_actions, self._recipe_resources)
self._recipes[recipe.name] = recipe
for ship_file in [x for x in os.listdir(recipe_folder) if x.endswith('.ship')]:
if whitelist is not None and ship_file not in whitelist:
continue
recipe = RecipeObject.FromArchive(os.path.join(recipe_folder, ship_file), self._recipe_actions, self._recipe_resources)
self._recipes[recipe.name] = recipe
|
python
|
def add_recipe_folder(self, recipe_folder, whitelist=None):
"""Add all recipes inside a folder to this RecipeManager with an optional whitelist.
Args:
recipe_folder (str): The path to the folder of recipes to add.
whitelist (list): Only include files whose os.basename() matches something
on the whitelist
"""
if whitelist is not None:
whitelist = set(whitelist)
if recipe_folder == '':
recipe_folder = '.'
for yaml_file in [x for x in os.listdir(recipe_folder) if x.endswith('.yaml')]:
if whitelist is not None and yaml_file not in whitelist:
continue
recipe = RecipeObject.FromFile(os.path.join(recipe_folder, yaml_file), self._recipe_actions, self._recipe_resources)
self._recipes[recipe.name] = recipe
for ship_file in [x for x in os.listdir(recipe_folder) if x.endswith('.ship')]:
if whitelist is not None and ship_file not in whitelist:
continue
recipe = RecipeObject.FromArchive(os.path.join(recipe_folder, ship_file), self._recipe_actions, self._recipe_resources)
self._recipes[recipe.name] = recipe
|
[
"def",
"add_recipe_folder",
"(",
"self",
",",
"recipe_folder",
",",
"whitelist",
"=",
"None",
")",
":",
"if",
"whitelist",
"is",
"not",
"None",
":",
"whitelist",
"=",
"set",
"(",
"whitelist",
")",
"if",
"recipe_folder",
"==",
"''",
":",
"recipe_folder",
"=",
"'.'",
"for",
"yaml_file",
"in",
"[",
"x",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"recipe_folder",
")",
"if",
"x",
".",
"endswith",
"(",
"'.yaml'",
")",
"]",
":",
"if",
"whitelist",
"is",
"not",
"None",
"and",
"yaml_file",
"not",
"in",
"whitelist",
":",
"continue",
"recipe",
"=",
"RecipeObject",
".",
"FromFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"recipe_folder",
",",
"yaml_file",
")",
",",
"self",
".",
"_recipe_actions",
",",
"self",
".",
"_recipe_resources",
")",
"self",
".",
"_recipes",
"[",
"recipe",
".",
"name",
"]",
"=",
"recipe",
"for",
"ship_file",
"in",
"[",
"x",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"recipe_folder",
")",
"if",
"x",
".",
"endswith",
"(",
"'.ship'",
")",
"]",
":",
"if",
"whitelist",
"is",
"not",
"None",
"and",
"ship_file",
"not",
"in",
"whitelist",
":",
"continue",
"recipe",
"=",
"RecipeObject",
".",
"FromArchive",
"(",
"os",
".",
"path",
".",
"join",
"(",
"recipe_folder",
",",
"ship_file",
")",
",",
"self",
".",
"_recipe_actions",
",",
"self",
".",
"_recipe_resources",
")",
"self",
".",
"_recipes",
"[",
"recipe",
".",
"name",
"]",
"=",
"recipe"
] |
Add all recipes inside a folder to this RecipeManager with an optional whitelist.
Args:
recipe_folder (str): The path to the folder of recipes to add.
whitelist (list): Only include files whose os.basename() matches something
on the whitelist
|
[
"Add",
"all",
"recipes",
"inside",
"a",
"folder",
"to",
"this",
"RecipeManager",
"with",
"an",
"optional",
"whitelist",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe_manager.py#L58-L85
|
train
|
iotile/coretools
|
iotileship/iotile/ship/recipe_manager.py
|
RecipeManager.add_recipe_actions
|
def add_recipe_actions(self, recipe_actions):
"""Add additional valid recipe actions to RecipeManager
args:
recipe_actions (list): List of tuples. First value of tuple is the classname,
second value of tuple is RecipeAction Object
"""
for action_name, action in recipe_actions:
self._recipe_actions[action_name] = action
|
python
|
def add_recipe_actions(self, recipe_actions):
"""Add additional valid recipe actions to RecipeManager
args:
recipe_actions (list): List of tuples. First value of tuple is the classname,
second value of tuple is RecipeAction Object
"""
for action_name, action in recipe_actions:
self._recipe_actions[action_name] = action
|
[
"def",
"add_recipe_actions",
"(",
"self",
",",
"recipe_actions",
")",
":",
"for",
"action_name",
",",
"action",
"in",
"recipe_actions",
":",
"self",
".",
"_recipe_actions",
"[",
"action_name",
"]",
"=",
"action"
] |
Add additional valid recipe actions to RecipeManager
args:
recipe_actions (list): List of tuples. First value of tuple is the classname,
second value of tuple is RecipeAction Object
|
[
"Add",
"additional",
"valid",
"recipe",
"actions",
"to",
"RecipeManager"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe_manager.py#L87-L96
|
train
|
iotile/coretools
|
iotileship/iotile/ship/recipe_manager.py
|
RecipeManager.get_recipe
|
def get_recipe(self, recipe_name):
"""Get a recipe by name.
Args:
recipe_name (str): The name of the recipe to fetch. Can be either the
yaml file name or the name of the recipe.
"""
if recipe_name.endswith('.yaml'):
recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name)
else:
recipe = self._recipes.get(recipe_name)
if recipe is None:
raise RecipeNotFoundError("Could not find recipe", recipe_name=recipe_name, known_recipes=[x for x in self._recipes.keys()])
return recipe
|
python
|
def get_recipe(self, recipe_name):
"""Get a recipe by name.
Args:
recipe_name (str): The name of the recipe to fetch. Can be either the
yaml file name or the name of the recipe.
"""
if recipe_name.endswith('.yaml'):
recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name)
else:
recipe = self._recipes.get(recipe_name)
if recipe is None:
raise RecipeNotFoundError("Could not find recipe", recipe_name=recipe_name, known_recipes=[x for x in self._recipes.keys()])
return recipe
|
[
"def",
"get_recipe",
"(",
"self",
",",
"recipe_name",
")",
":",
"if",
"recipe_name",
".",
"endswith",
"(",
"'.yaml'",
")",
":",
"recipe",
"=",
"self",
".",
"_recipes",
".",
"get",
"(",
"RecipeObject",
".",
"FromFile",
"(",
"recipe_name",
",",
"self",
".",
"_recipe_actions",
",",
"self",
".",
"_recipe_resources",
")",
".",
"name",
")",
"else",
":",
"recipe",
"=",
"self",
".",
"_recipes",
".",
"get",
"(",
"recipe_name",
")",
"if",
"recipe",
"is",
"None",
":",
"raise",
"RecipeNotFoundError",
"(",
"\"Could not find recipe\"",
",",
"recipe_name",
"=",
"recipe_name",
",",
"known_recipes",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_recipes",
".",
"keys",
"(",
")",
"]",
")",
"return",
"recipe"
] |
Get a recipe by name.
Args:
recipe_name (str): The name of the recipe to fetch. Can be either the
yaml file name or the name of the recipe.
|
[
"Get",
"a",
"recipe",
"by",
"name",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe_manager.py#L98-L112
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/timeout.py
|
TimeoutInterval._check_time_backwards
|
def _check_time_backwards(self):
"""Make sure a clock reset didn't cause time to go backwards
"""
now = time.time()
if now < self.start:
self.start = now
self.end = self.start + self.length
|
python
|
def _check_time_backwards(self):
"""Make sure a clock reset didn't cause time to go backwards
"""
now = time.time()
if now < self.start:
self.start = now
self.end = self.start + self.length
|
[
"def",
"_check_time_backwards",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"now",
"<",
"self",
".",
"start",
":",
"self",
".",
"start",
"=",
"now",
"self",
".",
"end",
"=",
"self",
".",
"start",
"+",
"self",
".",
"length"
] |
Make sure a clock reset didn't cause time to go backwards
|
[
"Make",
"sure",
"a",
"clock",
"reset",
"didn",
"t",
"cause",
"time",
"to",
"go",
"backwards"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/timeout.py#L27-L35
|
train
|
iotile/coretools
|
transport_plugins/awsiot/iotile_transport_awsiot/timeout.py
|
TimeoutInterval.expired
|
def expired(self):
"""Boolean property if this timeout has expired
"""
if self._expired_latch:
return True
self._check_time_backwards()
if time.time() > self.end:
self._expired_latch = True
return True
return False
|
python
|
def expired(self):
"""Boolean property if this timeout has expired
"""
if self._expired_latch:
return True
self._check_time_backwards()
if time.time() > self.end:
self._expired_latch = True
return True
return False
|
[
"def",
"expired",
"(",
"self",
")",
":",
"if",
"self",
".",
"_expired_latch",
":",
"return",
"True",
"self",
".",
"_check_time_backwards",
"(",
")",
"if",
"time",
".",
"time",
"(",
")",
">",
"self",
".",
"end",
":",
"self",
".",
"_expired_latch",
"=",
"True",
"return",
"True",
"return",
"False"
] |
Boolean property if this timeout has expired
|
[
"Boolean",
"property",
"if",
"this",
"timeout",
"has",
"expired"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/timeout.py#L38-L50
|
train
|
iotile/coretools
|
transport_plugins/jlink/iotile_transport_jlink/jlink_background.py
|
JLinkControlThread.command
|
def command(self, cmd_name, callback, *args):
"""Run an asynchronous command.
Args:
cmd_name (int): The unique code for the command to execute.
callback (callable): The optional callback to run when the command finishes.
The signature should be callback(cmd_name, result, exception)
*args: Any arguments that are passed to the underlying command handler
"""
cmd = JLinkCommand(cmd_name, args, callback)
self._commands.put(cmd)
|
python
|
def command(self, cmd_name, callback, *args):
"""Run an asynchronous command.
Args:
cmd_name (int): The unique code for the command to execute.
callback (callable): The optional callback to run when the command finishes.
The signature should be callback(cmd_name, result, exception)
*args: Any arguments that are passed to the underlying command handler
"""
cmd = JLinkCommand(cmd_name, args, callback)
self._commands.put(cmd)
|
[
"def",
"command",
"(",
"self",
",",
"cmd_name",
",",
"callback",
",",
"*",
"args",
")",
":",
"cmd",
"=",
"JLinkCommand",
"(",
"cmd_name",
",",
"args",
",",
"callback",
")",
"self",
".",
"_commands",
".",
"put",
"(",
"cmd",
")"
] |
Run an asynchronous command.
Args:
cmd_name (int): The unique code for the command to execute.
callback (callable): The optional callback to run when the command finishes.
The signature should be callback(cmd_name, result, exception)
*args: Any arguments that are passed to the underlying command handler
|
[
"Run",
"an",
"asynchronous",
"command",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L96-L106
|
train
|
iotile/coretools
|
transport_plugins/jlink/iotile_transport_jlink/jlink_background.py
|
JLinkControlThread._send_rpc
|
def _send_rpc(self, device_info, control_info, address, rpc_id, payload, poll_interval, timeout):
"""Write and trigger an RPC."""
write_address, write_data = control_info.format_rpc(address, rpc_id, payload)
self._jlink.memory_write32(write_address, write_data)
self._trigger_rpc(device_info)
start = monotonic()
now = start
poll_address, poll_mask = control_info.poll_info()
while (now - start) < timeout:
time.sleep(poll_interval)
value, = self._jlink.memory_read8(poll_address, 1)
if value & poll_mask:
break
now = monotonic()
if (now - start) >= timeout:
raise HardwareError("Timeout waiting for RPC response", timeout=timeout, poll_interval=poll_interval)
read_address, read_length = control_info.response_info()
read_data = self._read_memory(read_address, read_length, join=True)
return control_info.format_response(read_data)
|
python
|
def _send_rpc(self, device_info, control_info, address, rpc_id, payload, poll_interval, timeout):
"""Write and trigger an RPC."""
write_address, write_data = control_info.format_rpc(address, rpc_id, payload)
self._jlink.memory_write32(write_address, write_data)
self._trigger_rpc(device_info)
start = monotonic()
now = start
poll_address, poll_mask = control_info.poll_info()
while (now - start) < timeout:
time.sleep(poll_interval)
value, = self._jlink.memory_read8(poll_address, 1)
if value & poll_mask:
break
now = monotonic()
if (now - start) >= timeout:
raise HardwareError("Timeout waiting for RPC response", timeout=timeout, poll_interval=poll_interval)
read_address, read_length = control_info.response_info()
read_data = self._read_memory(read_address, read_length, join=True)
return control_info.format_response(read_data)
|
[
"def",
"_send_rpc",
"(",
"self",
",",
"device_info",
",",
"control_info",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"poll_interval",
",",
"timeout",
")",
":",
"write_address",
",",
"write_data",
"=",
"control_info",
".",
"format_rpc",
"(",
"address",
",",
"rpc_id",
",",
"payload",
")",
"self",
".",
"_jlink",
".",
"memory_write32",
"(",
"write_address",
",",
"write_data",
")",
"self",
".",
"_trigger_rpc",
"(",
"device_info",
")",
"start",
"=",
"monotonic",
"(",
")",
"now",
"=",
"start",
"poll_address",
",",
"poll_mask",
"=",
"control_info",
".",
"poll_info",
"(",
")",
"while",
"(",
"now",
"-",
"start",
")",
"<",
"timeout",
":",
"time",
".",
"sleep",
"(",
"poll_interval",
")",
"value",
",",
"=",
"self",
".",
"_jlink",
".",
"memory_read8",
"(",
"poll_address",
",",
"1",
")",
"if",
"value",
"&",
"poll_mask",
":",
"break",
"now",
"=",
"monotonic",
"(",
")",
"if",
"(",
"now",
"-",
"start",
")",
">=",
"timeout",
":",
"raise",
"HardwareError",
"(",
"\"Timeout waiting for RPC response\"",
",",
"timeout",
"=",
"timeout",
",",
"poll_interval",
"=",
"poll_interval",
")",
"read_address",
",",
"read_length",
"=",
"control_info",
".",
"response_info",
"(",
")",
"read_data",
"=",
"self",
".",
"_read_memory",
"(",
"read_address",
",",
"read_length",
",",
"join",
"=",
"True",
")",
"return",
"control_info",
".",
"format_response",
"(",
"read_data",
")"
] |
Write and trigger an RPC.
|
[
"Write",
"and",
"trigger",
"an",
"RPC",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L112-L140
|
train
|
iotile/coretools
|
transport_plugins/jlink/iotile_transport_jlink/jlink_background.py
|
JLinkControlThread._send_script
|
def _send_script(self, device_info, control_info, script, progress_callback):
"""Send a script by repeatedly sending it as a bunch of RPCs.
This function doesn't do anything special, it just sends a bunch of RPCs
with each chunk of the script until it's finished.
"""
for i in range(0, len(script), 20):
chunk = script[i:i+20]
self._send_rpc(device_info, control_info, 8, 0x2101, chunk, 0.001, 1.0)
if progress_callback is not None:
progress_callback(i + len(chunk), len(script))
|
python
|
def _send_script(self, device_info, control_info, script, progress_callback):
"""Send a script by repeatedly sending it as a bunch of RPCs.
This function doesn't do anything special, it just sends a bunch of RPCs
with each chunk of the script until it's finished.
"""
for i in range(0, len(script), 20):
chunk = script[i:i+20]
self._send_rpc(device_info, control_info, 8, 0x2101, chunk, 0.001, 1.0)
if progress_callback is not None:
progress_callback(i + len(chunk), len(script))
|
[
"def",
"_send_script",
"(",
"self",
",",
"device_info",
",",
"control_info",
",",
"script",
",",
"progress_callback",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"script",
")",
",",
"20",
")",
":",
"chunk",
"=",
"script",
"[",
"i",
":",
"i",
"+",
"20",
"]",
"self",
".",
"_send_rpc",
"(",
"device_info",
",",
"control_info",
",",
"8",
",",
"0x2101",
",",
"chunk",
",",
"0.001",
",",
"1.0",
")",
"if",
"progress_callback",
"is",
"not",
"None",
":",
"progress_callback",
"(",
"i",
"+",
"len",
"(",
"chunk",
")",
",",
"len",
"(",
"script",
")",
")"
] |
Send a script by repeatedly sending it as a bunch of RPCs.
This function doesn't do anything special, it just sends a bunch of RPCs
with each chunk of the script until it's finished.
|
[
"Send",
"a",
"script",
"by",
"repeatedly",
"sending",
"it",
"as",
"a",
"bunch",
"of",
"RPCs",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L142-L153
|
train
|
iotile/coretools
|
transport_plugins/jlink/iotile_transport_jlink/jlink_background.py
|
JLinkControlThread._trigger_rpc
|
def _trigger_rpc(self, device_info):
"""Trigger an RPC in a device specific way."""
method = device_info.rpc_trigger
if isinstance(method, devices.RPCTriggerViaSWI):
self._jlink.memory_write32(method.register, [1 << method.bit])
else:
raise HardwareError("Unknown RPC trigger method", method=method)
|
python
|
def _trigger_rpc(self, device_info):
"""Trigger an RPC in a device specific way."""
method = device_info.rpc_trigger
if isinstance(method, devices.RPCTriggerViaSWI):
self._jlink.memory_write32(method.register, [1 << method.bit])
else:
raise HardwareError("Unknown RPC trigger method", method=method)
|
[
"def",
"_trigger_rpc",
"(",
"self",
",",
"device_info",
")",
":",
"method",
"=",
"device_info",
".",
"rpc_trigger",
"if",
"isinstance",
"(",
"method",
",",
"devices",
".",
"RPCTriggerViaSWI",
")",
":",
"self",
".",
"_jlink",
".",
"memory_write32",
"(",
"method",
".",
"register",
",",
"[",
"1",
"<<",
"method",
".",
"bit",
"]",
")",
"else",
":",
"raise",
"HardwareError",
"(",
"\"Unknown RPC trigger method\"",
",",
"method",
"=",
"method",
")"
] |
Trigger an RPC in a device specific way.
|
[
"Trigger",
"an",
"RPC",
"in",
"a",
"device",
"specific",
"way",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L155-L162
|
train
|
iotile/coretools
|
transport_plugins/jlink/iotile_transport_jlink/jlink_background.py
|
JLinkControlThread._find_control_structure
|
def _find_control_structure(self, start_address, search_length):
"""Find the control structure in RAM for this device.
Returns:
ControlStructure: The decoded contents of the shared memory control structure
used for communication with this IOTile device.
"""
words = self._read_memory(start_address, search_length, chunk_size=4, join=False)
found_offset = None
for i, word in enumerate(words):
if word == ControlStructure.CONTROL_MAGIC_1:
if (len(words) - i) < 4:
continue
if words[i + 1] == ControlStructure.CONTROL_MAGIC_2 and words[i + 2] == ControlStructure.CONTROL_MAGIC_3 and words[i + 3] == ControlStructure.CONTROL_MAGIC_4:
found_offset = i
break
if found_offset is None:
raise HardwareError("Could not find control structure magic value in search area")
struct_info = words[found_offset + 4]
_version, _flags, length = struct.unpack("<BBH", struct.pack("<L", struct_info))
if length % 4 != 0:
raise HardwareError("Invalid control structure length that was not a multiple of 4", length=length)
word_length = length // 4
control_data = struct.pack("<%dL" % word_length, *words[found_offset:found_offset + word_length])
logger.info("Found control stucture at address 0x%08X, word_length=%d", start_address + 4*found_offset, word_length)
return ControlStructure(start_address + 4*found_offset, control_data)
|
python
|
def _find_control_structure(self, start_address, search_length):
"""Find the control structure in RAM for this device.
Returns:
ControlStructure: The decoded contents of the shared memory control structure
used for communication with this IOTile device.
"""
words = self._read_memory(start_address, search_length, chunk_size=4, join=False)
found_offset = None
for i, word in enumerate(words):
if word == ControlStructure.CONTROL_MAGIC_1:
if (len(words) - i) < 4:
continue
if words[i + 1] == ControlStructure.CONTROL_MAGIC_2 and words[i + 2] == ControlStructure.CONTROL_MAGIC_3 and words[i + 3] == ControlStructure.CONTROL_MAGIC_4:
found_offset = i
break
if found_offset is None:
raise HardwareError("Could not find control structure magic value in search area")
struct_info = words[found_offset + 4]
_version, _flags, length = struct.unpack("<BBH", struct.pack("<L", struct_info))
if length % 4 != 0:
raise HardwareError("Invalid control structure length that was not a multiple of 4", length=length)
word_length = length // 4
control_data = struct.pack("<%dL" % word_length, *words[found_offset:found_offset + word_length])
logger.info("Found control stucture at address 0x%08X, word_length=%d", start_address + 4*found_offset, word_length)
return ControlStructure(start_address + 4*found_offset, control_data)
|
[
"def",
"_find_control_structure",
"(",
"self",
",",
"start_address",
",",
"search_length",
")",
":",
"words",
"=",
"self",
".",
"_read_memory",
"(",
"start_address",
",",
"search_length",
",",
"chunk_size",
"=",
"4",
",",
"join",
"=",
"False",
")",
"found_offset",
"=",
"None",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"words",
")",
":",
"if",
"word",
"==",
"ControlStructure",
".",
"CONTROL_MAGIC_1",
":",
"if",
"(",
"len",
"(",
"words",
")",
"-",
"i",
")",
"<",
"4",
":",
"continue",
"if",
"words",
"[",
"i",
"+",
"1",
"]",
"==",
"ControlStructure",
".",
"CONTROL_MAGIC_2",
"and",
"words",
"[",
"i",
"+",
"2",
"]",
"==",
"ControlStructure",
".",
"CONTROL_MAGIC_3",
"and",
"words",
"[",
"i",
"+",
"3",
"]",
"==",
"ControlStructure",
".",
"CONTROL_MAGIC_4",
":",
"found_offset",
"=",
"i",
"break",
"if",
"found_offset",
"is",
"None",
":",
"raise",
"HardwareError",
"(",
"\"Could not find control structure magic value in search area\"",
")",
"struct_info",
"=",
"words",
"[",
"found_offset",
"+",
"4",
"]",
"_version",
",",
"_flags",
",",
"length",
"=",
"struct",
".",
"unpack",
"(",
"\"<BBH\"",
",",
"struct",
".",
"pack",
"(",
"\"<L\"",
",",
"struct_info",
")",
")",
"if",
"length",
"%",
"4",
"!=",
"0",
":",
"raise",
"HardwareError",
"(",
"\"Invalid control structure length that was not a multiple of 4\"",
",",
"length",
"=",
"length",
")",
"word_length",
"=",
"length",
"//",
"4",
"control_data",
"=",
"struct",
".",
"pack",
"(",
"\"<%dL\"",
"%",
"word_length",
",",
"*",
"words",
"[",
"found_offset",
":",
"found_offset",
"+",
"word_length",
"]",
")",
"logger",
".",
"info",
"(",
"\"Found control stucture at address 0x%08X, word_length=%d\"",
",",
"start_address",
"+",
"4",
"*",
"found_offset",
",",
"word_length",
")",
"return",
"ControlStructure",
"(",
"start_address",
"+",
"4",
"*",
"found_offset",
",",
"control_data",
")"
] |
Find the control structure in RAM for this device.
Returns:
ControlStructure: The decoded contents of the shared memory control structure
used for communication with this IOTile device.
|
[
"Find",
"the",
"control",
"structure",
"in",
"RAM",
"for",
"this",
"device",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L213-L247
|
train
|
iotile/coretools
|
transport_plugins/jlink/iotile_transport_jlink/jlink_background.py
|
JLinkControlThread._verify_control_structure
|
def _verify_control_structure(self, device_info, control_info=None):
"""Verify that a control structure is still valid or find one.
Returns:
ControlStructure: The verified or discovered control structure.
"""
if control_info is None:
control_info = self._find_control_structure(device_info.ram_start, device_info.ram_size)
#FIXME: Actually reread the memory here to verify that the control structure is still valid
return control_info
|
python
|
def _verify_control_structure(self, device_info, control_info=None):
"""Verify that a control structure is still valid or find one.
Returns:
ControlStructure: The verified or discovered control structure.
"""
if control_info is None:
control_info = self._find_control_structure(device_info.ram_start, device_info.ram_size)
#FIXME: Actually reread the memory here to verify that the control structure is still valid
return control_info
|
[
"def",
"_verify_control_structure",
"(",
"self",
",",
"device_info",
",",
"control_info",
"=",
"None",
")",
":",
"if",
"control_info",
"is",
"None",
":",
"control_info",
"=",
"self",
".",
"_find_control_structure",
"(",
"device_info",
".",
"ram_start",
",",
"device_info",
".",
"ram_size",
")",
"#FIXME: Actually reread the memory here to verify that the control structure is still valid",
"return",
"control_info"
] |
Verify that a control structure is still valid or find one.
Returns:
ControlStructure: The verified or discovered control structure.
|
[
"Verify",
"that",
"a",
"control",
"structure",
"is",
"still",
"valid",
"or",
"find",
"one",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink_background.py#L249-L260
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/trace.py
|
SimulationTrace.save
|
def save(self, out_path):
"""Save an ascii representation of this simulation trace.
Args:
out_path (str): The output path to save this simulation trace.
"""
out = {
'selectors': [str(x) for x in self.selectors],
'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]
}
with open(out_path, "wb") as outfile:
json.dump(out, outfile, indent=4)
|
python
|
def save(self, out_path):
"""Save an ascii representation of this simulation trace.
Args:
out_path (str): The output path to save this simulation trace.
"""
out = {
'selectors': [str(x) for x in self.selectors],
'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]
}
with open(out_path, "wb") as outfile:
json.dump(out, outfile, indent=4)
|
[
"def",
"save",
"(",
"self",
",",
"out_path",
")",
":",
"out",
"=",
"{",
"'selectors'",
":",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"selectors",
"]",
",",
"'trace'",
":",
"[",
"{",
"'stream'",
":",
"str",
"(",
"DataStream",
".",
"FromEncoded",
"(",
"x",
".",
"stream",
")",
")",
",",
"'time'",
":",
"x",
".",
"raw_time",
",",
"'value'",
":",
"x",
".",
"value",
",",
"'reading_id'",
":",
"x",
".",
"reading_id",
"}",
"for",
"x",
"in",
"self",
"]",
"}",
"with",
"open",
"(",
"out_path",
",",
"\"wb\"",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"out",
",",
"outfile",
",",
"indent",
"=",
"4",
")"
] |
Save an ascii representation of this simulation trace.
Args:
out_path (str): The output path to save this simulation trace.
|
[
"Save",
"an",
"ascii",
"representation",
"of",
"this",
"simulation",
"trace",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/trace.py#L39-L52
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/trace.py
|
SimulationTrace.FromFile
|
def FromFile(cls, in_path):
"""Load a previously saved ascii representation of this simulation trace.
Args:
in_path (str): The path of the input file that we should load.
Returns:
SimulationTrace: The loaded trace object.
"""
with open(in_path, "rb") as infile:
in_data = json.load(infile)
if not ('trace', 'selectors') in in_data:
raise ArgumentError("Invalid trace file format", keys=in_data.keys(), expected=('trace', 'selectors'))
selectors = [DataStreamSelector.FromString(x) for x in in_data['selectors']]
readings = [IOTileReading(x['time'], DataStream.FromString(x['stream']).encode(), x['value'], reading_id=x['reading_id']) for x in in_data['trace']]
return SimulationTrace(readings, selectors=selectors)
|
python
|
def FromFile(cls, in_path):
"""Load a previously saved ascii representation of this simulation trace.
Args:
in_path (str): The path of the input file that we should load.
Returns:
SimulationTrace: The loaded trace object.
"""
with open(in_path, "rb") as infile:
in_data = json.load(infile)
if not ('trace', 'selectors') in in_data:
raise ArgumentError("Invalid trace file format", keys=in_data.keys(), expected=('trace', 'selectors'))
selectors = [DataStreamSelector.FromString(x) for x in in_data['selectors']]
readings = [IOTileReading(x['time'], DataStream.FromString(x['stream']).encode(), x['value'], reading_id=x['reading_id']) for x in in_data['trace']]
return SimulationTrace(readings, selectors=selectors)
|
[
"def",
"FromFile",
"(",
"cls",
",",
"in_path",
")",
":",
"with",
"open",
"(",
"in_path",
",",
"\"rb\"",
")",
"as",
"infile",
":",
"in_data",
"=",
"json",
".",
"load",
"(",
"infile",
")",
"if",
"not",
"(",
"'trace'",
",",
"'selectors'",
")",
"in",
"in_data",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid trace file format\"",
",",
"keys",
"=",
"in_data",
".",
"keys",
"(",
")",
",",
"expected",
"=",
"(",
"'trace'",
",",
"'selectors'",
")",
")",
"selectors",
"=",
"[",
"DataStreamSelector",
".",
"FromString",
"(",
"x",
")",
"for",
"x",
"in",
"in_data",
"[",
"'selectors'",
"]",
"]",
"readings",
"=",
"[",
"IOTileReading",
"(",
"x",
"[",
"'time'",
"]",
",",
"DataStream",
".",
"FromString",
"(",
"x",
"[",
"'stream'",
"]",
")",
".",
"encode",
"(",
")",
",",
"x",
"[",
"'value'",
"]",
",",
"reading_id",
"=",
"x",
"[",
"'reading_id'",
"]",
")",
"for",
"x",
"in",
"in_data",
"[",
"'trace'",
"]",
"]",
"return",
"SimulationTrace",
"(",
"readings",
",",
"selectors",
"=",
"selectors",
")"
] |
Load a previously saved ascii representation of this simulation trace.
Args:
in_path (str): The path of the input file that we should load.
Returns:
SimulationTrace: The loaded trace object.
|
[
"Load",
"a",
"previously",
"saved",
"ascii",
"representation",
"of",
"this",
"simulation",
"trace",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/trace.py#L55-L74
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
_on_scan
|
def _on_scan(_loop, adapter, _adapter_id, info, expiration_time):
"""Callback when a new device is seen."""
info['validity_period'] = expiration_time
adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info)
|
python
|
def _on_scan(_loop, adapter, _adapter_id, info, expiration_time):
"""Callback when a new device is seen."""
info['validity_period'] = expiration_time
adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info)
|
[
"def",
"_on_scan",
"(",
"_loop",
",",
"adapter",
",",
"_adapter_id",
",",
"info",
",",
"expiration_time",
")",
":",
"info",
"[",
"'validity_period'",
"]",
"=",
"expiration_time",
"adapter",
".",
"notify_event_nowait",
"(",
"info",
".",
"get",
"(",
"'connection_string'",
")",
",",
"'device_seen'",
",",
"info",
")"
] |
Callback when a new device is seen.
|
[
"Callback",
"when",
"a",
"new",
"device",
"is",
"seen",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L227-L231
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
_on_report
|
def _on_report(_loop, adapter, conn_id, report):
"""Callback when a report is received."""
conn_string = None
if conn_id is not None:
conn_string = adapter._get_property(conn_id, 'connection_string')
if isinstance(report, BroadcastReport):
adapter.notify_event_nowait(conn_string, 'broadcast', report)
elif conn_string is not None:
adapter.notify_event_nowait(conn_string, 'report', report)
else:
adapter._logger.debug("Dropping report with unknown conn_id=%s", conn_id)
|
python
|
def _on_report(_loop, adapter, conn_id, report):
"""Callback when a report is received."""
conn_string = None
if conn_id is not None:
conn_string = adapter._get_property(conn_id, 'connection_string')
if isinstance(report, BroadcastReport):
adapter.notify_event_nowait(conn_string, 'broadcast', report)
elif conn_string is not None:
adapter.notify_event_nowait(conn_string, 'report', report)
else:
adapter._logger.debug("Dropping report with unknown conn_id=%s", conn_id)
|
[
"def",
"_on_report",
"(",
"_loop",
",",
"adapter",
",",
"conn_id",
",",
"report",
")",
":",
"conn_string",
"=",
"None",
"if",
"conn_id",
"is",
"not",
"None",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'",
")",
"if",
"isinstance",
"(",
"report",
",",
"BroadcastReport",
")",
":",
"adapter",
".",
"notify_event_nowait",
"(",
"conn_string",
",",
"'broadcast'",
",",
"report",
")",
"elif",
"conn_string",
"is",
"not",
"None",
":",
"adapter",
".",
"notify_event_nowait",
"(",
"conn_string",
",",
"'report'",
",",
"report",
")",
"else",
":",
"adapter",
".",
"_logger",
".",
"debug",
"(",
"\"Dropping report with unknown conn_id=%s\"",
",",
"conn_id",
")"
] |
Callback when a report is received.
|
[
"Callback",
"when",
"a",
"report",
"is",
"received",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L234-L246
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
_on_trace
|
def _on_trace(_loop, adapter, conn_id, trace):
"""Callback when tracing data is received."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping trace data with unknown conn_id=%s", conn_id)
return
adapter.notify_event_nowait(conn_string, 'trace', trace)
|
python
|
def _on_trace(_loop, adapter, conn_id, trace):
"""Callback when tracing data is received."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping trace data with unknown conn_id=%s", conn_id)
return
adapter.notify_event_nowait(conn_string, 'trace', trace)
|
[
"def",
"_on_trace",
"(",
"_loop",
",",
"adapter",
",",
"conn_id",
",",
"trace",
")",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'",
")",
"if",
"conn_string",
"is",
"None",
":",
"adapter",
".",
"_logger",
".",
"debug",
"(",
"\"Dropping trace data with unknown conn_id=%s\"",
",",
"conn_id",
")",
"return",
"adapter",
".",
"notify_event_nowait",
"(",
"conn_string",
",",
"'trace'",
",",
"trace",
")"
] |
Callback when tracing data is received.
|
[
"Callback",
"when",
"tracing",
"data",
"is",
"received",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L249-L257
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
_on_disconnect
|
def _on_disconnect(_loop, adapter, _adapter_id, conn_id):
"""Callback when a device disconnects unexpectedly."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping disconnect notification with unknown conn_id=%s", conn_id)
return
adapter._teardown_connection(conn_id, force=True)
event = dict(reason='no reason passed from legacy adapter', expected=False)
adapter.notify_event_nowait(conn_string, 'disconnection', event)
|
python
|
def _on_disconnect(_loop, adapter, _adapter_id, conn_id):
"""Callback when a device disconnects unexpectedly."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping disconnect notification with unknown conn_id=%s", conn_id)
return
adapter._teardown_connection(conn_id, force=True)
event = dict(reason='no reason passed from legacy adapter', expected=False)
adapter.notify_event_nowait(conn_string, 'disconnection', event)
|
[
"def",
"_on_disconnect",
"(",
"_loop",
",",
"adapter",
",",
"_adapter_id",
",",
"conn_id",
")",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'",
")",
"if",
"conn_string",
"is",
"None",
":",
"adapter",
".",
"_logger",
".",
"debug",
"(",
"\"Dropping disconnect notification with unknown conn_id=%s\"",
",",
"conn_id",
")",
"return",
"adapter",
".",
"_teardown_connection",
"(",
"conn_id",
",",
"force",
"=",
"True",
")",
"event",
"=",
"dict",
"(",
"reason",
"=",
"'no reason passed from legacy adapter'",
",",
"expected",
"=",
"False",
")",
"adapter",
".",
"notify_event_nowait",
"(",
"conn_string",
",",
"'disconnection'",
",",
"event",
")"
] |
Callback when a device disconnects unexpectedly.
|
[
"Callback",
"when",
"a",
"device",
"disconnects",
"unexpectedly",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L260-L270
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
_on_progress
|
def _on_progress(adapter, operation, conn_id, done, total):
"""Callback when progress is reported."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
return
adapter.notify_progress(conn_string, operation, done, total)
|
python
|
def _on_progress(adapter, operation, conn_id, done, total):
"""Callback when progress is reported."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
return
adapter.notify_progress(conn_string, operation, done, total)
|
[
"def",
"_on_progress",
"(",
"adapter",
",",
"operation",
",",
"conn_id",
",",
"done",
",",
"total",
")",
":",
"conn_string",
"=",
"adapter",
".",
"_get_property",
"(",
"conn_id",
",",
"'connection_string'",
")",
"if",
"conn_string",
"is",
"None",
":",
"return",
"adapter",
".",
"notify_progress",
"(",
"conn_string",
",",
"operation",
",",
"done",
",",
"total",
")"
] |
Callback when progress is reported.
|
[
"Callback",
"when",
"progress",
"is",
"reported",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L273-L280
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
AsynchronousModernWrapper.start
|
async def start(self):
"""Start the device adapter.
See :meth:`AbstractDeviceAdapter.start`.
"""
self._loop.add_task(self._periodic_loop, name="periodic task for %s" % self._adapter.__class__.__name__,
parent=self._task)
self._adapter.add_callback('on_scan', functools.partial(_on_scan, self._loop, self))
self._adapter.add_callback('on_report', functools.partial(_on_report, self._loop, self))
self._adapter.add_callback('on_trace', functools.partial(_on_trace, self._loop, self))
self._adapter.add_callback('on_disconnect', functools.partial(_on_disconnect, self._loop, self))
|
python
|
async def start(self):
"""Start the device adapter.
See :meth:`AbstractDeviceAdapter.start`.
"""
self._loop.add_task(self._periodic_loop, name="periodic task for %s" % self._adapter.__class__.__name__,
parent=self._task)
self._adapter.add_callback('on_scan', functools.partial(_on_scan, self._loop, self))
self._adapter.add_callback('on_report', functools.partial(_on_report, self._loop, self))
self._adapter.add_callback('on_trace', functools.partial(_on_trace, self._loop, self))
self._adapter.add_callback('on_disconnect', functools.partial(_on_disconnect, self._loop, self))
|
[
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_loop",
".",
"add_task",
"(",
"self",
".",
"_periodic_loop",
",",
"name",
"=",
"\"periodic task for %s\"",
"%",
"self",
".",
"_adapter",
".",
"__class__",
".",
"__name__",
",",
"parent",
"=",
"self",
".",
"_task",
")",
"self",
".",
"_adapter",
".",
"add_callback",
"(",
"'on_scan'",
",",
"functools",
".",
"partial",
"(",
"_on_scan",
",",
"self",
".",
"_loop",
",",
"self",
")",
")",
"self",
".",
"_adapter",
".",
"add_callback",
"(",
"'on_report'",
",",
"functools",
".",
"partial",
"(",
"_on_report",
",",
"self",
".",
"_loop",
",",
"self",
")",
")",
"self",
".",
"_adapter",
".",
"add_callback",
"(",
"'on_trace'",
",",
"functools",
".",
"partial",
"(",
"_on_trace",
",",
"self",
".",
"_loop",
",",
"self",
")",
")",
"self",
".",
"_adapter",
".",
"add_callback",
"(",
"'on_disconnect'",
",",
"functools",
".",
"partial",
"(",
"_on_disconnect",
",",
"self",
".",
"_loop",
",",
"self",
")",
")"
] |
Start the device adapter.
See :meth:`AbstractDeviceAdapter.start`.
|
[
"Start",
"the",
"device",
"adapter",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L74-L86
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
AsynchronousModernWrapper.stop
|
async def stop(self, _task=None):
"""Stop the device adapter.
See :meth:`AbstractDeviceAdapter.stop`.
"""
self._logger.info("Stopping adapter wrapper")
if self._task.stopped:
return
for task in self._task.subtasks:
await task.stop()
self._logger.debug("Stopping underlying adapter %s", self._adapter.__class__.__name__)
await self._execute(self._adapter.stop_sync)
|
python
|
async def stop(self, _task=None):
"""Stop the device adapter.
See :meth:`AbstractDeviceAdapter.stop`.
"""
self._logger.info("Stopping adapter wrapper")
if self._task.stopped:
return
for task in self._task.subtasks:
await task.stop()
self._logger.debug("Stopping underlying adapter %s", self._adapter.__class__.__name__)
await self._execute(self._adapter.stop_sync)
|
[
"async",
"def",
"stop",
"(",
"self",
",",
"_task",
"=",
"None",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Stopping adapter wrapper\"",
")",
"if",
"self",
".",
"_task",
".",
"stopped",
":",
"return",
"for",
"task",
"in",
"self",
".",
"_task",
".",
"subtasks",
":",
"await",
"task",
".",
"stop",
"(",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Stopping underlying adapter %s\"",
",",
"self",
".",
"_adapter",
".",
"__class__",
".",
"__name__",
")",
"await",
"self",
".",
"_execute",
"(",
"self",
".",
"_adapter",
".",
"stop_sync",
")"
] |
Stop the device adapter.
See :meth:`AbstractDeviceAdapter.stop`.
|
[
"Stop",
"the",
"device",
"adapter",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L88-L103
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
AsynchronousModernWrapper.probe
|
async def probe(self):
"""Probe for devices connected to this adapter.
See :meth:`AbstractDeviceAdapter.probe`.
"""
resp = await self._execute(self._adapter.probe_sync)
_raise_error(None, 'probe', resp)
|
python
|
async def probe(self):
"""Probe for devices connected to this adapter.
See :meth:`AbstractDeviceAdapter.probe`.
"""
resp = await self._execute(self._adapter.probe_sync)
_raise_error(None, 'probe', resp)
|
[
"async",
"def",
"probe",
"(",
"self",
")",
":",
"resp",
"=",
"await",
"self",
".",
"_execute",
"(",
"self",
".",
"_adapter",
".",
"probe_sync",
")",
"_raise_error",
"(",
"None",
",",
"'probe'",
",",
"resp",
")"
] |
Probe for devices connected to this adapter.
See :meth:`AbstractDeviceAdapter.probe`.
|
[
"Probe",
"for",
"devices",
"connected",
"to",
"this",
"adapter",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L173-L180
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py
|
AsynchronousModernWrapper.send_script
|
async def send_script(self, conn_id, data):
"""Send a a script to a device.
See :meth:`AbstractDeviceAdapter.send_script`.
"""
progress_callback = functools.partial(_on_progress, self, 'script', conn_id)
resp = await self._execute(self._adapter.send_script_sync, conn_id, data, progress_callback)
_raise_error(conn_id, 'send_rpc', resp)
|
python
|
async def send_script(self, conn_id, data):
"""Send a a script to a device.
See :meth:`AbstractDeviceAdapter.send_script`.
"""
progress_callback = functools.partial(_on_progress, self, 'script', conn_id)
resp = await self._execute(self._adapter.send_script_sync, conn_id, data, progress_callback)
_raise_error(conn_id, 'send_rpc', resp)
|
[
"async",
"def",
"send_script",
"(",
"self",
",",
"conn_id",
",",
"data",
")",
":",
"progress_callback",
"=",
"functools",
".",
"partial",
"(",
"_on_progress",
",",
"self",
",",
"'script'",
",",
"conn_id",
")",
"resp",
"=",
"await",
"self",
".",
"_execute",
"(",
"self",
".",
"_adapter",
".",
"send_script_sync",
",",
"conn_id",
",",
"data",
",",
"progress_callback",
")",
"_raise_error",
"(",
"conn_id",
",",
"'send_rpc'",
",",
"resp",
")"
] |
Send a a script to a device.
See :meth:`AbstractDeviceAdapter.send_script`.
|
[
"Send",
"a",
"a",
"script",
"to",
"a",
"device",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/async_wrapper.py#L210-L219
|
train
|
iotile/coretools
|
iotileship/iotile/ship/autobuild/ship_file.py
|
autobuild_shiparchive
|
def autobuild_shiparchive(src_file):
"""Create a ship file archive containing a yaml_file and its dependencies.
If yaml_file depends on any build products as external files, it must
be a jinja2 template that references the file using the find_product
filter so that we can figure out where those build products are going
and create the right dependency graph.
Args:
src_file (str): The path to the input yaml file template. This
file path must end .yaml.tpl and is rendered into a .yaml
file and then packaged into a .ship file along with any
products that are referenced in it.
"""
if not src_file.endswith('.tpl'):
raise BuildError("You must pass a .tpl file to autobuild_shiparchive", src_file=src_file)
env = Environment(tools=[])
family = ArchitectureGroup('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
#Parse through build_step products to see what needs to imported
custom_steps = []
for build_step in family.tile.find_products('build_step'):
full_file_name = build_step.split(":")[0]
basename = os.path.splitext(os.path.basename(full_file_name))[0]
folder = os.path.dirname(full_file_name)
fileobj, pathname, description = imp.find_module(basename, [folder])
mod = imp.load_module(basename, fileobj, pathname, description)
full_file_name, class_name = build_step.split(":")
custom_steps.append((class_name, getattr(mod, class_name)))
env['CUSTOM_STEPS'] = custom_steps
env["RESOLVER"] = resolver
base_name, tpl_name = _find_basename(src_file)
yaml_name = tpl_name[:-4]
ship_name = yaml_name[:-5] + ".ship"
output_dir = target.build_dirs()['output']
build_dir = os.path.join(target.build_dirs()['build'], base_name)
tpl_path = os.path.join(build_dir, tpl_name)
yaml_path = os.path.join(build_dir, yaml_name)
ship_path = os.path.join(build_dir, ship_name)
output_path = os.path.join(output_dir, ship_name)
# We want to build up all related files in
# <build_dir>/<ship archive_folder>/
# - First copy the template yaml over
# - Then render the template yaml
# - Then find all products referenced in the template yaml and copy them
# - over
# - Then build a .ship archive
# - Then copy that archive into output_dir
ship_deps = [yaml_path]
env.Command([tpl_path], [src_file], Copy("$TARGET", "$SOURCE"))
prod_deps = _find_product_dependencies(src_file, resolver)
env.Command([yaml_path], [tpl_path], action=Action(template_shipfile_action, "Rendering $TARGET"))
for prod in prod_deps:
dest_file = os.path.join(build_dir, prod.short_name)
ship_deps.append(dest_file)
env.Command([dest_file], [prod.full_path], Copy("$TARGET", "$SOURCE"))
env.Command([ship_path], [ship_deps], action=Action(create_shipfile, "Archiving Ship Recipe $TARGET"))
env.Command([output_path], [ship_path], Copy("$TARGET", "$SOURCE"))
|
python
|
def autobuild_shiparchive(src_file):
"""Create a ship file archive containing a yaml_file and its dependencies.
If yaml_file depends on any build products as external files, it must
be a jinja2 template that references the file using the find_product
filter so that we can figure out where those build products are going
and create the right dependency graph.
Args:
src_file (str): The path to the input yaml file template. This
file path must end .yaml.tpl and is rendered into a .yaml
file and then packaged into a .ship file along with any
products that are referenced in it.
"""
if not src_file.endswith('.tpl'):
raise BuildError("You must pass a .tpl file to autobuild_shiparchive", src_file=src_file)
env = Environment(tools=[])
family = ArchitectureGroup('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
#Parse through build_step products to see what needs to imported
custom_steps = []
for build_step in family.tile.find_products('build_step'):
full_file_name = build_step.split(":")[0]
basename = os.path.splitext(os.path.basename(full_file_name))[0]
folder = os.path.dirname(full_file_name)
fileobj, pathname, description = imp.find_module(basename, [folder])
mod = imp.load_module(basename, fileobj, pathname, description)
full_file_name, class_name = build_step.split(":")
custom_steps.append((class_name, getattr(mod, class_name)))
env['CUSTOM_STEPS'] = custom_steps
env["RESOLVER"] = resolver
base_name, tpl_name = _find_basename(src_file)
yaml_name = tpl_name[:-4]
ship_name = yaml_name[:-5] + ".ship"
output_dir = target.build_dirs()['output']
build_dir = os.path.join(target.build_dirs()['build'], base_name)
tpl_path = os.path.join(build_dir, tpl_name)
yaml_path = os.path.join(build_dir, yaml_name)
ship_path = os.path.join(build_dir, ship_name)
output_path = os.path.join(output_dir, ship_name)
# We want to build up all related files in
# <build_dir>/<ship archive_folder>/
# - First copy the template yaml over
# - Then render the template yaml
# - Then find all products referenced in the template yaml and copy them
# - over
# - Then build a .ship archive
# - Then copy that archive into output_dir
ship_deps = [yaml_path]
env.Command([tpl_path], [src_file], Copy("$TARGET", "$SOURCE"))
prod_deps = _find_product_dependencies(src_file, resolver)
env.Command([yaml_path], [tpl_path], action=Action(template_shipfile_action, "Rendering $TARGET"))
for prod in prod_deps:
dest_file = os.path.join(build_dir, prod.short_name)
ship_deps.append(dest_file)
env.Command([dest_file], [prod.full_path], Copy("$TARGET", "$SOURCE"))
env.Command([ship_path], [ship_deps], action=Action(create_shipfile, "Archiving Ship Recipe $TARGET"))
env.Command([output_path], [ship_path], Copy("$TARGET", "$SOURCE"))
|
[
"def",
"autobuild_shiparchive",
"(",
"src_file",
")",
":",
"if",
"not",
"src_file",
".",
"endswith",
"(",
"'.tpl'",
")",
":",
"raise",
"BuildError",
"(",
"\"You must pass a .tpl file to autobuild_shiparchive\"",
",",
"src_file",
"=",
"src_file",
")",
"env",
"=",
"Environment",
"(",
"tools",
"=",
"[",
"]",
")",
"family",
"=",
"ArchitectureGroup",
"(",
"'module_settings.json'",
")",
"target",
"=",
"family",
".",
"platform_independent_target",
"(",
")",
"resolver",
"=",
"ProductResolver",
".",
"Create",
"(",
")",
"#Parse through build_step products to see what needs to imported",
"custom_steps",
"=",
"[",
"]",
"for",
"build_step",
"in",
"family",
".",
"tile",
".",
"find_products",
"(",
"'build_step'",
")",
":",
"full_file_name",
"=",
"build_step",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"basename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"full_file_name",
")",
")",
"[",
"0",
"]",
"folder",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"full_file_name",
")",
"fileobj",
",",
"pathname",
",",
"description",
"=",
"imp",
".",
"find_module",
"(",
"basename",
",",
"[",
"folder",
"]",
")",
"mod",
"=",
"imp",
".",
"load_module",
"(",
"basename",
",",
"fileobj",
",",
"pathname",
",",
"description",
")",
"full_file_name",
",",
"class_name",
"=",
"build_step",
".",
"split",
"(",
"\":\"",
")",
"custom_steps",
".",
"append",
"(",
"(",
"class_name",
",",
"getattr",
"(",
"mod",
",",
"class_name",
")",
")",
")",
"env",
"[",
"'CUSTOM_STEPS'",
"]",
"=",
"custom_steps",
"env",
"[",
"\"RESOLVER\"",
"]",
"=",
"resolver",
"base_name",
",",
"tpl_name",
"=",
"_find_basename",
"(",
"src_file",
")",
"yaml_name",
"=",
"tpl_name",
"[",
":",
"-",
"4",
"]",
"ship_name",
"=",
"yaml_name",
"[",
":",
"-",
"5",
"]",
"+",
"\".ship\"",
"output_dir",
"=",
"target",
".",
"build_dirs",
"(",
")",
"[",
"'output'",
"]",
"build_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target",
".",
"build_dirs",
"(",
")",
"[",
"'build'",
"]",
",",
"base_name",
")",
"tpl_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"tpl_name",
")",
"yaml_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"yaml_name",
")",
"ship_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"ship_name",
")",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"ship_name",
")",
"# We want to build up all related files in",
"# <build_dir>/<ship archive_folder>/",
"# - First copy the template yaml over",
"# - Then render the template yaml",
"# - Then find all products referenced in the template yaml and copy them",
"# - over",
"# - Then build a .ship archive",
"# - Then copy that archive into output_dir",
"ship_deps",
"=",
"[",
"yaml_path",
"]",
"env",
".",
"Command",
"(",
"[",
"tpl_path",
"]",
",",
"[",
"src_file",
"]",
",",
"Copy",
"(",
"\"$TARGET\"",
",",
"\"$SOURCE\"",
")",
")",
"prod_deps",
"=",
"_find_product_dependencies",
"(",
"src_file",
",",
"resolver",
")",
"env",
".",
"Command",
"(",
"[",
"yaml_path",
"]",
",",
"[",
"tpl_path",
"]",
",",
"action",
"=",
"Action",
"(",
"template_shipfile_action",
",",
"\"Rendering $TARGET\"",
")",
")",
"for",
"prod",
"in",
"prod_deps",
":",
"dest_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"prod",
".",
"short_name",
")",
"ship_deps",
".",
"append",
"(",
"dest_file",
")",
"env",
".",
"Command",
"(",
"[",
"dest_file",
"]",
",",
"[",
"prod",
".",
"full_path",
"]",
",",
"Copy",
"(",
"\"$TARGET\"",
",",
"\"$SOURCE\"",
")",
")",
"env",
".",
"Command",
"(",
"[",
"ship_path",
"]",
",",
"[",
"ship_deps",
"]",
",",
"action",
"=",
"Action",
"(",
"create_shipfile",
",",
"\"Archiving Ship Recipe $TARGET\"",
")",
")",
"env",
".",
"Command",
"(",
"[",
"output_path",
"]",
",",
"[",
"ship_path",
"]",
",",
"Copy",
"(",
"\"$TARGET\"",
",",
"\"$SOURCE\"",
")",
")"
] |
Create a ship file archive containing a yaml_file and its dependencies.
If yaml_file depends on any build products as external files, it must
be a jinja2 template that references the file using the find_product
filter so that we can figure out where those build products are going
and create the right dependency graph.
Args:
src_file (str): The path to the input yaml file template. This
file path must end .yaml.tpl and is rendered into a .yaml
file and then packaged into a .ship file along with any
products that are referenced in it.
|
[
"Create",
"a",
"ship",
"file",
"archive",
"containing",
"a",
"yaml_file",
"and",
"its",
"dependencies",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/autobuild/ship_file.py#L15-L88
|
train
|
iotile/coretools
|
iotileship/iotile/ship/autobuild/ship_file.py
|
create_shipfile
|
def create_shipfile(target, source, env):
"""Create a .ship file with all dependencies."""
source_dir = os.path.dirname(str(source[0]))
recipe_name = os.path.basename(str(source[0]))[:-5]
resman = RecipeManager()
resman.add_recipe_actions(env['CUSTOM_STEPS'])
resman.add_recipe_folder(source_dir, whitelist=[os.path.basename(str(source[0]))])
recipe = resman.get_recipe(recipe_name)
recipe.archive(str(target[0]))
|
python
|
def create_shipfile(target, source, env):
"""Create a .ship file with all dependencies."""
source_dir = os.path.dirname(str(source[0]))
recipe_name = os.path.basename(str(source[0]))[:-5]
resman = RecipeManager()
resman.add_recipe_actions(env['CUSTOM_STEPS'])
resman.add_recipe_folder(source_dir, whitelist=[os.path.basename(str(source[0]))])
recipe = resman.get_recipe(recipe_name)
recipe.archive(str(target[0]))
|
[
"def",
"create_shipfile",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"source_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
")",
"recipe_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
")",
"[",
":",
"-",
"5",
"]",
"resman",
"=",
"RecipeManager",
"(",
")",
"resman",
".",
"add_recipe_actions",
"(",
"env",
"[",
"'CUSTOM_STEPS'",
"]",
")",
"resman",
".",
"add_recipe_folder",
"(",
"source_dir",
",",
"whitelist",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
")",
"]",
")",
"recipe",
"=",
"resman",
".",
"get_recipe",
"(",
"recipe_name",
")",
"recipe",
".",
"archive",
"(",
"str",
"(",
"target",
"[",
"0",
"]",
")",
")"
] |
Create a .ship file with all dependencies.
|
[
"Create",
"a",
".",
"ship",
"file",
"with",
"all",
"dependencies",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/autobuild/ship_file.py#L113-L125
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/simulator.py
|
SensorGraphSimulator.record_trace
|
def record_trace(self, selectors=None):
"""Record a trace of readings produced by this simulator.
This causes the property `self.trace` to be populated with a
SimulationTrace object that contains all of the readings that
are produced during the course of the simulation. Only readings
that respond to specific selectors are given.
You can pass whatever selectors you want in the optional selectors
argument. If you pass None, then the default behavior to trace
all of the output streams of the sensor graph, which are defined
as the streams that are selected by a DataStreamer object in the
sensor graph. This is typically what is meant by sensor graph
output.
You can inspect the current trace by looking at the trace
property. It will initially be an empty list and will be updated
with each call to step() or run() that results in new readings
responsive to the selectors you pick (or the graph streamers if
you did not explicitly pass a list of DataStreamSelector objects).
Args:
selectors (list of DataStreamSelector): The selectors to add watch
statements on to produce this trace. This is optional.
If it is not specified, a the streamers of the sensor
graph are used.
"""
if selectors is None:
selectors = [x.selector for x in self.sensor_graph.streamers]
self.trace = SimulationTrace(selectors=selectors)
for sel in selectors:
self.sensor_graph.sensor_log.watch(sel, self._on_trace_callback)
|
python
|
def record_trace(self, selectors=None):
"""Record a trace of readings produced by this simulator.
This causes the property `self.trace` to be populated with a
SimulationTrace object that contains all of the readings that
are produced during the course of the simulation. Only readings
that respond to specific selectors are given.
You can pass whatever selectors you want in the optional selectors
argument. If you pass None, then the default behavior to trace
all of the output streams of the sensor graph, which are defined
as the streams that are selected by a DataStreamer object in the
sensor graph. This is typically what is meant by sensor graph
output.
You can inspect the current trace by looking at the trace
property. It will initially be an empty list and will be updated
with each call to step() or run() that results in new readings
responsive to the selectors you pick (or the graph streamers if
you did not explicitly pass a list of DataStreamSelector objects).
Args:
selectors (list of DataStreamSelector): The selectors to add watch
statements on to produce this trace. This is optional.
If it is not specified, a the streamers of the sensor
graph are used.
"""
if selectors is None:
selectors = [x.selector for x in self.sensor_graph.streamers]
self.trace = SimulationTrace(selectors=selectors)
for sel in selectors:
self.sensor_graph.sensor_log.watch(sel, self._on_trace_callback)
|
[
"def",
"record_trace",
"(",
"self",
",",
"selectors",
"=",
"None",
")",
":",
"if",
"selectors",
"is",
"None",
":",
"selectors",
"=",
"[",
"x",
".",
"selector",
"for",
"x",
"in",
"self",
".",
"sensor_graph",
".",
"streamers",
"]",
"self",
".",
"trace",
"=",
"SimulationTrace",
"(",
"selectors",
"=",
"selectors",
")",
"for",
"sel",
"in",
"selectors",
":",
"self",
".",
"sensor_graph",
".",
"sensor_log",
".",
"watch",
"(",
"sel",
",",
"self",
".",
"_on_trace_callback",
")"
] |
Record a trace of readings produced by this simulator.
This causes the property `self.trace` to be populated with a
SimulationTrace object that contains all of the readings that
are produced during the course of the simulation. Only readings
that respond to specific selectors are given.
You can pass whatever selectors you want in the optional selectors
argument. If you pass None, then the default behavior to trace
all of the output streams of the sensor graph, which are defined
as the streams that are selected by a DataStreamer object in the
sensor graph. This is typically what is meant by sensor graph
output.
You can inspect the current trace by looking at the trace
property. It will initially be an empty list and will be updated
with each call to step() or run() that results in new readings
responsive to the selectors you pick (or the graph streamers if
you did not explicitly pass a list of DataStreamSelector objects).
Args:
selectors (list of DataStreamSelector): The selectors to add watch
statements on to produce this trace. This is optional.
If it is not specified, a the streamers of the sensor
graph are used.
|
[
"Record",
"a",
"trace",
"of",
"readings",
"produced",
"by",
"this",
"simulator",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L56-L90
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/simulator.py
|
SensorGraphSimulator.step
|
def step(self, input_stream, value):
"""Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
value into
value (int): The reading value to push as an integer
"""
reading = IOTileReading(input_stream.encode(), self.tick_count, value)
self.sensor_graph.process_input(input_stream, reading, self.rpc_executor)
|
python
|
def step(self, input_stream, value):
"""Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
value into
value (int): The reading value to push as an integer
"""
reading = IOTileReading(input_stream.encode(), self.tick_count, value)
self.sensor_graph.process_input(input_stream, reading, self.rpc_executor)
|
[
"def",
"step",
"(",
"self",
",",
"input_stream",
",",
"value",
")",
":",
"reading",
"=",
"IOTileReading",
"(",
"input_stream",
".",
"encode",
"(",
")",
",",
"self",
".",
"tick_count",
",",
"value",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
"(",
"input_stream",
",",
"reading",
",",
"self",
".",
"rpc_executor",
")"
] |
Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
value into
value (int): The reading value to push as an integer
|
[
"Step",
"the",
"sensor",
"graph",
"through",
"one",
"since",
"input",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L95-L109
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/simulator.py
|
SensorGraphSimulator.run
|
def run(self, include_reset=True, accelerated=True):
"""Run this sensor graph until a stop condition is hit.
Multiple calls to this function are useful only if
there has been some change in the stop conditions that would
cause the second call to not exit immediately.
Args:
include_reset (bool): Start the sensor graph run with
a reset event to match what would happen when an
actual device powers on.
accelerated (bool): Whether to run this sensor graph as
fast as possible or to delay tick events to simulate
the actual passage of wall clock time.
"""
self._start_tick = self.tick_count
if self._check_stop_conditions(self.sensor_graph):
return
if include_reset:
pass # TODO: include a reset event here
# Process all stimuli that occur at the start of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != 0:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
while not self._check_stop_conditions(self.sensor_graph):
# Process one more one second tick
now = monotonic()
next_tick = now + 1.0
# To match what is done in actual hardware, we increment tick count so the first tick
# is 1.
self.tick_count += 1
# Process all stimuli that occur at this tick of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != self.tick_count:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
self._check_additional_ticks(self.tick_count)
if (self.tick_count % 10) == 0:
reading = IOTileReading(self.tick_count, system_tick.encode(), self.tick_count)
self.sensor_graph.process_input(system_tick, reading, self.rpc_executor)
# Every 10 seconds the battery voltage is reported in 16.16 fixed point format in volts
reading = IOTileReading(self.tick_count, battery_voltage.encode(), int(self.voltage * 65536))
self.sensor_graph.process_input(battery_voltage, reading, self.rpc_executor)
now = monotonic()
# If we are trying to execute this sensor graph in realtime, wait for
# the remaining slice of this tick.
if (not accelerated) and (now < next_tick):
time.sleep(next_tick - now)
|
python
|
def run(self, include_reset=True, accelerated=True):
"""Run this sensor graph until a stop condition is hit.
Multiple calls to this function are useful only if
there has been some change in the stop conditions that would
cause the second call to not exit immediately.
Args:
include_reset (bool): Start the sensor graph run with
a reset event to match what would happen when an
actual device powers on.
accelerated (bool): Whether to run this sensor graph as
fast as possible or to delay tick events to simulate
the actual passage of wall clock time.
"""
self._start_tick = self.tick_count
if self._check_stop_conditions(self.sensor_graph):
return
if include_reset:
pass # TODO: include a reset event here
# Process all stimuli that occur at the start of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != 0:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
while not self._check_stop_conditions(self.sensor_graph):
# Process one more one second tick
now = monotonic()
next_tick = now + 1.0
# To match what is done in actual hardware, we increment tick count so the first tick
# is 1.
self.tick_count += 1
# Process all stimuli that occur at this tick of the simulation
i = None
for i, stim in enumerate(self.stimuli):
if stim.time != self.tick_count:
break
reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
if i is not None and i > 0:
self.stimuli = self.stimuli[i:]
self._check_additional_ticks(self.tick_count)
if (self.tick_count % 10) == 0:
reading = IOTileReading(self.tick_count, system_tick.encode(), self.tick_count)
self.sensor_graph.process_input(system_tick, reading, self.rpc_executor)
# Every 10 seconds the battery voltage is reported in 16.16 fixed point format in volts
reading = IOTileReading(self.tick_count, battery_voltage.encode(), int(self.voltage * 65536))
self.sensor_graph.process_input(battery_voltage, reading, self.rpc_executor)
now = monotonic()
# If we are trying to execute this sensor graph in realtime, wait for
# the remaining slice of this tick.
if (not accelerated) and (now < next_tick):
time.sleep(next_tick - now)
|
[
"def",
"run",
"(",
"self",
",",
"include_reset",
"=",
"True",
",",
"accelerated",
"=",
"True",
")",
":",
"self",
".",
"_start_tick",
"=",
"self",
".",
"tick_count",
"if",
"self",
".",
"_check_stop_conditions",
"(",
"self",
".",
"sensor_graph",
")",
":",
"return",
"if",
"include_reset",
":",
"pass",
"# TODO: include a reset event here",
"# Process all stimuli that occur at the start of the simulation",
"i",
"=",
"None",
"for",
"i",
",",
"stim",
"in",
"enumerate",
"(",
"self",
".",
"stimuli",
")",
":",
"if",
"stim",
".",
"time",
"!=",
"0",
":",
"break",
"reading",
"=",
"IOTileReading",
"(",
"self",
".",
"tick_count",
",",
"stim",
".",
"stream",
".",
"encode",
"(",
")",
",",
"stim",
".",
"value",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
"(",
"stim",
".",
"stream",
",",
"reading",
",",
"self",
".",
"rpc_executor",
")",
"if",
"i",
"is",
"not",
"None",
"and",
"i",
">",
"0",
":",
"self",
".",
"stimuli",
"=",
"self",
".",
"stimuli",
"[",
"i",
":",
"]",
"while",
"not",
"self",
".",
"_check_stop_conditions",
"(",
"self",
".",
"sensor_graph",
")",
":",
"# Process one more one second tick",
"now",
"=",
"monotonic",
"(",
")",
"next_tick",
"=",
"now",
"+",
"1.0",
"# To match what is done in actual hardware, we increment tick count so the first tick",
"# is 1.",
"self",
".",
"tick_count",
"+=",
"1",
"# Process all stimuli that occur at this tick of the simulation",
"i",
"=",
"None",
"for",
"i",
",",
"stim",
"in",
"enumerate",
"(",
"self",
".",
"stimuli",
")",
":",
"if",
"stim",
".",
"time",
"!=",
"self",
".",
"tick_count",
":",
"break",
"reading",
"=",
"IOTileReading",
"(",
"self",
".",
"tick_count",
",",
"stim",
".",
"stream",
".",
"encode",
"(",
")",
",",
"stim",
".",
"value",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
"(",
"stim",
".",
"stream",
",",
"reading",
",",
"self",
".",
"rpc_executor",
")",
"if",
"i",
"is",
"not",
"None",
"and",
"i",
">",
"0",
":",
"self",
".",
"stimuli",
"=",
"self",
".",
"stimuli",
"[",
"i",
":",
"]",
"self",
".",
"_check_additional_ticks",
"(",
"self",
".",
"tick_count",
")",
"if",
"(",
"self",
".",
"tick_count",
"%",
"10",
")",
"==",
"0",
":",
"reading",
"=",
"IOTileReading",
"(",
"self",
".",
"tick_count",
",",
"system_tick",
".",
"encode",
"(",
")",
",",
"self",
".",
"tick_count",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
"(",
"system_tick",
",",
"reading",
",",
"self",
".",
"rpc_executor",
")",
"# Every 10 seconds the battery voltage is reported in 16.16 fixed point format in volts",
"reading",
"=",
"IOTileReading",
"(",
"self",
".",
"tick_count",
",",
"battery_voltage",
".",
"encode",
"(",
")",
",",
"int",
"(",
"self",
".",
"voltage",
"*",
"65536",
")",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
"(",
"battery_voltage",
",",
"reading",
",",
"self",
".",
"rpc_executor",
")",
"now",
"=",
"monotonic",
"(",
")",
"# If we are trying to execute this sensor graph in realtime, wait for",
"# the remaining slice of this tick.",
"if",
"(",
"not",
"accelerated",
")",
"and",
"(",
"now",
"<",
"next_tick",
")",
":",
"time",
".",
"sleep",
"(",
"next_tick",
"-",
"now",
")"
] |
Run this sensor graph until a stop condition is hit.
Multiple calls to this function are useful only if
there has been some change in the stop conditions that would
cause the second call to not exit immediately.
Args:
include_reset (bool): Start the sensor graph run with
a reset event to match what would happen when an
actual device powers on.
accelerated (bool): Whether to run this sensor graph as
fast as possible or to delay tick events to simulate
the actual passage of wall clock time.
|
[
"Run",
"this",
"sensor",
"graph",
"until",
"a",
"stop",
"condition",
"is",
"hit",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L111-L183
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/simulator.py
|
SensorGraphSimulator._check_stop_conditions
|
def _check_stop_conditions(self, sensor_graph):
"""Check if any of our stop conditions are met.
Args:
sensor_graph (SensorGraph): The sensor graph we are currently simulating
Returns:
bool: True if we should stop the simulation
"""
for stop in self.stop_conditions:
if stop.should_stop(self.tick_count, self.tick_count - self._start_tick, sensor_graph):
return True
return False
|
python
|
def _check_stop_conditions(self, sensor_graph):
"""Check if any of our stop conditions are met.
Args:
sensor_graph (SensorGraph): The sensor graph we are currently simulating
Returns:
bool: True if we should stop the simulation
"""
for stop in self.stop_conditions:
if stop.should_stop(self.tick_count, self.tick_count - self._start_tick, sensor_graph):
return True
return False
|
[
"def",
"_check_stop_conditions",
"(",
"self",
",",
"sensor_graph",
")",
":",
"for",
"stop",
"in",
"self",
".",
"stop_conditions",
":",
"if",
"stop",
".",
"should_stop",
"(",
"self",
".",
"tick_count",
",",
"self",
".",
"tick_count",
"-",
"self",
".",
"_start_tick",
",",
"sensor_graph",
")",
":",
"return",
"True",
"return",
"False"
] |
Check if any of our stop conditions are met.
Args:
sensor_graph (SensorGraph): The sensor graph we are currently simulating
Returns:
bool: True if we should stop the simulation
|
[
"Check",
"if",
"any",
"of",
"our",
"stop",
"conditions",
"are",
"met",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L203-L217
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/simulator.py
|
SensorGraphSimulator.stimulus
|
def stimulus(self, stimulus):
"""Add a simulation stimulus at a given time.
A stimulus is a specific input given to the graph at a specific
time to a specific input stream. The format for specifying a
stimulus is:
[time: ][system ]input X = Y
where X and Y are integers.
This will cause the simulator to inject this input at the given time.
If you specify a time of 0 seconds, it will happen before the simulation
starts. Similarly, if you specify a time of 1 second it will also happen
before anything else since the simulations start with a tick value of 1.
The stimulus is injected before any other things happen at each new tick.
Args:
stimulus (str or SimulationStimulus): A prebuilt stimulus object or
a string description of the stimulus of the format:
[time: ][system ]input X = Y
where time is optional and defaults to 0 seconds if not specified.
Examples:
sim.stimulus('system input 10 = 15')
sim.stimulus('1 minute: input 1 = 5')
"""
if not isinstance(stimulus, SimulationStimulus):
stimulus = SimulationStimulus.FromString(stimulus)
self.stimuli.append(stimulus)
self.stimuli.sort(key=lambda x:x.time)
|
python
|
def stimulus(self, stimulus):
"""Add a simulation stimulus at a given time.
A stimulus is a specific input given to the graph at a specific
time to a specific input stream. The format for specifying a
stimulus is:
[time: ][system ]input X = Y
where X and Y are integers.
This will cause the simulator to inject this input at the given time.
If you specify a time of 0 seconds, it will happen before the simulation
starts. Similarly, if you specify a time of 1 second it will also happen
before anything else since the simulations start with a tick value of 1.
The stimulus is injected before any other things happen at each new tick.
Args:
stimulus (str or SimulationStimulus): A prebuilt stimulus object or
a string description of the stimulus of the format:
[time: ][system ]input X = Y
where time is optional and defaults to 0 seconds if not specified.
Examples:
sim.stimulus('system input 10 = 15')
sim.stimulus('1 minute: input 1 = 5')
"""
if not isinstance(stimulus, SimulationStimulus):
stimulus = SimulationStimulus.FromString(stimulus)
self.stimuli.append(stimulus)
self.stimuli.sort(key=lambda x:x.time)
|
[
"def",
"stimulus",
"(",
"self",
",",
"stimulus",
")",
":",
"if",
"not",
"isinstance",
"(",
"stimulus",
",",
"SimulationStimulus",
")",
":",
"stimulus",
"=",
"SimulationStimulus",
".",
"FromString",
"(",
"stimulus",
")",
"self",
".",
"stimuli",
".",
"append",
"(",
"stimulus",
")",
"self",
".",
"stimuli",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"time",
")"
] |
Add a simulation stimulus at a given time.
A stimulus is a specific input given to the graph at a specific
time to a specific input stream. The format for specifying a
stimulus is:
[time: ][system ]input X = Y
where X and Y are integers.
This will cause the simulator to inject this input at the given time.
If you specify a time of 0 seconds, it will happen before the simulation
starts. Similarly, if you specify a time of 1 second it will also happen
before anything else since the simulations start with a tick value of 1.
The stimulus is injected before any other things happen at each new tick.
Args:
stimulus (str or SimulationStimulus): A prebuilt stimulus object or
a string description of the stimulus of the format:
[time: ][system ]input X = Y
where time is optional and defaults to 0 seconds if not specified.
Examples:
sim.stimulus('system input 10 = 15')
sim.stimulus('1 minute: input 1 = 5')
|
[
"Add",
"a",
"simulation",
"stimulus",
"at",
"a",
"given",
"time",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L219-L250
|
train
|
iotile/coretools
|
iotilesensorgraph/iotile/sg/sim/simulator.py
|
SensorGraphSimulator.stop_condition
|
def stop_condition(self, condition):
"""Add a stop condition to this simulation.
Stop conditions are specified as strings and parsed into
the appropriate internal structures.
Args:
condition (str): a string description of the stop condition
"""
# Try to parse this into a stop condition with each of our registered
# condition types
for cond_format in self._known_conditions:
try:
cond = cond_format.FromString(condition)
self.stop_conditions.append(cond)
return
except ArgumentError:
continue
raise ArgumentError("Stop condition could not be processed by any known StopCondition type", condition=condition, suggestion="It may be mistyped or otherwise invalid.")
|
python
|
def stop_condition(self, condition):
"""Add a stop condition to this simulation.
Stop conditions are specified as strings and parsed into
the appropriate internal structures.
Args:
condition (str): a string description of the stop condition
"""
# Try to parse this into a stop condition with each of our registered
# condition types
for cond_format in self._known_conditions:
try:
cond = cond_format.FromString(condition)
self.stop_conditions.append(cond)
return
except ArgumentError:
continue
raise ArgumentError("Stop condition could not be processed by any known StopCondition type", condition=condition, suggestion="It may be mistyped or otherwise invalid.")
|
[
"def",
"stop_condition",
"(",
"self",
",",
"condition",
")",
":",
"# Try to parse this into a stop condition with each of our registered",
"# condition types",
"for",
"cond_format",
"in",
"self",
".",
"_known_conditions",
":",
"try",
":",
"cond",
"=",
"cond_format",
".",
"FromString",
"(",
"condition",
")",
"self",
".",
"stop_conditions",
".",
"append",
"(",
"cond",
")",
"return",
"except",
"ArgumentError",
":",
"continue",
"raise",
"ArgumentError",
"(",
"\"Stop condition could not be processed by any known StopCondition type\"",
",",
"condition",
"=",
"condition",
",",
"suggestion",
"=",
"\"It may be mistyped or otherwise invalid.\"",
")"
] |
Add a stop condition to this simulation.
Stop conditions are specified as strings and parsed into
the appropriate internal structures.
Args:
condition (str): a string description of the stop condition
|
[
"Add",
"a",
"stop",
"condition",
"to",
"this",
"simulation",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L252-L272
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.dump
|
def dump(self):
"""Serialize the state of this subsystem into a dict.
Returns:
dict: The serialized state
"""
walker = self.dump_walker
if walker is not None:
walker = walker.dump()
state = {
'storage': self.storage.dump(),
'dump_walker': walker,
'next_id': self.next_id
}
return state
|
python
|
def dump(self):
"""Serialize the state of this subsystem into a dict.
Returns:
dict: The serialized state
"""
walker = self.dump_walker
if walker is not None:
walker = walker.dump()
state = {
'storage': self.storage.dump(),
'dump_walker': walker,
'next_id': self.next_id
}
return state
|
[
"def",
"dump",
"(",
"self",
")",
":",
"walker",
"=",
"self",
".",
"dump_walker",
"if",
"walker",
"is",
"not",
"None",
":",
"walker",
"=",
"walker",
".",
"dump",
"(",
")",
"state",
"=",
"{",
"'storage'",
":",
"self",
".",
"storage",
".",
"dump",
"(",
")",
",",
"'dump_walker'",
":",
"walker",
",",
"'next_id'",
":",
"self",
".",
"next_id",
"}",
"return",
"state"
] |
Serialize the state of this subsystem into a dict.
Returns:
dict: The serialized state
|
[
"Serialize",
"the",
"state",
"of",
"this",
"subsystem",
"into",
"a",
"dict",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L36-L53
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.clear
|
def clear(self, timestamp):
"""Clear all data from the RSL.
This pushes a single reading once we clear everything so that
we keep track of the highest ID that we have allocated to date.
This needs the current timestamp to be able to properly timestamp
the cleared storage reading that it pushes.
Args:
timestamp (int): The current timestamp to store with the
reading.
"""
self.storage.clear()
self.push(streams.DATA_CLEARED, timestamp, 1)
|
python
|
def clear(self, timestamp):
"""Clear all data from the RSL.
This pushes a single reading once we clear everything so that
we keep track of the highest ID that we have allocated to date.
This needs the current timestamp to be able to properly timestamp
the cleared storage reading that it pushes.
Args:
timestamp (int): The current timestamp to store with the
reading.
"""
self.storage.clear()
self.push(streams.DATA_CLEARED, timestamp, 1)
|
[
"def",
"clear",
"(",
"self",
",",
"timestamp",
")",
":",
"self",
".",
"storage",
".",
"clear",
"(",
")",
"self",
".",
"push",
"(",
"streams",
".",
"DATA_CLEARED",
",",
"timestamp",
",",
"1",
")"
] |
Clear all data from the RSL.
This pushes a single reading once we clear everything so that
we keep track of the highest ID that we have allocated to date.
This needs the current timestamp to be able to properly timestamp
the cleared storage reading that it pushes.
Args:
timestamp (int): The current timestamp to store with the
reading.
|
[
"Clear",
"all",
"data",
"from",
"the",
"RSL",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L86-L102
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.push
|
def push(self, stream_id, timestamp, value):
"""Push a value to a stream.
Args:
stream_id (int): The stream we want to push to.
timestamp (int): The raw timestamp of the value we want to
store.
value (int): The 32-bit integer value we want to push.
Returns:
int: Packed 32-bit error code.
"""
stream = DataStream.FromEncoded(stream_id)
reading = IOTileReading(stream_id, timestamp, value)
try:
self.storage.push(stream, reading)
return Error.NO_ERROR
except StorageFullError:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.RING_BUFFER_FULL)
|
python
|
def push(self, stream_id, timestamp, value):
"""Push a value to a stream.
Args:
stream_id (int): The stream we want to push to.
timestamp (int): The raw timestamp of the value we want to
store.
value (int): The 32-bit integer value we want to push.
Returns:
int: Packed 32-bit error code.
"""
stream = DataStream.FromEncoded(stream_id)
reading = IOTileReading(stream_id, timestamp, value)
try:
self.storage.push(stream, reading)
return Error.NO_ERROR
except StorageFullError:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.RING_BUFFER_FULL)
|
[
"def",
"push",
"(",
"self",
",",
"stream_id",
",",
"timestamp",
",",
"value",
")",
":",
"stream",
"=",
"DataStream",
".",
"FromEncoded",
"(",
"stream_id",
")",
"reading",
"=",
"IOTileReading",
"(",
"stream_id",
",",
"timestamp",
",",
"value",
")",
"try",
":",
"self",
".",
"storage",
".",
"push",
"(",
"stream",
",",
"reading",
")",
"return",
"Error",
".",
"NO_ERROR",
"except",
"StorageFullError",
":",
"return",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"RING_BUFFER_FULL",
")"
] |
Push a value to a stream.
Args:
stream_id (int): The stream we want to push to.
timestamp (int): The raw timestamp of the value we want to
store.
value (int): The 32-bit integer value we want to push.
Returns:
int: Packed 32-bit error code.
|
[
"Push",
"a",
"value",
"to",
"a",
"stream",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L142-L162
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.inspect_virtual
|
def inspect_virtual(self, stream_id):
"""Inspect the last value written into a virtual stream.
Args:
stream_id (int): The virtual stream was want to inspect.
Returns:
(int, int): An error code and the stream value.
"""
stream = DataStream.FromEncoded(stream_id)
if stream.buffered:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0]
try:
reading = self.storage.inspect_last(stream, only_allocated=True)
return [Error.NO_ERROR, reading.value]
except StreamEmptyError:
return [Error.NO_ERROR, 0]
except UnresolvedIdentifierError:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0]
|
python
|
def inspect_virtual(self, stream_id):
"""Inspect the last value written into a virtual stream.
Args:
stream_id (int): The virtual stream was want to inspect.
Returns:
(int, int): An error code and the stream value.
"""
stream = DataStream.FromEncoded(stream_id)
if stream.buffered:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0]
try:
reading = self.storage.inspect_last(stream, only_allocated=True)
return [Error.NO_ERROR, reading.value]
except StreamEmptyError:
return [Error.NO_ERROR, 0]
except UnresolvedIdentifierError:
return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0]
|
[
"def",
"inspect_virtual",
"(",
"self",
",",
"stream_id",
")",
":",
"stream",
"=",
"DataStream",
".",
"FromEncoded",
"(",
"stream_id",
")",
"if",
"stream",
".",
"buffered",
":",
"return",
"[",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"VIRTUAL_STREAM_NOT_FOUND",
")",
",",
"0",
"]",
"try",
":",
"reading",
"=",
"self",
".",
"storage",
".",
"inspect_last",
"(",
"stream",
",",
"only_allocated",
"=",
"True",
")",
"return",
"[",
"Error",
".",
"NO_ERROR",
",",
"reading",
".",
"value",
"]",
"except",
"StreamEmptyError",
":",
"return",
"[",
"Error",
".",
"NO_ERROR",
",",
"0",
"]",
"except",
"UnresolvedIdentifierError",
":",
"return",
"[",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"VIRTUAL_STREAM_NOT_FOUND",
")",
",",
"0",
"]"
] |
Inspect the last value written into a virtual stream.
Args:
stream_id (int): The virtual stream was want to inspect.
Returns:
(int, int): An error code and the stream value.
|
[
"Inspect",
"the",
"last",
"value",
"written",
"into",
"a",
"virtual",
"stream",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L164-L185
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.dump_begin
|
def dump_begin(self, selector_id):
"""Start dumping a stream.
Args:
selector_id (int): The buffered stream we want to dump.
Returns:
(int, int, int): Error code, second error code, number of available readings
"""
if self.dump_walker is not None:
self.storage.destroy_walker(self.dump_walker)
selector = DataStreamSelector.FromEncoded(selector_id)
self.dump_walker = self.storage.create_walker(selector, skip_all=False)
return Error.NO_ERROR, Error.NO_ERROR, self.dump_walker.count()
|
python
|
def dump_begin(self, selector_id):
"""Start dumping a stream.
Args:
selector_id (int): The buffered stream we want to dump.
Returns:
(int, int, int): Error code, second error code, number of available readings
"""
if self.dump_walker is not None:
self.storage.destroy_walker(self.dump_walker)
selector = DataStreamSelector.FromEncoded(selector_id)
self.dump_walker = self.storage.create_walker(selector, skip_all=False)
return Error.NO_ERROR, Error.NO_ERROR, self.dump_walker.count()
|
[
"def",
"dump_begin",
"(",
"self",
",",
"selector_id",
")",
":",
"if",
"self",
".",
"dump_walker",
"is",
"not",
"None",
":",
"self",
".",
"storage",
".",
"destroy_walker",
"(",
"self",
".",
"dump_walker",
")",
"selector",
"=",
"DataStreamSelector",
".",
"FromEncoded",
"(",
"selector_id",
")",
"self",
".",
"dump_walker",
"=",
"self",
".",
"storage",
".",
"create_walker",
"(",
"selector",
",",
"skip_all",
"=",
"False",
")",
"return",
"Error",
".",
"NO_ERROR",
",",
"Error",
".",
"NO_ERROR",
",",
"self",
".",
"dump_walker",
".",
"count",
"(",
")"
] |
Start dumping a stream.
Args:
selector_id (int): The buffered stream we want to dump.
Returns:
(int, int, int): Error code, second error code, number of available readings
|
[
"Start",
"dumping",
"a",
"stream",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L187-L203
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.dump_seek
|
def dump_seek(self, reading_id):
"""Seek the dump streamer to a given ID.
Returns:
(int, int, int): Two error codes and the count of remaining readings.
The first error code covers the seeking process.
The second error code covers the stream counting process (cannot fail)
The third item in the tuple is the number of readings left in the stream.
"""
if self.dump_walker is None:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED),
Error.NO_ERROR, 0)
try:
exact = self.dump_walker.seek(reading_id, target='id')
except UnresolvedIdentifierError:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS),
Error.NO_ERROR, 0)
error = Error.NO_ERROR
if not exact:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.ID_FOUND_FOR_ANOTHER_STREAM)
return (error, error.NO_ERROR, self.dump_walker.count())
|
python
|
def dump_seek(self, reading_id):
"""Seek the dump streamer to a given ID.
Returns:
(int, int, int): Two error codes and the count of remaining readings.
The first error code covers the seeking process.
The second error code covers the stream counting process (cannot fail)
The third item in the tuple is the number of readings left in the stream.
"""
if self.dump_walker is None:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED),
Error.NO_ERROR, 0)
try:
exact = self.dump_walker.seek(reading_id, target='id')
except UnresolvedIdentifierError:
return (pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS),
Error.NO_ERROR, 0)
error = Error.NO_ERROR
if not exact:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.ID_FOUND_FOR_ANOTHER_STREAM)
return (error, error.NO_ERROR, self.dump_walker.count())
|
[
"def",
"dump_seek",
"(",
"self",
",",
"reading_id",
")",
":",
"if",
"self",
".",
"dump_walker",
"is",
"None",
":",
"return",
"(",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"STREAM_WALKER_NOT_INITIALIZED",
")",
",",
"Error",
".",
"NO_ERROR",
",",
"0",
")",
"try",
":",
"exact",
"=",
"self",
".",
"dump_walker",
".",
"seek",
"(",
"reading_id",
",",
"target",
"=",
"'id'",
")",
"except",
"UnresolvedIdentifierError",
":",
"return",
"(",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"NO_MORE_READINGS",
")",
",",
"Error",
".",
"NO_ERROR",
",",
"0",
")",
"error",
"=",
"Error",
".",
"NO_ERROR",
"if",
"not",
"exact",
":",
"error",
"=",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"ID_FOUND_FOR_ANOTHER_STREAM",
")",
"return",
"(",
"error",
",",
"error",
".",
"NO_ERROR",
",",
"self",
".",
"dump_walker",
".",
"count",
"(",
")",
")"
] |
Seek the dump streamer to a given ID.
Returns:
(int, int, int): Two error codes and the count of remaining readings.
The first error code covers the seeking process.
The second error code covers the stream counting process (cannot fail)
The third item in the tuple is the number of readings left in the stream.
|
[
"Seek",
"the",
"dump",
"streamer",
"to",
"a",
"given",
"ID",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L205-L230
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.dump_next
|
def dump_next(self):
"""Dump the next reading from the stream.
Returns:
IOTileReading: The next reading or None if there isn't one
"""
if self.dump_walker is None:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED)
try:
return self.dump_walker.pop()
except StreamEmptyError:
return None
|
python
|
def dump_next(self):
"""Dump the next reading from the stream.
Returns:
IOTileReading: The next reading or None if there isn't one
"""
if self.dump_walker is None:
return pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.STREAM_WALKER_NOT_INITIALIZED)
try:
return self.dump_walker.pop()
except StreamEmptyError:
return None
|
[
"def",
"dump_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"dump_walker",
"is",
"None",
":",
"return",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"STREAM_WALKER_NOT_INITIALIZED",
")",
"try",
":",
"return",
"self",
".",
"dump_walker",
".",
"pop",
"(",
")",
"except",
"StreamEmptyError",
":",
"return",
"None"
] |
Dump the next reading from the stream.
Returns:
IOTileReading: The next reading or None if there isn't one
|
[
"Dump",
"the",
"next",
"reading",
"from",
"the",
"stream",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L232-L245
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
SensorLogSubsystem.highest_stored_id
|
def highest_stored_id(self):
"""Scan through the stored readings and report the highest stored id.
Returns:
int: The highest stored id.
"""
shared = [0]
def _keep_max(_i, reading):
if reading.reading_id > shared[0]:
shared[0] = reading.reading_id
self.engine.scan_storage('storage', _keep_max)
self.engine.scan_storage('streaming', _keep_max)
return shared[0]
|
python
|
def highest_stored_id(self):
"""Scan through the stored readings and report the highest stored id.
Returns:
int: The highest stored id.
"""
shared = [0]
def _keep_max(_i, reading):
if reading.reading_id > shared[0]:
shared[0] = reading.reading_id
self.engine.scan_storage('storage', _keep_max)
self.engine.scan_storage('streaming', _keep_max)
return shared[0]
|
[
"def",
"highest_stored_id",
"(",
"self",
")",
":",
"shared",
"=",
"[",
"0",
"]",
"def",
"_keep_max",
"(",
"_i",
",",
"reading",
")",
":",
"if",
"reading",
".",
"reading_id",
">",
"shared",
"[",
"0",
"]",
":",
"shared",
"[",
"0",
"]",
"=",
"reading",
".",
"reading_id",
"self",
".",
"engine",
".",
"scan_storage",
"(",
"'storage'",
",",
"_keep_max",
")",
"self",
".",
"engine",
".",
"scan_storage",
"(",
"'streaming'",
",",
"_keep_max",
")",
"return",
"shared",
"[",
"0",
"]"
] |
Scan through the stored readings and report the highest stored id.
Returns:
int: The highest stored id.
|
[
"Scan",
"through",
"the",
"stored",
"readings",
"and",
"report",
"the",
"highest",
"stored",
"id",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L247-L262
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
RawSensorLogMixin.rsl_push_reading
|
def rsl_push_reading(self, value, stream_id):
"""Push a reading to the RSL directly."""
#FIXME: Fix this with timestamp from clock manager task
err = self.sensor_log.push(stream_id, 0, value)
return [err]
|
python
|
def rsl_push_reading(self, value, stream_id):
"""Push a reading to the RSL directly."""
#FIXME: Fix this with timestamp from clock manager task
err = self.sensor_log.push(stream_id, 0, value)
return [err]
|
[
"def",
"rsl_push_reading",
"(",
"self",
",",
"value",
",",
"stream_id",
")",
":",
"#FIXME: Fix this with timestamp from clock manager task",
"err",
"=",
"self",
".",
"sensor_log",
".",
"push",
"(",
"stream_id",
",",
"0",
",",
"value",
")",
"return",
"[",
"err",
"]"
] |
Push a reading to the RSL directly.
|
[
"Push",
"a",
"reading",
"to",
"the",
"RSL",
"directly",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L286-L291
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
RawSensorLogMixin.rsl_push_many_readings
|
def rsl_push_many_readings(self, value, count, stream_id):
"""Push many copies of a reading to the RSL."""
#FIXME: Fix this with timestamp from clock manager task
for i in range(1, count+1):
err = self.sensor_log.push(stream_id, 0, value)
if err != Error.NO_ERROR:
return [err, i]
return [Error.NO_ERROR, count]
|
python
|
def rsl_push_many_readings(self, value, count, stream_id):
"""Push many copies of a reading to the RSL."""
#FIXME: Fix this with timestamp from clock manager task
for i in range(1, count+1):
err = self.sensor_log.push(stream_id, 0, value)
if err != Error.NO_ERROR:
return [err, i]
return [Error.NO_ERROR, count]
|
[
"def",
"rsl_push_many_readings",
"(",
"self",
",",
"value",
",",
"count",
",",
"stream_id",
")",
":",
"#FIXME: Fix this with timestamp from clock manager task",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"count",
"+",
"1",
")",
":",
"err",
"=",
"self",
".",
"sensor_log",
".",
"push",
"(",
"stream_id",
",",
"0",
",",
"value",
")",
"if",
"err",
"!=",
"Error",
".",
"NO_ERROR",
":",
"return",
"[",
"err",
",",
"i",
"]",
"return",
"[",
"Error",
".",
"NO_ERROR",
",",
"count",
"]"
] |
Push many copies of a reading to the RSL.
|
[
"Push",
"many",
"copies",
"of",
"a",
"reading",
"to",
"the",
"RSL",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L294-L304
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
RawSensorLogMixin.rsl_count_readings
|
def rsl_count_readings(self):
"""Count how many readings are stored in the RSL."""
storage, output = self.sensor_log.count()
return [Error.NO_ERROR, storage, output]
|
python
|
def rsl_count_readings(self):
"""Count how many readings are stored in the RSL."""
storage, output = self.sensor_log.count()
return [Error.NO_ERROR, storage, output]
|
[
"def",
"rsl_count_readings",
"(",
"self",
")",
":",
"storage",
",",
"output",
"=",
"self",
".",
"sensor_log",
".",
"count",
"(",
")",
"return",
"[",
"Error",
".",
"NO_ERROR",
",",
"storage",
",",
"output",
"]"
] |
Count how many readings are stored in the RSL.
|
[
"Count",
"how",
"many",
"readings",
"are",
"stored",
"in",
"the",
"RSL",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L307-L311
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
RawSensorLogMixin.rsl_dump_stream_begin
|
def rsl_dump_stream_begin(self, stream_id):
"""Begin dumping the contents of a stream."""
err, err2, count = self.sensor_log.dump_begin(stream_id)
#FIXME: Fix this with the uptime of the clock manager task
return [err, err2, count, 0]
|
python
|
def rsl_dump_stream_begin(self, stream_id):
"""Begin dumping the contents of a stream."""
err, err2, count = self.sensor_log.dump_begin(stream_id)
#FIXME: Fix this with the uptime of the clock manager task
return [err, err2, count, 0]
|
[
"def",
"rsl_dump_stream_begin",
"(",
"self",
",",
"stream_id",
")",
":",
"err",
",",
"err2",
",",
"count",
"=",
"self",
".",
"sensor_log",
".",
"dump_begin",
"(",
"stream_id",
")",
"#FIXME: Fix this with the uptime of the clock manager task",
"return",
"[",
"err",
",",
"err2",
",",
"count",
",",
"0",
"]"
] |
Begin dumping the contents of a stream.
|
[
"Begin",
"dumping",
"the",
"contents",
"of",
"a",
"stream",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L328-L334
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py
|
RawSensorLogMixin.rsl_dump_stream_next
|
def rsl_dump_stream_next(self, output_format):
"""Dump the next reading from the output stream."""
timestamp = 0
stream_id = 0
value = 0
reading_id = 0
error = Error.NO_ERROR
reading = self.sensor_log.dump_next()
if reading is not None:
timestamp = reading.raw_time
stream_id = reading.stream
value = reading.value
reading_id = reading.reading_id
else:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS)
if output_format == 0:
return [struct.pack("<LLL", error, timestamp, value)]
elif output_format != 1:
raise ValueError("Output format other than 1 not yet supported")
return [struct.pack("<LLLLH2x", error, timestamp, value, reading_id, stream_id)]
|
python
|
def rsl_dump_stream_next(self, output_format):
"""Dump the next reading from the output stream."""
timestamp = 0
stream_id = 0
value = 0
reading_id = 0
error = Error.NO_ERROR
reading = self.sensor_log.dump_next()
if reading is not None:
timestamp = reading.raw_time
stream_id = reading.stream
value = reading.value
reading_id = reading.reading_id
else:
error = pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.NO_MORE_READINGS)
if output_format == 0:
return [struct.pack("<LLL", error, timestamp, value)]
elif output_format != 1:
raise ValueError("Output format other than 1 not yet supported")
return [struct.pack("<LLLLH2x", error, timestamp, value, reading_id, stream_id)]
|
[
"def",
"rsl_dump_stream_next",
"(",
"self",
",",
"output_format",
")",
":",
"timestamp",
"=",
"0",
"stream_id",
"=",
"0",
"value",
"=",
"0",
"reading_id",
"=",
"0",
"error",
"=",
"Error",
".",
"NO_ERROR",
"reading",
"=",
"self",
".",
"sensor_log",
".",
"dump_next",
"(",
")",
"if",
"reading",
"is",
"not",
"None",
":",
"timestamp",
"=",
"reading",
".",
"raw_time",
"stream_id",
"=",
"reading",
".",
"stream",
"value",
"=",
"reading",
".",
"value",
"reading_id",
"=",
"reading",
".",
"reading_id",
"else",
":",
"error",
"=",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_LOG",
",",
"SensorLogError",
".",
"NO_MORE_READINGS",
")",
"if",
"output_format",
"==",
"0",
":",
"return",
"[",
"struct",
".",
"pack",
"(",
"\"<LLL\"",
",",
"error",
",",
"timestamp",
",",
"value",
")",
"]",
"elif",
"output_format",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Output format other than 1 not yet supported\"",
")",
"return",
"[",
"struct",
".",
"pack",
"(",
"\"<LLLLH2x\"",
",",
"error",
",",
"timestamp",
",",
"value",
",",
"reading_id",
",",
"stream_id",
")",
"]"
] |
Dump the next reading from the output stream.
|
[
"Dump",
"the",
"next",
"reading",
"from",
"the",
"output",
"stream",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L343-L366
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
parse_size_name
|
def parse_size_name(type_name):
"""Calculate size and encoding from a type name.
This method takes a C-style type string like uint8_t[10] and returns
- the total size in bytes
- the unit size of each member (if it's an array)
- the scruct.{pack,unpack} format code for decoding the base type
- whether it is an array.
"""
if ' ' in type_name:
raise ArgumentError("There should not be a space in config variable type specifier", specifier=type_name)
variable = False
count = 1
base_type = type_name
if type_name[-1] == ']':
variable = True
start_index = type_name.find('[')
if start_index == -1:
raise ArgumentError("Could not find matching [ for ] character", specifier=type_name)
count = int(type_name[start_index+1:-1], 0)
base_type = type_name[:start_index]
matched_type = TYPE_CODES.get(base_type)
if matched_type is None:
raise ArgumentError("Could not find base type name", base_type=base_type, type_string=type_name)
base_size = struct.calcsize("<%s" % matched_type)
total_size = base_size*count
return total_size, base_size, matched_type, variable
|
python
|
def parse_size_name(type_name):
"""Calculate size and encoding from a type name.
This method takes a C-style type string like uint8_t[10] and returns
- the total size in bytes
- the unit size of each member (if it's an array)
- the scruct.{pack,unpack} format code for decoding the base type
- whether it is an array.
"""
if ' ' in type_name:
raise ArgumentError("There should not be a space in config variable type specifier", specifier=type_name)
variable = False
count = 1
base_type = type_name
if type_name[-1] == ']':
variable = True
start_index = type_name.find('[')
if start_index == -1:
raise ArgumentError("Could not find matching [ for ] character", specifier=type_name)
count = int(type_name[start_index+1:-1], 0)
base_type = type_name[:start_index]
matched_type = TYPE_CODES.get(base_type)
if matched_type is None:
raise ArgumentError("Could not find base type name", base_type=base_type, type_string=type_name)
base_size = struct.calcsize("<%s" % matched_type)
total_size = base_size*count
return total_size, base_size, matched_type, variable
|
[
"def",
"parse_size_name",
"(",
"type_name",
")",
":",
"if",
"' '",
"in",
"type_name",
":",
"raise",
"ArgumentError",
"(",
"\"There should not be a space in config variable type specifier\"",
",",
"specifier",
"=",
"type_name",
")",
"variable",
"=",
"False",
"count",
"=",
"1",
"base_type",
"=",
"type_name",
"if",
"type_name",
"[",
"-",
"1",
"]",
"==",
"']'",
":",
"variable",
"=",
"True",
"start_index",
"=",
"type_name",
".",
"find",
"(",
"'['",
")",
"if",
"start_index",
"==",
"-",
"1",
":",
"raise",
"ArgumentError",
"(",
"\"Could not find matching [ for ] character\"",
",",
"specifier",
"=",
"type_name",
")",
"count",
"=",
"int",
"(",
"type_name",
"[",
"start_index",
"+",
"1",
":",
"-",
"1",
"]",
",",
"0",
")",
"base_type",
"=",
"type_name",
"[",
":",
"start_index",
"]",
"matched_type",
"=",
"TYPE_CODES",
".",
"get",
"(",
"base_type",
")",
"if",
"matched_type",
"is",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"Could not find base type name\"",
",",
"base_type",
"=",
"base_type",
",",
"type_string",
"=",
"type_name",
")",
"base_size",
"=",
"struct",
".",
"calcsize",
"(",
"\"<%s\"",
"%",
"matched_type",
")",
"total_size",
"=",
"base_size",
"*",
"count",
"return",
"total_size",
",",
"base_size",
",",
"matched_type",
",",
"variable"
] |
Calculate size and encoding from a type name.
This method takes a C-style type string like uint8_t[10] and returns
- the total size in bytes
- the unit size of each member (if it's an array)
- the scruct.{pack,unpack} format code for decoding the base type
- whether it is an array.
|
[
"Calculate",
"size",
"and",
"encoding",
"from",
"a",
"type",
"name",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L446-L479
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
ConfigDescriptor._validate_python_type
|
def _validate_python_type(self, python_type):
"""Validate the possible combinations of python_type and type_name."""
if python_type == 'bool':
if self.variable:
raise ArgumentError("You can only specify a bool python type on a scalar (non-array) type_name", type_name=self.type_name)
return
if python_type == 'string':
if not (self.variable and self.unit_size == 1):
raise ArgumentError("You can only pass a string python type on an array of 1-byte objects", type_name=self.type_name)
return
if python_type is not None:
raise ArgumentError("You can only declare a bool or string python type. Otherwise it must be passed as None", python_type=python_type)
|
python
|
def _validate_python_type(self, python_type):
"""Validate the possible combinations of python_type and type_name."""
if python_type == 'bool':
if self.variable:
raise ArgumentError("You can only specify a bool python type on a scalar (non-array) type_name", type_name=self.type_name)
return
if python_type == 'string':
if not (self.variable and self.unit_size == 1):
raise ArgumentError("You can only pass a string python type on an array of 1-byte objects", type_name=self.type_name)
return
if python_type is not None:
raise ArgumentError("You can only declare a bool or string python type. Otherwise it must be passed as None", python_type=python_type)
|
[
"def",
"_validate_python_type",
"(",
"self",
",",
"python_type",
")",
":",
"if",
"python_type",
"==",
"'bool'",
":",
"if",
"self",
".",
"variable",
":",
"raise",
"ArgumentError",
"(",
"\"You can only specify a bool python type on a scalar (non-array) type_name\"",
",",
"type_name",
"=",
"self",
".",
"type_name",
")",
"return",
"if",
"python_type",
"==",
"'string'",
":",
"if",
"not",
"(",
"self",
".",
"variable",
"and",
"self",
".",
"unit_size",
"==",
"1",
")",
":",
"raise",
"ArgumentError",
"(",
"\"You can only pass a string python type on an array of 1-byte objects\"",
",",
"type_name",
"=",
"self",
".",
"type_name",
")",
"return",
"if",
"python_type",
"is",
"not",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"You can only declare a bool or string python type. Otherwise it must be passed as None\"",
",",
"python_type",
"=",
"python_type",
")"
] |
Validate the possible combinations of python_type and type_name.
|
[
"Validate",
"the",
"possible",
"combinations",
"of",
"python_type",
"and",
"type_name",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L34-L50
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
ConfigDescriptor._convert_default_value
|
def _convert_default_value(self, default):
"""Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
If you pass a bytes object with python_type as True, do not null terminate
it, an additional null termination will be added.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
"""
if default is None:
return None
if isinstance(default, str):
if self.special_type == 'string':
return default.encode('utf-8') + b'\0'
raise DataError("You can only pass a unicode string if you are declaring a string type config variable", default=default)
if isinstance(default, (bytes, bytearray)):
if self.special_type == 'string' and isinstance(default, bytes):
default += b'\0'
return default
if isinstance(default, int):
default = [default]
format_string = "<" + (self.base_type*len(default))
return struct.pack(format_string, *default)
|
python
|
def _convert_default_value(self, default):
"""Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
If you pass a bytes object with python_type as True, do not null terminate
it, an additional null termination will be added.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
"""
if default is None:
return None
if isinstance(default, str):
if self.special_type == 'string':
return default.encode('utf-8') + b'\0'
raise DataError("You can only pass a unicode string if you are declaring a string type config variable", default=default)
if isinstance(default, (bytes, bytearray)):
if self.special_type == 'string' and isinstance(default, bytes):
default += b'\0'
return default
if isinstance(default, int):
default = [default]
format_string = "<" + (self.base_type*len(default))
return struct.pack(format_string, *default)
|
[
"def",
"_convert_default_value",
"(",
"self",
",",
"default",
")",
":",
"if",
"default",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"default",
",",
"str",
")",
":",
"if",
"self",
".",
"special_type",
"==",
"'string'",
":",
"return",
"default",
".",
"encode",
"(",
"'utf-8'",
")",
"+",
"b'\\0'",
"raise",
"DataError",
"(",
"\"You can only pass a unicode string if you are declaring a string type config variable\"",
",",
"default",
"=",
"default",
")",
"if",
"isinstance",
"(",
"default",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
":",
"if",
"self",
".",
"special_type",
"==",
"'string'",
"and",
"isinstance",
"(",
"default",
",",
"bytes",
")",
":",
"default",
"+=",
"b'\\0'",
"return",
"default",
"if",
"isinstance",
"(",
"default",
",",
"int",
")",
":",
"default",
"=",
"[",
"default",
"]",
"format_string",
"=",
"\"<\"",
"+",
"(",
"self",
".",
"base_type",
"*",
"len",
"(",
"default",
")",
")",
"return",
"struct",
".",
"pack",
"(",
"format_string",
",",
"*",
"default",
")"
] |
Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
If you pass a bytes object with python_type as True, do not null terminate
it, an additional null termination will be added.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
|
[
"Convert",
"the",
"passed",
"default",
"value",
"to",
"binary",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L52-L86
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
ConfigDescriptor.clear
|
def clear(self):
"""Clear this config variable to its reset value."""
if self.default_value is None:
self.current_value = bytearray()
else:
self.current_value = bytearray(self.default_value)
|
python
|
def clear(self):
"""Clear this config variable to its reset value."""
if self.default_value is None:
self.current_value = bytearray()
else:
self.current_value = bytearray(self.default_value)
|
[
"def",
"clear",
"(",
"self",
")",
":",
"if",
"self",
".",
"default_value",
"is",
"None",
":",
"self",
".",
"current_value",
"=",
"bytearray",
"(",
")",
"else",
":",
"self",
".",
"current_value",
"=",
"bytearray",
"(",
"self",
".",
"default_value",
")"
] |
Clear this config variable to its reset value.
|
[
"Clear",
"this",
"config",
"variable",
"to",
"its",
"reset",
"value",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L88-L94
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
ConfigDescriptor.update_value
|
def update_value(self, offset, value):
"""Update the binary value currently stored for this config value.
Returns:
int: An opaque error code that can be returned from a set_config rpc
"""
if offset + len(value) > self.total_size:
return Error.INPUT_BUFFER_TOO_LONG
if len(self.current_value) < offset:
self.current_value += bytearray(offset - len(self.current_value))
if len(self.current_value) > offset:
self.current_value = self.current_value[:offset]
self.current_value += bytearray(value)
return 0
|
python
|
def update_value(self, offset, value):
"""Update the binary value currently stored for this config value.
Returns:
int: An opaque error code that can be returned from a set_config rpc
"""
if offset + len(value) > self.total_size:
return Error.INPUT_BUFFER_TOO_LONG
if len(self.current_value) < offset:
self.current_value += bytearray(offset - len(self.current_value))
if len(self.current_value) > offset:
self.current_value = self.current_value[:offset]
self.current_value += bytearray(value)
return 0
|
[
"def",
"update_value",
"(",
"self",
",",
"offset",
",",
"value",
")",
":",
"if",
"offset",
"+",
"len",
"(",
"value",
")",
">",
"self",
".",
"total_size",
":",
"return",
"Error",
".",
"INPUT_BUFFER_TOO_LONG",
"if",
"len",
"(",
"self",
".",
"current_value",
")",
"<",
"offset",
":",
"self",
".",
"current_value",
"+=",
"bytearray",
"(",
"offset",
"-",
"len",
"(",
"self",
".",
"current_value",
")",
")",
"if",
"len",
"(",
"self",
".",
"current_value",
")",
">",
"offset",
":",
"self",
".",
"current_value",
"=",
"self",
".",
"current_value",
"[",
":",
"offset",
"]",
"self",
".",
"current_value",
"+=",
"bytearray",
"(",
"value",
")",
"return",
"0"
] |
Update the binary value currently stored for this config value.
Returns:
int: An opaque error code that can be returned from a set_config rpc
|
[
"Update",
"the",
"binary",
"value",
"currently",
"stored",
"for",
"this",
"config",
"value",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L96-L112
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
ConfigDescriptor.latch
|
def latch(self):
"""Convert the current value inside this config descriptor to a python object.
The conversion proceeds by mapping the given type name to a native
python class and performing the conversion. You can override what
python object is used as the destination class by passing a
python_type parameter to __init__.
The default mapping is:
- char (u)int8_t, (u)int16_t, (u)int32_t: int
- char[] (u)int8_t[], (u)int16_t[]0, u(int32_t): list of int
If you want to parse a char[] or uint8_t[] as a python string, it
needs to be null terminated and you should pass python_type='string'.
If you are declaring a scalar integer type and wish it to be decoded
as a bool, you can pass python_type='bool' to the constructor.
All integers are decoded as little-endian.
Returns:
object: The corresponding python object.
This will either be an int, list of int or string based on the
type_name specified and the optional python_type keyword argument
to the constructor.
Raises:
DataError: if the object cannot be converted to the desired type.
ArgumentError: if an invalid python_type was specified during construction.
"""
if len(self.current_value) == 0:
raise DataError("There was no data in a config variable during latching", name=self.name)
# Make sure the data ends on a unit boundary. This would have happened automatically
# in an actual device by the C runtime 0 padding out the storage area.
remaining = len(self.current_value) % self.unit_size
if remaining > 0:
self.current_value += bytearray(remaining)
if self.special_type == 'string':
if self.current_value[-1] != 0:
raise DataError("String type was specified by data did not end with a null byte", data=self.current_value, name=self.name)
return bytes(self.current_value[:-1]).decode('utf-8')
fmt_code = "<" + (self.base_type * (len(self.current_value) // self.unit_size))
data = struct.unpack(fmt_code, self.current_value)
if self.variable:
data = list(data)
else:
data = data[0]
if self.special_type == 'bool':
data = bool(data)
return data
|
python
|
def latch(self):
"""Convert the current value inside this config descriptor to a python object.
The conversion proceeds by mapping the given type name to a native
python class and performing the conversion. You can override what
python object is used as the destination class by passing a
python_type parameter to __init__.
The default mapping is:
- char (u)int8_t, (u)int16_t, (u)int32_t: int
- char[] (u)int8_t[], (u)int16_t[]0, u(int32_t): list of int
If you want to parse a char[] or uint8_t[] as a python string, it
needs to be null terminated and you should pass python_type='string'.
If you are declaring a scalar integer type and wish it to be decoded
as a bool, you can pass python_type='bool' to the constructor.
All integers are decoded as little-endian.
Returns:
object: The corresponding python object.
This will either be an int, list of int or string based on the
type_name specified and the optional python_type keyword argument
to the constructor.
Raises:
DataError: if the object cannot be converted to the desired type.
ArgumentError: if an invalid python_type was specified during construction.
"""
if len(self.current_value) == 0:
raise DataError("There was no data in a config variable during latching", name=self.name)
# Make sure the data ends on a unit boundary. This would have happened automatically
# in an actual device by the C runtime 0 padding out the storage area.
remaining = len(self.current_value) % self.unit_size
if remaining > 0:
self.current_value += bytearray(remaining)
if self.special_type == 'string':
if self.current_value[-1] != 0:
raise DataError("String type was specified by data did not end with a null byte", data=self.current_value, name=self.name)
return bytes(self.current_value[:-1]).decode('utf-8')
fmt_code = "<" + (self.base_type * (len(self.current_value) // self.unit_size))
data = struct.unpack(fmt_code, self.current_value)
if self.variable:
data = list(data)
else:
data = data[0]
if self.special_type == 'bool':
data = bool(data)
return data
|
[
"def",
"latch",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"current_value",
")",
"==",
"0",
":",
"raise",
"DataError",
"(",
"\"There was no data in a config variable during latching\"",
",",
"name",
"=",
"self",
".",
"name",
")",
"# Make sure the data ends on a unit boundary. This would have happened automatically",
"# in an actual device by the C runtime 0 padding out the storage area.",
"remaining",
"=",
"len",
"(",
"self",
".",
"current_value",
")",
"%",
"self",
".",
"unit_size",
"if",
"remaining",
">",
"0",
":",
"self",
".",
"current_value",
"+=",
"bytearray",
"(",
"remaining",
")",
"if",
"self",
".",
"special_type",
"==",
"'string'",
":",
"if",
"self",
".",
"current_value",
"[",
"-",
"1",
"]",
"!=",
"0",
":",
"raise",
"DataError",
"(",
"\"String type was specified by data did not end with a null byte\"",
",",
"data",
"=",
"self",
".",
"current_value",
",",
"name",
"=",
"self",
".",
"name",
")",
"return",
"bytes",
"(",
"self",
".",
"current_value",
"[",
":",
"-",
"1",
"]",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"fmt_code",
"=",
"\"<\"",
"+",
"(",
"self",
".",
"base_type",
"*",
"(",
"len",
"(",
"self",
".",
"current_value",
")",
"//",
"self",
".",
"unit_size",
")",
")",
"data",
"=",
"struct",
".",
"unpack",
"(",
"fmt_code",
",",
"self",
".",
"current_value",
")",
"if",
"self",
".",
"variable",
":",
"data",
"=",
"list",
"(",
"data",
")",
"else",
":",
"data",
"=",
"data",
"[",
"0",
"]",
"if",
"self",
".",
"special_type",
"==",
"'bool'",
":",
"data",
"=",
"bool",
"(",
"data",
")",
"return",
"data"
] |
Convert the current value inside this config descriptor to a python object.
The conversion proceeds by mapping the given type name to a native
python class and performing the conversion. You can override what
python object is used as the destination class by passing a
python_type parameter to __init__.
The default mapping is:
- char (u)int8_t, (u)int16_t, (u)int32_t: int
- char[] (u)int8_t[], (u)int16_t[]0, u(int32_t): list of int
If you want to parse a char[] or uint8_t[] as a python string, it
needs to be null terminated and you should pass python_type='string'.
If you are declaring a scalar integer type and wish it to be decoded
as a bool, you can pass python_type='bool' to the constructor.
All integers are decoded as little-endian.
Returns:
object: The corresponding python object.
This will either be an int, list of int or string based on the
type_name specified and the optional python_type keyword argument
to the constructor.
Raises:
DataError: if the object cannot be converted to the desired type.
ArgumentError: if an invalid python_type was specified during construction.
|
[
"Convert",
"the",
"current",
"value",
"inside",
"this",
"config",
"descriptor",
"to",
"a",
"python",
"object",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L114-L172
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
EmulatedTile.declare_config_variable
|
def declare_config_variable(self, name, config_id, type_name, default=None, convert=None): #pylint:disable=too-many-arguments;These are all necessary with sane defaults.
"""Declare a config variable that this emulated tile accepts.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
Args:
name (str): A user friendly name for this config variable so that it can
be printed nicely.
config_id (int): A 16-bit integer id number to identify the config variable.
type_name (str): An encoded type name that will be parsed by parse_size_name()
default (object): The default value if there is one. This should be a
python object that will be converted to binary according to the rules for
the config variable type specified in type_name.
convert (str): whether this variable should be converted to a
python string or bool rather than an int or a list of ints. You can
pass either 'bool', 'string' or None
"""
config = ConfigDescriptor(config_id, type_name, default, name=name, python_type=convert)
self._config_variables[config_id] = config
|
python
|
def declare_config_variable(self, name, config_id, type_name, default=None, convert=None): #pylint:disable=too-many-arguments;These are all necessary with sane defaults.
"""Declare a config variable that this emulated tile accepts.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
Args:
name (str): A user friendly name for this config variable so that it can
be printed nicely.
config_id (int): A 16-bit integer id number to identify the config variable.
type_name (str): An encoded type name that will be parsed by parse_size_name()
default (object): The default value if there is one. This should be a
python object that will be converted to binary according to the rules for
the config variable type specified in type_name.
convert (str): whether this variable should be converted to a
python string or bool rather than an int or a list of ints. You can
pass either 'bool', 'string' or None
"""
config = ConfigDescriptor(config_id, type_name, default, name=name, python_type=convert)
self._config_variables[config_id] = config
|
[
"def",
"declare_config_variable",
"(",
"self",
",",
"name",
",",
"config_id",
",",
"type_name",
",",
"default",
"=",
"None",
",",
"convert",
"=",
"None",
")",
":",
"#pylint:disable=too-many-arguments;These are all necessary with sane defaults.",
"config",
"=",
"ConfigDescriptor",
"(",
"config_id",
",",
"type_name",
",",
"default",
",",
"name",
"=",
"name",
",",
"python_type",
"=",
"convert",
")",
"self",
".",
"_config_variables",
"[",
"config_id",
"]",
"=",
"config"
] |
Declare a config variable that this emulated tile accepts.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
Passing a unicode string is only allowed if as_string is True and it
will be encoded as utf-8 and null terminated for use as a default value.
Args:
name (str): A user friendly name for this config variable so that it can
be printed nicely.
config_id (int): A 16-bit integer id number to identify the config variable.
type_name (str): An encoded type name that will be parsed by parse_size_name()
default (object): The default value if there is one. This should be a
python object that will be converted to binary according to the rules for
the config variable type specified in type_name.
convert (str): whether this variable should be converted to a
python string or bool rather than an int or a list of ints. You can
pass either 'bool', 'string' or None
|
[
"Declare",
"a",
"config",
"variable",
"that",
"this",
"emulated",
"tile",
"accepts",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L230-L255
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
EmulatedTile.latch_config_variables
|
def latch_config_variables(self):
"""Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default values in the config
variables have been properly set otherwise DataError will be thrown.
Conceptually this method performs the operation that happens just
before a tile executive hands control to the tile application
firmware. It latches in the value of all config variables at that
point in time.
For convenience, this method does all necessary binary -> python
native object conversion so that you just get python objects back.
Returns:
dict: A dict of str -> object with the config variable values.
The keys in the dict will be the name passed to
`declare_config_variable`.
The values will be the python objects that result from calling
latch() on each config variable. Consult ConfigDescriptor.latch()
for documentation on how that method works.
"""
return {desc.name: desc.latch() for desc in self._config_variables.values()}
|
python
|
def latch_config_variables(self):
"""Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default values in the config
variables have been properly set otherwise DataError will be thrown.
Conceptually this method performs the operation that happens just
before a tile executive hands control to the tile application
firmware. It latches in the value of all config variables at that
point in time.
For convenience, this method does all necessary binary -> python
native object conversion so that you just get python objects back.
Returns:
dict: A dict of str -> object with the config variable values.
The keys in the dict will be the name passed to
`declare_config_variable`.
The values will be the python objects that result from calling
latch() on each config variable. Consult ConfigDescriptor.latch()
for documentation on how that method works.
"""
return {desc.name: desc.latch() for desc in self._config_variables.values()}
|
[
"def",
"latch_config_variables",
"(",
"self",
")",
":",
"return",
"{",
"desc",
".",
"name",
":",
"desc",
".",
"latch",
"(",
")",
"for",
"desc",
"in",
"self",
".",
"_config_variables",
".",
"values",
"(",
")",
"}"
] |
Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default values in the config
variables have been properly set otherwise DataError will be thrown.
Conceptually this method performs the operation that happens just
before a tile executive hands control to the tile application
firmware. It latches in the value of all config variables at that
point in time.
For convenience, this method does all necessary binary -> python
native object conversion so that you just get python objects back.
Returns:
dict: A dict of str -> object with the config variable values.
The keys in the dict will be the name passed to
`declare_config_variable`.
The values will be the python objects that result from calling
latch() on each config variable. Consult ConfigDescriptor.latch()
for documentation on how that method works.
|
[
"Latch",
"the",
"current",
"value",
"of",
"all",
"config",
"variables",
"as",
"python",
"objects",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L268-L295
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
EmulatedTile.reset
|
async def reset(self):
"""Synchronously reset a tile.
This method must be called from the emulation loop and will
synchronously shut down all background tasks running this tile, clear
it to reset state and then restart the initialization background task.
"""
await self._device.emulator.stop_tasks(self.address)
self._handle_reset()
self._logger.info("Tile at address %d has reset itself.", self.address)
self._logger.info("Starting main task for tile at address %d", self.address)
self._device.emulator.add_task(self.address, self._reset_vector())
|
python
|
async def reset(self):
"""Synchronously reset a tile.
This method must be called from the emulation loop and will
synchronously shut down all background tasks running this tile, clear
it to reset state and then restart the initialization background task.
"""
await self._device.emulator.stop_tasks(self.address)
self._handle_reset()
self._logger.info("Tile at address %d has reset itself.", self.address)
self._logger.info("Starting main task for tile at address %d", self.address)
self._device.emulator.add_task(self.address, self._reset_vector())
|
[
"async",
"def",
"reset",
"(",
"self",
")",
":",
"await",
"self",
".",
"_device",
".",
"emulator",
".",
"stop_tasks",
"(",
"self",
".",
"address",
")",
"self",
".",
"_handle_reset",
"(",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Tile at address %d has reset itself.\"",
",",
"self",
".",
"address",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Starting main task for tile at address %d\"",
",",
"self",
".",
"address",
")",
"self",
".",
"_device",
".",
"emulator",
".",
"add_task",
"(",
"self",
".",
"address",
",",
"self",
".",
"_reset_vector",
"(",
")",
")"
] |
Synchronously reset a tile.
This method must be called from the emulation loop and will
synchronously shut down all background tasks running this tile, clear
it to reset state and then restart the initialization background task.
|
[
"Synchronously",
"reset",
"a",
"tile",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L359-L374
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
EmulatedTile.list_config_variables
|
def list_config_variables(self, offset):
"""List defined config variables up to 9 at a time."""
names = sorted(self._config_variables)
names = names[offset:offset + 9]
count = len(names)
if len(names) < 9:
names += [0]*(9 - count)
return [count] + names
|
python
|
def list_config_variables(self, offset):
"""List defined config variables up to 9 at a time."""
names = sorted(self._config_variables)
names = names[offset:offset + 9]
count = len(names)
if len(names) < 9:
names += [0]*(9 - count)
return [count] + names
|
[
"def",
"list_config_variables",
"(",
"self",
",",
"offset",
")",
":",
"names",
"=",
"sorted",
"(",
"self",
".",
"_config_variables",
")",
"names",
"=",
"names",
"[",
"offset",
":",
"offset",
"+",
"9",
"]",
"count",
"=",
"len",
"(",
"names",
")",
"if",
"len",
"(",
"names",
")",
"<",
"9",
":",
"names",
"+=",
"[",
"0",
"]",
"*",
"(",
"9",
"-",
"count",
")",
"return",
"[",
"count",
"]",
"+",
"names"
] |
List defined config variables up to 9 at a time.
|
[
"List",
"defined",
"config",
"variables",
"up",
"to",
"9",
"at",
"a",
"time",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L383-L393
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
EmulatedTile.describe_config_variable
|
def describe_config_variable(self, config_id):
"""Describe the config variable by its id."""
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, 0]
packed_size = config.total_size
packed_size |= int(config.variable) << 15
return [0, 0, 0, config_id, packed_size]
|
python
|
def describe_config_variable(self, config_id):
"""Describe the config variable by its id."""
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, 0]
packed_size = config.total_size
packed_size |= int(config.variable) << 15
return [0, 0, 0, config_id, packed_size]
|
[
"def",
"describe_config_variable",
"(",
"self",
",",
"config_id",
")",
":",
"config",
"=",
"self",
".",
"_config_variables",
".",
"get",
"(",
"config_id",
")",
"if",
"config",
"is",
"None",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"packed_size",
"=",
"config",
".",
"total_size",
"packed_size",
"|=",
"int",
"(",
"config",
".",
"variable",
")",
"<<",
"15",
"return",
"[",
"0",
",",
"0",
",",
"0",
",",
"config_id",
",",
"packed_size",
"]"
] |
Describe the config variable by its id.
|
[
"Describe",
"the",
"config",
"variable",
"by",
"its",
"id",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L396-L406
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
EmulatedTile.set_config_variable
|
def set_config_variable(self, config_id, offset, value):
"""Set a chunk of the current config value's value."""
if self.initialized.is_set():
return [Error.STATE_CHANGE_AT_INVALID_TIME]
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY]
error = config.update_value(offset, value)
return [error]
|
python
|
def set_config_variable(self, config_id, offset, value):
"""Set a chunk of the current config value's value."""
if self.initialized.is_set():
return [Error.STATE_CHANGE_AT_INVALID_TIME]
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY]
error = config.update_value(offset, value)
return [error]
|
[
"def",
"set_config_variable",
"(",
"self",
",",
"config_id",
",",
"offset",
",",
"value",
")",
":",
"if",
"self",
".",
"initialized",
".",
"is_set",
"(",
")",
":",
"return",
"[",
"Error",
".",
"STATE_CHANGE_AT_INVALID_TIME",
"]",
"config",
"=",
"self",
".",
"_config_variables",
".",
"get",
"(",
"config_id",
")",
"if",
"config",
"is",
"None",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
"]",
"error",
"=",
"config",
".",
"update_value",
"(",
"offset",
",",
"value",
")",
"return",
"[",
"error",
"]"
] |
Set a chunk of the current config value's value.
|
[
"Set",
"a",
"chunk",
"of",
"the",
"current",
"config",
"value",
"s",
"value",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L409-L420
|
train
|
iotile/coretools
|
iotileemulate/iotile/emulate/virtual/emulated_tile.py
|
EmulatedTile.get_config_variable
|
def get_config_variable(self, config_id, offset):
"""Get a chunk of a config variable's value."""
config = self._config_variables.get(config_id)
if config is None:
return [b""]
return [bytes(config.current_value[offset:offset + 20])]
|
python
|
def get_config_variable(self, config_id, offset):
"""Get a chunk of a config variable's value."""
config = self._config_variables.get(config_id)
if config is None:
return [b""]
return [bytes(config.current_value[offset:offset + 20])]
|
[
"def",
"get_config_variable",
"(",
"self",
",",
"config_id",
",",
"offset",
")",
":",
"config",
"=",
"self",
".",
"_config_variables",
".",
"get",
"(",
"config_id",
")",
"if",
"config",
"is",
"None",
":",
"return",
"[",
"b\"\"",
"]",
"return",
"[",
"bytes",
"(",
"config",
".",
"current_value",
"[",
"offset",
":",
"offset",
"+",
"20",
"]",
")",
"]"
] |
Get a chunk of a config variable's value.
|
[
"Get",
"a",
"chunk",
"of",
"a",
"config",
"variable",
"s",
"value",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L423-L430
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/legacy.py
|
DeviceAdapter.add_callback
|
def add_callback(self, name, func):
"""Add a callback when Device events happen
Args:
name (str): currently support 'on_scan' and 'on_disconnect'
func (callable): the function that should be called
"""
if name not in self.callbacks:
raise ValueError("Unknown callback name: %s" % name)
self.callbacks[name].add(func)
|
python
|
def add_callback(self, name, func):
"""Add a callback when Device events happen
Args:
name (str): currently support 'on_scan' and 'on_disconnect'
func (callable): the function that should be called
"""
if name not in self.callbacks:
raise ValueError("Unknown callback name: %s" % name)
self.callbacks[name].add(func)
|
[
"def",
"add_callback",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"callbacks",
":",
"raise",
"ValueError",
"(",
"\"Unknown callback name: %s\"",
"%",
"name",
")",
"self",
".",
"callbacks",
"[",
"name",
"]",
".",
"add",
"(",
"func",
")"
] |
Add a callback when Device events happen
Args:
name (str): currently support 'on_scan' and 'on_disconnect'
func (callable): the function that should be called
|
[
"Add",
"a",
"callback",
"when",
"Device",
"events",
"happen"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L120-L131
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/legacy.py
|
DeviceAdapter.connect_sync
|
def connect_sync(self, connection_id, connection_string):
"""Synchronously connect to a device
Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
"""
calldone = threading.Event()
results = {}
def connect_done(callback_connid, callback_adapterid, callback_success, failure_reason):
results['success'] = callback_success
results['failure_reason'] = failure_reason
calldone.set() # Be sure to set after all operations are done to prevent race condition
self.connect_async(connection_id, connection_string, connect_done)
calldone.wait()
return results
|
python
|
def connect_sync(self, connection_id, connection_string):
"""Synchronously connect to a device
Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
"""
calldone = threading.Event()
results = {}
def connect_done(callback_connid, callback_adapterid, callback_success, failure_reason):
results['success'] = callback_success
results['failure_reason'] = failure_reason
calldone.set() # Be sure to set after all operations are done to prevent race condition
self.connect_async(connection_id, connection_string, connect_done)
calldone.wait()
return results
|
[
"def",
"connect_sync",
"(",
"self",
",",
"connection_id",
",",
"connection_string",
")",
":",
"calldone",
"=",
"threading",
".",
"Event",
"(",
")",
"results",
"=",
"{",
"}",
"def",
"connect_done",
"(",
"callback_connid",
",",
"callback_adapterid",
",",
"callback_success",
",",
"failure_reason",
")",
":",
"results",
"[",
"'success'",
"]",
"=",
"callback_success",
"results",
"[",
"'failure_reason'",
"]",
"=",
"failure_reason",
"calldone",
".",
"set",
"(",
")",
"# Be sure to set after all operations are done to prevent race condition",
"self",
".",
"connect_async",
"(",
"connection_id",
",",
"connection_string",
",",
"connect_done",
")",
"calldone",
".",
"wait",
"(",
")",
"return",
"results"
] |
Synchronously connect to a device
Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
|
[
"Synchronously",
"connect",
"to",
"a",
"device"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L151-L176
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/legacy.py
|
DeviceAdapter.disconnect_sync
|
def disconnect_sync(self, conn_id):
"""Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
"""
done = threading.Event()
result = {}
def disconnect_done(conn_id, adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.disconnect_async(conn_id, disconnect_done)
done.wait()
return result
|
python
|
def disconnect_sync(self, conn_id):
"""Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
"""
done = threading.Event()
result = {}
def disconnect_done(conn_id, adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.disconnect_async(conn_id, disconnect_done)
done.wait()
return result
|
[
"def",
"disconnect_sync",
"(",
"self",
",",
"conn_id",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"disconnect_done",
"(",
"conn_id",
",",
"adapter_id",
",",
"status",
",",
"reason",
")",
":",
"result",
"[",
"'success'",
"]",
"=",
"status",
"result",
"[",
"'failure_reason'",
"]",
"=",
"reason",
"done",
".",
"set",
"(",
")",
"self",
".",
"disconnect_async",
"(",
"conn_id",
",",
"disconnect_done",
")",
"done",
".",
"wait",
"(",
")",
"return",
"result"
] |
Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed
|
[
"Synchronously",
"disconnect",
"from",
"a",
"connected",
"device"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L189-L212
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/legacy.py
|
DeviceAdapter.probe_sync
|
def probe_sync(self):
"""Synchronously probe for devices on this adapter."""
done = threading.Event()
result = {}
def probe_done(adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.probe_async(probe_done)
done.wait()
return result
|
python
|
def probe_sync(self):
"""Synchronously probe for devices on this adapter."""
done = threading.Event()
result = {}
def probe_done(adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.probe_async(probe_done)
done.wait()
return result
|
[
"def",
"probe_sync",
"(",
"self",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"probe_done",
"(",
"adapter_id",
",",
"status",
",",
"reason",
")",
":",
"result",
"[",
"'success'",
"]",
"=",
"status",
"result",
"[",
"'failure_reason'",
"]",
"=",
"reason",
"done",
".",
"set",
"(",
")",
"self",
".",
"probe_async",
"(",
"probe_done",
")",
"done",
".",
"wait",
"(",
")",
"return",
"result"
] |
Synchronously probe for devices on this adapter.
|
[
"Synchronously",
"probe",
"for",
"devices",
"on",
"this",
"adapter",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L288-L302
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/transport/adapter/legacy.py
|
DeviceAdapter.send_rpc_sync
|
def send_rpc_sync(self, conn_id, address, rpc_id, payload, timeout):
"""Synchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (bytearray): the payload of the command
timeout (float): the number of seconds to wait for the RPC to execute
Returns:
dict: A dictionary with four elements
'success': a bool indicating whether we received a response to our attempted RPC
'failure_reason': a string with the reason for the failure if success == False
'status': the one byte status code returned for the RPC if success == True else None
'payload': a bytearray with the payload returned by RPC if success == True else None
"""
done = threading.Event()
result = {}
def send_rpc_done(conn_id, adapter_id, status, reason, rpc_status, resp_payload):
result['success'] = status
result['failure_reason'] = reason
result['status'] = rpc_status
result['payload'] = resp_payload
done.set()
self.send_rpc_async(conn_id, address, rpc_id, payload, timeout, send_rpc_done)
done.wait()
return result
|
python
|
def send_rpc_sync(self, conn_id, address, rpc_id, payload, timeout):
"""Synchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (bytearray): the payload of the command
timeout (float): the number of seconds to wait for the RPC to execute
Returns:
dict: A dictionary with four elements
'success': a bool indicating whether we received a response to our attempted RPC
'failure_reason': a string with the reason for the failure if success == False
'status': the one byte status code returned for the RPC if success == True else None
'payload': a bytearray with the payload returned by RPC if success == True else None
"""
done = threading.Event()
result = {}
def send_rpc_done(conn_id, adapter_id, status, reason, rpc_status, resp_payload):
result['success'] = status
result['failure_reason'] = reason
result['status'] = rpc_status
result['payload'] = resp_payload
done.set()
self.send_rpc_async(conn_id, address, rpc_id, payload, timeout, send_rpc_done)
done.wait()
return result
|
[
"def",
"send_rpc_sync",
"(",
"self",
",",
"conn_id",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"timeout",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"send_rpc_done",
"(",
"conn_id",
",",
"adapter_id",
",",
"status",
",",
"reason",
",",
"rpc_status",
",",
"resp_payload",
")",
":",
"result",
"[",
"'success'",
"]",
"=",
"status",
"result",
"[",
"'failure_reason'",
"]",
"=",
"reason",
"result",
"[",
"'status'",
"]",
"=",
"rpc_status",
"result",
"[",
"'payload'",
"]",
"=",
"resp_payload",
"done",
".",
"set",
"(",
")",
"self",
".",
"send_rpc_async",
"(",
"conn_id",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"timeout",
",",
"send_rpc_done",
")",
"done",
".",
"wait",
"(",
")",
"return",
"result"
] |
Synchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (bytearray): the payload of the command
timeout (float): the number of seconds to wait for the RPC to execute
Returns:
dict: A dictionary with four elements
'success': a bool indicating whether we received a response to our attempted RPC
'failure_reason': a string with the reason for the failure if success == False
'status': the one byte status code returned for the RPC if success == True else None
'payload': a bytearray with the payload returned by RPC if success == True else None
|
[
"Synchronously",
"send",
"an",
"RPC",
"to",
"this",
"IOTile",
"device"
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L325-L357
|
train
|
iotile/coretools
|
iotilecore/iotile/core/hw/auth/auth_provider.py
|
AuthProvider.FindByName
|
def FindByName(cls, name):
"""Find a specific installed auth provider by name."""
reg = ComponentRegistry()
for _, entry in reg.load_extensions('iotile.auth_provider', name_filter=name):
return entry
|
python
|
def FindByName(cls, name):
"""Find a specific installed auth provider by name."""
reg = ComponentRegistry()
for _, entry in reg.load_extensions('iotile.auth_provider', name_filter=name):
return entry
|
[
"def",
"FindByName",
"(",
"cls",
",",
"name",
")",
":",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_",
",",
"entry",
"in",
"reg",
".",
"load_extensions",
"(",
"'iotile.auth_provider'",
",",
"name_filter",
"=",
"name",
")",
":",
"return",
"entry"
] |
Find a specific installed auth provider by name.
|
[
"Find",
"a",
"specific",
"installed",
"auth",
"provider",
"by",
"name",
"."
] |
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/auth_provider.py#L51-L56
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.