id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
247,300 | jorgenschaefer/elpy | elpy/server.py | ElpyRPCServer.rpc_refactor | def rpc_refactor(self, filename, method, args):
"""Return a list of changes from the refactoring action.
A change is a dictionary describing the change. See
elpy.refactor.translate_changes for a description.
"""
try:
from elpy import refactor
except:
raise ImportError("Rope not installed, refactorings unavailable")
if args is None:
args = ()
ref = refactor.Refactor(self.project_root, filename)
return ref.get_changes(method, *args) | python | def rpc_refactor(self, filename, method, args):
try:
from elpy import refactor
except:
raise ImportError("Rope not installed, refactorings unavailable")
if args is None:
args = ()
ref = refactor.Refactor(self.project_root, filename)
return ref.get_changes(method, *args) | [
"def",
"rpc_refactor",
"(",
"self",
",",
"filename",
",",
"method",
",",
"args",
")",
":",
"try",
":",
"from",
"elpy",
"import",
"refactor",
"except",
":",
"raise",
"ImportError",
"(",
"\"Rope not installed, refactorings unavailable\"",
")",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"(",
")",
"ref",
"=",
"refactor",
".",
"Refactor",
"(",
"self",
".",
"project_root",
",",
"filename",
")",
"return",
"ref",
".",
"get_changes",
"(",
"method",
",",
"*",
"args",
")"
] | Return a list of changes from the refactoring action.
A change is a dictionary describing the change. See
elpy.refactor.translate_changes for a description. | [
"Return",
"a",
"list",
"of",
"changes",
"from",
"the",
"refactoring",
"action",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L172-L186 |
247,301 | jorgenschaefer/elpy | elpy/server.py | ElpyRPCServer.rpc_get_names | def rpc_get_names(self, filename, source, offset):
"""Get all possible names
"""
source = get_source(source)
if hasattr(self.backend, "rpc_get_names"):
return self.backend.rpc_get_names(filename, source, offset)
else:
raise Fault("get_names not implemented by current backend",
code=400) | python | def rpc_get_names(self, filename, source, offset):
source = get_source(source)
if hasattr(self.backend, "rpc_get_names"):
return self.backend.rpc_get_names(filename, source, offset)
else:
raise Fault("get_names not implemented by current backend",
code=400) | [
"def",
"rpc_get_names",
"(",
"self",
",",
"filename",
",",
"source",
",",
"offset",
")",
":",
"source",
"=",
"get_source",
"(",
"source",
")",
"if",
"hasattr",
"(",
"self",
".",
"backend",
",",
"\"rpc_get_names\"",
")",
":",
"return",
"self",
".",
"backend",
".",
"rpc_get_names",
"(",
"filename",
",",
"source",
",",
"offset",
")",
"else",
":",
"raise",
"Fault",
"(",
"\"get_names not implemented by current backend\"",
",",
"code",
"=",
"400",
")"
] | Get all possible names | [
"Get",
"all",
"possible",
"names"
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L199-L208 |
247,302 | jorgenschaefer/elpy | elpy/jedibackend.py | pos_to_linecol | def pos_to_linecol(text, pos):
"""Return a tuple of line and column for offset pos in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why.
"""
line_start = text.rfind("\n", 0, pos) + 1
line = text.count("\n", 0, line_start) + 1
col = pos - line_start
return line, col | python | def pos_to_linecol(text, pos):
line_start = text.rfind("\n", 0, pos) + 1
line = text.count("\n", 0, line_start) + 1
col = pos - line_start
return line, col | [
"def",
"pos_to_linecol",
"(",
"text",
",",
"pos",
")",
":",
"line_start",
"=",
"text",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"pos",
")",
"+",
"1",
"line",
"=",
"text",
".",
"count",
"(",
"\"\\n\"",
",",
"0",
",",
"line_start",
")",
"+",
"1",
"col",
"=",
"pos",
"-",
"line_start",
"return",
"line",
",",
"col"
] | Return a tuple of line and column for offset pos in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why. | [
"Return",
"a",
"tuple",
"of",
"line",
"and",
"column",
"for",
"offset",
"pos",
"in",
"text",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L272-L283 |
247,303 | jorgenschaefer/elpy | elpy/jedibackend.py | linecol_to_pos | def linecol_to_pos(text, line, col):
"""Return the offset of this line and column in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why.
"""
nth_newline_offset = 0
for i in range(line - 1):
new_offset = text.find("\n", nth_newline_offset)
if new_offset < 0:
raise ValueError("Text does not have {0} lines."
.format(line))
nth_newline_offset = new_offset + 1
offset = nth_newline_offset + col
if offset > len(text):
raise ValueError("Line {0} column {1} is not within the text"
.format(line, col))
return offset | python | def linecol_to_pos(text, line, col):
nth_newline_offset = 0
for i in range(line - 1):
new_offset = text.find("\n", nth_newline_offset)
if new_offset < 0:
raise ValueError("Text does not have {0} lines."
.format(line))
nth_newline_offset = new_offset + 1
offset = nth_newline_offset + col
if offset > len(text):
raise ValueError("Line {0} column {1} is not within the text"
.format(line, col))
return offset | [
"def",
"linecol_to_pos",
"(",
"text",
",",
"line",
",",
"col",
")",
":",
"nth_newline_offset",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"line",
"-",
"1",
")",
":",
"new_offset",
"=",
"text",
".",
"find",
"(",
"\"\\n\"",
",",
"nth_newline_offset",
")",
"if",
"new_offset",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Text does not have {0} lines.\"",
".",
"format",
"(",
"line",
")",
")",
"nth_newline_offset",
"=",
"new_offset",
"+",
"1",
"offset",
"=",
"nth_newline_offset",
"+",
"col",
"if",
"offset",
">",
"len",
"(",
"text",
")",
":",
"raise",
"ValueError",
"(",
"\"Line {0} column {1} is not within the text\"",
".",
"format",
"(",
"line",
",",
"col",
")",
")",
"return",
"offset"
] | Return the offset of this line and column in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why. | [
"Return",
"the",
"offset",
"of",
"this",
"line",
"and",
"column",
"in",
"text",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L286-L305 |
247,304 | jorgenschaefer/elpy | elpy/jedibackend.py | JediBackend.rpc_get_oneline_docstring | def rpc_get_oneline_docstring(self, filename, source, offset):
"""Return a oneline docstring for the symbol at offset"""
line, column = pos_to_linecol(source, offset)
definitions = run_with_debug(jedi, 'goto_definitions',
source=source, line=line, column=column,
path=filename, encoding='utf-8')
assignments = run_with_debug(jedi, 'goto_assignments',
source=source, line=line, column=column,
path=filename, encoding='utf-8')
if definitions:
definition = definitions[0]
else:
definition = None
if assignments:
assignment = assignments[0]
else:
assignment = None
if definition:
# Get name
if definition.type in ['function', 'class']:
raw_name = definition.name
name = '{}()'.format(raw_name)
doc = definition.docstring().split('\n')
elif definition.type in ['module']:
raw_name = definition.name
name = '{} {}'.format(raw_name, definition.type)
doc = definition.docstring().split('\n')
elif (definition.type in ['instance']
and hasattr(assignment, "name")):
raw_name = assignment.name
name = raw_name
doc = assignment.docstring().split('\n')
else:
return None
# Keep only the first paragraph that is not a function declaration
lines = []
call = "{}(".format(raw_name)
# last line
doc.append('')
for i in range(len(doc)):
if doc[i] == '' and len(lines) != 0:
paragraph = " ".join(lines)
lines = []
if call != paragraph[0:len(call)]:
break
paragraph = ""
continue
lines.append(doc[i])
# Keep only the first sentence
onelinedoc = paragraph.split('. ', 1)
if len(onelinedoc) == 2:
onelinedoc = onelinedoc[0] + '.'
else:
onelinedoc = onelinedoc[0]
if onelinedoc == '':
onelinedoc = "No documentation"
return {"name": name,
"doc": onelinedoc}
return None | python | def rpc_get_oneline_docstring(self, filename, source, offset):
line, column = pos_to_linecol(source, offset)
definitions = run_with_debug(jedi, 'goto_definitions',
source=source, line=line, column=column,
path=filename, encoding='utf-8')
assignments = run_with_debug(jedi, 'goto_assignments',
source=source, line=line, column=column,
path=filename, encoding='utf-8')
if definitions:
definition = definitions[0]
else:
definition = None
if assignments:
assignment = assignments[0]
else:
assignment = None
if definition:
# Get name
if definition.type in ['function', 'class']:
raw_name = definition.name
name = '{}()'.format(raw_name)
doc = definition.docstring().split('\n')
elif definition.type in ['module']:
raw_name = definition.name
name = '{} {}'.format(raw_name, definition.type)
doc = definition.docstring().split('\n')
elif (definition.type in ['instance']
and hasattr(assignment, "name")):
raw_name = assignment.name
name = raw_name
doc = assignment.docstring().split('\n')
else:
return None
# Keep only the first paragraph that is not a function declaration
lines = []
call = "{}(".format(raw_name)
# last line
doc.append('')
for i in range(len(doc)):
if doc[i] == '' and len(lines) != 0:
paragraph = " ".join(lines)
lines = []
if call != paragraph[0:len(call)]:
break
paragraph = ""
continue
lines.append(doc[i])
# Keep only the first sentence
onelinedoc = paragraph.split('. ', 1)
if len(onelinedoc) == 2:
onelinedoc = onelinedoc[0] + '.'
else:
onelinedoc = onelinedoc[0]
if onelinedoc == '':
onelinedoc = "No documentation"
return {"name": name,
"doc": onelinedoc}
return None | [
"def",
"rpc_get_oneline_docstring",
"(",
"self",
",",
"filename",
",",
"source",
",",
"offset",
")",
":",
"line",
",",
"column",
"=",
"pos_to_linecol",
"(",
"source",
",",
"offset",
")",
"definitions",
"=",
"run_with_debug",
"(",
"jedi",
",",
"'goto_definitions'",
",",
"source",
"=",
"source",
",",
"line",
"=",
"line",
",",
"column",
"=",
"column",
",",
"path",
"=",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"assignments",
"=",
"run_with_debug",
"(",
"jedi",
",",
"'goto_assignments'",
",",
"source",
"=",
"source",
",",
"line",
"=",
"line",
",",
"column",
"=",
"column",
",",
"path",
"=",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"definitions",
":",
"definition",
"=",
"definitions",
"[",
"0",
"]",
"else",
":",
"definition",
"=",
"None",
"if",
"assignments",
":",
"assignment",
"=",
"assignments",
"[",
"0",
"]",
"else",
":",
"assignment",
"=",
"None",
"if",
"definition",
":",
"# Get name",
"if",
"definition",
".",
"type",
"in",
"[",
"'function'",
",",
"'class'",
"]",
":",
"raw_name",
"=",
"definition",
".",
"name",
"name",
"=",
"'{}()'",
".",
"format",
"(",
"raw_name",
")",
"doc",
"=",
"definition",
".",
"docstring",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"elif",
"definition",
".",
"type",
"in",
"[",
"'module'",
"]",
":",
"raw_name",
"=",
"definition",
".",
"name",
"name",
"=",
"'{} {}'",
".",
"format",
"(",
"raw_name",
",",
"definition",
".",
"type",
")",
"doc",
"=",
"definition",
".",
"docstring",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"elif",
"(",
"definition",
".",
"type",
"in",
"[",
"'instance'",
"]",
"and",
"hasattr",
"(",
"assignment",
",",
"\"name\"",
")",
")",
":",
"raw_name",
"=",
"assignment",
".",
"name",
"name",
"=",
"raw_name",
"doc",
"=",
"assignment",
".",
"docstring",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"else",
":",
"return",
"None",
"# Keep only the first paragraph that is not a function declaration",
"lines",
"=",
"[",
"]",
"call",
"=",
"\"{}(\"",
".",
"format",
"(",
"raw_name",
")",
"# last line",
"doc",
".",
"append",
"(",
"''",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"doc",
")",
")",
":",
"if",
"doc",
"[",
"i",
"]",
"==",
"''",
"and",
"len",
"(",
"lines",
")",
"!=",
"0",
":",
"paragraph",
"=",
"\" \"",
".",
"join",
"(",
"lines",
")",
"lines",
"=",
"[",
"]",
"if",
"call",
"!=",
"paragraph",
"[",
"0",
":",
"len",
"(",
"call",
")",
"]",
":",
"break",
"paragraph",
"=",
"\"\"",
"continue",
"lines",
".",
"append",
"(",
"doc",
"[",
"i",
"]",
")",
"# Keep only the first sentence",
"onelinedoc",
"=",
"paragraph",
".",
"split",
"(",
"'. '",
",",
"1",
")",
"if",
"len",
"(",
"onelinedoc",
")",
"==",
"2",
":",
"onelinedoc",
"=",
"onelinedoc",
"[",
"0",
"]",
"+",
"'.'",
"else",
":",
"onelinedoc",
"=",
"onelinedoc",
"[",
"0",
"]",
"if",
"onelinedoc",
"==",
"''",
":",
"onelinedoc",
"=",
"\"No documentation\"",
"return",
"{",
"\"name\"",
":",
"name",
",",
"\"doc\"",
":",
"onelinedoc",
"}",
"return",
"None"
] | Return a oneline docstring for the symbol at offset | [
"Return",
"a",
"oneline",
"docstring",
"for",
"the",
"symbol",
"at",
"offset"
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L155-L213 |
247,305 | jorgenschaefer/elpy | elpy/jedibackend.py | JediBackend.rpc_get_usages | def rpc_get_usages(self, filename, source, offset):
"""Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset.
"""
line, column = pos_to_linecol(source, offset)
uses = run_with_debug(jedi, 'usages',
source=source, line=line, column=column,
path=filename, encoding='utf-8')
if uses is None:
return None
result = []
for use in uses:
if use.module_path == filename:
offset = linecol_to_pos(source, use.line, use.column)
elif use.module_path is not None:
with open(use.module_path) as f:
text = f.read()
offset = linecol_to_pos(text, use.line, use.column)
result.append({"name": use.name,
"filename": use.module_path,
"offset": offset})
return result | python | def rpc_get_usages(self, filename, source, offset):
line, column = pos_to_linecol(source, offset)
uses = run_with_debug(jedi, 'usages',
source=source, line=line, column=column,
path=filename, encoding='utf-8')
if uses is None:
return None
result = []
for use in uses:
if use.module_path == filename:
offset = linecol_to_pos(source, use.line, use.column)
elif use.module_path is not None:
with open(use.module_path) as f:
text = f.read()
offset = linecol_to_pos(text, use.line, use.column)
result.append({"name": use.name,
"filename": use.module_path,
"offset": offset})
return result | [
"def",
"rpc_get_usages",
"(",
"self",
",",
"filename",
",",
"source",
",",
"offset",
")",
":",
"line",
",",
"column",
"=",
"pos_to_linecol",
"(",
"source",
",",
"offset",
")",
"uses",
"=",
"run_with_debug",
"(",
"jedi",
",",
"'usages'",
",",
"source",
"=",
"source",
",",
"line",
"=",
"line",
",",
"column",
"=",
"column",
",",
"path",
"=",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"uses",
"is",
"None",
":",
"return",
"None",
"result",
"=",
"[",
"]",
"for",
"use",
"in",
"uses",
":",
"if",
"use",
".",
"module_path",
"==",
"filename",
":",
"offset",
"=",
"linecol_to_pos",
"(",
"source",
",",
"use",
".",
"line",
",",
"use",
".",
"column",
")",
"elif",
"use",
".",
"module_path",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"use",
".",
"module_path",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",
"offset",
"=",
"linecol_to_pos",
"(",
"text",
",",
"use",
".",
"line",
",",
"use",
".",
"column",
")",
"result",
".",
"append",
"(",
"{",
"\"name\"",
":",
"use",
".",
"name",
",",
"\"filename\"",
":",
"use",
".",
"module_path",
",",
"\"offset\"",
":",
"offset",
"}",
")",
"return",
"result"
] | Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset. | [
"Return",
"the",
"uses",
"of",
"the",
"symbol",
"at",
"offset",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L215-L241 |
247,306 | jorgenschaefer/elpy | elpy/jedibackend.py | JediBackend.rpc_get_names | def rpc_get_names(self, filename, source, offset):
"""Return the list of possible names"""
names = jedi.api.names(source=source,
path=filename, encoding='utf-8',
all_scopes=True,
definitions=True,
references=True)
result = []
for name in names:
if name.module_path == filename:
offset = linecol_to_pos(source, name.line, name.column)
elif name.module_path is not None:
with open(name.module_path) as f:
text = f.read()
offset = linecol_to_pos(text, name.line, name.column)
result.append({"name": name.name,
"filename": name.module_path,
"offset": offset})
return result | python | def rpc_get_names(self, filename, source, offset):
names = jedi.api.names(source=source,
path=filename, encoding='utf-8',
all_scopes=True,
definitions=True,
references=True)
result = []
for name in names:
if name.module_path == filename:
offset = linecol_to_pos(source, name.line, name.column)
elif name.module_path is not None:
with open(name.module_path) as f:
text = f.read()
offset = linecol_to_pos(text, name.line, name.column)
result.append({"name": name.name,
"filename": name.module_path,
"offset": offset})
return result | [
"def",
"rpc_get_names",
"(",
"self",
",",
"filename",
",",
"source",
",",
"offset",
")",
":",
"names",
"=",
"jedi",
".",
"api",
".",
"names",
"(",
"source",
"=",
"source",
",",
"path",
"=",
"filename",
",",
"encoding",
"=",
"'utf-8'",
",",
"all_scopes",
"=",
"True",
",",
"definitions",
"=",
"True",
",",
"references",
"=",
"True",
")",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"if",
"name",
".",
"module_path",
"==",
"filename",
":",
"offset",
"=",
"linecol_to_pos",
"(",
"source",
",",
"name",
".",
"line",
",",
"name",
".",
"column",
")",
"elif",
"name",
".",
"module_path",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"name",
".",
"module_path",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",
"offset",
"=",
"linecol_to_pos",
"(",
"text",
",",
"name",
".",
"line",
",",
"name",
".",
"column",
")",
"result",
".",
"append",
"(",
"{",
"\"name\"",
":",
"name",
".",
"name",
",",
"\"filename\"",
":",
"name",
".",
"module_path",
",",
"\"offset\"",
":",
"offset",
"}",
")",
"return",
"result"
] | Return the list of possible names | [
"Return",
"the",
"list",
"of",
"possible",
"names"
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L243-L262 |
247,307 | jorgenschaefer/elpy | elpy/refactor.py | options | def options(description, **kwargs):
"""Decorator to set some options on a method."""
def set_notes(function):
function.refactor_notes = {'name': function.__name__,
'category': "Miscellaneous",
'description': description,
'doc': getattr(function, '__doc__',
''),
'args': []}
function.refactor_notes.update(kwargs)
return function
return set_notes | python | def options(description, **kwargs):
def set_notes(function):
function.refactor_notes = {'name': function.__name__,
'category': "Miscellaneous",
'description': description,
'doc': getattr(function, '__doc__',
''),
'args': []}
function.refactor_notes.update(kwargs)
return function
return set_notes | [
"def",
"options",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"set_notes",
"(",
"function",
")",
":",
"function",
".",
"refactor_notes",
"=",
"{",
"'name'",
":",
"function",
".",
"__name__",
",",
"'category'",
":",
"\"Miscellaneous\"",
",",
"'description'",
":",
"description",
",",
"'doc'",
":",
"getattr",
"(",
"function",
",",
"'__doc__'",
",",
"''",
")",
",",
"'args'",
":",
"[",
"]",
"}",
"function",
".",
"refactor_notes",
".",
"update",
"(",
"kwargs",
")",
"return",
"function",
"return",
"set_notes"
] | Decorator to set some options on a method. | [
"Decorator",
"to",
"set",
"some",
"options",
"on",
"a",
"method",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L75-L86 |
247,308 | jorgenschaefer/elpy | elpy/refactor.py | translate_changes | def translate_changes(initial_change):
"""Translate rope.base.change.Change instances to dictionaries.
See Refactor.get_changes for an explanation of the resulting
dictionary.
"""
agenda = [initial_change]
result = []
while agenda:
change = agenda.pop(0)
if isinstance(change, rope_change.ChangeSet):
agenda.extend(change.changes)
elif isinstance(change, rope_change.ChangeContents):
result.append({'action': 'change',
'file': change.resource.real_path,
'contents': change.new_contents,
'diff': change.get_description()})
elif isinstance(change, rope_change.CreateFile):
result.append({'action': 'create',
'type': 'file',
'file': change.resource.real_path})
elif isinstance(change, rope_change.CreateFolder):
result.append({'action': 'create',
'type': 'directory',
'path': change.resource.real_path})
elif isinstance(change, rope_change.MoveResource):
result.append({'action': 'move',
'type': ('directory'
if change.new_resource.is_folder()
else 'file'),
'source': change.resource.real_path,
'destination': change.new_resource.real_path})
elif isinstance(change, rope_change.RemoveResource):
if change.resource.is_folder():
result.append({'action': 'delete',
'type': 'directory',
'path': change.resource.real_path})
else:
result.append({'action': 'delete',
'type': 'file',
'file': change.resource.real_path})
return result | python | def translate_changes(initial_change):
agenda = [initial_change]
result = []
while agenda:
change = agenda.pop(0)
if isinstance(change, rope_change.ChangeSet):
agenda.extend(change.changes)
elif isinstance(change, rope_change.ChangeContents):
result.append({'action': 'change',
'file': change.resource.real_path,
'contents': change.new_contents,
'diff': change.get_description()})
elif isinstance(change, rope_change.CreateFile):
result.append({'action': 'create',
'type': 'file',
'file': change.resource.real_path})
elif isinstance(change, rope_change.CreateFolder):
result.append({'action': 'create',
'type': 'directory',
'path': change.resource.real_path})
elif isinstance(change, rope_change.MoveResource):
result.append({'action': 'move',
'type': ('directory'
if change.new_resource.is_folder()
else 'file'),
'source': change.resource.real_path,
'destination': change.new_resource.real_path})
elif isinstance(change, rope_change.RemoveResource):
if change.resource.is_folder():
result.append({'action': 'delete',
'type': 'directory',
'path': change.resource.real_path})
else:
result.append({'action': 'delete',
'type': 'file',
'file': change.resource.real_path})
return result | [
"def",
"translate_changes",
"(",
"initial_change",
")",
":",
"agenda",
"=",
"[",
"initial_change",
"]",
"result",
"=",
"[",
"]",
"while",
"agenda",
":",
"change",
"=",
"agenda",
".",
"pop",
"(",
"0",
")",
"if",
"isinstance",
"(",
"change",
",",
"rope_change",
".",
"ChangeSet",
")",
":",
"agenda",
".",
"extend",
"(",
"change",
".",
"changes",
")",
"elif",
"isinstance",
"(",
"change",
",",
"rope_change",
".",
"ChangeContents",
")",
":",
"result",
".",
"append",
"(",
"{",
"'action'",
":",
"'change'",
",",
"'file'",
":",
"change",
".",
"resource",
".",
"real_path",
",",
"'contents'",
":",
"change",
".",
"new_contents",
",",
"'diff'",
":",
"change",
".",
"get_description",
"(",
")",
"}",
")",
"elif",
"isinstance",
"(",
"change",
",",
"rope_change",
".",
"CreateFile",
")",
":",
"result",
".",
"append",
"(",
"{",
"'action'",
":",
"'create'",
",",
"'type'",
":",
"'file'",
",",
"'file'",
":",
"change",
".",
"resource",
".",
"real_path",
"}",
")",
"elif",
"isinstance",
"(",
"change",
",",
"rope_change",
".",
"CreateFolder",
")",
":",
"result",
".",
"append",
"(",
"{",
"'action'",
":",
"'create'",
",",
"'type'",
":",
"'directory'",
",",
"'path'",
":",
"change",
".",
"resource",
".",
"real_path",
"}",
")",
"elif",
"isinstance",
"(",
"change",
",",
"rope_change",
".",
"MoveResource",
")",
":",
"result",
".",
"append",
"(",
"{",
"'action'",
":",
"'move'",
",",
"'type'",
":",
"(",
"'directory'",
"if",
"change",
".",
"new_resource",
".",
"is_folder",
"(",
")",
"else",
"'file'",
")",
",",
"'source'",
":",
"change",
".",
"resource",
".",
"real_path",
",",
"'destination'",
":",
"change",
".",
"new_resource",
".",
"real_path",
"}",
")",
"elif",
"isinstance",
"(",
"change",
",",
"rope_change",
".",
"RemoveResource",
")",
":",
"if",
"change",
".",
"resource",
".",
"is_folder",
"(",
")",
":",
"result",
".",
"append",
"(",
"{",
"'action'",
":",
"'delete'",
",",
"'type'",
":",
"'directory'",
",",
"'path'",
":",
"change",
".",
"resource",
".",
"real_path",
"}",
")",
"else",
":",
"result",
".",
"append",
"(",
"{",
"'action'",
":",
"'delete'",
",",
"'type'",
":",
"'file'",
",",
"'file'",
":",
"change",
".",
"resource",
".",
"real_path",
"}",
")",
"return",
"result"
] | Translate rope.base.change.Change instances to dictionaries.
See Refactor.get_changes for an explanation of the resulting
dictionary. | [
"Translate",
"rope",
".",
"base",
".",
"change",
".",
"Change",
"instances",
"to",
"dictionaries",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L328-L370 |
247,309 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.get_refactor_options | def get_refactor_options(self, start, end=None):
"""Return a list of options for refactoring at the given position.
If `end` is also given, refactoring on a region is assumed.
Each option is a dictionary of key/value pairs. The value of
the key 'name' is the one to be used for get_changes.
The key 'args' contains a list of additional arguments
required for get_changes.
"""
result = []
for symbol in dir(self):
if not symbol.startswith("refactor_"):
continue
method = getattr(self, symbol)
if not method.refactor_notes.get('available', True):
continue
category = method.refactor_notes['category']
if end is not None and category != 'Region':
continue
if end is None and category == 'Region':
continue
is_on_symbol = self._is_on_symbol(start)
if not is_on_symbol and category in ('Symbol', 'Method'):
continue
requires_import = method.refactor_notes.get('only_on_imports',
False)
if requires_import and not self._is_on_import_statement(start):
continue
result.append(method.refactor_notes)
return result | python | def get_refactor_options(self, start, end=None):
result = []
for symbol in dir(self):
if not symbol.startswith("refactor_"):
continue
method = getattr(self, symbol)
if not method.refactor_notes.get('available', True):
continue
category = method.refactor_notes['category']
if end is not None and category != 'Region':
continue
if end is None and category == 'Region':
continue
is_on_symbol = self._is_on_symbol(start)
if not is_on_symbol and category in ('Symbol', 'Method'):
continue
requires_import = method.refactor_notes.get('only_on_imports',
False)
if requires_import and not self._is_on_import_statement(start):
continue
result.append(method.refactor_notes)
return result | [
"def",
"get_refactor_options",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"for",
"symbol",
"in",
"dir",
"(",
"self",
")",
":",
"if",
"not",
"symbol",
".",
"startswith",
"(",
"\"refactor_\"",
")",
":",
"continue",
"method",
"=",
"getattr",
"(",
"self",
",",
"symbol",
")",
"if",
"not",
"method",
".",
"refactor_notes",
".",
"get",
"(",
"'available'",
",",
"True",
")",
":",
"continue",
"category",
"=",
"method",
".",
"refactor_notes",
"[",
"'category'",
"]",
"if",
"end",
"is",
"not",
"None",
"and",
"category",
"!=",
"'Region'",
":",
"continue",
"if",
"end",
"is",
"None",
"and",
"category",
"==",
"'Region'",
":",
"continue",
"is_on_symbol",
"=",
"self",
".",
"_is_on_symbol",
"(",
"start",
")",
"if",
"not",
"is_on_symbol",
"and",
"category",
"in",
"(",
"'Symbol'",
",",
"'Method'",
")",
":",
"continue",
"requires_import",
"=",
"method",
".",
"refactor_notes",
".",
"get",
"(",
"'only_on_imports'",
",",
"False",
")",
"if",
"requires_import",
"and",
"not",
"self",
".",
"_is_on_import_statement",
"(",
"start",
")",
":",
"continue",
"result",
".",
"append",
"(",
"method",
".",
"refactor_notes",
")",
"return",
"result"
] | Return a list of options for refactoring at the given position.
If `end` is also given, refactoring on a region is assumed.
Each option is a dictionary of key/value pairs. The value of
the key 'name' is the one to be used for get_changes.
The key 'args' contains a list of additional arguments
required for get_changes. | [
"Return",
"a",
"list",
"of",
"options",
"for",
"refactoring",
"at",
"the",
"given",
"position",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L113-L145 |
247,310 | jorgenschaefer/elpy | elpy/refactor.py | Refactor._is_on_import_statement | def _is_on_import_statement(self, offset):
"Does this offset point to an import statement?"
data = self.resource.read()
bol = data.rfind("\n", 0, offset) + 1
eol = data.find("\n", 0, bol)
if eol == -1:
eol = len(data)
line = data[bol:eol]
line = line.strip()
if line.startswith("import ") or line.startswith("from "):
return True
else:
return False | python | def _is_on_import_statement(self, offset):
"Does this offset point to an import statement?"
data = self.resource.read()
bol = data.rfind("\n", 0, offset) + 1
eol = data.find("\n", 0, bol)
if eol == -1:
eol = len(data)
line = data[bol:eol]
line = line.strip()
if line.startswith("import ") or line.startswith("from "):
return True
else:
return False | [
"def",
"_is_on_import_statement",
"(",
"self",
",",
"offset",
")",
":",
"data",
"=",
"self",
".",
"resource",
".",
"read",
"(",
")",
"bol",
"=",
"data",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"offset",
")",
"+",
"1",
"eol",
"=",
"data",
".",
"find",
"(",
"\"\\n\"",
",",
"0",
",",
"bol",
")",
"if",
"eol",
"==",
"-",
"1",
":",
"eol",
"=",
"len",
"(",
"data",
")",
"line",
"=",
"data",
"[",
"bol",
":",
"eol",
"]",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"\"import \"",
")",
"or",
"line",
".",
"startswith",
"(",
"\"from \"",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Does this offset point to an import statement? | [
"Does",
"this",
"offset",
"point",
"to",
"an",
"import",
"statement?"
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L147-L159 |
247,311 | jorgenschaefer/elpy | elpy/refactor.py | Refactor._is_on_symbol | def _is_on_symbol(self, offset):
"Is this offset on a symbol?"
if not ROPE_AVAILABLE:
return False
data = self.resource.read()
if offset >= len(data):
return False
if data[offset] != '_' and not data[offset].isalnum():
return False
word = worder.get_name_at(self.resource, offset)
if word:
return True
else:
return False | python | def _is_on_symbol(self, offset):
"Is this offset on a symbol?"
if not ROPE_AVAILABLE:
return False
data = self.resource.read()
if offset >= len(data):
return False
if data[offset] != '_' and not data[offset].isalnum():
return False
word = worder.get_name_at(self.resource, offset)
if word:
return True
else:
return False | [
"def",
"_is_on_symbol",
"(",
"self",
",",
"offset",
")",
":",
"if",
"not",
"ROPE_AVAILABLE",
":",
"return",
"False",
"data",
"=",
"self",
".",
"resource",
".",
"read",
"(",
")",
"if",
"offset",
">=",
"len",
"(",
"data",
")",
":",
"return",
"False",
"if",
"data",
"[",
"offset",
"]",
"!=",
"'_'",
"and",
"not",
"data",
"[",
"offset",
"]",
".",
"isalnum",
"(",
")",
":",
"return",
"False",
"word",
"=",
"worder",
".",
"get_name_at",
"(",
"self",
".",
"resource",
",",
"offset",
")",
"if",
"word",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Is this offset on a symbol? | [
"Is",
"this",
"offset",
"on",
"a",
"symbol?"
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L161-L174 |
247,312 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.get_changes | def get_changes(self, name, *args):
"""Return a list of changes for the named refactoring action.
Changes are dictionaries describing a single action to be
taken for the refactoring to be successful.
A change has an action and possibly a type. In the description
below, the action is before the slash and the type after it.
change: Change file contents
- file: The path to the file to change
- contents: The new contents for the file
- Diff: A unified diff showing the changes introduced
create/file: Create a new file
- file: The file to create
create/directory: Create a new directory
- path: The directory to create
move/file: Rename a file
- source: The path to the source file
- destination: The path to the destination file name
move/directory: Rename a directory
- source: The path to the source directory
- destination: The path to the destination directory name
delete/file: Delete a file
- file: The file to delete
delete/directory: Delete a directory
- path: The directory to delete
"""
if not name.startswith("refactor_"):
raise ValueError("Bad refactoring name {0}".format(name))
method = getattr(self, name)
if not method.refactor_notes.get('available', True):
raise RuntimeError("Method not available")
return method(*args) | python | def get_changes(self, name, *args):
if not name.startswith("refactor_"):
raise ValueError("Bad refactoring name {0}".format(name))
method = getattr(self, name)
if not method.refactor_notes.get('available', True):
raise RuntimeError("Method not available")
return method(*args) | [
"def",
"get_changes",
"(",
"self",
",",
"name",
",",
"*",
"args",
")",
":",
"if",
"not",
"name",
".",
"startswith",
"(",
"\"refactor_\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Bad refactoring name {0}\"",
".",
"format",
"(",
"name",
")",
")",
"method",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"if",
"not",
"method",
".",
"refactor_notes",
".",
"get",
"(",
"'available'",
",",
"True",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Method not available\"",
")",
"return",
"method",
"(",
"*",
"args",
")"
] | Return a list of changes for the named refactoring action.
Changes are dictionaries describing a single action to be
taken for the refactoring to be successful.
A change has an action and possibly a type. In the description
below, the action is before the slash and the type after it.
change: Change file contents
- file: The path to the file to change
- contents: The new contents for the file
- Diff: A unified diff showing the changes introduced
create/file: Create a new file
- file: The file to create
create/directory: Create a new directory
- path: The directory to create
move/file: Rename a file
- source: The path to the source file
- destination: The path to the destination file name
move/directory: Rename a directory
- source: The path to the source directory
- destination: The path to the destination directory name
delete/file: Delete a file
- file: The file to delete
delete/directory: Delete a directory
- path: The directory to delete | [
"Return",
"a",
"list",
"of",
"changes",
"for",
"the",
"named",
"refactoring",
"action",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L176-L216 |
247,313 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_froms_to_imports | def refactor_froms_to_imports(self, offset):
"""Converting imports of the form "from ..." to "import ..."."""
refactor = ImportOrganizer(self.project)
changes = refactor.froms_to_imports(self.resource, offset)
return translate_changes(changes) | python | def refactor_froms_to_imports(self, offset):
refactor = ImportOrganizer(self.project)
changes = refactor.froms_to_imports(self.resource, offset)
return translate_changes(changes) | [
"def",
"refactor_froms_to_imports",
"(",
"self",
",",
"offset",
")",
":",
"refactor",
"=",
"ImportOrganizer",
"(",
"self",
".",
"project",
")",
"changes",
"=",
"refactor",
".",
"froms_to_imports",
"(",
"self",
".",
"resource",
",",
"offset",
")",
"return",
"translate_changes",
"(",
"changes",
")"
] | Converting imports of the form "from ..." to "import ...". | [
"Converting",
"imports",
"of",
"the",
"form",
"from",
"...",
"to",
"import",
"...",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L222-L226 |
247,314 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_organize_imports | def refactor_organize_imports(self):
"""Clean up and organize imports."""
refactor = ImportOrganizer(self.project)
changes = refactor.organize_imports(self.resource)
return translate_changes(changes) | python | def refactor_organize_imports(self):
refactor = ImportOrganizer(self.project)
changes = refactor.organize_imports(self.resource)
return translate_changes(changes) | [
"def",
"refactor_organize_imports",
"(",
"self",
")",
":",
"refactor",
"=",
"ImportOrganizer",
"(",
"self",
".",
"project",
")",
"changes",
"=",
"refactor",
".",
"organize_imports",
"(",
"self",
".",
"resource",
")",
"return",
"translate_changes",
"(",
"changes",
")"
] | Clean up and organize imports. | [
"Clean",
"up",
"and",
"organize",
"imports",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L230-L234 |
247,315 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_module_to_package | def refactor_module_to_package(self):
"""Convert the current module into a package."""
refactor = ModuleToPackage(self.project, self.resource)
return self._get_changes(refactor) | python | def refactor_module_to_package(self):
refactor = ModuleToPackage(self.project, self.resource)
return self._get_changes(refactor) | [
"def",
"refactor_module_to_package",
"(",
"self",
")",
":",
"refactor",
"=",
"ModuleToPackage",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
")",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
")"
] | Convert the current module into a package. | [
"Convert",
"the",
"current",
"module",
"into",
"a",
"package",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L238-L241 |
247,316 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_rename_at_point | def refactor_rename_at_point(self, offset, new_name, in_hierarchy, docs):
"""Rename the symbol at point."""
try:
refactor = Rename(self.project, self.resource, offset)
except RefactoringError as e:
raise Fault(str(e), code=400)
return self._get_changes(refactor, new_name,
in_hierarchy=in_hierarchy, docs=docs) | python | def refactor_rename_at_point(self, offset, new_name, in_hierarchy, docs):
try:
refactor = Rename(self.project, self.resource, offset)
except RefactoringError as e:
raise Fault(str(e), code=400)
return self._get_changes(refactor, new_name,
in_hierarchy=in_hierarchy, docs=docs) | [
"def",
"refactor_rename_at_point",
"(",
"self",
",",
"offset",
",",
"new_name",
",",
"in_hierarchy",
",",
"docs",
")",
":",
"try",
":",
"refactor",
"=",
"Rename",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
",",
"offset",
")",
"except",
"RefactoringError",
"as",
"e",
":",
"raise",
"Fault",
"(",
"str",
"(",
"e",
")",
",",
"code",
"=",
"400",
")",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
",",
"new_name",
",",
"in_hierarchy",
"=",
"in_hierarchy",
",",
"docs",
"=",
"docs",
")"
] | Rename the symbol at point. | [
"Rename",
"the",
"symbol",
"at",
"point",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L252-L259 |
247,317 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_rename_current_module | def refactor_rename_current_module(self, new_name):
"""Rename the current module."""
refactor = Rename(self.project, self.resource, None)
return self._get_changes(refactor, new_name) | python | def refactor_rename_current_module(self, new_name):
refactor = Rename(self.project, self.resource, None)
return self._get_changes(refactor, new_name) | [
"def",
"refactor_rename_current_module",
"(",
"self",
",",
"new_name",
")",
":",
"refactor",
"=",
"Rename",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
",",
"None",
")",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
",",
"new_name",
")"
] | Rename the current module. | [
"Rename",
"the",
"current",
"module",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L264-L267 |
247,318 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_move_module | def refactor_move_module(self, new_name):
"""Move the current module."""
refactor = create_move(self.project, self.resource)
resource = path_to_resource(self.project, new_name)
return self._get_changes(refactor, resource) | python | def refactor_move_module(self, new_name):
refactor = create_move(self.project, self.resource)
resource = path_to_resource(self.project, new_name)
return self._get_changes(refactor, resource) | [
"def",
"refactor_move_module",
"(",
"self",
",",
"new_name",
")",
":",
"refactor",
"=",
"create_move",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
")",
"resource",
"=",
"path_to_resource",
"(",
"self",
".",
"project",
",",
"new_name",
")",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
",",
"resource",
")"
] | Move the current module. | [
"Move",
"the",
"current",
"module",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L273-L277 |
247,319 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_create_inline | def refactor_create_inline(self, offset, only_this):
"""Inline the function call at point."""
refactor = create_inline(self.project, self.resource, offset)
if only_this:
return self._get_changes(refactor, remove=False, only_current=True)
else:
return self._get_changes(refactor, remove=True, only_current=False) | python | def refactor_create_inline(self, offset, only_this):
refactor = create_inline(self.project, self.resource, offset)
if only_this:
return self._get_changes(refactor, remove=False, only_current=True)
else:
return self._get_changes(refactor, remove=True, only_current=False) | [
"def",
"refactor_create_inline",
"(",
"self",
",",
"offset",
",",
"only_this",
")",
":",
"refactor",
"=",
"create_inline",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
",",
"offset",
")",
"if",
"only_this",
":",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
",",
"remove",
"=",
"False",
",",
"only_current",
"=",
"True",
")",
"else",
":",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
",",
"remove",
"=",
"True",
",",
"only_current",
"=",
"False",
")"
] | Inline the function call at point. | [
"Inline",
"the",
"function",
"call",
"at",
"point",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L283-L289 |
247,320 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_extract_method | def refactor_extract_method(self, start, end, name,
make_global):
"""Extract region as a method."""
refactor = ExtractMethod(self.project, self.resource, start, end)
return self._get_changes(
refactor, name, similar=True, global_=make_global
) | python | def refactor_extract_method(self, start, end, name,
make_global):
refactor = ExtractMethod(self.project, self.resource, start, end)
return self._get_changes(
refactor, name, similar=True, global_=make_global
) | [
"def",
"refactor_extract_method",
"(",
"self",
",",
"start",
",",
"end",
",",
"name",
",",
"make_global",
")",
":",
"refactor",
"=",
"ExtractMethod",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
",",
"start",
",",
"end",
")",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
",",
"name",
",",
"similar",
"=",
"True",
",",
"global_",
"=",
"make_global",
")"
] | Extract region as a method. | [
"Extract",
"region",
"as",
"a",
"method",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L297-L303 |
247,321 | jorgenschaefer/elpy | elpy/refactor.py | Refactor.refactor_use_function | def refactor_use_function(self, offset):
"""Use the function at point wherever possible."""
try:
refactor = UseFunction(self.project, self.resource, offset)
except RefactoringError as e:
raise Fault(
'Refactoring error: {}'.format(e),
code=400
)
return self._get_changes(refactor) | python | def refactor_use_function(self, offset):
try:
refactor = UseFunction(self.project, self.resource, offset)
except RefactoringError as e:
raise Fault(
'Refactoring error: {}'.format(e),
code=400
)
return self._get_changes(refactor) | [
"def",
"refactor_use_function",
"(",
"self",
",",
"offset",
")",
":",
"try",
":",
"refactor",
"=",
"UseFunction",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
",",
"offset",
")",
"except",
"RefactoringError",
"as",
"e",
":",
"raise",
"Fault",
"(",
"'Refactoring error: {}'",
".",
"format",
"(",
"e",
")",
",",
"code",
"=",
"400",
")",
"return",
"self",
".",
"_get_changes",
"(",
"refactor",
")"
] | Use the function at point wherever possible. | [
"Use",
"the",
"function",
"at",
"point",
"wherever",
"possible",
"."
] | ffd982f829b11e53f2be187c7b770423341f29bc | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L308-L317 |
247,322 | clach04/python-tuya | pytuya/__init__.py | XenonDevice.generate_payload | def generate_payload(self, command, data=None):
"""
Generate the payload to send.
Args:
command(str): The type of command.
This is one of the entries from payload_dict
data(dict, optional): The data to be send.
This is what will be passed via the 'dps' entry
"""
json_data = payload_dict[self.dev_type][command]['command']
if 'gwId' in json_data:
json_data['gwId'] = self.id
if 'devId' in json_data:
json_data['devId'] = self.id
if 'uid' in json_data:
json_data['uid'] = self.id # still use id, no seperate uid
if 't' in json_data:
json_data['t'] = str(int(time.time()))
if data is not None:
json_data['dps'] = data
# Create byte buffer from hex data
json_payload = json.dumps(json_data)
#print(json_payload)
json_payload = json_payload.replace(' ', '') # if spaces are not removed device does not respond!
json_payload = json_payload.encode('utf-8')
log.debug('json_payload=%r', json_payload)
if command == SET:
# need to encrypt
#print('json_payload %r' % json_payload)
self.cipher = AESCipher(self.local_key) # expect to connect and then disconnect to set new
json_payload = self.cipher.encrypt(json_payload)
#print('crypted json_payload %r' % json_payload)
preMd5String = b'data=' + json_payload + b'||lpv=' + PROTOCOL_VERSION_BYTES + b'||' + self.local_key
#print('preMd5String %r' % preMd5String)
m = md5()
m.update(preMd5String)
#print(repr(m.digest()))
hexdigest = m.hexdigest()
#print(hexdigest)
#print(hexdigest[8:][:16])
json_payload = PROTOCOL_VERSION_BYTES + hexdigest[8:][:16].encode('latin1') + json_payload
#print('data_to_send')
#print(json_payload)
#print('crypted json_payload (%d) %r' % (len(json_payload), json_payload))
#print('json_payload %r' % repr(json_payload))
#print('json_payload len %r' % len(json_payload))
#print(bin2hex(json_payload))
self.cipher = None # expect to connect and then disconnect to set new
postfix_payload = hex2bin(bin2hex(json_payload) + payload_dict[self.dev_type]['suffix'])
#print('postfix_payload %r' % postfix_payload)
#print('postfix_payload %r' % len(postfix_payload))
#print('postfix_payload %x' % len(postfix_payload))
#print('postfix_payload %r' % hex(len(postfix_payload)))
assert len(postfix_payload) <= 0xff
postfix_payload_hex_len = '%x' % len(postfix_payload) # TODO this assumes a single byte 0-255 (0x00-0xff)
buffer = hex2bin( payload_dict[self.dev_type]['prefix'] +
payload_dict[self.dev_type][command]['hexByte'] +
'000000' +
postfix_payload_hex_len ) + postfix_payload
#print('command', command)
#print('prefix')
#print(payload_dict[self.dev_type][command]['prefix'])
#print(repr(buffer))
#print(bin2hex(buffer, pretty=True))
#print(bin2hex(buffer, pretty=False))
#print('full buffer(%d) %r' % (len(buffer), buffer))
return buffer | python | def generate_payload(self, command, data=None):
json_data = payload_dict[self.dev_type][command]['command']
if 'gwId' in json_data:
json_data['gwId'] = self.id
if 'devId' in json_data:
json_data['devId'] = self.id
if 'uid' in json_data:
json_data['uid'] = self.id # still use id, no seperate uid
if 't' in json_data:
json_data['t'] = str(int(time.time()))
if data is not None:
json_data['dps'] = data
# Create byte buffer from hex data
json_payload = json.dumps(json_data)
#print(json_payload)
json_payload = json_payload.replace(' ', '') # if spaces are not removed device does not respond!
json_payload = json_payload.encode('utf-8')
log.debug('json_payload=%r', json_payload)
if command == SET:
# need to encrypt
#print('json_payload %r' % json_payload)
self.cipher = AESCipher(self.local_key) # expect to connect and then disconnect to set new
json_payload = self.cipher.encrypt(json_payload)
#print('crypted json_payload %r' % json_payload)
preMd5String = b'data=' + json_payload + b'||lpv=' + PROTOCOL_VERSION_BYTES + b'||' + self.local_key
#print('preMd5String %r' % preMd5String)
m = md5()
m.update(preMd5String)
#print(repr(m.digest()))
hexdigest = m.hexdigest()
#print(hexdigest)
#print(hexdigest[8:][:16])
json_payload = PROTOCOL_VERSION_BYTES + hexdigest[8:][:16].encode('latin1') + json_payload
#print('data_to_send')
#print(json_payload)
#print('crypted json_payload (%d) %r' % (len(json_payload), json_payload))
#print('json_payload %r' % repr(json_payload))
#print('json_payload len %r' % len(json_payload))
#print(bin2hex(json_payload))
self.cipher = None # expect to connect and then disconnect to set new
postfix_payload = hex2bin(bin2hex(json_payload) + payload_dict[self.dev_type]['suffix'])
#print('postfix_payload %r' % postfix_payload)
#print('postfix_payload %r' % len(postfix_payload))
#print('postfix_payload %x' % len(postfix_payload))
#print('postfix_payload %r' % hex(len(postfix_payload)))
assert len(postfix_payload) <= 0xff
postfix_payload_hex_len = '%x' % len(postfix_payload) # TODO this assumes a single byte 0-255 (0x00-0xff)
buffer = hex2bin( payload_dict[self.dev_type]['prefix'] +
payload_dict[self.dev_type][command]['hexByte'] +
'000000' +
postfix_payload_hex_len ) + postfix_payload
#print('command', command)
#print('prefix')
#print(payload_dict[self.dev_type][command]['prefix'])
#print(repr(buffer))
#print(bin2hex(buffer, pretty=True))
#print(bin2hex(buffer, pretty=False))
#print('full buffer(%d) %r' % (len(buffer), buffer))
return buffer | [
"def",
"generate_payload",
"(",
"self",
",",
"command",
",",
"data",
"=",
"None",
")",
":",
"json_data",
"=",
"payload_dict",
"[",
"self",
".",
"dev_type",
"]",
"[",
"command",
"]",
"[",
"'command'",
"]",
"if",
"'gwId'",
"in",
"json_data",
":",
"json_data",
"[",
"'gwId'",
"]",
"=",
"self",
".",
"id",
"if",
"'devId'",
"in",
"json_data",
":",
"json_data",
"[",
"'devId'",
"]",
"=",
"self",
".",
"id",
"if",
"'uid'",
"in",
"json_data",
":",
"json_data",
"[",
"'uid'",
"]",
"=",
"self",
".",
"id",
"# still use id, no seperate uid",
"if",
"'t'",
"in",
"json_data",
":",
"json_data",
"[",
"'t'",
"]",
"=",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"if",
"data",
"is",
"not",
"None",
":",
"json_data",
"[",
"'dps'",
"]",
"=",
"data",
"# Create byte buffer from hex data",
"json_payload",
"=",
"json",
".",
"dumps",
"(",
"json_data",
")",
"#print(json_payload)",
"json_payload",
"=",
"json_payload",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"# if spaces are not removed device does not respond!",
"json_payload",
"=",
"json_payload",
".",
"encode",
"(",
"'utf-8'",
")",
"log",
".",
"debug",
"(",
"'json_payload=%r'",
",",
"json_payload",
")",
"if",
"command",
"==",
"SET",
":",
"# need to encrypt",
"#print('json_payload %r' % json_payload)",
"self",
".",
"cipher",
"=",
"AESCipher",
"(",
"self",
".",
"local_key",
")",
"# expect to connect and then disconnect to set new",
"json_payload",
"=",
"self",
".",
"cipher",
".",
"encrypt",
"(",
"json_payload",
")",
"#print('crypted json_payload %r' % json_payload)",
"preMd5String",
"=",
"b'data='",
"+",
"json_payload",
"+",
"b'||lpv='",
"+",
"PROTOCOL_VERSION_BYTES",
"+",
"b'||'",
"+",
"self",
".",
"local_key",
"#print('preMd5String %r' % preMd5String)",
"m",
"=",
"md5",
"(",
")",
"m",
".",
"update",
"(",
"preMd5String",
")",
"#print(repr(m.digest()))",
"hexdigest",
"=",
"m",
".",
"hexdigest",
"(",
")",
"#print(hexdigest)",
"#print(hexdigest[8:][:16])",
"json_payload",
"=",
"PROTOCOL_VERSION_BYTES",
"+",
"hexdigest",
"[",
"8",
":",
"]",
"[",
":",
"16",
"]",
".",
"encode",
"(",
"'latin1'",
")",
"+",
"json_payload",
"#print('data_to_send')",
"#print(json_payload)",
"#print('crypted json_payload (%d) %r' % (len(json_payload), json_payload))",
"#print('json_payload %r' % repr(json_payload))",
"#print('json_payload len %r' % len(json_payload))",
"#print(bin2hex(json_payload))",
"self",
".",
"cipher",
"=",
"None",
"# expect to connect and then disconnect to set new",
"postfix_payload",
"=",
"hex2bin",
"(",
"bin2hex",
"(",
"json_payload",
")",
"+",
"payload_dict",
"[",
"self",
".",
"dev_type",
"]",
"[",
"'suffix'",
"]",
")",
"#print('postfix_payload %r' % postfix_payload)",
"#print('postfix_payload %r' % len(postfix_payload))",
"#print('postfix_payload %x' % len(postfix_payload))",
"#print('postfix_payload %r' % hex(len(postfix_payload)))",
"assert",
"len",
"(",
"postfix_payload",
")",
"<=",
"0xff",
"postfix_payload_hex_len",
"=",
"'%x'",
"%",
"len",
"(",
"postfix_payload",
")",
"# TODO this assumes a single byte 0-255 (0x00-0xff)",
"buffer",
"=",
"hex2bin",
"(",
"payload_dict",
"[",
"self",
".",
"dev_type",
"]",
"[",
"'prefix'",
"]",
"+",
"payload_dict",
"[",
"self",
".",
"dev_type",
"]",
"[",
"command",
"]",
"[",
"'hexByte'",
"]",
"+",
"'000000'",
"+",
"postfix_payload_hex_len",
")",
"+",
"postfix_payload",
"#print('command', command)",
"#print('prefix')",
"#print(payload_dict[self.dev_type][command]['prefix'])",
"#print(repr(buffer))",
"#print(bin2hex(buffer, pretty=True))",
"#print(bin2hex(buffer, pretty=False))",
"#print('full buffer(%d) %r' % (len(buffer), buffer))",
"return",
"buffer"
] | Generate the payload to send.
Args:
command(str): The type of command.
This is one of the entries from payload_dict
data(dict, optional): The data to be send.
This is what will be passed via the 'dps' entry | [
"Generate",
"the",
"payload",
"to",
"send",
"."
] | 7b89d38c56f6e25700e2a333000d25bc8d923622 | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L176-L249 |
247,323 | clach04/python-tuya | pytuya/__init__.py | BulbDevice.set_colour | def set_colour(self, r, g, b):
"""
Set colour of an rgb bulb.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.
"""
if not 0 <= r <= 255:
raise ValueError("The value for red needs to be between 0 and 255.")
if not 0 <= g <= 255:
raise ValueError("The value for green needs to be between 0 and 255.")
if not 0 <= b <= 255:
raise ValueError("The value for blue needs to be between 0 and 255.")
#print(BulbDevice)
hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b)
payload = self.generate_payload(SET, {
self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR,
self.DPS_INDEX_COLOUR: hexvalue})
data = self._send_receive(payload)
return data | python | def set_colour(self, r, g, b):
if not 0 <= r <= 255:
raise ValueError("The value for red needs to be between 0 and 255.")
if not 0 <= g <= 255:
raise ValueError("The value for green needs to be between 0 and 255.")
if not 0 <= b <= 255:
raise ValueError("The value for blue needs to be between 0 and 255.")
#print(BulbDevice)
hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b)
payload = self.generate_payload(SET, {
self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR,
self.DPS_INDEX_COLOUR: hexvalue})
data = self._send_receive(payload)
return data | [
"def",
"set_colour",
"(",
"self",
",",
"r",
",",
"g",
",",
"b",
")",
":",
"if",
"not",
"0",
"<=",
"r",
"<=",
"255",
":",
"raise",
"ValueError",
"(",
"\"The value for red needs to be between 0 and 255.\"",
")",
"if",
"not",
"0",
"<=",
"g",
"<=",
"255",
":",
"raise",
"ValueError",
"(",
"\"The value for green needs to be between 0 and 255.\"",
")",
"if",
"not",
"0",
"<=",
"b",
"<=",
"255",
":",
"raise",
"ValueError",
"(",
"\"The value for blue needs to be between 0 and 255.\"",
")",
"#print(BulbDevice)",
"hexvalue",
"=",
"BulbDevice",
".",
"_rgb_to_hexvalue",
"(",
"r",
",",
"g",
",",
"b",
")",
"payload",
"=",
"self",
".",
"generate_payload",
"(",
"SET",
",",
"{",
"self",
".",
"DPS_INDEX_MODE",
":",
"self",
".",
"DPS_MODE_COLOUR",
",",
"self",
".",
"DPS_INDEX_COLOUR",
":",
"hexvalue",
"}",
")",
"data",
"=",
"self",
".",
"_send_receive",
"(",
"payload",
")",
"return",
"data"
] | Set colour of an rgb bulb.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255. | [
"Set",
"colour",
"of",
"an",
"rgb",
"bulb",
"."
] | 7b89d38c56f6e25700e2a333000d25bc8d923622 | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L437-L460 |
247,324 | clach04/python-tuya | pytuya/__init__.py | BulbDevice.set_white | def set_white(self, brightness, colourtemp):
"""
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
colourtemp(int): Value for the colour temperature (0-255).
"""
if not 25 <= brightness <= 255:
raise ValueError("The brightness needs to be between 25 and 255.")
if not 0 <= colourtemp <= 255:
raise ValueError("The colour temperature needs to be between 0 and 255.")
payload = self.generate_payload(SET, {
self.DPS_INDEX_MODE: self.DPS_MODE_WHITE,
self.DPS_INDEX_BRIGHTNESS: brightness,
self.DPS_INDEX_COLOURTEMP: colourtemp})
data = self._send_receive(payload)
return data | python | def set_white(self, brightness, colourtemp):
if not 25 <= brightness <= 255:
raise ValueError("The brightness needs to be between 25 and 255.")
if not 0 <= colourtemp <= 255:
raise ValueError("The colour temperature needs to be between 0 and 255.")
payload = self.generate_payload(SET, {
self.DPS_INDEX_MODE: self.DPS_MODE_WHITE,
self.DPS_INDEX_BRIGHTNESS: brightness,
self.DPS_INDEX_COLOURTEMP: colourtemp})
data = self._send_receive(payload)
return data | [
"def",
"set_white",
"(",
"self",
",",
"brightness",
",",
"colourtemp",
")",
":",
"if",
"not",
"25",
"<=",
"brightness",
"<=",
"255",
":",
"raise",
"ValueError",
"(",
"\"The brightness needs to be between 25 and 255.\"",
")",
"if",
"not",
"0",
"<=",
"colourtemp",
"<=",
"255",
":",
"raise",
"ValueError",
"(",
"\"The colour temperature needs to be between 0 and 255.\"",
")",
"payload",
"=",
"self",
".",
"generate_payload",
"(",
"SET",
",",
"{",
"self",
".",
"DPS_INDEX_MODE",
":",
"self",
".",
"DPS_MODE_WHITE",
",",
"self",
".",
"DPS_INDEX_BRIGHTNESS",
":",
"brightness",
",",
"self",
".",
"DPS_INDEX_COLOURTEMP",
":",
"colourtemp",
"}",
")",
"data",
"=",
"self",
".",
"_send_receive",
"(",
"payload",
")",
"return",
"data"
] | Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
colourtemp(int): Value for the colour temperature (0-255). | [
"Set",
"white",
"coloured",
"theme",
"of",
"an",
"rgb",
"bulb",
"."
] | 7b89d38c56f6e25700e2a333000d25bc8d923622 | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L462-L481 |
247,325 | clach04/python-tuya | pytuya/__init__.py | BulbDevice.set_brightness | def set_brightness(self, brightness):
"""
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
"""
if not 25 <= brightness <= 255:
raise ValueError("The brightness needs to be between 25 and 255.")
payload = self.generate_payload(SET, {self.DPS_INDEX_BRIGHTNESS: brightness})
data = self._send_receive(payload)
return data | python | def set_brightness(self, brightness):
if not 25 <= brightness <= 255:
raise ValueError("The brightness needs to be between 25 and 255.")
payload = self.generate_payload(SET, {self.DPS_INDEX_BRIGHTNESS: brightness})
data = self._send_receive(payload)
return data | [
"def",
"set_brightness",
"(",
"self",
",",
"brightness",
")",
":",
"if",
"not",
"25",
"<=",
"brightness",
"<=",
"255",
":",
"raise",
"ValueError",
"(",
"\"The brightness needs to be between 25 and 255.\"",
")",
"payload",
"=",
"self",
".",
"generate_payload",
"(",
"SET",
",",
"{",
"self",
".",
"DPS_INDEX_BRIGHTNESS",
":",
"brightness",
"}",
")",
"data",
"=",
"self",
".",
"_send_receive",
"(",
"payload",
")",
"return",
"data"
] | Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255). | [
"Set",
"the",
"brightness",
"value",
"of",
"an",
"rgb",
"bulb",
"."
] | 7b89d38c56f6e25700e2a333000d25bc8d923622 | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L483-L495 |
247,326 | clach04/python-tuya | pytuya/__init__.py | BulbDevice.set_colourtemp | def set_colourtemp(self, colourtemp):
"""
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255).
"""
if not 0 <= colourtemp <= 255:
raise ValueError("The colour temperature needs to be between 0 and 255.")
payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp})
data = self._send_receive(payload)
return data | python | def set_colourtemp(self, colourtemp):
if not 0 <= colourtemp <= 255:
raise ValueError("The colour temperature needs to be between 0 and 255.")
payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp})
data = self._send_receive(payload)
return data | [
"def",
"set_colourtemp",
"(",
"self",
",",
"colourtemp",
")",
":",
"if",
"not",
"0",
"<=",
"colourtemp",
"<=",
"255",
":",
"raise",
"ValueError",
"(",
"\"The colour temperature needs to be between 0 and 255.\"",
")",
"payload",
"=",
"self",
".",
"generate_payload",
"(",
"SET",
",",
"{",
"self",
".",
"DPS_INDEX_COLOURTEMP",
":",
"colourtemp",
"}",
")",
"data",
"=",
"self",
".",
"_send_receive",
"(",
"payload",
")",
"return",
"data"
] | Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255). | [
"Set",
"the",
"colour",
"temperature",
"of",
"an",
"rgb",
"bulb",
"."
] | 7b89d38c56f6e25700e2a333000d25bc8d923622 | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L497-L509 |
247,327 | clach04/python-tuya | pytuya/__init__.py | BulbDevice.colour_rgb | def colour_rgb(self):
"""Return colour as RGB value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_rgb(hexvalue) | python | def colour_rgb(self):
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_rgb(hexvalue) | [
"def",
"colour_rgb",
"(",
"self",
")",
":",
"hexvalue",
"=",
"self",
".",
"status",
"(",
")",
"[",
"self",
".",
"DPS",
"]",
"[",
"self",
".",
"DPS_INDEX_COLOUR",
"]",
"return",
"BulbDevice",
".",
"_hexvalue_to_rgb",
"(",
"hexvalue",
")"
] | Return colour as RGB value | [
"Return",
"colour",
"as",
"RGB",
"value"
] | 7b89d38c56f6e25700e2a333000d25bc8d923622 | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L519-L522 |
247,328 | clach04/python-tuya | pytuya/__init__.py | BulbDevice.colour_hsv | def colour_hsv(self):
"""Return colour as HSV value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_hsv(hexvalue) | python | def colour_hsv(self):
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_hsv(hexvalue) | [
"def",
"colour_hsv",
"(",
"self",
")",
":",
"hexvalue",
"=",
"self",
".",
"status",
"(",
")",
"[",
"self",
".",
"DPS",
"]",
"[",
"self",
".",
"DPS_INDEX_COLOUR",
"]",
"return",
"BulbDevice",
".",
"_hexvalue_to_hsv",
"(",
"hexvalue",
")"
] | Return colour as HSV value | [
"Return",
"colour",
"as",
"HSV",
"value"
] | 7b89d38c56f6e25700e2a333000d25bc8d923622 | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L524-L527 |
247,329 | bitcraze/crazyflie-lib-python | cflib/crazyflie/high_level_commander.py | HighLevelCommander.set_group_mask | def set_group_mask(self, group_mask=ALL_GROUPS):
"""
Set the group mask that the Crazyflie belongs to
:param group_mask: mask for which groups this CF belongs to
"""
self._send_packet(struct.pack('<BB',
self.COMMAND_SET_GROUP_MASK,
group_mask)) | python | def set_group_mask(self, group_mask=ALL_GROUPS):
self._send_packet(struct.pack('<BB',
self.COMMAND_SET_GROUP_MASK,
group_mask)) | [
"def",
"set_group_mask",
"(",
"self",
",",
"group_mask",
"=",
"ALL_GROUPS",
")",
":",
"self",
".",
"_send_packet",
"(",
"struct",
".",
"pack",
"(",
"'<BB'",
",",
"self",
".",
"COMMAND_SET_GROUP_MASK",
",",
"group_mask",
")",
")"
] | Set the group mask that the Crazyflie belongs to
:param group_mask: mask for which groups this CF belongs to | [
"Set",
"the",
"group",
"mask",
"that",
"the",
"Crazyflie",
"belongs",
"to"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L63-L71 |
247,330 | bitcraze/crazyflie-lib-python | cflib/crazyflie/high_level_commander.py | HighLevelCommander.takeoff | def takeoff(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS):
"""
vertical takeoff from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:param group_mask: mask for which CFs this should apply to
"""
self._send_packet(struct.pack('<BBff',
self.COMMAND_TAKEOFF,
group_mask,
absolute_height_m,
duration_s)) | python | def takeoff(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS):
self._send_packet(struct.pack('<BBff',
self.COMMAND_TAKEOFF,
group_mask,
absolute_height_m,
duration_s)) | [
"def",
"takeoff",
"(",
"self",
",",
"absolute_height_m",
",",
"duration_s",
",",
"group_mask",
"=",
"ALL_GROUPS",
")",
":",
"self",
".",
"_send_packet",
"(",
"struct",
".",
"pack",
"(",
"'<BBff'",
",",
"self",
".",
"COMMAND_TAKEOFF",
",",
"group_mask",
",",
"absolute_height_m",
",",
"duration_s",
")",
")"
] | vertical takeoff from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:param group_mask: mask for which CFs this should apply to | [
"vertical",
"takeoff",
"from",
"current",
"x",
"-",
"y",
"position",
"to",
"given",
"height"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L73-L86 |
247,331 | bitcraze/crazyflie-lib-python | cflib/crazyflie/high_level_commander.py | HighLevelCommander.land | def land(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS):
"""
vertical land from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:param group_mask: mask for which CFs this should apply to
"""
self._send_packet(struct.pack('<BBff',
self.COMMAND_LAND,
group_mask,
absolute_height_m,
duration_s)) | python | def land(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS):
self._send_packet(struct.pack('<BBff',
self.COMMAND_LAND,
group_mask,
absolute_height_m,
duration_s)) | [
"def",
"land",
"(",
"self",
",",
"absolute_height_m",
",",
"duration_s",
",",
"group_mask",
"=",
"ALL_GROUPS",
")",
":",
"self",
".",
"_send_packet",
"(",
"struct",
".",
"pack",
"(",
"'<BBff'",
",",
"self",
".",
"COMMAND_LAND",
",",
"group_mask",
",",
"absolute_height_m",
",",
"duration_s",
")",
")"
] | vertical land from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:param group_mask: mask for which CFs this should apply to | [
"vertical",
"land",
"from",
"current",
"x",
"-",
"y",
"position",
"to",
"given",
"height"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L88-L101 |
247,332 | bitcraze/crazyflie-lib-python | cflib/crazyflie/high_level_commander.py | HighLevelCommander.go_to | def go_to(self, x, y, z, yaw, duration_s, relative=False,
group_mask=ALL_GROUPS):
"""
Go to an absolute or relative position
:param x: x (m)
:param y: y (m)
:param z: z (m)
:param yaw: yaw (radians)
:param duration_s: time it should take to reach the position (s)
:param relative: True if x, y, z is relative to the current position
:param group_mask: mask for which CFs this should apply to
"""
self._send_packet(struct.pack('<BBBfffff',
self.COMMAND_GO_TO,
group_mask,
relative,
x, y, z,
yaw,
duration_s)) | python | def go_to(self, x, y, z, yaw, duration_s, relative=False,
group_mask=ALL_GROUPS):
self._send_packet(struct.pack('<BBBfffff',
self.COMMAND_GO_TO,
group_mask,
relative,
x, y, z,
yaw,
duration_s)) | [
"def",
"go_to",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"yaw",
",",
"duration_s",
",",
"relative",
"=",
"False",
",",
"group_mask",
"=",
"ALL_GROUPS",
")",
":",
"self",
".",
"_send_packet",
"(",
"struct",
".",
"pack",
"(",
"'<BBBfffff'",
",",
"self",
".",
"COMMAND_GO_TO",
",",
"group_mask",
",",
"relative",
",",
"x",
",",
"y",
",",
"z",
",",
"yaw",
",",
"duration_s",
")",
")"
] | Go to an absolute or relative position
:param x: x (m)
:param y: y (m)
:param z: z (m)
:param yaw: yaw (radians)
:param duration_s: time it should take to reach the position (s)
:param relative: True if x, y, z is relative to the current position
:param group_mask: mask for which CFs this should apply to | [
"Go",
"to",
"an",
"absolute",
"or",
"relative",
"position"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L114-L133 |
247,333 | bitcraze/crazyflie-lib-python | cflib/crazyflie/high_level_commander.py | HighLevelCommander.start_trajectory | def start_trajectory(self, trajectory_id, time_scale=1.0, relative=False,
reversed=False, group_mask=ALL_GROUPS):
"""
starts executing a specified trajectory
:param trajectory_id: id of the trajectory (previously defined by
define_trajectory)
:param time_scale: time factor; 1.0 = original speed;
>1.0: slower;
<1.0: faster
:param relative: set to True, if trajectory should be shifted to
current setpoint
:param reversed: set to True, if trajectory should be executed in
reverse
:param group_mask: mask for which CFs this should apply to
:return:
"""
self._send_packet(struct.pack('<BBBBBf',
self.COMMAND_START_TRAJECTORY,
group_mask,
relative,
reversed,
trajectory_id,
time_scale)) | python | def start_trajectory(self, trajectory_id, time_scale=1.0, relative=False,
reversed=False, group_mask=ALL_GROUPS):
self._send_packet(struct.pack('<BBBBBf',
self.COMMAND_START_TRAJECTORY,
group_mask,
relative,
reversed,
trajectory_id,
time_scale)) | [
"def",
"start_trajectory",
"(",
"self",
",",
"trajectory_id",
",",
"time_scale",
"=",
"1.0",
",",
"relative",
"=",
"False",
",",
"reversed",
"=",
"False",
",",
"group_mask",
"=",
"ALL_GROUPS",
")",
":",
"self",
".",
"_send_packet",
"(",
"struct",
".",
"pack",
"(",
"'<BBBBBf'",
",",
"self",
".",
"COMMAND_START_TRAJECTORY",
",",
"group_mask",
",",
"relative",
",",
"reversed",
",",
"trajectory_id",
",",
"time_scale",
")",
")"
] | starts executing a specified trajectory
:param trajectory_id: id of the trajectory (previously defined by
define_trajectory)
:param time_scale: time factor; 1.0 = original speed;
>1.0: slower;
<1.0: faster
:param relative: set to True, if trajectory should be shifted to
current setpoint
:param reversed: set to True, if trajectory should be executed in
reverse
:param group_mask: mask for which CFs this should apply to
:return: | [
"starts",
"executing",
"a",
"specified",
"trajectory"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L135-L158 |
247,334 | bitcraze/crazyflie-lib-python | cflib/crazyflie/high_level_commander.py | HighLevelCommander.define_trajectory | def define_trajectory(self, trajectory_id, offset, n_pieces):
"""
Define a trajectory that has previously been uploaded to memory.
:param trajectory_id: The id of the trajectory
:param offset: offset in uploaded memory
:param n_pieces: Nr of pieces in the trajectory
:return:
"""
self._send_packet(struct.pack('<BBBBIB',
self.COMMAND_DEFINE_TRAJECTORY,
trajectory_id,
self.TRAJECTORY_LOCATION_MEM,
self.TRAJECTORY_TYPE_POLY4D,
offset,
n_pieces)) | python | def define_trajectory(self, trajectory_id, offset, n_pieces):
self._send_packet(struct.pack('<BBBBIB',
self.COMMAND_DEFINE_TRAJECTORY,
trajectory_id,
self.TRAJECTORY_LOCATION_MEM,
self.TRAJECTORY_TYPE_POLY4D,
offset,
n_pieces)) | [
"def",
"define_trajectory",
"(",
"self",
",",
"trajectory_id",
",",
"offset",
",",
"n_pieces",
")",
":",
"self",
".",
"_send_packet",
"(",
"struct",
".",
"pack",
"(",
"'<BBBBIB'",
",",
"self",
".",
"COMMAND_DEFINE_TRAJECTORY",
",",
"trajectory_id",
",",
"self",
".",
"TRAJECTORY_LOCATION_MEM",
",",
"self",
".",
"TRAJECTORY_TYPE_POLY4D",
",",
"offset",
",",
"n_pieces",
")",
")"
] | Define a trajectory that has previously been uploaded to memory.
:param trajectory_id: The id of the trajectory
:param offset: offset in uploaded memory
:param n_pieces: Nr of pieces in the trajectory
:return: | [
"Define",
"a",
"trajectory",
"that",
"has",
"previously",
"been",
"uploaded",
"to",
"memory",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L160-L175 |
247,335 | bitcraze/crazyflie-lib-python | examples/flash-memory.py | choose | def choose(items, title_text, question_text):
"""
Interactively choose one of the items.
"""
print(title_text)
for i, item in enumerate(items, start=1):
print('%d) %s' % (i, item))
print('%d) Abort' % (i + 1))
selected = input(question_text)
try:
index = int(selected)
except ValueError:
index = -1
if not (index - 1) in range(len(items)):
print('Aborting.')
return None
return items[index - 1] | python | def choose(items, title_text, question_text):
print(title_text)
for i, item in enumerate(items, start=1):
print('%d) %s' % (i, item))
print('%d) Abort' % (i + 1))
selected = input(question_text)
try:
index = int(selected)
except ValueError:
index = -1
if not (index - 1) in range(len(items)):
print('Aborting.')
return None
return items[index - 1] | [
"def",
"choose",
"(",
"items",
",",
"title_text",
",",
"question_text",
")",
":",
"print",
"(",
"title_text",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"items",
",",
"start",
"=",
"1",
")",
":",
"print",
"(",
"'%d) %s'",
"%",
"(",
"i",
",",
"item",
")",
")",
"print",
"(",
"'%d) Abort'",
"%",
"(",
"i",
"+",
"1",
")",
")",
"selected",
"=",
"input",
"(",
"question_text",
")",
"try",
":",
"index",
"=",
"int",
"(",
"selected",
")",
"except",
"ValueError",
":",
"index",
"=",
"-",
"1",
"if",
"not",
"(",
"index",
"-",
"1",
")",
"in",
"range",
"(",
"len",
"(",
"items",
")",
")",
":",
"print",
"(",
"'Aborting.'",
")",
"return",
"None",
"return",
"items",
"[",
"index",
"-",
"1",
"]"
] | Interactively choose one of the items. | [
"Interactively",
"choose",
"one",
"of",
"the",
"items",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L110-L129 |
247,336 | bitcraze/crazyflie-lib-python | examples/flash-memory.py | scan | def scan():
"""
Scan for Crazyflie and return its URI.
"""
# Initiate the low level drivers
cflib.crtp.init_drivers(enable_debug_driver=False)
# Scan for Crazyflies
print('Scanning interfaces for Crazyflies...')
available = cflib.crtp.scan_interfaces()
interfaces = [uri for uri, _ in available]
if not interfaces:
return None
return choose(interfaces, 'Crazyflies found:', 'Select interface: ') | python | def scan():
# Initiate the low level drivers
cflib.crtp.init_drivers(enable_debug_driver=False)
# Scan for Crazyflies
print('Scanning interfaces for Crazyflies...')
available = cflib.crtp.scan_interfaces()
interfaces = [uri for uri, _ in available]
if not interfaces:
return None
return choose(interfaces, 'Crazyflies found:', 'Select interface: ') | [
"def",
"scan",
"(",
")",
":",
"# Initiate the low level drivers",
"cflib",
".",
"crtp",
".",
"init_drivers",
"(",
"enable_debug_driver",
"=",
"False",
")",
"# Scan for Crazyflies",
"print",
"(",
"'Scanning interfaces for Crazyflies...'",
")",
"available",
"=",
"cflib",
".",
"crtp",
".",
"scan_interfaces",
"(",
")",
"interfaces",
"=",
"[",
"uri",
"for",
"uri",
",",
"_",
"in",
"available",
"]",
"if",
"not",
"interfaces",
":",
"return",
"None",
"return",
"choose",
"(",
"interfaces",
",",
"'Crazyflies found:'",
",",
"'Select interface: '",
")"
] | Scan for Crazyflie and return its URI. | [
"Scan",
"for",
"Crazyflie",
"and",
"return",
"its",
"URI",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L132-L147 |
247,337 | bitcraze/crazyflie-lib-python | examples/flash-memory.py | Flasher.connect | def connect(self):
"""
Connect to the crazyflie.
"""
print('Connecting to %s' % self._link_uri)
self._cf.open_link(self._link_uri) | python | def connect(self):
print('Connecting to %s' % self._link_uri)
self._cf.open_link(self._link_uri) | [
"def",
"connect",
"(",
"self",
")",
":",
"print",
"(",
"'Connecting to %s'",
"%",
"self",
".",
"_link_uri",
")",
"self",
".",
"_cf",
".",
"open_link",
"(",
"self",
".",
"_link_uri",
")"
] | Connect to the crazyflie. | [
"Connect",
"to",
"the",
"crazyflie",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L55-L60 |
247,338 | bitcraze/crazyflie-lib-python | examples/flash-memory.py | Flasher.wait_for_connection | def wait_for_connection(self, timeout=10):
"""
Busy loop until connection is established.
Will abort after timeout (seconds). Return value is a boolean, whether
connection could be established.
"""
start_time = datetime.datetime.now()
while True:
if self.connected:
return True
now = datetime.datetime.now()
if (now - start_time).total_seconds() > timeout:
return False
time.sleep(0.5) | python | def wait_for_connection(self, timeout=10):
start_time = datetime.datetime.now()
while True:
if self.connected:
return True
now = datetime.datetime.now()
if (now - start_time).total_seconds() > timeout:
return False
time.sleep(0.5) | [
"def",
"wait_for_connection",
"(",
"self",
",",
"timeout",
"=",
"10",
")",
":",
"start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"while",
"True",
":",
"if",
"self",
".",
"connected",
":",
"return",
"True",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"(",
"now",
"-",
"start_time",
")",
".",
"total_seconds",
"(",
")",
">",
"timeout",
":",
"return",
"False",
"time",
".",
"sleep",
"(",
"0.5",
")"
] | Busy loop until connection is established.
Will abort after timeout (seconds). Return value is a boolean, whether
connection could be established. | [
"Busy",
"loop",
"until",
"connection",
"is",
"established",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L66-L81 |
247,339 | bitcraze/crazyflie-lib-python | examples/flash-memory.py | Flasher.search_memories | def search_memories(self):
"""
Search and return list of 1-wire memories.
"""
if not self.connected:
raise NotConnected()
return self._cf.mem.get_mems(MemoryElement.TYPE_1W) | python | def search_memories(self):
if not self.connected:
raise NotConnected()
return self._cf.mem.get_mems(MemoryElement.TYPE_1W) | [
"def",
"search_memories",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"NotConnected",
"(",
")",
"return",
"self",
".",
"_cf",
".",
"mem",
".",
"get_mems",
"(",
"MemoryElement",
".",
"TYPE_1W",
")"
] | Search and return list of 1-wire memories. | [
"Search",
"and",
"return",
"list",
"of",
"1",
"-",
"wire",
"memories",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L83-L89 |
247,340 | bitcraze/crazyflie-lib-python | examples/cfbridge.py | RadioBridge._stab_log_data | def _stab_log_data(self, timestamp, data, logconf):
"""Callback froma the log API when data arrives"""
print('[%d][%s]: %s' % (timestamp, logconf.name, data)) | python | def _stab_log_data(self, timestamp, data, logconf):
print('[%d][%s]: %s' % (timestamp, logconf.name, data)) | [
"def",
"_stab_log_data",
"(",
"self",
",",
"timestamp",
",",
"data",
",",
"logconf",
")",
":",
"print",
"(",
"'[%d][%s]: %s'",
"%",
"(",
"timestamp",
",",
"logconf",
".",
"name",
",",
"data",
")",
")"
] | Callback froma the log API when data arrives | [
"Callback",
"froma",
"the",
"log",
"API",
"when",
"data",
"arrives"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/cfbridge.py#L93-L95 |
247,341 | bitcraze/crazyflie-lib-python | cflib/crazyflie/platformservice.py | PlatformService.fetch_platform_informations | def fetch_platform_informations(self, callback):
"""
Fetch platform info from the firmware
Should be called at the earliest in the connection sequence
"""
self._protocolVersion = -1
self._callback = callback
self._request_protocol_version() | python | def fetch_platform_informations(self, callback):
self._protocolVersion = -1
self._callback = callback
self._request_protocol_version() | [
"def",
"fetch_platform_informations",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"_protocolVersion",
"=",
"-",
"1",
"self",
".",
"_callback",
"=",
"callback",
"self",
".",
"_request_protocol_version",
"(",
")"
] | Fetch platform info from the firmware
Should be called at the earliest in the connection sequence | [
"Fetch",
"platform",
"info",
"from",
"the",
"firmware",
"Should",
"be",
"called",
"at",
"the",
"earliest",
"in",
"the",
"connection",
"sequence"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/platformservice.py#L74-L83 |
247,342 | bitcraze/crazyflie-lib-python | cflib/crtp/usbdriver.py | UsbDriver.receive_packet | def receive_packet(self, time=0):
"""
Receive a packet though the link. This call is blocking but will
timeout and return None if a timeout is supplied.
"""
if time == 0:
try:
return self.in_queue.get(False)
except queue.Empty:
return None
elif time < 0:
try:
return self.in_queue.get(True)
except queue.Empty:
return None
else:
try:
return self.in_queue.get(True, time)
except queue.Empty:
return None | python | def receive_packet(self, time=0):
if time == 0:
try:
return self.in_queue.get(False)
except queue.Empty:
return None
elif time < 0:
try:
return self.in_queue.get(True)
except queue.Empty:
return None
else:
try:
return self.in_queue.get(True, time)
except queue.Empty:
return None | [
"def",
"receive_packet",
"(",
"self",
",",
"time",
"=",
"0",
")",
":",
"if",
"time",
"==",
"0",
":",
"try",
":",
"return",
"self",
".",
"in_queue",
".",
"get",
"(",
"False",
")",
"except",
"queue",
".",
"Empty",
":",
"return",
"None",
"elif",
"time",
"<",
"0",
":",
"try",
":",
"return",
"self",
".",
"in_queue",
".",
"get",
"(",
"True",
")",
"except",
"queue",
".",
"Empty",
":",
"return",
"None",
"else",
":",
"try",
":",
"return",
"self",
".",
"in_queue",
".",
"get",
"(",
"True",
",",
"time",
")",
"except",
"queue",
".",
"Empty",
":",
"return",
"None"
] | Receive a packet though the link. This call is blocking but will
timeout and return None if a timeout is supplied. | [
"Receive",
"a",
"packet",
"though",
"the",
"link",
".",
"This",
"call",
"is",
"blocking",
"but",
"will",
"timeout",
"and",
"return",
"None",
"if",
"a",
"timeout",
"is",
"supplied",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/usbdriver.py#L116-L135 |
247,343 | bitcraze/crazyflie-lib-python | cflib/utils/callbacks.py | Caller.add_callback | def add_callback(self, cb):
""" Register cb as a new callback. Will not register duplicates. """
if ((cb in self.callbacks) is False):
self.callbacks.append(cb) | python | def add_callback(self, cb):
if ((cb in self.callbacks) is False):
self.callbacks.append(cb) | [
"def",
"add_callback",
"(",
"self",
",",
"cb",
")",
":",
"if",
"(",
"(",
"cb",
"in",
"self",
".",
"callbacks",
")",
"is",
"False",
")",
":",
"self",
".",
"callbacks",
".",
"append",
"(",
"cb",
")"
] | Register cb as a new callback. Will not register duplicates. | [
"Register",
"cb",
"as",
"a",
"new",
"callback",
".",
"Will",
"not",
"register",
"duplicates",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/utils/callbacks.py#L42-L45 |
247,344 | bitcraze/crazyflie-lib-python | cflib/bootloader/__init__.py | Bootloader.read_cf1_config | def read_cf1_config(self):
"""Read a flash page from the specified target"""
target = self._cload.targets[0xFF]
config_page = target.flash_pages - 1
return self._cload.read_flash(addr=0xFF, page=config_page) | python | def read_cf1_config(self):
target = self._cload.targets[0xFF]
config_page = target.flash_pages - 1
return self._cload.read_flash(addr=0xFF, page=config_page) | [
"def",
"read_cf1_config",
"(",
"self",
")",
":",
"target",
"=",
"self",
".",
"_cload",
".",
"targets",
"[",
"0xFF",
"]",
"config_page",
"=",
"target",
".",
"flash_pages",
"-",
"1",
"return",
"self",
".",
"_cload",
".",
"read_flash",
"(",
"addr",
"=",
"0xFF",
",",
"page",
"=",
"config_page",
")"
] | Read a flash page from the specified target | [
"Read",
"a",
"flash",
"page",
"from",
"the",
"specified",
"target"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/__init__.py#L122-L127 |
247,345 | bitcraze/crazyflie-lib-python | cflib/drivers/crazyradio.py | Crazyradio.set_channel | def set_channel(self, channel):
""" Set the radio channel to be used """
if channel != self.current_channel:
_send_vendor_setup(self.handle, SET_RADIO_CHANNEL, channel, 0, ())
self.current_channel = channel | python | def set_channel(self, channel):
if channel != self.current_channel:
_send_vendor_setup(self.handle, SET_RADIO_CHANNEL, channel, 0, ())
self.current_channel = channel | [
"def",
"set_channel",
"(",
"self",
",",
"channel",
")",
":",
"if",
"channel",
"!=",
"self",
".",
"current_channel",
":",
"_send_vendor_setup",
"(",
"self",
".",
"handle",
",",
"SET_RADIO_CHANNEL",
",",
"channel",
",",
"0",
",",
"(",
")",
")",
"self",
".",
"current_channel",
"=",
"channel"
] | Set the radio channel to be used | [
"Set",
"the",
"radio",
"channel",
"to",
"be",
"used"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L185-L189 |
247,346 | bitcraze/crazyflie-lib-python | cflib/drivers/crazyradio.py | Crazyradio.set_address | def set_address(self, address):
""" Set the radio address to be used"""
if len(address) != 5:
raise Exception('Crazyradio: the radio address shall be 5'
' bytes long')
if address != self.current_address:
_send_vendor_setup(self.handle, SET_RADIO_ADDRESS, 0, 0, address)
self.current_address = address | python | def set_address(self, address):
if len(address) != 5:
raise Exception('Crazyradio: the radio address shall be 5'
' bytes long')
if address != self.current_address:
_send_vendor_setup(self.handle, SET_RADIO_ADDRESS, 0, 0, address)
self.current_address = address | [
"def",
"set_address",
"(",
"self",
",",
"address",
")",
":",
"if",
"len",
"(",
"address",
")",
"!=",
"5",
":",
"raise",
"Exception",
"(",
"'Crazyradio: the radio address shall be 5'",
"' bytes long'",
")",
"if",
"address",
"!=",
"self",
".",
"current_address",
":",
"_send_vendor_setup",
"(",
"self",
".",
"handle",
",",
"SET_RADIO_ADDRESS",
",",
"0",
",",
"0",
",",
"address",
")",
"self",
".",
"current_address",
"=",
"address"
] | Set the radio address to be used | [
"Set",
"the",
"radio",
"address",
"to",
"be",
"used"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L191-L198 |
247,347 | bitcraze/crazyflie-lib-python | cflib/drivers/crazyradio.py | Crazyradio.set_data_rate | def set_data_rate(self, datarate):
""" Set the radio datarate to be used """
if datarate != self.current_datarate:
_send_vendor_setup(self.handle, SET_DATA_RATE, datarate, 0, ())
self.current_datarate = datarate | python | def set_data_rate(self, datarate):
if datarate != self.current_datarate:
_send_vendor_setup(self.handle, SET_DATA_RATE, datarate, 0, ())
self.current_datarate = datarate | [
"def",
"set_data_rate",
"(",
"self",
",",
"datarate",
")",
":",
"if",
"datarate",
"!=",
"self",
".",
"current_datarate",
":",
"_send_vendor_setup",
"(",
"self",
".",
"handle",
",",
"SET_DATA_RATE",
",",
"datarate",
",",
"0",
",",
"(",
")",
")",
"self",
".",
"current_datarate",
"=",
"datarate"
] | Set the radio datarate to be used | [
"Set",
"the",
"radio",
"datarate",
"to",
"be",
"used"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L200-L204 |
247,348 | bitcraze/crazyflie-lib-python | cflib/drivers/crazyradio.py | Crazyradio.set_arc | def set_arc(self, arc):
""" Set the ACK retry count for radio communication """
_send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ())
self.arc = arc | python | def set_arc(self, arc):
_send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ())
self.arc = arc | [
"def",
"set_arc",
"(",
"self",
",",
"arc",
")",
":",
"_send_vendor_setup",
"(",
"self",
".",
"handle",
",",
"SET_RADIO_ARC",
",",
"arc",
",",
"0",
",",
"(",
")",
")",
"self",
".",
"arc",
"=",
"arc"
] | Set the ACK retry count for radio communication | [
"Set",
"the",
"ACK",
"retry",
"count",
"for",
"radio",
"communication"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L210-L213 |
247,349 | bitcraze/crazyflie-lib-python | cflib/drivers/crazyradio.py | Crazyradio.set_ard_time | def set_ard_time(self, us):
""" Set the ACK retry delay for radio communication """
# Auto Retransmit Delay:
# 0000 - Wait 250uS
# 0001 - Wait 500uS
# 0010 - Wait 750uS
# ........
# 1111 - Wait 4000uS
# Round down, to value representing a multiple of 250uS
t = int((us / 250) - 1)
if (t < 0):
t = 0
if (t > 0xF):
t = 0xF
_send_vendor_setup(self.handle, SET_RADIO_ARD, t, 0, ()) | python | def set_ard_time(self, us):
# Auto Retransmit Delay:
# 0000 - Wait 250uS
# 0001 - Wait 500uS
# 0010 - Wait 750uS
# ........
# 1111 - Wait 4000uS
# Round down, to value representing a multiple of 250uS
t = int((us / 250) - 1)
if (t < 0):
t = 0
if (t > 0xF):
t = 0xF
_send_vendor_setup(self.handle, SET_RADIO_ARD, t, 0, ()) | [
"def",
"set_ard_time",
"(",
"self",
",",
"us",
")",
":",
"# Auto Retransmit Delay:",
"# 0000 - Wait 250uS",
"# 0001 - Wait 500uS",
"# 0010 - Wait 750uS",
"# ........",
"# 1111 - Wait 4000uS",
"# Round down, to value representing a multiple of 250uS",
"t",
"=",
"int",
"(",
"(",
"us",
"/",
"250",
")",
"-",
"1",
")",
"if",
"(",
"t",
"<",
"0",
")",
":",
"t",
"=",
"0",
"if",
"(",
"t",
">",
"0xF",
")",
":",
"t",
"=",
"0xF",
"_send_vendor_setup",
"(",
"self",
".",
"handle",
",",
"SET_RADIO_ARD",
",",
"t",
",",
"0",
",",
"(",
")",
")"
] | Set the ACK retry delay for radio communication | [
"Set",
"the",
"ACK",
"retry",
"delay",
"for",
"radio",
"communication"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L215-L230 |
247,350 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toccache.py | TocCache.fetch | def fetch(self, crc):
""" Try to get a hit in the cache, return None otherwise """
cache_data = None
pattern = '%08X.json' % crc
hit = None
for name in self._cache_files:
if (name.endswith(pattern)):
hit = name
if (hit):
try:
cache = open(hit)
cache_data = json.load(cache,
object_hook=self._decoder)
cache.close()
except Exception as exp:
logger.warning('Error while parsing cache file [%s]:%s',
hit, str(exp))
return cache_data | python | def fetch(self, crc):
cache_data = None
pattern = '%08X.json' % crc
hit = None
for name in self._cache_files:
if (name.endswith(pattern)):
hit = name
if (hit):
try:
cache = open(hit)
cache_data = json.load(cache,
object_hook=self._decoder)
cache.close()
except Exception as exp:
logger.warning('Error while parsing cache file [%s]:%s',
hit, str(exp))
return cache_data | [
"def",
"fetch",
"(",
"self",
",",
"crc",
")",
":",
"cache_data",
"=",
"None",
"pattern",
"=",
"'%08X.json'",
"%",
"crc",
"hit",
"=",
"None",
"for",
"name",
"in",
"self",
".",
"_cache_files",
":",
"if",
"(",
"name",
".",
"endswith",
"(",
"pattern",
")",
")",
":",
"hit",
"=",
"name",
"if",
"(",
"hit",
")",
":",
"try",
":",
"cache",
"=",
"open",
"(",
"hit",
")",
"cache_data",
"=",
"json",
".",
"load",
"(",
"cache",
",",
"object_hook",
"=",
"self",
".",
"_decoder",
")",
"cache",
".",
"close",
"(",
")",
"except",
"Exception",
"as",
"exp",
":",
"logger",
".",
"warning",
"(",
"'Error while parsing cache file [%s]:%s'",
",",
"hit",
",",
"str",
"(",
"exp",
")",
")",
"return",
"cache_data"
] | Try to get a hit in the cache, return None otherwise | [
"Try",
"to",
"get",
"a",
"hit",
"in",
"the",
"cache",
"return",
"None",
"otherwise"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L62-L82 |
247,351 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toccache.py | TocCache.insert | def insert(self, crc, toc):
""" Save a new cache to file """
if self._rw_cache:
try:
filename = '%s/%08X.json' % (self._rw_cache, crc)
cache = open(filename, 'w')
cache.write(json.dumps(toc, indent=2,
default=self._encoder))
cache.close()
logger.info('Saved cache to [%s]', filename)
self._cache_files += [filename]
except Exception as exp:
logger.warning('Could not save cache to file [%s]: %s',
filename, str(exp))
else:
logger.warning('Could not save cache, no writable directory') | python | def insert(self, crc, toc):
if self._rw_cache:
try:
filename = '%s/%08X.json' % (self._rw_cache, crc)
cache = open(filename, 'w')
cache.write(json.dumps(toc, indent=2,
default=self._encoder))
cache.close()
logger.info('Saved cache to [%s]', filename)
self._cache_files += [filename]
except Exception as exp:
logger.warning('Could not save cache to file [%s]: %s',
filename, str(exp))
else:
logger.warning('Could not save cache, no writable directory') | [
"def",
"insert",
"(",
"self",
",",
"crc",
",",
"toc",
")",
":",
"if",
"self",
".",
"_rw_cache",
":",
"try",
":",
"filename",
"=",
"'%s/%08X.json'",
"%",
"(",
"self",
".",
"_rw_cache",
",",
"crc",
")",
"cache",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"cache",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"toc",
",",
"indent",
"=",
"2",
",",
"default",
"=",
"self",
".",
"_encoder",
")",
")",
"cache",
".",
"close",
"(",
")",
"logger",
".",
"info",
"(",
"'Saved cache to [%s]'",
",",
"filename",
")",
"self",
".",
"_cache_files",
"+=",
"[",
"filename",
"]",
"except",
"Exception",
"as",
"exp",
":",
"logger",
".",
"warning",
"(",
"'Could not save cache to file [%s]: %s'",
",",
"filename",
",",
"str",
"(",
"exp",
")",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"'Could not save cache, no writable directory'",
")"
] | Save a new cache to file | [
"Save",
"a",
"new",
"cache",
"to",
"file"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L84-L99 |
247,352 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toccache.py | TocCache._encoder | def _encoder(self, obj):
""" Encode a toc element leaf-node """
return {'__class__': obj.__class__.__name__,
'ident': obj.ident,
'group': obj.group,
'name': obj.name,
'ctype': obj.ctype,
'pytype': obj.pytype,
'access': obj.access}
raise TypeError(repr(obj) + ' is not JSON serializable') | python | def _encoder(self, obj):
return {'__class__': obj.__class__.__name__,
'ident': obj.ident,
'group': obj.group,
'name': obj.name,
'ctype': obj.ctype,
'pytype': obj.pytype,
'access': obj.access}
raise TypeError(repr(obj) + ' is not JSON serializable') | [
"def",
"_encoder",
"(",
"self",
",",
"obj",
")",
":",
"return",
"{",
"'__class__'",
":",
"obj",
".",
"__class__",
".",
"__name__",
",",
"'ident'",
":",
"obj",
".",
"ident",
",",
"'group'",
":",
"obj",
".",
"group",
",",
"'name'",
":",
"obj",
".",
"name",
",",
"'ctype'",
":",
"obj",
".",
"ctype",
",",
"'pytype'",
":",
"obj",
".",
"pytype",
",",
"'access'",
":",
"obj",
".",
"access",
"}",
"raise",
"TypeError",
"(",
"repr",
"(",
"obj",
")",
"+",
"' is not JSON serializable'",
")"
] | Encode a toc element leaf-node | [
"Encode",
"a",
"toc",
"element",
"leaf",
"-",
"node"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L101-L110 |
247,353 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toccache.py | TocCache._decoder | def _decoder(self, obj):
""" Decode a toc element leaf-node """
if '__class__' in obj:
elem = eval(obj['__class__'])()
elem.ident = obj['ident']
elem.group = str(obj['group'])
elem.name = str(obj['name'])
elem.ctype = str(obj['ctype'])
elem.pytype = str(obj['pytype'])
elem.access = obj['access']
return elem
return obj | python | def _decoder(self, obj):
if '__class__' in obj:
elem = eval(obj['__class__'])()
elem.ident = obj['ident']
elem.group = str(obj['group'])
elem.name = str(obj['name'])
elem.ctype = str(obj['ctype'])
elem.pytype = str(obj['pytype'])
elem.access = obj['access']
return elem
return obj | [
"def",
"_decoder",
"(",
"self",
",",
"obj",
")",
":",
"if",
"'__class__'",
"in",
"obj",
":",
"elem",
"=",
"eval",
"(",
"obj",
"[",
"'__class__'",
"]",
")",
"(",
")",
"elem",
".",
"ident",
"=",
"obj",
"[",
"'ident'",
"]",
"elem",
".",
"group",
"=",
"str",
"(",
"obj",
"[",
"'group'",
"]",
")",
"elem",
".",
"name",
"=",
"str",
"(",
"obj",
"[",
"'name'",
"]",
")",
"elem",
".",
"ctype",
"=",
"str",
"(",
"obj",
"[",
"'ctype'",
"]",
")",
"elem",
".",
"pytype",
"=",
"str",
"(",
"obj",
"[",
"'pytype'",
"]",
")",
"elem",
".",
"access",
"=",
"obj",
"[",
"'access'",
"]",
"return",
"elem",
"return",
"obj"
] | Decode a toc element leaf-node | [
"Decode",
"a",
"toc",
"element",
"leaf",
"-",
"node"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L112-L123 |
247,354 | bitcraze/crazyflie-lib-python | lpslib/lopoanchor.py | LoPoAnchor.set_mode | def set_mode(self, anchor_id, mode):
"""
Send a packet to set the anchor mode. If the anchor receive the packet,
it will change mode and resets.
"""
data = struct.pack('<BB', LoPoAnchor.LPP_TYPE_MODE, mode)
self.crazyflie.loc.send_short_lpp_packet(anchor_id, data) | python | def set_mode(self, anchor_id, mode):
data = struct.pack('<BB', LoPoAnchor.LPP_TYPE_MODE, mode)
self.crazyflie.loc.send_short_lpp_packet(anchor_id, data) | [
"def",
"set_mode",
"(",
"self",
",",
"anchor_id",
",",
"mode",
")",
":",
"data",
"=",
"struct",
".",
"pack",
"(",
"'<BB'",
",",
"LoPoAnchor",
".",
"LPP_TYPE_MODE",
",",
"mode",
")",
"self",
".",
"crazyflie",
".",
"loc",
".",
"send_short_lpp_packet",
"(",
"anchor_id",
",",
"data",
")"
] | Send a packet to set the anchor mode. If the anchor receive the packet,
it will change mode and resets. | [
"Send",
"a",
"packet",
"to",
"set",
"the",
"anchor",
"mode",
".",
"If",
"the",
"anchor",
"receive",
"the",
"packet",
"it",
"will",
"change",
"mode",
"and",
"resets",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/lpslib/lopoanchor.py#L66-L72 |
247,355 | bitcraze/crazyflie-lib-python | cflib/crazyflie/swarm.py | Swarm.open_links | def open_links(self):
"""
Open links to all individuals in the swarm
"""
if self._is_open:
raise Exception('Already opened')
try:
self.parallel_safe(lambda scf: scf.open_link())
self._is_open = True
except Exception as e:
self.close_links()
raise e | python | def open_links(self):
if self._is_open:
raise Exception('Already opened')
try:
self.parallel_safe(lambda scf: scf.open_link())
self._is_open = True
except Exception as e:
self.close_links()
raise e | [
"def",
"open_links",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_open",
":",
"raise",
"Exception",
"(",
"'Already opened'",
")",
"try",
":",
"self",
".",
"parallel_safe",
"(",
"lambda",
"scf",
":",
"scf",
".",
"open_link",
"(",
")",
")",
"self",
".",
"_is_open",
"=",
"True",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"close_links",
"(",
")",
"raise",
"e"
] | Open links to all individuals in the swarm | [
"Open",
"links",
"to",
"all",
"individuals",
"in",
"the",
"swarm"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L80-L92 |
247,356 | bitcraze/crazyflie-lib-python | cflib/crazyflie/swarm.py | Swarm.close_links | def close_links(self):
"""
Close all open links
"""
for uri, cf in self._cfs.items():
cf.close_link()
self._is_open = False | python | def close_links(self):
for uri, cf in self._cfs.items():
cf.close_link()
self._is_open = False | [
"def",
"close_links",
"(",
"self",
")",
":",
"for",
"uri",
",",
"cf",
"in",
"self",
".",
"_cfs",
".",
"items",
"(",
")",
":",
"cf",
".",
"close_link",
"(",
")",
"self",
".",
"_is_open",
"=",
"False"
] | Close all open links | [
"Close",
"all",
"open",
"links"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L94-L101 |
247,357 | bitcraze/crazyflie-lib-python | cflib/crazyflie/swarm.py | Swarm.sequential | def sequential(self, func, args_dict=None):
"""
Execute a function for all Crazyflies in the swarm, in sequence.
The first argument of the function that is passed in will be a
SyncCrazyflie instance connected to the Crazyflie to operate on.
A list of optional parameters (per Crazyflie) may follow defined by
the args_dict. The dictionary is keyed on URI.
Example:
def my_function(scf, optional_param0, optional_param1)
...
args_dict = {
URI0: [optional_param0_cf0, optional_param1_cf0],
URI1: [optional_param0_cf1, optional_param1_cf1],
...
}
self.sequential(my_function, args_dict)
:param func: the function to execute
:param args_dict: parameters to pass to the function
"""
for uri, cf in self._cfs.items():
args = self._process_args_dict(cf, uri, args_dict)
func(*args) | python | def sequential(self, func, args_dict=None):
for uri, cf in self._cfs.items():
args = self._process_args_dict(cf, uri, args_dict)
func(*args) | [
"def",
"sequential",
"(",
"self",
",",
"func",
",",
"args_dict",
"=",
"None",
")",
":",
"for",
"uri",
",",
"cf",
"in",
"self",
".",
"_cfs",
".",
"items",
"(",
")",
":",
"args",
"=",
"self",
".",
"_process_args_dict",
"(",
"cf",
",",
"uri",
",",
"args_dict",
")",
"func",
"(",
"*",
"args",
")"
] | Execute a function for all Crazyflies in the swarm, in sequence.
The first argument of the function that is passed in will be a
SyncCrazyflie instance connected to the Crazyflie to operate on.
A list of optional parameters (per Crazyflie) may follow defined by
the args_dict. The dictionary is keyed on URI.
Example:
def my_function(scf, optional_param0, optional_param1)
...
args_dict = {
URI0: [optional_param0_cf0, optional_param1_cf0],
URI1: [optional_param0_cf1, optional_param1_cf1],
...
}
self.sequential(my_function, args_dict)
:param func: the function to execute
:param args_dict: parameters to pass to the function | [
"Execute",
"a",
"function",
"for",
"all",
"Crazyflies",
"in",
"the",
"swarm",
"in",
"sequence",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L110-L137 |
247,358 | bitcraze/crazyflie-lib-python | cflib/crazyflie/swarm.py | Swarm.parallel_safe | def parallel_safe(self, func, args_dict=None):
"""
Execute a function for all Crazyflies in the swarm, in parallel.
One thread per Crazyflie is started to execute the function. The
threads are joined at the end and if one or more of the threads raised
an exception this function will also raise an exception.
For a description of the arguments, see sequential()
:param func:
:param args_dict:
"""
threads = []
reporter = self.Reporter()
for uri, scf in self._cfs.items():
args = [func, reporter] + \
self._process_args_dict(scf, uri, args_dict)
thread = Thread(target=self._thread_function_wrapper, args=args)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if reporter.is_error_reported():
raise Exception('One or more threads raised an exception when '
'executing parallel task') | python | def parallel_safe(self, func, args_dict=None):
threads = []
reporter = self.Reporter()
for uri, scf in self._cfs.items():
args = [func, reporter] + \
self._process_args_dict(scf, uri, args_dict)
thread = Thread(target=self._thread_function_wrapper, args=args)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if reporter.is_error_reported():
raise Exception('One or more threads raised an exception when '
'executing parallel task') | [
"def",
"parallel_safe",
"(",
"self",
",",
"func",
",",
"args_dict",
"=",
"None",
")",
":",
"threads",
"=",
"[",
"]",
"reporter",
"=",
"self",
".",
"Reporter",
"(",
")",
"for",
"uri",
",",
"scf",
"in",
"self",
".",
"_cfs",
".",
"items",
"(",
")",
":",
"args",
"=",
"[",
"func",
",",
"reporter",
"]",
"+",
"self",
".",
"_process_args_dict",
"(",
"scf",
",",
"uri",
",",
"args_dict",
")",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_thread_function_wrapper",
",",
"args",
"=",
"args",
")",
"threads",
".",
"append",
"(",
"thread",
")",
"thread",
".",
"start",
"(",
")",
"for",
"thread",
"in",
"threads",
":",
"thread",
".",
"join",
"(",
")",
"if",
"reporter",
".",
"is_error_reported",
"(",
")",
":",
"raise",
"Exception",
"(",
"'One or more threads raised an exception when '",
"'executing parallel task'",
")"
] | Execute a function for all Crazyflies in the swarm, in parallel.
One thread per Crazyflie is started to execute the function. The
threads are joined at the end and if one or more of the threads raised
an exception this function will also raise an exception.
For a description of the arguments, see sequential()
:param func:
:param args_dict: | [
"Execute",
"a",
"function",
"for",
"all",
"Crazyflies",
"in",
"the",
"swarm",
"in",
"parallel",
".",
"One",
"thread",
"per",
"Crazyflie",
"is",
"started",
"to",
"execute",
"the",
"function",
".",
"The",
"threads",
"are",
"joined",
"at",
"the",
"end",
"and",
"if",
"one",
"or",
"more",
"of",
"the",
"threads",
"raised",
"an",
"exception",
"this",
"function",
"will",
"also",
"raise",
"an",
"exception",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L156-L184 |
247,359 | bitcraze/crazyflie-lib-python | cflib/positioning/position_hl_commander.py | PositionHlCommander.take_off | def take_off(self, height=DEFAULT, velocity=DEFAULT):
"""
Takes off, that is starts the motors, goes straight up and hovers.
Do not call this function if you use the with keyword. Take off is
done automatically when the context is created.
:param height: the height (meters) to hover at. None uses the default
height set when constructed.
:param velocity: the velocity (meters/second) when taking off
:return:
"""
if self._is_flying:
raise Exception('Already flying')
if not self._cf.is_connected():
raise Exception('Crazyflie is not connected')
self._is_flying = True
self._reset_position_estimator()
self._activate_controller()
self._activate_high_level_commander()
self._hl_commander = self._cf.high_level_commander
height = self._height(height)
duration_s = height / self._velocity(velocity)
self._hl_commander.takeoff(height, duration_s)
time.sleep(duration_s)
self._z = height | python | def take_off(self, height=DEFAULT, velocity=DEFAULT):
if self._is_flying:
raise Exception('Already flying')
if not self._cf.is_connected():
raise Exception('Crazyflie is not connected')
self._is_flying = True
self._reset_position_estimator()
self._activate_controller()
self._activate_high_level_commander()
self._hl_commander = self._cf.high_level_commander
height = self._height(height)
duration_s = height / self._velocity(velocity)
self._hl_commander.takeoff(height, duration_s)
time.sleep(duration_s)
self._z = height | [
"def",
"take_off",
"(",
"self",
",",
"height",
"=",
"DEFAULT",
",",
"velocity",
"=",
"DEFAULT",
")",
":",
"if",
"self",
".",
"_is_flying",
":",
"raise",
"Exception",
"(",
"'Already flying'",
")",
"if",
"not",
"self",
".",
"_cf",
".",
"is_connected",
"(",
")",
":",
"raise",
"Exception",
"(",
"'Crazyflie is not connected'",
")",
"self",
".",
"_is_flying",
"=",
"True",
"self",
".",
"_reset_position_estimator",
"(",
")",
"self",
".",
"_activate_controller",
"(",
")",
"self",
".",
"_activate_high_level_commander",
"(",
")",
"self",
".",
"_hl_commander",
"=",
"self",
".",
"_cf",
".",
"high_level_commander",
"height",
"=",
"self",
".",
"_height",
"(",
"height",
")",
"duration_s",
"=",
"height",
"/",
"self",
".",
"_velocity",
"(",
"velocity",
")",
"self",
".",
"_hl_commander",
".",
"takeoff",
"(",
"height",
",",
"duration_s",
")",
"time",
".",
"sleep",
"(",
"duration_s",
")",
"self",
".",
"_z",
"=",
"height"
] | Takes off, that is starts the motors, goes straight up and hovers.
Do not call this function if you use the with keyword. Take off is
done automatically when the context is created.
:param height: the height (meters) to hover at. None uses the default
height set when constructed.
:param velocity: the velocity (meters/second) when taking off
:return: | [
"Takes",
"off",
"that",
"is",
"starts",
"the",
"motors",
"goes",
"straight",
"up",
"and",
"hovers",
".",
"Do",
"not",
"call",
"this",
"function",
"if",
"you",
"use",
"the",
"with",
"keyword",
".",
"Take",
"off",
"is",
"done",
"automatically",
"when",
"the",
"context",
"is",
"created",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/position_hl_commander.py#L82-L110 |
247,360 | bitcraze/crazyflie-lib-python | cflib/positioning/position_hl_commander.py | PositionHlCommander.go_to | def go_to(self, x, y, z=DEFAULT, velocity=DEFAULT):
"""
Go to a position
:param x: X coordinate
:param y: Y coordinate
:param z: Z coordinate
:param velocity: the velocity (meters/second)
:return:
"""
z = self._height(z)
dx = x - self._x
dy = y - self._y
dz = z - self._z
distance = math.sqrt(dx * dx + dy * dy + dz * dz)
duration_s = distance / self._velocity(velocity)
self._hl_commander.go_to(x, y, z, 0, duration_s)
time.sleep(duration_s)
self._x = x
self._y = y
self._z = z | python | def go_to(self, x, y, z=DEFAULT, velocity=DEFAULT):
z = self._height(z)
dx = x - self._x
dy = y - self._y
dz = z - self._z
distance = math.sqrt(dx * dx + dy * dy + dz * dz)
duration_s = distance / self._velocity(velocity)
self._hl_commander.go_to(x, y, z, 0, duration_s)
time.sleep(duration_s)
self._x = x
self._y = y
self._z = z | [
"def",
"go_to",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
"=",
"DEFAULT",
",",
"velocity",
"=",
"DEFAULT",
")",
":",
"z",
"=",
"self",
".",
"_height",
"(",
"z",
")",
"dx",
"=",
"x",
"-",
"self",
".",
"_x",
"dy",
"=",
"y",
"-",
"self",
".",
"_y",
"dz",
"=",
"z",
"-",
"self",
".",
"_z",
"distance",
"=",
"math",
".",
"sqrt",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
"+",
"dz",
"*",
"dz",
")",
"duration_s",
"=",
"distance",
"/",
"self",
".",
"_velocity",
"(",
"velocity",
")",
"self",
".",
"_hl_commander",
".",
"go_to",
"(",
"x",
",",
"y",
",",
"z",
",",
"0",
",",
"duration_s",
")",
"time",
".",
"sleep",
"(",
"duration_s",
")",
"self",
".",
"_x",
"=",
"x",
"self",
".",
"_y",
"=",
"y",
"self",
".",
"_z",
"=",
"z"
] | Go to a position
:param x: X coordinate
:param y: Y coordinate
:param z: Z coordinate
:param velocity: the velocity (meters/second)
:return: | [
"Go",
"to",
"a",
"position"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/position_hl_commander.py#L219-L243 |
247,361 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.request_update_of_all_params | def request_update_of_all_params(self):
"""Request an update of all the parameters in the TOC"""
for group in self.toc.toc:
for name in self.toc.toc[group]:
complete_name = '%s.%s' % (group, name)
self.request_param_update(complete_name) | python | def request_update_of_all_params(self):
for group in self.toc.toc:
for name in self.toc.toc[group]:
complete_name = '%s.%s' % (group, name)
self.request_param_update(complete_name) | [
"def",
"request_update_of_all_params",
"(",
"self",
")",
":",
"for",
"group",
"in",
"self",
".",
"toc",
".",
"toc",
":",
"for",
"name",
"in",
"self",
".",
"toc",
".",
"toc",
"[",
"group",
"]",
":",
"complete_name",
"=",
"'%s.%s'",
"%",
"(",
"group",
",",
"name",
")",
"self",
".",
"request_param_update",
"(",
"complete_name",
")"
] | Request an update of all the parameters in the TOC | [
"Request",
"an",
"update",
"of",
"all",
"the",
"parameters",
"in",
"the",
"TOC"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L145-L150 |
247,362 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param._check_if_all_updated | def _check_if_all_updated(self):
"""Check if all parameters from the TOC has at least been fetched
once"""
for g in self.toc.toc:
if g not in self.values:
return False
for n in self.toc.toc[g]:
if n not in self.values[g]:
return False
return True | python | def _check_if_all_updated(self):
for g in self.toc.toc:
if g not in self.values:
return False
for n in self.toc.toc[g]:
if n not in self.values[g]:
return False
return True | [
"def",
"_check_if_all_updated",
"(",
"self",
")",
":",
"for",
"g",
"in",
"self",
".",
"toc",
".",
"toc",
":",
"if",
"g",
"not",
"in",
"self",
".",
"values",
":",
"return",
"False",
"for",
"n",
"in",
"self",
".",
"toc",
".",
"toc",
"[",
"g",
"]",
":",
"if",
"n",
"not",
"in",
"self",
".",
"values",
"[",
"g",
"]",
":",
"return",
"False",
"return",
"True"
] | Check if all parameters from the TOC has at least been fetched
once | [
"Check",
"if",
"all",
"parameters",
"from",
"the",
"TOC",
"has",
"at",
"least",
"been",
"fetched",
"once"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L152-L162 |
247,363 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param._param_updated | def _param_updated(self, pk):
"""Callback with data for an updated parameter"""
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
else:
var_id = pk.data[0]
element = self.toc.get_element_by_id(var_id)
if element:
if self._useV2:
s = struct.unpack(element.pytype, pk.data[2:])[0]
else:
s = struct.unpack(element.pytype, pk.data[1:])[0]
s = s.__str__()
complete_name = '%s.%s' % (element.group, element.name)
# Save the value for synchronous access
if element.group not in self.values:
self.values[element.group] = {}
self.values[element.group][element.name] = s
logger.debug('Updated parameter [%s]' % complete_name)
if complete_name in self.param_update_callbacks:
self.param_update_callbacks[complete_name].call(
complete_name, s)
if element.group in self.group_update_callbacks:
self.group_update_callbacks[element.group].call(
complete_name, s)
self.all_update_callback.call(complete_name, s)
# Once all the parameters are updated call the
# callback for "everything updated" (after all the param
# updated callbacks)
if self._check_if_all_updated() and not self.is_updated:
self.is_updated = True
self.all_updated.call()
else:
logger.debug('Variable id [%d] not found in TOC', var_id) | python | def _param_updated(self, pk):
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
else:
var_id = pk.data[0]
element = self.toc.get_element_by_id(var_id)
if element:
if self._useV2:
s = struct.unpack(element.pytype, pk.data[2:])[0]
else:
s = struct.unpack(element.pytype, pk.data[1:])[0]
s = s.__str__()
complete_name = '%s.%s' % (element.group, element.name)
# Save the value for synchronous access
if element.group not in self.values:
self.values[element.group] = {}
self.values[element.group][element.name] = s
logger.debug('Updated parameter [%s]' % complete_name)
if complete_name in self.param_update_callbacks:
self.param_update_callbacks[complete_name].call(
complete_name, s)
if element.group in self.group_update_callbacks:
self.group_update_callbacks[element.group].call(
complete_name, s)
self.all_update_callback.call(complete_name, s)
# Once all the parameters are updated call the
# callback for "everything updated" (after all the param
# updated callbacks)
if self._check_if_all_updated() and not self.is_updated:
self.is_updated = True
self.all_updated.call()
else:
logger.debug('Variable id [%d] not found in TOC', var_id) | [
"def",
"_param_updated",
"(",
"self",
",",
"pk",
")",
":",
"if",
"self",
".",
"_useV2",
":",
"var_id",
"=",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"pk",
".",
"data",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"else",
":",
"var_id",
"=",
"pk",
".",
"data",
"[",
"0",
"]",
"element",
"=",
"self",
".",
"toc",
".",
"get_element_by_id",
"(",
"var_id",
")",
"if",
"element",
":",
"if",
"self",
".",
"_useV2",
":",
"s",
"=",
"struct",
".",
"unpack",
"(",
"element",
".",
"pytype",
",",
"pk",
".",
"data",
"[",
"2",
":",
"]",
")",
"[",
"0",
"]",
"else",
":",
"s",
"=",
"struct",
".",
"unpack",
"(",
"element",
".",
"pytype",
",",
"pk",
".",
"data",
"[",
"1",
":",
"]",
")",
"[",
"0",
"]",
"s",
"=",
"s",
".",
"__str__",
"(",
")",
"complete_name",
"=",
"'%s.%s'",
"%",
"(",
"element",
".",
"group",
",",
"element",
".",
"name",
")",
"# Save the value for synchronous access",
"if",
"element",
".",
"group",
"not",
"in",
"self",
".",
"values",
":",
"self",
".",
"values",
"[",
"element",
".",
"group",
"]",
"=",
"{",
"}",
"self",
".",
"values",
"[",
"element",
".",
"group",
"]",
"[",
"element",
".",
"name",
"]",
"=",
"s",
"logger",
".",
"debug",
"(",
"'Updated parameter [%s]'",
"%",
"complete_name",
")",
"if",
"complete_name",
"in",
"self",
".",
"param_update_callbacks",
":",
"self",
".",
"param_update_callbacks",
"[",
"complete_name",
"]",
".",
"call",
"(",
"complete_name",
",",
"s",
")",
"if",
"element",
".",
"group",
"in",
"self",
".",
"group_update_callbacks",
":",
"self",
".",
"group_update_callbacks",
"[",
"element",
".",
"group",
"]",
".",
"call",
"(",
"complete_name",
",",
"s",
")",
"self",
".",
"all_update_callback",
".",
"call",
"(",
"complete_name",
",",
"s",
")",
"# Once all the parameters are updated call the",
"# callback for \"everything updated\" (after all the param",
"# updated callbacks)",
"if",
"self",
".",
"_check_if_all_updated",
"(",
")",
"and",
"not",
"self",
".",
"is_updated",
":",
"self",
".",
"is_updated",
"=",
"True",
"self",
".",
"all_updated",
".",
"call",
"(",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Variable id [%d] not found in TOC'",
",",
"var_id",
")"
] | Callback with data for an updated parameter | [
"Callback",
"with",
"data",
"for",
"an",
"updated",
"parameter"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L164-L200 |
247,364 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.remove_update_callback | def remove_update_callback(self, group, name=None, cb=None):
"""Remove the supplied callback for a group or a group.name"""
if not cb:
return
if not name:
if group in self.group_update_callbacks:
self.group_update_callbacks[group].remove_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname in self.param_update_callbacks:
self.param_update_callbacks[paramname].remove_callback(cb) | python | def remove_update_callback(self, group, name=None, cb=None):
if not cb:
return
if not name:
if group in self.group_update_callbacks:
self.group_update_callbacks[group].remove_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname in self.param_update_callbacks:
self.param_update_callbacks[paramname].remove_callback(cb) | [
"def",
"remove_update_callback",
"(",
"self",
",",
"group",
",",
"name",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"if",
"not",
"cb",
":",
"return",
"if",
"not",
"name",
":",
"if",
"group",
"in",
"self",
".",
"group_update_callbacks",
":",
"self",
".",
"group_update_callbacks",
"[",
"group",
"]",
".",
"remove_callback",
"(",
"cb",
")",
"else",
":",
"paramname",
"=",
"'{}.{}'",
".",
"format",
"(",
"group",
",",
"name",
")",
"if",
"paramname",
"in",
"self",
".",
"param_update_callbacks",
":",
"self",
".",
"param_update_callbacks",
"[",
"paramname",
"]",
".",
"remove_callback",
"(",
"cb",
")"
] | Remove the supplied callback for a group or a group.name | [
"Remove",
"the",
"supplied",
"callback",
"for",
"a",
"group",
"or",
"a",
"group",
".",
"name"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L202-L213 |
247,365 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.add_update_callback | def add_update_callback(self, group=None, name=None, cb=None):
"""
Add a callback for a specific parameter name. This callback will be
executed when a new value is read from the Crazyflie.
"""
if not group and not name:
self.all_update_callback.add_callback(cb)
elif not name:
if group not in self.group_update_callbacks:
self.group_update_callbacks[group] = Caller()
self.group_update_callbacks[group].add_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname not in self.param_update_callbacks:
self.param_update_callbacks[paramname] = Caller()
self.param_update_callbacks[paramname].add_callback(cb) | python | def add_update_callback(self, group=None, name=None, cb=None):
if not group and not name:
self.all_update_callback.add_callback(cb)
elif not name:
if group not in self.group_update_callbacks:
self.group_update_callbacks[group] = Caller()
self.group_update_callbacks[group].add_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname not in self.param_update_callbacks:
self.param_update_callbacks[paramname] = Caller()
self.param_update_callbacks[paramname].add_callback(cb) | [
"def",
"add_update_callback",
"(",
"self",
",",
"group",
"=",
"None",
",",
"name",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"if",
"not",
"group",
"and",
"not",
"name",
":",
"self",
".",
"all_update_callback",
".",
"add_callback",
"(",
"cb",
")",
"elif",
"not",
"name",
":",
"if",
"group",
"not",
"in",
"self",
".",
"group_update_callbacks",
":",
"self",
".",
"group_update_callbacks",
"[",
"group",
"]",
"=",
"Caller",
"(",
")",
"self",
".",
"group_update_callbacks",
"[",
"group",
"]",
".",
"add_callback",
"(",
"cb",
")",
"else",
":",
"paramname",
"=",
"'{}.{}'",
".",
"format",
"(",
"group",
",",
"name",
")",
"if",
"paramname",
"not",
"in",
"self",
".",
"param_update_callbacks",
":",
"self",
".",
"param_update_callbacks",
"[",
"paramname",
"]",
"=",
"Caller",
"(",
")",
"self",
".",
"param_update_callbacks",
"[",
"paramname",
"]",
".",
"add_callback",
"(",
"cb",
")"
] | Add a callback for a specific parameter name. This callback will be
executed when a new value is read from the Crazyflie. | [
"Add",
"a",
"callback",
"for",
"a",
"specific",
"parameter",
"name",
".",
"This",
"callback",
"will",
"be",
"executed",
"when",
"a",
"new",
"value",
"is",
"read",
"from",
"the",
"Crazyflie",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L215-L230 |
247,366 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.refresh_toc | def refresh_toc(self, refresh_done_callback, toc_cache):
"""
Initiate a refresh of the parameter TOC.
"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
toc_fetcher = TocFetcher(self.cf, ParamTocElement,
CRTPPort.PARAM, self.toc,
refresh_done_callback, toc_cache)
toc_fetcher.start() | python | def refresh_toc(self, refresh_done_callback, toc_cache):
self._useV2 = self.cf.platform.get_protocol_version() >= 4
toc_fetcher = TocFetcher(self.cf, ParamTocElement,
CRTPPort.PARAM, self.toc,
refresh_done_callback, toc_cache)
toc_fetcher.start() | [
"def",
"refresh_toc",
"(",
"self",
",",
"refresh_done_callback",
",",
"toc_cache",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"toc_fetcher",
"=",
"TocFetcher",
"(",
"self",
".",
"cf",
",",
"ParamTocElement",
",",
"CRTPPort",
".",
"PARAM",
",",
"self",
".",
"toc",
",",
"refresh_done_callback",
",",
"toc_cache",
")",
"toc_fetcher",
".",
"start",
"(",
")"
] | Initiate a refresh of the parameter TOC. | [
"Initiate",
"a",
"refresh",
"of",
"the",
"parameter",
"TOC",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L232-L240 |
247,367 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param._disconnected | def _disconnected(self, uri):
"""Disconnected callback from Crazyflie API"""
self.param_updater.close()
self.is_updated = False
# Clear all values from the previous Crazyflie
self.toc = Toc()
self.values = {} | python | def _disconnected(self, uri):
self.param_updater.close()
self.is_updated = False
# Clear all values from the previous Crazyflie
self.toc = Toc()
self.values = {} | [
"def",
"_disconnected",
"(",
"self",
",",
"uri",
")",
":",
"self",
".",
"param_updater",
".",
"close",
"(",
")",
"self",
".",
"is_updated",
"=",
"False",
"# Clear all values from the previous Crazyflie",
"self",
".",
"toc",
"=",
"Toc",
"(",
")",
"self",
".",
"values",
"=",
"{",
"}"
] | Disconnected callback from Crazyflie API | [
"Disconnected",
"callback",
"from",
"Crazyflie",
"API"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L242-L248 |
247,368 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.request_param_update | def request_param_update(self, complete_name):
"""
Request an update of the value for the supplied parameter.
"""
self.param_updater.request_param_update(
self.toc.get_element_id(complete_name)) | python | def request_param_update(self, complete_name):
self.param_updater.request_param_update(
self.toc.get_element_id(complete_name)) | [
"def",
"request_param_update",
"(",
"self",
",",
"complete_name",
")",
":",
"self",
".",
"param_updater",
".",
"request_param_update",
"(",
"self",
".",
"toc",
".",
"get_element_id",
"(",
"complete_name",
")",
")"
] | Request an update of the value for the supplied parameter. | [
"Request",
"an",
"update",
"of",
"the",
"value",
"for",
"the",
"supplied",
"parameter",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L250-L255 |
247,369 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.set_value | def set_value(self, complete_name, value):
"""
Set the value for the supplied parameter.
"""
element = self.toc.get_element_by_complete_name(complete_name)
if not element:
logger.warning("Cannot set value for [%s], it's not in the TOC!",
complete_name)
raise KeyError('{} not in param TOC'.format(complete_name))
elif element.access == ParamTocElement.RO_ACCESS:
logger.debug('[%s] is read only, no trying to set value',
complete_name)
raise AttributeError('{} is read-only!'.format(complete_name))
else:
varid = element.ident
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, WRITE_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', varid)
else:
pk.data = struct.pack('<B', varid)
try:
value_nr = eval(value)
except TypeError:
value_nr = value
pk.data += struct.pack(element.pytype, value_nr)
self.param_updater.request_param_setvalue(pk) | python | def set_value(self, complete_name, value):
element = self.toc.get_element_by_complete_name(complete_name)
if not element:
logger.warning("Cannot set value for [%s], it's not in the TOC!",
complete_name)
raise KeyError('{} not in param TOC'.format(complete_name))
elif element.access == ParamTocElement.RO_ACCESS:
logger.debug('[%s] is read only, no trying to set value',
complete_name)
raise AttributeError('{} is read-only!'.format(complete_name))
else:
varid = element.ident
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, WRITE_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', varid)
else:
pk.data = struct.pack('<B', varid)
try:
value_nr = eval(value)
except TypeError:
value_nr = value
pk.data += struct.pack(element.pytype, value_nr)
self.param_updater.request_param_setvalue(pk) | [
"def",
"set_value",
"(",
"self",
",",
"complete_name",
",",
"value",
")",
":",
"element",
"=",
"self",
".",
"toc",
".",
"get_element_by_complete_name",
"(",
"complete_name",
")",
"if",
"not",
"element",
":",
"logger",
".",
"warning",
"(",
"\"Cannot set value for [%s], it's not in the TOC!\"",
",",
"complete_name",
")",
"raise",
"KeyError",
"(",
"'{} not in param TOC'",
".",
"format",
"(",
"complete_name",
")",
")",
"elif",
"element",
".",
"access",
"==",
"ParamTocElement",
".",
"RO_ACCESS",
":",
"logger",
".",
"debug",
"(",
"'[%s] is read only, no trying to set value'",
",",
"complete_name",
")",
"raise",
"AttributeError",
"(",
"'{} is read-only!'",
".",
"format",
"(",
"complete_name",
")",
")",
"else",
":",
"varid",
"=",
"element",
".",
"ident",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"CRTPPort",
".",
"PARAM",
",",
"WRITE_CHANNEL",
")",
"if",
"self",
".",
"_useV2",
":",
"pk",
".",
"data",
"=",
"struct",
".",
"pack",
"(",
"'<H'",
",",
"varid",
")",
"else",
":",
"pk",
".",
"data",
"=",
"struct",
".",
"pack",
"(",
"'<B'",
",",
"varid",
")",
"try",
":",
"value_nr",
"=",
"eval",
"(",
"value",
")",
"except",
"TypeError",
":",
"value_nr",
"=",
"value",
"pk",
".",
"data",
"+=",
"struct",
".",
"pack",
"(",
"element",
".",
"pytype",
",",
"value_nr",
")",
"self",
".",
"param_updater",
".",
"request_param_setvalue",
"(",
"pk",
")"
] | Set the value for the supplied parameter. | [
"Set",
"the",
"value",
"for",
"the",
"supplied",
"parameter",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L257-L286 |
247,370 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | _ParamUpdater._new_packet_cb | def _new_packet_cb(self, pk):
"""Callback for newly arrived packets"""
if pk.channel == READ_CHANNEL or pk.channel == WRITE_CHANNEL:
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
if pk.channel == READ_CHANNEL:
pk.data = pk.data[:2] + pk.data[3:]
else:
var_id = pk.data[0]
if (pk.channel != TOC_CHANNEL and self._req_param == var_id and
pk is not None):
self.updated_callback(pk)
self._req_param = -1
try:
self.wait_lock.release()
except Exception:
pass | python | def _new_packet_cb(self, pk):
if pk.channel == READ_CHANNEL or pk.channel == WRITE_CHANNEL:
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
if pk.channel == READ_CHANNEL:
pk.data = pk.data[:2] + pk.data[3:]
else:
var_id = pk.data[0]
if (pk.channel != TOC_CHANNEL and self._req_param == var_id and
pk is not None):
self.updated_callback(pk)
self._req_param = -1
try:
self.wait_lock.release()
except Exception:
pass | [
"def",
"_new_packet_cb",
"(",
"self",
",",
"pk",
")",
":",
"if",
"pk",
".",
"channel",
"==",
"READ_CHANNEL",
"or",
"pk",
".",
"channel",
"==",
"WRITE_CHANNEL",
":",
"if",
"self",
".",
"_useV2",
":",
"var_id",
"=",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"pk",
".",
"data",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"if",
"pk",
".",
"channel",
"==",
"READ_CHANNEL",
":",
"pk",
".",
"data",
"=",
"pk",
".",
"data",
"[",
":",
"2",
"]",
"+",
"pk",
".",
"data",
"[",
"3",
":",
"]",
"else",
":",
"var_id",
"=",
"pk",
".",
"data",
"[",
"0",
"]",
"if",
"(",
"pk",
".",
"channel",
"!=",
"TOC_CHANNEL",
"and",
"self",
".",
"_req_param",
"==",
"var_id",
"and",
"pk",
"is",
"not",
"None",
")",
":",
"self",
".",
"updated_callback",
"(",
"pk",
")",
"self",
".",
"_req_param",
"=",
"-",
"1",
"try",
":",
"self",
".",
"wait_lock",
".",
"release",
"(",
")",
"except",
"Exception",
":",
"pass"
] | Callback for newly arrived packets | [
"Callback",
"for",
"newly",
"arrived",
"packets"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L322-L338 |
247,371 | bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | _ParamUpdater.request_param_update | def request_param_update(self, var_id):
"""Place a param update request on the queue"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, READ_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', var_id)
else:
pk.data = struct.pack('<B', var_id)
logger.debug('Requesting request to update param [%d]', var_id)
self.request_queue.put(pk) | python | def request_param_update(self, var_id):
self._useV2 = self.cf.platform.get_protocol_version() >= 4
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, READ_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', var_id)
else:
pk.data = struct.pack('<B', var_id)
logger.debug('Requesting request to update param [%d]', var_id)
self.request_queue.put(pk) | [
"def",
"request_param_update",
"(",
"self",
",",
"var_id",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"CRTPPort",
".",
"PARAM",
",",
"READ_CHANNEL",
")",
"if",
"self",
".",
"_useV2",
":",
"pk",
".",
"data",
"=",
"struct",
".",
"pack",
"(",
"'<H'",
",",
"var_id",
")",
"else",
":",
"pk",
".",
"data",
"=",
"struct",
".",
"pack",
"(",
"'<B'",
",",
"var_id",
")",
"logger",
".",
"debug",
"(",
"'Requesting request to update param [%d]'",
",",
"var_id",
")",
"self",
".",
"request_queue",
".",
"put",
"(",
"pk",
")"
] | Place a param update request on the queue | [
"Place",
"a",
"param",
"update",
"request",
"on",
"the",
"queue"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L340-L350 |
247,372 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | Toc.add_element | def add_element(self, element):
"""Add a new TocElement to the TOC container."""
try:
self.toc[element.group][element.name] = element
except KeyError:
self.toc[element.group] = {}
self.toc[element.group][element.name] = element | python | def add_element(self, element):
try:
self.toc[element.group][element.name] = element
except KeyError:
self.toc[element.group] = {}
self.toc[element.group][element.name] = element | [
"def",
"add_element",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"self",
".",
"toc",
"[",
"element",
".",
"group",
"]",
"[",
"element",
".",
"name",
"]",
"=",
"element",
"except",
"KeyError",
":",
"self",
".",
"toc",
"[",
"element",
".",
"group",
"]",
"=",
"{",
"}",
"self",
".",
"toc",
"[",
"element",
".",
"group",
"]",
"[",
"element",
".",
"name",
"]",
"=",
"element"
] | Add a new TocElement to the TOC container. | [
"Add",
"a",
"new",
"TocElement",
"to",
"the",
"TOC",
"container",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L65-L71 |
247,373 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | Toc.get_element_id | def get_element_id(self, complete_name):
"""Get the TocElement element id-number of the element with the
supplied name."""
[group, name] = complete_name.split('.')
element = self.get_element(group, name)
if element:
return element.ident
else:
logger.warning('Unable to find variable [%s]', complete_name)
return None | python | def get_element_id(self, complete_name):
[group, name] = complete_name.split('.')
element = self.get_element(group, name)
if element:
return element.ident
else:
logger.warning('Unable to find variable [%s]', complete_name)
return None | [
"def",
"get_element_id",
"(",
"self",
",",
"complete_name",
")",
":",
"[",
"group",
",",
"name",
"]",
"=",
"complete_name",
".",
"split",
"(",
"'.'",
")",
"element",
"=",
"self",
".",
"get_element",
"(",
"group",
",",
"name",
")",
"if",
"element",
":",
"return",
"element",
".",
"ident",
"else",
":",
"logger",
".",
"warning",
"(",
"'Unable to find variable [%s]'",
",",
"complete_name",
")",
"return",
"None"
] | Get the TocElement element id-number of the element with the
supplied name. | [
"Get",
"the",
"TocElement",
"element",
"id",
"-",
"number",
"of",
"the",
"element",
"with",
"the",
"supplied",
"name",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L82-L91 |
247,374 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | Toc.get_element_by_id | def get_element_by_id(self, ident):
"""Get a TocElement element identified by index number from the
container."""
for group in list(self.toc.keys()):
for name in list(self.toc[group].keys()):
if self.toc[group][name].ident == ident:
return self.toc[group][name]
return None | python | def get_element_by_id(self, ident):
for group in list(self.toc.keys()):
for name in list(self.toc[group].keys()):
if self.toc[group][name].ident == ident:
return self.toc[group][name]
return None | [
"def",
"get_element_by_id",
"(",
"self",
",",
"ident",
")",
":",
"for",
"group",
"in",
"list",
"(",
"self",
".",
"toc",
".",
"keys",
"(",
")",
")",
":",
"for",
"name",
"in",
"list",
"(",
"self",
".",
"toc",
"[",
"group",
"]",
".",
"keys",
"(",
")",
")",
":",
"if",
"self",
".",
"toc",
"[",
"group",
"]",
"[",
"name",
"]",
".",
"ident",
"==",
"ident",
":",
"return",
"self",
".",
"toc",
"[",
"group",
"]",
"[",
"name",
"]",
"return",
"None"
] | Get a TocElement element identified by index number from the
container. | [
"Get",
"a",
"TocElement",
"element",
"identified",
"by",
"index",
"number",
"from",
"the",
"container",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L101-L108 |
247,375 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher.start | def start(self):
"""Initiate fetching of the TOC."""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
logger.debug('[%d]: Using V2 protocol: %d', self.port, self._useV2)
logger.debug('[%d]: Start fetching...', self.port)
# Register callback in this class for the port
self.cf.add_port_callback(self.port, self._new_packet_cb)
# Request the TOC CRC
self.state = GET_TOC_INFO
pk = CRTPPacket()
pk.set_header(self.port, TOC_CHANNEL)
if self._useV2:
pk.data = (CMD_TOC_INFO_V2,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO_V2,))
else:
pk.data = (CMD_TOC_INFO,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO,)) | python | def start(self):
self._useV2 = self.cf.platform.get_protocol_version() >= 4
logger.debug('[%d]: Using V2 protocol: %d', self.port, self._useV2)
logger.debug('[%d]: Start fetching...', self.port)
# Register callback in this class for the port
self.cf.add_port_callback(self.port, self._new_packet_cb)
# Request the TOC CRC
self.state = GET_TOC_INFO
pk = CRTPPacket()
pk.set_header(self.port, TOC_CHANNEL)
if self._useV2:
pk.data = (CMD_TOC_INFO_V2,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO_V2,))
else:
pk.data = (CMD_TOC_INFO,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO,)) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"logger",
".",
"debug",
"(",
"'[%d]: Using V2 protocol: %d'",
",",
"self",
".",
"port",
",",
"self",
".",
"_useV2",
")",
"logger",
".",
"debug",
"(",
"'[%d]: Start fetching...'",
",",
"self",
".",
"port",
")",
"# Register callback in this class for the port",
"self",
".",
"cf",
".",
"add_port_callback",
"(",
"self",
".",
"port",
",",
"self",
".",
"_new_packet_cb",
")",
"# Request the TOC CRC",
"self",
".",
"state",
"=",
"GET_TOC_INFO",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"self",
".",
"port",
",",
"TOC_CHANNEL",
")",
"if",
"self",
".",
"_useV2",
":",
"pk",
".",
"data",
"=",
"(",
"CMD_TOC_INFO_V2",
",",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_TOC_INFO_V2",
",",
")",
")",
"else",
":",
"pk",
".",
"data",
"=",
"(",
"CMD_TOC_INFO",
",",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_TOC_INFO",
",",
")",
")"
] | Initiate fetching of the TOC. | [
"Initiate",
"fetching",
"of",
"the",
"TOC",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L128-L147 |
247,376 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher._toc_fetch_finished | def _toc_fetch_finished(self):
"""Callback for when the TOC fetching is finished"""
self.cf.remove_port_callback(self.port, self._new_packet_cb)
logger.debug('[%d]: Done!', self.port)
self.finished_callback() | python | def _toc_fetch_finished(self):
self.cf.remove_port_callback(self.port, self._new_packet_cb)
logger.debug('[%d]: Done!', self.port)
self.finished_callback() | [
"def",
"_toc_fetch_finished",
"(",
"self",
")",
":",
"self",
".",
"cf",
".",
"remove_port_callback",
"(",
"self",
".",
"port",
",",
"self",
".",
"_new_packet_cb",
")",
"logger",
".",
"debug",
"(",
"'[%d]: Done!'",
",",
"self",
".",
"port",
")",
"self",
".",
"finished_callback",
"(",
")"
] | Callback for when the TOC fetching is finished | [
"Callback",
"for",
"when",
"the",
"TOC",
"fetching",
"is",
"finished"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L149-L153 |
247,377 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher._new_packet_cb | def _new_packet_cb(self, packet):
"""Handle a newly arrived packet"""
chan = packet.channel
if (chan != 0):
return
payload = packet.data[1:]
if (self.state == GET_TOC_INFO):
if self._useV2:
[self.nbr_of_items, self._crc] = struct.unpack(
'<HI', payload[:6])
else:
[self.nbr_of_items, self._crc] = struct.unpack(
'<BI', payload[:5])
logger.debug('[%d]: Got TOC CRC, %d items and crc=0x%08X',
self.port, self.nbr_of_items, self._crc)
cache_data = self._toc_cache.fetch(self._crc)
if (cache_data):
self.toc.toc = cache_data
logger.info('TOC for port [%s] found in cache' % self.port)
self._toc_fetch_finished()
else:
self.state = GET_TOC_ELEMENT
self.requested_index = 0
self._request_toc_element(self.requested_index)
elif (self.state == GET_TOC_ELEMENT):
# Always add new element, but only request new if it's not the
# last one.
if self._useV2:
ident = struct.unpack('<H', payload[:2])[0]
else:
ident = payload[0]
if ident != self.requested_index:
return
if self._useV2:
self.toc.add_element(self.element_class(ident, payload[2:]))
else:
self.toc.add_element(self.element_class(ident, payload[1:]))
logger.debug('Added element [%s]', ident)
if (self.requested_index < (self.nbr_of_items - 1)):
logger.debug('[%d]: More variables, requesting index %d',
self.port, self.requested_index + 1)
self.requested_index = self.requested_index + 1
self._request_toc_element(self.requested_index)
else: # No more variables in TOC
self._toc_cache.insert(self._crc, self.toc.toc)
self._toc_fetch_finished() | python | def _new_packet_cb(self, packet):
chan = packet.channel
if (chan != 0):
return
payload = packet.data[1:]
if (self.state == GET_TOC_INFO):
if self._useV2:
[self.nbr_of_items, self._crc] = struct.unpack(
'<HI', payload[:6])
else:
[self.nbr_of_items, self._crc] = struct.unpack(
'<BI', payload[:5])
logger.debug('[%d]: Got TOC CRC, %d items and crc=0x%08X',
self.port, self.nbr_of_items, self._crc)
cache_data = self._toc_cache.fetch(self._crc)
if (cache_data):
self.toc.toc = cache_data
logger.info('TOC for port [%s] found in cache' % self.port)
self._toc_fetch_finished()
else:
self.state = GET_TOC_ELEMENT
self.requested_index = 0
self._request_toc_element(self.requested_index)
elif (self.state == GET_TOC_ELEMENT):
# Always add new element, but only request new if it's not the
# last one.
if self._useV2:
ident = struct.unpack('<H', payload[:2])[0]
else:
ident = payload[0]
if ident != self.requested_index:
return
if self._useV2:
self.toc.add_element(self.element_class(ident, payload[2:]))
else:
self.toc.add_element(self.element_class(ident, payload[1:]))
logger.debug('Added element [%s]', ident)
if (self.requested_index < (self.nbr_of_items - 1)):
logger.debug('[%d]: More variables, requesting index %d',
self.port, self.requested_index + 1)
self.requested_index = self.requested_index + 1
self._request_toc_element(self.requested_index)
else: # No more variables in TOC
self._toc_cache.insert(self._crc, self.toc.toc)
self._toc_fetch_finished() | [
"def",
"_new_packet_cb",
"(",
"self",
",",
"packet",
")",
":",
"chan",
"=",
"packet",
".",
"channel",
"if",
"(",
"chan",
"!=",
"0",
")",
":",
"return",
"payload",
"=",
"packet",
".",
"data",
"[",
"1",
":",
"]",
"if",
"(",
"self",
".",
"state",
"==",
"GET_TOC_INFO",
")",
":",
"if",
"self",
".",
"_useV2",
":",
"[",
"self",
".",
"nbr_of_items",
",",
"self",
".",
"_crc",
"]",
"=",
"struct",
".",
"unpack",
"(",
"'<HI'",
",",
"payload",
"[",
":",
"6",
"]",
")",
"else",
":",
"[",
"self",
".",
"nbr_of_items",
",",
"self",
".",
"_crc",
"]",
"=",
"struct",
".",
"unpack",
"(",
"'<BI'",
",",
"payload",
"[",
":",
"5",
"]",
")",
"logger",
".",
"debug",
"(",
"'[%d]: Got TOC CRC, %d items and crc=0x%08X'",
",",
"self",
".",
"port",
",",
"self",
".",
"nbr_of_items",
",",
"self",
".",
"_crc",
")",
"cache_data",
"=",
"self",
".",
"_toc_cache",
".",
"fetch",
"(",
"self",
".",
"_crc",
")",
"if",
"(",
"cache_data",
")",
":",
"self",
".",
"toc",
".",
"toc",
"=",
"cache_data",
"logger",
".",
"info",
"(",
"'TOC for port [%s] found in cache'",
"%",
"self",
".",
"port",
")",
"self",
".",
"_toc_fetch_finished",
"(",
")",
"else",
":",
"self",
".",
"state",
"=",
"GET_TOC_ELEMENT",
"self",
".",
"requested_index",
"=",
"0",
"self",
".",
"_request_toc_element",
"(",
"self",
".",
"requested_index",
")",
"elif",
"(",
"self",
".",
"state",
"==",
"GET_TOC_ELEMENT",
")",
":",
"# Always add new element, but only request new if it's not the",
"# last one.",
"if",
"self",
".",
"_useV2",
":",
"ident",
"=",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"payload",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"else",
":",
"ident",
"=",
"payload",
"[",
"0",
"]",
"if",
"ident",
"!=",
"self",
".",
"requested_index",
":",
"return",
"if",
"self",
".",
"_useV2",
":",
"self",
".",
"toc",
".",
"add_element",
"(",
"self",
".",
"element_class",
"(",
"ident",
",",
"payload",
"[",
"2",
":",
"]",
")",
")",
"else",
":",
"self",
".",
"toc",
".",
"add_element",
"(",
"self",
".",
"element_class",
"(",
"ident",
",",
"payload",
"[",
"1",
":",
"]",
")",
")",
"logger",
".",
"debug",
"(",
"'Added element [%s]'",
",",
"ident",
")",
"if",
"(",
"self",
".",
"requested_index",
"<",
"(",
"self",
".",
"nbr_of_items",
"-",
"1",
")",
")",
":",
"logger",
".",
"debug",
"(",
"'[%d]: More variables, requesting index %d'",
",",
"self",
".",
"port",
",",
"self",
".",
"requested_index",
"+",
"1",
")",
"self",
".",
"requested_index",
"=",
"self",
".",
"requested_index",
"+",
"1",
"self",
".",
"_request_toc_element",
"(",
"self",
".",
"requested_index",
")",
"else",
":",
"# No more variables in TOC",
"self",
".",
"_toc_cache",
".",
"insert",
"(",
"self",
".",
"_crc",
",",
"self",
".",
"toc",
".",
"toc",
")",
"self",
".",
"_toc_fetch_finished",
"(",
")"
] | Handle a newly arrived packet | [
"Handle",
"a",
"newly",
"arrived",
"packet"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L155-L204 |
247,378 | bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher._request_toc_element | def _request_toc_element(self, index):
"""Request information about a specific item in the TOC"""
logger.debug('Requesting index %d on port %d', index, self.port)
pk = CRTPPacket()
if self._useV2:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff)
self.cf.send_packet(pk, expected_reply=(
CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff))
else:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ELEMENT, index)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_ELEMENT, index)) | python | def _request_toc_element(self, index):
logger.debug('Requesting index %d on port %d', index, self.port)
pk = CRTPPacket()
if self._useV2:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff)
self.cf.send_packet(pk, expected_reply=(
CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff))
else:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ELEMENT, index)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_ELEMENT, index)) | [
"def",
"_request_toc_element",
"(",
"self",
",",
"index",
")",
":",
"logger",
".",
"debug",
"(",
"'Requesting index %d on port %d'",
",",
"index",
",",
"self",
".",
"port",
")",
"pk",
"=",
"CRTPPacket",
"(",
")",
"if",
"self",
".",
"_useV2",
":",
"pk",
".",
"set_header",
"(",
"self",
".",
"port",
",",
"TOC_CHANNEL",
")",
"pk",
".",
"data",
"=",
"(",
"CMD_TOC_ITEM_V2",
",",
"index",
"&",
"0x0ff",
",",
"(",
"index",
">>",
"8",
")",
"&",
"0x0ff",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_TOC_ITEM_V2",
",",
"index",
"&",
"0x0ff",
",",
"(",
"index",
">>",
"8",
")",
"&",
"0x0ff",
")",
")",
"else",
":",
"pk",
".",
"set_header",
"(",
"self",
".",
"port",
",",
"TOC_CHANNEL",
")",
"pk",
".",
"data",
"=",
"(",
"CMD_TOC_ELEMENT",
",",
"index",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_TOC_ELEMENT",
",",
"index",
")",
")"
] | Request information about a specific item in the TOC | [
"Request",
"information",
"about",
"a",
"specific",
"item",
"in",
"the",
"TOC"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L206-L218 |
247,379 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._start_connection_setup | def _start_connection_setup(self):
"""Start the connection setup by refreshing the TOCs"""
logger.info('We are connected[%s], request connection setup',
self.link_uri)
self.platform.fetch_platform_informations(self._platform_info_fetched) | python | def _start_connection_setup(self):
logger.info('We are connected[%s], request connection setup',
self.link_uri)
self.platform.fetch_platform_informations(self._platform_info_fetched) | [
"def",
"_start_connection_setup",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'We are connected[%s], request connection setup'",
",",
"self",
".",
"link_uri",
")",
"self",
".",
"platform",
".",
"fetch_platform_informations",
"(",
"self",
".",
"_platform_info_fetched",
")"
] | Start the connection setup by refreshing the TOCs | [
"Start",
"the",
"connection",
"setup",
"by",
"refreshing",
"the",
"TOCs"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L156-L160 |
247,380 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._param_toc_updated_cb | def _param_toc_updated_cb(self):
"""Called when the param TOC has been fully updated"""
logger.info('Param TOC finished updating')
self.connected_ts = datetime.datetime.now()
self.connected.call(self.link_uri)
# Trigger the update for all the parameters
self.param.request_update_of_all_params() | python | def _param_toc_updated_cb(self):
logger.info('Param TOC finished updating')
self.connected_ts = datetime.datetime.now()
self.connected.call(self.link_uri)
# Trigger the update for all the parameters
self.param.request_update_of_all_params() | [
"def",
"_param_toc_updated_cb",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Param TOC finished updating'",
")",
"self",
".",
"connected_ts",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"connected",
".",
"call",
"(",
"self",
".",
"link_uri",
")",
"# Trigger the update for all the parameters",
"self",
".",
"param",
".",
"request_update_of_all_params",
"(",
")"
] | Called when the param TOC has been fully updated | [
"Called",
"when",
"the",
"param",
"TOC",
"has",
"been",
"fully",
"updated"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L165-L171 |
247,381 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._mems_updated_cb | def _mems_updated_cb(self):
"""Called when the memories have been identified"""
logger.info('Memories finished updating')
self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache) | python | def _mems_updated_cb(self):
logger.info('Memories finished updating')
self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache) | [
"def",
"_mems_updated_cb",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Memories finished updating'",
")",
"self",
".",
"param",
".",
"refresh_toc",
"(",
"self",
".",
"_param_toc_updated_cb",
",",
"self",
".",
"_toc_cache",
")"
] | Called when the memories have been identified | [
"Called",
"when",
"the",
"memories",
"have",
"been",
"identified"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L173-L176 |
247,382 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._link_error_cb | def _link_error_cb(self, errmsg):
"""Called from the link driver when there's an error"""
logger.warning('Got link error callback [%s] in state [%s]',
errmsg, self.state)
if (self.link is not None):
self.link.close()
self.link = None
if (self.state == State.INITIALIZED):
self.connection_failed.call(self.link_uri, errmsg)
if (self.state == State.CONNECTED or
self.state == State.SETUP_FINISHED):
self.disconnected.call(self.link_uri)
self.connection_lost.call(self.link_uri, errmsg)
self.state = State.DISCONNECTED | python | def _link_error_cb(self, errmsg):
logger.warning('Got link error callback [%s] in state [%s]',
errmsg, self.state)
if (self.link is not None):
self.link.close()
self.link = None
if (self.state == State.INITIALIZED):
self.connection_failed.call(self.link_uri, errmsg)
if (self.state == State.CONNECTED or
self.state == State.SETUP_FINISHED):
self.disconnected.call(self.link_uri)
self.connection_lost.call(self.link_uri, errmsg)
self.state = State.DISCONNECTED | [
"def",
"_link_error_cb",
"(",
"self",
",",
"errmsg",
")",
":",
"logger",
".",
"warning",
"(",
"'Got link error callback [%s] in state [%s]'",
",",
"errmsg",
",",
"self",
".",
"state",
")",
"if",
"(",
"self",
".",
"link",
"is",
"not",
"None",
")",
":",
"self",
".",
"link",
".",
"close",
"(",
")",
"self",
".",
"link",
"=",
"None",
"if",
"(",
"self",
".",
"state",
"==",
"State",
".",
"INITIALIZED",
")",
":",
"self",
".",
"connection_failed",
".",
"call",
"(",
"self",
".",
"link_uri",
",",
"errmsg",
")",
"if",
"(",
"self",
".",
"state",
"==",
"State",
".",
"CONNECTED",
"or",
"self",
".",
"state",
"==",
"State",
".",
"SETUP_FINISHED",
")",
":",
"self",
".",
"disconnected",
".",
"call",
"(",
"self",
".",
"link_uri",
")",
"self",
".",
"connection_lost",
".",
"call",
"(",
"self",
".",
"link_uri",
",",
"errmsg",
")",
"self",
".",
"state",
"=",
"State",
".",
"DISCONNECTED"
] | Called from the link driver when there's an error | [
"Called",
"from",
"the",
"link",
"driver",
"when",
"there",
"s",
"an",
"error"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L183-L196 |
247,383 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._check_for_initial_packet_cb | def _check_for_initial_packet_cb(self, data):
"""
Called when first packet arrives from Crazyflie.
This is used to determine if we are connected to something that is
answering.
"""
self.state = State.CONNECTED
self.link_established.call(self.link_uri)
self.packet_received.remove_callback(self._check_for_initial_packet_cb) | python | def _check_for_initial_packet_cb(self, data):
self.state = State.CONNECTED
self.link_established.call(self.link_uri)
self.packet_received.remove_callback(self._check_for_initial_packet_cb) | [
"def",
"_check_for_initial_packet_cb",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"state",
"=",
"State",
".",
"CONNECTED",
"self",
".",
"link_established",
".",
"call",
"(",
"self",
".",
"link_uri",
")",
"self",
".",
"packet_received",
".",
"remove_callback",
"(",
"self",
".",
"_check_for_initial_packet_cb",
")"
] | Called when first packet arrives from Crazyflie.
This is used to determine if we are connected to something that is
answering. | [
"Called",
"when",
"first",
"packet",
"arrives",
"from",
"Crazyflie",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L202-L211 |
247,384 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie.close_link | def close_link(self):
"""Close the communication link."""
logger.info('Closing link')
if (self.link is not None):
self.commander.send_setpoint(0, 0, 0, 0)
if (self.link is not None):
self.link.close()
self.link = None
self._answer_patterns = {}
self.disconnected.call(self.link_uri) | python | def close_link(self):
logger.info('Closing link')
if (self.link is not None):
self.commander.send_setpoint(0, 0, 0, 0)
if (self.link is not None):
self.link.close()
self.link = None
self._answer_patterns = {}
self.disconnected.call(self.link_uri) | [
"def",
"close_link",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Closing link'",
")",
"if",
"(",
"self",
".",
"link",
"is",
"not",
"None",
")",
":",
"self",
".",
"commander",
".",
"send_setpoint",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"if",
"(",
"self",
".",
"link",
"is",
"not",
"None",
")",
":",
"self",
".",
"link",
".",
"close",
"(",
")",
"self",
".",
"link",
"=",
"None",
"self",
".",
"_answer_patterns",
"=",
"{",
"}",
"self",
".",
"disconnected",
".",
"call",
"(",
"self",
".",
"link_uri",
")"
] | Close the communication link. | [
"Close",
"the",
"communication",
"link",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L251-L260 |
247,385 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._no_answer_do_retry | def _no_answer_do_retry(self, pk, pattern):
"""Resend packets that we have not gotten answers to"""
logger.info('Resending for pattern %s', pattern)
# Set the timer to None before trying to send again
self.send_packet(pk, expected_reply=pattern, resend=True) | python | def _no_answer_do_retry(self, pk, pattern):
logger.info('Resending for pattern %s', pattern)
# Set the timer to None before trying to send again
self.send_packet(pk, expected_reply=pattern, resend=True) | [
"def",
"_no_answer_do_retry",
"(",
"self",
",",
"pk",
",",
"pattern",
")",
":",
"logger",
".",
"info",
"(",
"'Resending for pattern %s'",
",",
"pattern",
")",
"# Set the timer to None before trying to send again",
"self",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"pattern",
",",
"resend",
"=",
"True",
")"
] | Resend packets that we have not gotten answers to | [
"Resend",
"packets",
"that",
"we",
"have",
"not",
"gotten",
"answers",
"to"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L275-L279 |
247,386 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._check_for_answers | def _check_for_answers(self, pk):
"""
Callback called for every packet received to check if we are
waiting for an answer on this port. If so, then cancel the retry
timer.
"""
longest_match = ()
if len(self._answer_patterns) > 0:
data = (pk.header,) + tuple(pk.data)
for p in list(self._answer_patterns.keys()):
logger.debug('Looking for pattern match on %s vs %s', p, data)
if len(p) <= len(data):
if p == data[0:len(p)]:
match = data[0:len(p)]
if len(match) >= len(longest_match):
logger.debug('Found new longest match %s', match)
longest_match = match
if len(longest_match) > 0:
self._answer_patterns[longest_match].cancel()
del self._answer_patterns[longest_match] | python | def _check_for_answers(self, pk):
longest_match = ()
if len(self._answer_patterns) > 0:
data = (pk.header,) + tuple(pk.data)
for p in list(self._answer_patterns.keys()):
logger.debug('Looking for pattern match on %s vs %s', p, data)
if len(p) <= len(data):
if p == data[0:len(p)]:
match = data[0:len(p)]
if len(match) >= len(longest_match):
logger.debug('Found new longest match %s', match)
longest_match = match
if len(longest_match) > 0:
self._answer_patterns[longest_match].cancel()
del self._answer_patterns[longest_match] | [
"def",
"_check_for_answers",
"(",
"self",
",",
"pk",
")",
":",
"longest_match",
"=",
"(",
")",
"if",
"len",
"(",
"self",
".",
"_answer_patterns",
")",
">",
"0",
":",
"data",
"=",
"(",
"pk",
".",
"header",
",",
")",
"+",
"tuple",
"(",
"pk",
".",
"data",
")",
"for",
"p",
"in",
"list",
"(",
"self",
".",
"_answer_patterns",
".",
"keys",
"(",
")",
")",
":",
"logger",
".",
"debug",
"(",
"'Looking for pattern match on %s vs %s'",
",",
"p",
",",
"data",
")",
"if",
"len",
"(",
"p",
")",
"<=",
"len",
"(",
"data",
")",
":",
"if",
"p",
"==",
"data",
"[",
"0",
":",
"len",
"(",
"p",
")",
"]",
":",
"match",
"=",
"data",
"[",
"0",
":",
"len",
"(",
"p",
")",
"]",
"if",
"len",
"(",
"match",
")",
">=",
"len",
"(",
"longest_match",
")",
":",
"logger",
".",
"debug",
"(",
"'Found new longest match %s'",
",",
"match",
")",
"longest_match",
"=",
"match",
"if",
"len",
"(",
"longest_match",
")",
">",
"0",
":",
"self",
".",
"_answer_patterns",
"[",
"longest_match",
"]",
".",
"cancel",
"(",
")",
"del",
"self",
".",
"_answer_patterns",
"[",
"longest_match",
"]"
] | Callback called for every packet received to check if we are
waiting for an answer on this port. If so, then cancel the retry
timer. | [
"Callback",
"called",
"for",
"every",
"packet",
"received",
"to",
"check",
"if",
"we",
"are",
"waiting",
"for",
"an",
"answer",
"on",
"this",
"port",
".",
"If",
"so",
"then",
"cancel",
"the",
"retry",
"timer",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L281-L300 |
247,387 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie.send_packet | def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2):
"""
Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false
"""
self._send_lock.acquire()
if self.link is not None:
if len(expected_reply) > 0 and not resend and \
self.link.needs_resending:
pattern = (pk.header,) + expected_reply
logger.debug(
'Sending packet and expecting the %s pattern back',
pattern)
new_timer = Timer(timeout,
lambda: self._no_answer_do_retry(pk,
pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
elif resend:
# Check if we have gotten an answer, if not try again
pattern = expected_reply
if pattern in self._answer_patterns:
logger.debug('We want to resend and the pattern is there')
if self._answer_patterns[pattern]:
new_timer = Timer(timeout,
lambda:
self._no_answer_do_retry(
pk, pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
else:
logger.debug('Resend requested, but no pattern found: %s',
self._answer_patterns)
self.link.send_packet(pk)
self.packet_sent.call(pk)
self._send_lock.release() | python | def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2):
self._send_lock.acquire()
if self.link is not None:
if len(expected_reply) > 0 and not resend and \
self.link.needs_resending:
pattern = (pk.header,) + expected_reply
logger.debug(
'Sending packet and expecting the %s pattern back',
pattern)
new_timer = Timer(timeout,
lambda: self._no_answer_do_retry(pk,
pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
elif resend:
# Check if we have gotten an answer, if not try again
pattern = expected_reply
if pattern in self._answer_patterns:
logger.debug('We want to resend and the pattern is there')
if self._answer_patterns[pattern]:
new_timer = Timer(timeout,
lambda:
self._no_answer_do_retry(
pk, pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
else:
logger.debug('Resend requested, but no pattern found: %s',
self._answer_patterns)
self.link.send_packet(pk)
self.packet_sent.call(pk)
self._send_lock.release() | [
"def",
"send_packet",
"(",
"self",
",",
"pk",
",",
"expected_reply",
"=",
"(",
")",
",",
"resend",
"=",
"False",
",",
"timeout",
"=",
"0.2",
")",
":",
"self",
".",
"_send_lock",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"link",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"expected_reply",
")",
">",
"0",
"and",
"not",
"resend",
"and",
"self",
".",
"link",
".",
"needs_resending",
":",
"pattern",
"=",
"(",
"pk",
".",
"header",
",",
")",
"+",
"expected_reply",
"logger",
".",
"debug",
"(",
"'Sending packet and expecting the %s pattern back'",
",",
"pattern",
")",
"new_timer",
"=",
"Timer",
"(",
"timeout",
",",
"lambda",
":",
"self",
".",
"_no_answer_do_retry",
"(",
"pk",
",",
"pattern",
")",
")",
"self",
".",
"_answer_patterns",
"[",
"pattern",
"]",
"=",
"new_timer",
"new_timer",
".",
"start",
"(",
")",
"elif",
"resend",
":",
"# Check if we have gotten an answer, if not try again",
"pattern",
"=",
"expected_reply",
"if",
"pattern",
"in",
"self",
".",
"_answer_patterns",
":",
"logger",
".",
"debug",
"(",
"'We want to resend and the pattern is there'",
")",
"if",
"self",
".",
"_answer_patterns",
"[",
"pattern",
"]",
":",
"new_timer",
"=",
"Timer",
"(",
"timeout",
",",
"lambda",
":",
"self",
".",
"_no_answer_do_retry",
"(",
"pk",
",",
"pattern",
")",
")",
"self",
".",
"_answer_patterns",
"[",
"pattern",
"]",
"=",
"new_timer",
"new_timer",
".",
"start",
"(",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Resend requested, but no pattern found: %s'",
",",
"self",
".",
"_answer_patterns",
")",
"self",
".",
"link",
".",
"send_packet",
"(",
"pk",
")",
"self",
".",
"packet_sent",
".",
"call",
"(",
"pk",
")",
"self",
".",
"_send_lock",
".",
"release",
"(",
")"
] | Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false | [
"Send",
"a",
"packet",
"through",
"the",
"link",
"interface",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L302-L341 |
247,388 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | _IncomingPacketHandler.add_port_callback | def add_port_callback(self, port, cb):
"""Add a callback for data that comes on a specific port"""
logger.debug('Adding callback on port [%d] to [%s]', port, cb)
self.add_header_callback(cb, port, 0, 0xff, 0x0) | python | def add_port_callback(self, port, cb):
logger.debug('Adding callback on port [%d] to [%s]', port, cb)
self.add_header_callback(cb, port, 0, 0xff, 0x0) | [
"def",
"add_port_callback",
"(",
"self",
",",
"port",
",",
"cb",
")",
":",
"logger",
".",
"debug",
"(",
"'Adding callback on port [%d] to [%s]'",
",",
"port",
",",
"cb",
")",
"self",
".",
"add_header_callback",
"(",
"cb",
",",
"port",
",",
"0",
",",
"0xff",
",",
"0x0",
")"
] | Add a callback for data that comes on a specific port | [
"Add",
"a",
"callback",
"for",
"data",
"that",
"comes",
"on",
"a",
"specific",
"port"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L356-L359 |
247,389 | bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | _IncomingPacketHandler.remove_port_callback | def remove_port_callback(self, port, cb):
"""Remove a callback for data that comes on a specific port"""
logger.debug('Removing callback on port [%d] to [%s]', port, cb)
for port_callback in self.cb:
if port_callback.port == port and port_callback.callback == cb:
self.cb.remove(port_callback) | python | def remove_port_callback(self, port, cb):
logger.debug('Removing callback on port [%d] to [%s]', port, cb)
for port_callback in self.cb:
if port_callback.port == port and port_callback.callback == cb:
self.cb.remove(port_callback) | [
"def",
"remove_port_callback",
"(",
"self",
",",
"port",
",",
"cb",
")",
":",
"logger",
".",
"debug",
"(",
"'Removing callback on port [%d] to [%s]'",
",",
"port",
",",
"cb",
")",
"for",
"port_callback",
"in",
"self",
".",
"cb",
":",
"if",
"port_callback",
".",
"port",
"==",
"port",
"and",
"port_callback",
".",
"callback",
"==",
"cb",
":",
"self",
".",
"cb",
".",
"remove",
"(",
"port_callback",
")"
] | Remove a callback for data that comes on a specific port | [
"Remove",
"a",
"callback",
"for",
"data",
"that",
"comes",
"on",
"a",
"specific",
"port"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L361-L366 |
247,390 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.add_variable | def add_variable(self, name, fetch_as=None):
"""Add a new variable to the configuration.
name - Complete name of the variable in the form group.name
fetch_as - String representation of the type the variable should be
fetched as (i.e uint8_t, float, FP16, etc)
If no fetch_as type is supplied, then the stored as type will be used
(i.e the type of the fetched variable is the same as it's stored in the
Crazyflie)."""
if fetch_as:
self.variables.append(LogVariable(name, fetch_as))
else:
# We cannot determine the default type until we have connected. So
# save the name and we will add these once we are connected.
self.default_fetch_as.append(name) | python | def add_variable(self, name, fetch_as=None):
if fetch_as:
self.variables.append(LogVariable(name, fetch_as))
else:
# We cannot determine the default type until we have connected. So
# save the name and we will add these once we are connected.
self.default_fetch_as.append(name) | [
"def",
"add_variable",
"(",
"self",
",",
"name",
",",
"fetch_as",
"=",
"None",
")",
":",
"if",
"fetch_as",
":",
"self",
".",
"variables",
".",
"append",
"(",
"LogVariable",
"(",
"name",
",",
"fetch_as",
")",
")",
"else",
":",
"# We cannot determine the default type until we have connected. So",
"# save the name and we will add these once we are connected.",
"self",
".",
"default_fetch_as",
".",
"append",
"(",
"name",
")"
] | Add a new variable to the configuration.
name - Complete name of the variable in the form group.name
fetch_as - String representation of the type the variable should be
fetched as (i.e uint8_t, float, FP16, etc)
If no fetch_as type is supplied, then the stored as type will be used
(i.e the type of the fetched variable is the same as it's stored in the
Crazyflie). | [
"Add",
"a",
"new",
"variable",
"to",
"the",
"configuration",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L171-L186 |
247,391 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.add_memory | def add_memory(self, name, fetch_as, stored_as, address):
"""Add a raw memory position to log.
name - Arbitrary name of the variable
fetch_as - String representation of the type of the data the memory
should be fetch as (i.e uint8_t, float, FP16)
stored_as - String representation of the type the data is stored as
in the Crazyflie
address - The address of the data
"""
self.variables.append(LogVariable(name, fetch_as, LogVariable.MEM_TYPE,
stored_as, address)) | python | def add_memory(self, name, fetch_as, stored_as, address):
self.variables.append(LogVariable(name, fetch_as, LogVariable.MEM_TYPE,
stored_as, address)) | [
"def",
"add_memory",
"(",
"self",
",",
"name",
",",
"fetch_as",
",",
"stored_as",
",",
"address",
")",
":",
"self",
".",
"variables",
".",
"append",
"(",
"LogVariable",
"(",
"name",
",",
"fetch_as",
",",
"LogVariable",
".",
"MEM_TYPE",
",",
"stored_as",
",",
"address",
")",
")"
] | Add a raw memory position to log.
name - Arbitrary name of the variable
fetch_as - String representation of the type of the data the memory
should be fetch as (i.e uint8_t, float, FP16)
stored_as - String representation of the type the data is stored as
in the Crazyflie
address - The address of the data | [
"Add",
"a",
"raw",
"memory",
"position",
"to",
"log",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L188-L199 |
247,392 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.create | def create(self):
"""Save the log configuration in the Crazyflie"""
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
if self.useV2:
pk.data = (CMD_CREATE_BLOCK_V2, self.id)
else:
pk.data = (CMD_CREATE_BLOCK, self.id)
for var in self.variables:
if (var.is_toc_variable() is False): # Memory location
logger.debug('Logging to raw memory %d, 0x%04X',
var.get_storage_and_fetch_byte(), var.address)
pk.data.append(struct.pack('<B',
var.get_storage_and_fetch_byte()))
pk.data.append(struct.pack('<I', var.address))
else: # Item in TOC
logger.debug('Adding %s with id=%d and type=0x%02X',
var.name,
self.cf.log.toc.get_element_id(
var.name), var.get_storage_and_fetch_byte())
pk.data.append(var.get_storage_and_fetch_byte())
if self.useV2:
ident = self.cf.log.toc.get_element_id(var.name)
pk.data.append(ident & 0x0ff)
pk.data.append((ident >> 8) & 0x0ff)
else:
pk.data.append(self.cf.log.toc.get_element_id(var.name))
logger.debug('Adding log block id {}'.format(self.id))
if self.useV2:
self.cf.send_packet(pk, expected_reply=(
CMD_CREATE_BLOCK_V2, self.id))
else:
self.cf.send_packet(pk, expected_reply=(CMD_CREATE_BLOCK, self.id)) | python | def create(self):
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
if self.useV2:
pk.data = (CMD_CREATE_BLOCK_V2, self.id)
else:
pk.data = (CMD_CREATE_BLOCK, self.id)
for var in self.variables:
if (var.is_toc_variable() is False): # Memory location
logger.debug('Logging to raw memory %d, 0x%04X',
var.get_storage_and_fetch_byte(), var.address)
pk.data.append(struct.pack('<B',
var.get_storage_and_fetch_byte()))
pk.data.append(struct.pack('<I', var.address))
else: # Item in TOC
logger.debug('Adding %s with id=%d and type=0x%02X',
var.name,
self.cf.log.toc.get_element_id(
var.name), var.get_storage_and_fetch_byte())
pk.data.append(var.get_storage_and_fetch_byte())
if self.useV2:
ident = self.cf.log.toc.get_element_id(var.name)
pk.data.append(ident & 0x0ff)
pk.data.append((ident >> 8) & 0x0ff)
else:
pk.data.append(self.cf.log.toc.get_element_id(var.name))
logger.debug('Adding log block id {}'.format(self.id))
if self.useV2:
self.cf.send_packet(pk, expected_reply=(
CMD_CREATE_BLOCK_V2, self.id))
else:
self.cf.send_packet(pk, expected_reply=(CMD_CREATE_BLOCK, self.id)) | [
"def",
"create",
"(",
"self",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"5",
",",
"CHAN_SETTINGS",
")",
"if",
"self",
".",
"useV2",
":",
"pk",
".",
"data",
"=",
"(",
"CMD_CREATE_BLOCK_V2",
",",
"self",
".",
"id",
")",
"else",
":",
"pk",
".",
"data",
"=",
"(",
"CMD_CREATE_BLOCK",
",",
"self",
".",
"id",
")",
"for",
"var",
"in",
"self",
".",
"variables",
":",
"if",
"(",
"var",
".",
"is_toc_variable",
"(",
")",
"is",
"False",
")",
":",
"# Memory location",
"logger",
".",
"debug",
"(",
"'Logging to raw memory %d, 0x%04X'",
",",
"var",
".",
"get_storage_and_fetch_byte",
"(",
")",
",",
"var",
".",
"address",
")",
"pk",
".",
"data",
".",
"append",
"(",
"struct",
".",
"pack",
"(",
"'<B'",
",",
"var",
".",
"get_storage_and_fetch_byte",
"(",
")",
")",
")",
"pk",
".",
"data",
".",
"append",
"(",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"var",
".",
"address",
")",
")",
"else",
":",
"# Item in TOC",
"logger",
".",
"debug",
"(",
"'Adding %s with id=%d and type=0x%02X'",
",",
"var",
".",
"name",
",",
"self",
".",
"cf",
".",
"log",
".",
"toc",
".",
"get_element_id",
"(",
"var",
".",
"name",
")",
",",
"var",
".",
"get_storage_and_fetch_byte",
"(",
")",
")",
"pk",
".",
"data",
".",
"append",
"(",
"var",
".",
"get_storage_and_fetch_byte",
"(",
")",
")",
"if",
"self",
".",
"useV2",
":",
"ident",
"=",
"self",
".",
"cf",
".",
"log",
".",
"toc",
".",
"get_element_id",
"(",
"var",
".",
"name",
")",
"pk",
".",
"data",
".",
"append",
"(",
"ident",
"&",
"0x0ff",
")",
"pk",
".",
"data",
".",
"append",
"(",
"(",
"ident",
">>",
"8",
")",
"&",
"0x0ff",
")",
"else",
":",
"pk",
".",
"data",
".",
"append",
"(",
"self",
".",
"cf",
".",
"log",
".",
"toc",
".",
"get_element_id",
"(",
"var",
".",
"name",
")",
")",
"logger",
".",
"debug",
"(",
"'Adding log block id {}'",
".",
"format",
"(",
"self",
".",
"id",
")",
")",
"if",
"self",
".",
"useV2",
":",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_CREATE_BLOCK_V2",
",",
"self",
".",
"id",
")",
")",
"else",
":",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_CREATE_BLOCK",
",",
"self",
".",
"id",
")",
")"
] | Save the log configuration in the Crazyflie | [
"Save",
"the",
"log",
"configuration",
"in",
"the",
"Crazyflie"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L220-L252 |
247,393 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.start | def start(self):
"""Start the logging for this entry"""
if (self.cf.link is not None):
if (self._added is False):
self.create()
logger.debug('First time block is started, add block')
else:
logger.debug('Block already registered, starting logging'
' for id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_START_LOGGING, self.id, self.period)
self.cf.send_packet(pk, expected_reply=(
CMD_START_LOGGING, self.id)) | python | def start(self):
if (self.cf.link is not None):
if (self._added is False):
self.create()
logger.debug('First time block is started, add block')
else:
logger.debug('Block already registered, starting logging'
' for id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_START_LOGGING, self.id, self.period)
self.cf.send_packet(pk, expected_reply=(
CMD_START_LOGGING, self.id)) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"cf",
".",
"link",
"is",
"not",
"None",
")",
":",
"if",
"(",
"self",
".",
"_added",
"is",
"False",
")",
":",
"self",
".",
"create",
"(",
")",
"logger",
".",
"debug",
"(",
"'First time block is started, add block'",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Block already registered, starting logging'",
"' for id=%d'",
",",
"self",
".",
"id",
")",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"5",
",",
"CHAN_SETTINGS",
")",
"pk",
".",
"data",
"=",
"(",
"CMD_START_LOGGING",
",",
"self",
".",
"id",
",",
"self",
".",
"period",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_START_LOGGING",
",",
"self",
".",
"id",
")",
")"
] | Start the logging for this entry | [
"Start",
"the",
"logging",
"for",
"this",
"entry"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L254-L267 |
247,394 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.stop | def stop(self):
"""Stop the logging for this entry"""
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Stopping block, but no block registered')
else:
logger.debug('Sending stop logging for block id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_STOP_LOGGING, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_STOP_LOGGING, self.id)) | python | def stop(self):
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Stopping block, but no block registered')
else:
logger.debug('Sending stop logging for block id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_STOP_LOGGING, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_STOP_LOGGING, self.id)) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"cf",
".",
"link",
"is",
"not",
"None",
")",
":",
"if",
"(",
"self",
".",
"id",
"is",
"None",
")",
":",
"logger",
".",
"warning",
"(",
"'Stopping block, but no block registered'",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Sending stop logging for block id=%d'",
",",
"self",
".",
"id",
")",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"5",
",",
"CHAN_SETTINGS",
")",
"pk",
".",
"data",
"=",
"(",
"CMD_STOP_LOGGING",
",",
"self",
".",
"id",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_STOP_LOGGING",
",",
"self",
".",
"id",
")",
")"
] | Stop the logging for this entry | [
"Stop",
"the",
"logging",
"for",
"this",
"entry"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L269-L280 |
247,395 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.delete | def delete(self):
"""Delete this entry in the Crazyflie"""
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Delete block, but no block registered')
else:
logger.debug('LogEntry: Sending delete logging for block id=%d'
% self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_DELETE_BLOCK, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_DELETE_BLOCK, self.id)) | python | def delete(self):
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Delete block, but no block registered')
else:
logger.debug('LogEntry: Sending delete logging for block id=%d'
% self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_DELETE_BLOCK, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_DELETE_BLOCK, self.id)) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"cf",
".",
"link",
"is",
"not",
"None",
")",
":",
"if",
"(",
"self",
".",
"id",
"is",
"None",
")",
":",
"logger",
".",
"warning",
"(",
"'Delete block, but no block registered'",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'LogEntry: Sending delete logging for block id=%d'",
"%",
"self",
".",
"id",
")",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"5",
",",
"CHAN_SETTINGS",
")",
"pk",
".",
"data",
"=",
"(",
"CMD_DELETE_BLOCK",
",",
"self",
".",
"id",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_DELETE_BLOCK",
",",
"self",
".",
"id",
")",
")"
] | Delete this entry in the Crazyflie | [
"Delete",
"this",
"entry",
"in",
"the",
"Crazyflie"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L282-L294 |
247,396 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.unpack_log_data | def unpack_log_data(self, log_data, timestamp):
"""Unpack received logging data so it represent real values according
to the configuration in the entry"""
ret_data = {}
data_index = 0
for var in self.variables:
size = LogTocElement.get_size_from_id(var.fetch_as)
name = var.name
unpackstring = LogTocElement.get_unpack_string_from_id(
var.fetch_as)
value = struct.unpack(
unpackstring, log_data[data_index:data_index + size])[0]
data_index += size
ret_data[name] = value
self.data_received_cb.call(timestamp, ret_data, self) | python | def unpack_log_data(self, log_data, timestamp):
ret_data = {}
data_index = 0
for var in self.variables:
size = LogTocElement.get_size_from_id(var.fetch_as)
name = var.name
unpackstring = LogTocElement.get_unpack_string_from_id(
var.fetch_as)
value = struct.unpack(
unpackstring, log_data[data_index:data_index + size])[0]
data_index += size
ret_data[name] = value
self.data_received_cb.call(timestamp, ret_data, self) | [
"def",
"unpack_log_data",
"(",
"self",
",",
"log_data",
",",
"timestamp",
")",
":",
"ret_data",
"=",
"{",
"}",
"data_index",
"=",
"0",
"for",
"var",
"in",
"self",
".",
"variables",
":",
"size",
"=",
"LogTocElement",
".",
"get_size_from_id",
"(",
"var",
".",
"fetch_as",
")",
"name",
"=",
"var",
".",
"name",
"unpackstring",
"=",
"LogTocElement",
".",
"get_unpack_string_from_id",
"(",
"var",
".",
"fetch_as",
")",
"value",
"=",
"struct",
".",
"unpack",
"(",
"unpackstring",
",",
"log_data",
"[",
"data_index",
":",
"data_index",
"+",
"size",
"]",
")",
"[",
"0",
"]",
"data_index",
"+=",
"size",
"ret_data",
"[",
"name",
"]",
"=",
"value",
"self",
".",
"data_received_cb",
".",
"call",
"(",
"timestamp",
",",
"ret_data",
",",
"self",
")"
] | Unpack received logging data so it represent real values according
to the configuration in the entry | [
"Unpack",
"received",
"logging",
"data",
"so",
"it",
"represent",
"real",
"values",
"according",
"to",
"the",
"configuration",
"in",
"the",
"entry"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L296-L310 |
247,397 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogTocElement.get_id_from_cstring | def get_id_from_cstring(name):
"""Return variable type id given the C-storage name"""
for key in list(LogTocElement.types.keys()):
if (LogTocElement.types[key][0] == name):
return key
raise KeyError('Type [%s] not found in LogTocElement.types!' % name) | python | def get_id_from_cstring(name):
for key in list(LogTocElement.types.keys()):
if (LogTocElement.types[key][0] == name):
return key
raise KeyError('Type [%s] not found in LogTocElement.types!' % name) | [
"def",
"get_id_from_cstring",
"(",
"name",
")",
":",
"for",
"key",
"in",
"list",
"(",
"LogTocElement",
".",
"types",
".",
"keys",
"(",
")",
")",
":",
"if",
"(",
"LogTocElement",
".",
"types",
"[",
"key",
"]",
"[",
"0",
"]",
"==",
"name",
")",
":",
"return",
"key",
"raise",
"KeyError",
"(",
"'Type [%s] not found in LogTocElement.types!'",
"%",
"name",
")"
] | Return variable type id given the C-storage name | [
"Return",
"variable",
"type",
"id",
"given",
"the",
"C",
"-",
"storage",
"name"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L325-L330 |
247,398 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | Log.add_config | def add_config(self, logconf):
"""Add a log configuration to the logging framework.
When doing this the contents of the log configuration will be validated
and listeners for new log configurations will be notified. When
validating the configuration the variables are checked against the TOC
to see that they actually exist. If they don't then the configuration
cannot be used. Since a valid TOC is required, a Crazyflie has to be
connected when calling this method, otherwise it will fail."""
if not self.cf.link:
logger.error('Cannot add configs without being connected to a '
'Crazyflie!')
return
# If the log configuration contains variables that we added without
# type (i.e we want the stored as type for fetching as well) then
# resolve this now and add them to the block again.
for name in logconf.default_fetch_as:
var = self.toc.get_element_by_complete_name(name)
if not var:
logger.warning(
'%s not in TOC, this block cannot be used!', name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(name))
# Now that we know what type this variable has, add it to the log
# config again with the correct type
logconf.add_variable(name, var.ctype)
# Now check that all the added variables are in the TOC and that
# the total size constraint of a data packet with logging data is
# not
size = 0
for var in logconf.variables:
size += LogTocElement.get_size_from_id(var.fetch_as)
# Check that we are able to find the variable in the TOC so
# we can return error already now and not when the config is sent
if var.is_toc_variable():
if (self.toc.get_element_by_complete_name(var.name) is None):
logger.warning(
'Log: %s not in TOC, this block cannot be used!',
var.name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(var.name))
if (size <= MAX_LOG_DATA_PACKET_SIZE and
(logconf.period > 0 and logconf.period < 0xFF)):
logconf.valid = True
logconf.cf = self.cf
logconf.id = self._config_id_counter
logconf.useV2 = self._useV2
self._config_id_counter = (self._config_id_counter + 1) % 255
self.log_blocks.append(logconf)
self.block_added_cb.call(logconf)
else:
logconf.valid = False
raise AttributeError(
'The log configuration is too large or has an invalid '
'parameter') | python | def add_config(self, logconf):
if not self.cf.link:
logger.error('Cannot add configs without being connected to a '
'Crazyflie!')
return
# If the log configuration contains variables that we added without
# type (i.e we want the stored as type for fetching as well) then
# resolve this now and add them to the block again.
for name in logconf.default_fetch_as:
var = self.toc.get_element_by_complete_name(name)
if not var:
logger.warning(
'%s not in TOC, this block cannot be used!', name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(name))
# Now that we know what type this variable has, add it to the log
# config again with the correct type
logconf.add_variable(name, var.ctype)
# Now check that all the added variables are in the TOC and that
# the total size constraint of a data packet with logging data is
# not
size = 0
for var in logconf.variables:
size += LogTocElement.get_size_from_id(var.fetch_as)
# Check that we are able to find the variable in the TOC so
# we can return error already now and not when the config is sent
if var.is_toc_variable():
if (self.toc.get_element_by_complete_name(var.name) is None):
logger.warning(
'Log: %s not in TOC, this block cannot be used!',
var.name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(var.name))
if (size <= MAX_LOG_DATA_PACKET_SIZE and
(logconf.period > 0 and logconf.period < 0xFF)):
logconf.valid = True
logconf.cf = self.cf
logconf.id = self._config_id_counter
logconf.useV2 = self._useV2
self._config_id_counter = (self._config_id_counter + 1) % 255
self.log_blocks.append(logconf)
self.block_added_cb.call(logconf)
else:
logconf.valid = False
raise AttributeError(
'The log configuration is too large or has an invalid '
'parameter') | [
"def",
"add_config",
"(",
"self",
",",
"logconf",
")",
":",
"if",
"not",
"self",
".",
"cf",
".",
"link",
":",
"logger",
".",
"error",
"(",
"'Cannot add configs without being connected to a '",
"'Crazyflie!'",
")",
"return",
"# If the log configuration contains variables that we added without",
"# type (i.e we want the stored as type for fetching as well) then",
"# resolve this now and add them to the block again.",
"for",
"name",
"in",
"logconf",
".",
"default_fetch_as",
":",
"var",
"=",
"self",
".",
"toc",
".",
"get_element_by_complete_name",
"(",
"name",
")",
"if",
"not",
"var",
":",
"logger",
".",
"warning",
"(",
"'%s not in TOC, this block cannot be used!'",
",",
"name",
")",
"logconf",
".",
"valid",
"=",
"False",
"raise",
"KeyError",
"(",
"'Variable {} not in TOC'",
".",
"format",
"(",
"name",
")",
")",
"# Now that we know what type this variable has, add it to the log",
"# config again with the correct type",
"logconf",
".",
"add_variable",
"(",
"name",
",",
"var",
".",
"ctype",
")",
"# Now check that all the added variables are in the TOC and that",
"# the total size constraint of a data packet with logging data is",
"# not",
"size",
"=",
"0",
"for",
"var",
"in",
"logconf",
".",
"variables",
":",
"size",
"+=",
"LogTocElement",
".",
"get_size_from_id",
"(",
"var",
".",
"fetch_as",
")",
"# Check that we are able to find the variable in the TOC so",
"# we can return error already now and not when the config is sent",
"if",
"var",
".",
"is_toc_variable",
"(",
")",
":",
"if",
"(",
"self",
".",
"toc",
".",
"get_element_by_complete_name",
"(",
"var",
".",
"name",
")",
"is",
"None",
")",
":",
"logger",
".",
"warning",
"(",
"'Log: %s not in TOC, this block cannot be used!'",
",",
"var",
".",
"name",
")",
"logconf",
".",
"valid",
"=",
"False",
"raise",
"KeyError",
"(",
"'Variable {} not in TOC'",
".",
"format",
"(",
"var",
".",
"name",
")",
")",
"if",
"(",
"size",
"<=",
"MAX_LOG_DATA_PACKET_SIZE",
"and",
"(",
"logconf",
".",
"period",
">",
"0",
"and",
"logconf",
".",
"period",
"<",
"0xFF",
")",
")",
":",
"logconf",
".",
"valid",
"=",
"True",
"logconf",
".",
"cf",
"=",
"self",
".",
"cf",
"logconf",
".",
"id",
"=",
"self",
".",
"_config_id_counter",
"logconf",
".",
"useV2",
"=",
"self",
".",
"_useV2",
"self",
".",
"_config_id_counter",
"=",
"(",
"self",
".",
"_config_id_counter",
"+",
"1",
")",
"%",
"255",
"self",
".",
"log_blocks",
".",
"append",
"(",
"logconf",
")",
"self",
".",
"block_added_cb",
".",
"call",
"(",
"logconf",
")",
"else",
":",
"logconf",
".",
"valid",
"=",
"False",
"raise",
"AttributeError",
"(",
"'The log configuration is too large or has an invalid '",
"'parameter'",
")"
] | Add a log configuration to the logging framework.
When doing this the contents of the log configuration will be validated
and listeners for new log configurations will be notified. When
validating the configuration the variables are checked against the TOC
to see that they actually exist. If they don't then the configuration
cannot be used. Since a valid TOC is required, a Crazyflie has to be
connected when calling this method, otherwise it will fail. | [
"Add",
"a",
"log",
"configuration",
"to",
"the",
"logging",
"framework",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L410-L468 |
247,399 | bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | Log.refresh_toc | def refresh_toc(self, refresh_done_callback, toc_cache):
"""Start refreshing the table of loggale variables"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
self._toc_cache = toc_cache
self._refresh_callback = refresh_done_callback
self.toc = None
pk = CRTPPacket()
pk.set_header(CRTPPort.LOGGING, CHAN_SETTINGS)
pk.data = (CMD_RESET_LOGGING,)
self.cf.send_packet(pk, expected_reply=(CMD_RESET_LOGGING,)) | python | def refresh_toc(self, refresh_done_callback, toc_cache):
self._useV2 = self.cf.platform.get_protocol_version() >= 4
self._toc_cache = toc_cache
self._refresh_callback = refresh_done_callback
self.toc = None
pk = CRTPPacket()
pk.set_header(CRTPPort.LOGGING, CHAN_SETTINGS)
pk.data = (CMD_RESET_LOGGING,)
self.cf.send_packet(pk, expected_reply=(CMD_RESET_LOGGING,)) | [
"def",
"refresh_toc",
"(",
"self",
",",
"refresh_done_callback",
",",
"toc_cache",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"self",
".",
"_toc_cache",
"=",
"toc_cache",
"self",
".",
"_refresh_callback",
"=",
"refresh_done_callback",
"self",
".",
"toc",
"=",
"None",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"CRTPPort",
".",
"LOGGING",
",",
"CHAN_SETTINGS",
")",
"pk",
".",
"data",
"=",
"(",
"CMD_RESET_LOGGING",
",",
")",
"self",
".",
"cf",
".",
"send_packet",
"(",
"pk",
",",
"expected_reply",
"=",
"(",
"CMD_RESET_LOGGING",
",",
")",
")"
] | Start refreshing the table of loggale variables | [
"Start",
"refreshing",
"the",
"table",
"of",
"loggale",
"variables"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L470-L482 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.