INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Choose a random element from a non-empty sequence. Use this instead of random.choice, with random.random(), for reproducibility
def _choice(rand_gen: Callable[[], float], sequence: Sequence[T]) -> T: """Choose a random element from a non-empty sequence. Use this instead of random.choice, with random.random(), for reproducibility """ return sequence[int(rand_gen() * len(sequence))]
Each layer index corresponds to a shift/transpose of this CZ pattern: ●───● ● ● ●───● ● ● . . . ● ● ●───● ● ● ●───● . . . ●───● ● ● ●───● ● ● . . . ● ● ●───● ● ● ●───● . . . ●───● ● ● ●───● ● ● . . . ● ● ●───● ...
def _make_cz_layer(qubits: Iterable[devices.GridQubit], layer_index: int ) -> Iterable[ops.Operation]: """ Each layer index corresponds to a shift/transpose of this CZ pattern: ●───● ● ● ●───● ● ● . . . ● ● ●───● ● ● ●───● . . . ●───● ● ● ●...
Determines the effect of an operation on the given qubits. If the operation is a 1-qubit operation on one of the given qubits, or a 2-qubit operation on both of the given qubits, and also the operation has a known matrix, then a matrix is returned. Otherwise None is returned. A...
def _op_to_matrix(self, op: Optional[ops.Operation], qubits: Tuple[ops.Qid, ...] ) -> Optional[np.ndarray]: """Determines the effect of an operation on the given qubits. If the operation is a 1-qubit operation on one of the given qubits,...
Accumulates operations affecting the given pair of qubits. The scan terminates when it hits the end of the circuit, finds an operation without a known matrix, or finds an operation that interacts the given qubits with other qubits. Args: circuit: The circuit to scan for ope...
def _scan_two_qubit_ops_into_matrix( self, circuit: circuits.Circuit, index: Optional[int], qubits: Tuple[ops.Qid, ...] ) -> Tuple[List[ops.Operation], List[int], np.ndarray]: """Accumulates operations affecting the given pair of qubits. The scan term...
Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i)).
def _flip_kron_order(mat4x4: np.ndarray) -> np.ndarray: """Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i)).""" result = np.array([[0] * 4] * 4, dtype=np.complex128) order = [0, 2, 1, 3] for i in range(4): for j in range(4): result[order[i], ord...
Returns a Controlled version of the given value, if defined. Controllees define how to be controlled by defining a method controlled_by(self, control_qubits). Note that the method may return NotImplemented to indicate a particular controlling can't be done. Args: controllee: The gate, operatio...
def control(controllee: Union['cirq.Gate', op_tree.OP_TREE], control_qubits: Sequence['cirq.Qid'] = None, default: Any = RaiseTypeErrorIfNotProvided) -> Any: """Returns a Controlled version of the given value, if defined. Controllees define how to be controlled by defining a method ...
Returns the inverse `val**-1` of the given value, if defined. An object can define an inverse by defining a __pow__(self, exponent) method that returns something besides NotImplemented when given the exponent -1. The inverse of iterables is by default defined to be the iterable's items, each inverted, ...
def inverse(val: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any: """Returns the inverse `val**-1` of the given value, if defined. An object can define an inverse by defining a __pow__(self, exponent) method that returns something besides NotImplemented when given the exponent -1. The inverse o...
Decomposes a two-qubit operation into MS/single-qubit rotation gates. Args: q0: The first qubit being operated on. q1: The other qubit being operated on. mat: Defines the operation to apply to the pair of qubits. tolerance: A limit on the amount of error introduced by the ...
def two_qubit_matrix_to_ion_operations(q0: ops.Qid, q1: ops.Qid, mat: np.ndarray, atol: float = 1e-8 ) -> List[ops.Operation]: """Decomposes a two-qubit operati...
Yields an XX interaction framed by the given operation.
def _parity_interaction(q0: ops.Qid, q1: ops.Qid, rads: float, atol: float, gate: Optional[ops.Gate] = None): """Yields an XX interaction framed by the given operation.""" if abs(rads) < atol: return if...
Yields non-local operation of KAK decomposition.
def _non_local_part(q0: ops.Qid, q1: ops.Qid, interaction_coefficients: Tuple[float, float, float], atol: float = 1e-8): """Yields non-local operation of KAK decomposition.""" x, y, z = interaction_coefficients return [ _parity_interactio...
Attempt to resolve a Symbol or name or float to its assigned value. If unable to resolve a sympy.Symbol, returns it unchanged. If unable to resolve a name, returns a sympy.Symbol with that name. Args: value: The sympy.Symbol or name or float to try to resolve into just ...
def value_of( self, value: Union[sympy.Basic, float, str] ) -> Union[sympy.Basic, float]: """Attempt to resolve a Symbol or name or float to its assigned value. If unable to resolve a sympy.Symbol, returns it unchanged. If unable to resolve a name, returns a sympy.Sy...
Implements __eq__/__ne__/__hash__ via a _value_equality_values_ method. _value_equality_values_ is a method that the decorated class must implement. _value_equality_approximate_values_ is a method that the decorated class might implement if special support for approximate equality is required. This is...
def value_equality(cls: type = None, *, unhashable: bool = False, distinct_child_types: bool = False, manual_cls: bool = False, approximate: bool = False ) -> Union[Callable[[type], type], type]: """Impl...
Extracts a set of 'interesting' lines out of a GNU unified diff format. Format: gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html @@ from-line-numbers to-line-numbers @@ line-from-either-file ... @@ start,count start,count @@ line-from-either-file ...
def diff_to_new_interesting_lines(unified_diff_lines: List[str] ) -> Dict[int, str]: """ Extracts a set of 'interesting' lines out of a GNU unified diff format. Format: gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html @@ from-line-numbers to-l...
Uses git diff and the annotation files created by `pytest --cov-report annotate` to find touched but uncovered lines in the given file. Args: abs_path: The path of a file to look for uncovered lines in. base_commit: Old state to diff against. actual_commit: Current state. Use None t...
def get_incremental_uncovered_lines(abs_path: str, base_commit: str, actual_commit: Optional[str] ) -> List[Tuple[int, str, str]]: """ Uses git diff and the annotation files created by `pytest --cov-r...
Args: content: A line with indentation and tail comments/space removed. Returns: Whether the line could be included in the coverage report.
def line_content_counts_as_uncovered_manual(content: str) -> bool: """ Args: content: A line with indentation and tail comments/space removed. Returns: Whether the line could be included in the coverage report. """ # Omit empty lines. if not content: return False # ...
Args: line: The line of code (including coverage annotation). is_from_cover_annotation_file: Whether this line has been annotated. Returns: Does the line count as uncovered?
def line_counts_as_uncovered(line: str, is_from_cover_annotation_file: bool) -> bool: """ Args: line: The line of code (including coverage annotation). is_from_cover_annotation_file: Whether this line has been annotated. Returns: Does the line count as un...
Determines if a file should be included in incremental coverage analysis. Args: rel_path: The repo-relative file path being considered. Returns: Whether to include the file.
def is_applicable_python_file(rel_path: str) -> bool: """ Determines if a file should be included in incremental coverage analysis. Args: rel_path: The repo-relative file path being considered. Returns: Whether to include the file. """ return (rel_path.endswith('.py') and ...
Finds a value that is nearly an integer multiple of multiple periods. The returned value should be the smallest non-negative number with this property. If `approx_denom` is too small the computation can fail to satisfy the `reject_atol` criteria and return `None`. This is actually desirable behavior, s...
def _approximate_common_period(periods: List[float], approx_denom: int = 60, reject_atol: float = 1e-8) -> Optional[float]: """Finds a value that is nearly an integer multiple of multiple periods. The returned value should be the smallest non-negati...
Finds the least common integer multiple of some fractions. The solution is the smallest positive integer c such that there exists integers n_k satisfying p_k * n_k = c for all k.
def _common_rational_period(rational_periods: List[fractions.Fraction] ) -> fractions.Fraction: """Finds the least common integer multiple of some fractions. The solution is the smallest positive integer c such that there exists integers n_k satisfying p_k * n_k = c for all k. ...
Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self.
def fit(self, X): """Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self. """ X = column_or_1d(X, warn=True) _check_numpy_unicode_bug(X...
Fit label encoder and return encoded labels Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples]
def fit_transform(self, X, y=None, **fit_params): """Fit label encoder and return encoded labels Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] """ y = colu...
Transform labels to normalized encoding. Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples]
def transform(self, y): """Transform labels to normalized encoding. Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] """ check_is_fitted(self, 'classes_') ...
Transform labels back to original encoding. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- y : numpy array of shape [n_samples]
def inverse_transform(self, y): """Transform labels back to original encoding. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- y : numpy array of shape [n_samples] """ check_is_fitted(self, 'c...
Transform features per specified math function. :param y: :return:
def transform(self, y): """ Transform features per specified math function. :param y: :return: """ if self.transform_type == 'log': return np.log(y) elif self.transform_type == 'exp': return np.exp(y) elif self.transform_type == 'sq...
Fit Unary Math Operator :param y: :return:
def fit(self, X, y=None, **fit_params): """ Fit Unary Math Operator :param y: :return: """ if self.transform_type not in self.valid_transforms: warnings.warn("Invalid transform type.", stacklevel=2) return self
Transform features per specified math function. :param y: :return:
def transform(self, y): """ Transform features per specified math function. :param y: :return: """ if isinstance(y, pd.DataFrame): x = y.ix[:,0] y = y.ix[:,1] else: x = y[:,0] y = y[:,1] if self.transform_typ...
:type feature_names: list :type tree: sklearn.tree.tree.BaseDecisionTree :param tree: sklearn.tree.tree :param feature_names: :return:
def serialize_tree(tree, feature_names, outfile): """ :type feature_names: list :type tree: sklearn.tree.tree.BaseDecisionTree :param tree: sklearn.tree.tree :param feature_names: :return: """ tree_ = tree.tree_ feature_name = [feature_names[i] if...
:type transformer: sklearn.tree.tree.BaseDecisionTree :type path: str :type model_name: str :type serialize_node: bool :param transformer: :param path: :param model_name: :return:
def serialize_to_bundle(self, transformer, path, model_name, serialize_node=True): """ :type transformer: sklearn.tree.tree.BaseDecisionTree :type path: str :type model_name: str :type serialize_node: bool :param transformer: :param path: :param model_name...
Used with sqrt kernel :param words: :param transformer: :return:
def sent2vec(self, words, transformer): """ Used with sqrt kernel :param words: :param transformer: :return: """ sent_vec = np.zeros(transformer.vector_size) numw = 0 for w in words: try: sent_vec = np.add(sent_vec, tran...
:param transformer: Random Forest Regressor or Classifier :param path: Root path where to serialize the model :param model: Name of the model to be serialized :type transformer: sklearn.ensemble.forest.BaseForest :type path: str :type model: str :return: None
def serialize_to_bundle(self, transformer, path, model): """ :param transformer: Random Forest Regressor or Classifier :param path: Root path where to serialize the model :param model: Name of the model to be serialized :type transformer: sklearn.ensemble.forest.BaseForest ...
Generates the model.json given a list of attributes, which are a tuple comprised of: - name - value Type is figured out automatically, but we should consider specifying it explicitly. Note: this only supports doubles and tensors that are vectors/lists of doubles. :param t...
def get_mleap_model(self, transformer, attributes_to_serialize=None): """ Generates the model.json given a list of attributes, which are a tuple comprised of: - name - value Type is figured out automatically, but we should consider specifying it explicitly. Note: ...
:attributes_map: Map of attributes names. For example StandardScaler has `mean_` but is serialized as `mean` :param transformer: Scikit or Pandas transformer :param node: bundle.ml node json file :param model: bundle.ml model json file :return: Transformer
def deserialize_single_input_output(self, transformer, node_path, attributes_map=None): """ :attributes_map: Map of attributes names. For example StandardScaler has `mean_` but is serialized as `mean` :param transformer: Scikit or Pandas transformer :param node: bundle.ml node json file ...
Wait until `what` return True Args: what (Callable[bool]): Call `wait()` again and again until it returns True times (int): Maximum times of trials before giving up Returns: True if success, False if times threshold reached
def wait_until(what, times=-1): """Wait until `what` return True Args: what (Callable[bool]): Call `wait()` again and again until it returns True times (int): Maximum times of trials before giving up Returns: True if success, False if times threshold reached """ while time...
Reboot all usb devices. Note: If PDU_CONTROLLER_TYPE is not valid, usb devices is not rebooted.
def _init_devices(self): """Reboot all usb devices. Note: If PDU_CONTROLLER_TYPE is not valid, usb devices is not rebooted. """ if not settings.PDU_CONTROLLER_TYPE: if settings.AUTO_DUT: return for device in settings.GOLDEN_DEVICES: ...
Restart harness backend service. Please start the harness controller before running the cases, otherwise, nothing happens
def _init_harness(self): """Restart harness backend service. Please start the harness controller before running the cases, otherwise, nothing happens """ self._hc = HarnessController(self.result_dir) self._hc.stop() time.sleep(1) self._hc.start() time.sle...
Initialize the DUT. DUT will be restarted. and openthread will started.
def _init_dut(self): """Initialize the DUT. DUT will be restarted. and openthread will started. """ if self.auto_dut: self.dut = None return dut_port = settings.DUT_DEVICE[0] dut = OpenThreadController(dut_port) self.dut = dut
Open harness web page. Open a quiet chrome which: 1. disables extensions, 2. ignore certificate errors and 3. always allow notifications.
def _init_browser(self): """Open harness web page. Open a quiet chrome which: 1. disables extensions, 2. ignore certificate errors and 3. always allow notifications. """ chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--disable-ext...
Prepare to run test case. Start harness service, init golden devices, reset DUT and open browser.
def setUp(self): """Prepare to run test case. Start harness service, init golden devices, reset DUT and open browser. """ if self.__class__ is HarnessCase: return logger.info('Setting up') # clear files logger.info('Deleting all .pdf') os.sys...
Clean up after each case. Stop harness service, close browser and close DUT.
def tearDown(self): """Clean up after each case. Stop harness service, close browser and close DUT. """ if self.__class__ is HarnessCase: return logger.info('Tearing down') self._destroy_harness() self._destroy_browser() self._destroy_dut() ...
Do sniffer settings and general settings
def _setup_page(self): """Do sniffer settings and general settings """ if not self.started: self.started = time.time() if time.time() - self.started > 5*len(settings.GOLDEN_DEVICES): self._browser.refresh() return # Detect Sniffer try...
Select the test case.
def _select_case(self, role, case): """Select the test case. """ # select the case elem = Select(self._browser.find_element_by_id('select-dut')) elem.select_by_value(str(role)) time.sleep(1) checkbox = None wait_until(lambda: self._browser.find_elements_b...
Collect test result. Generate PDF, excel and pcap file
def _collect_result(self): """Collect test result. Generate PDF, excel and pcap file """ # generate pdf self._browser.find_element_by_class_name('save-pdf').click() time.sleep(1) try: dialog = self._browser.find_element_by_id('Testinfo') excep...
Wait for dialogs and handle them until done.
def _wait_dialog(self): """Wait for dialogs and handle them until done. """ logger.debug('waiting for dialog') done = False error = False logger.info("self timeout %d",self.timeout) while not done and self.timeout: try: dialog = self._...
Handle a dialog. Returns: bool True if no more dialogs expected, False if more dialogs needed, and None if not handled
def _handle_dialog(self, dialog, title): """Handle a dialog. Returns: bool True if no more dialogs expected, False if more dialogs needed, and None if not handled """ done = self.on_dialog(dialog, title) if isinstance(done, bool): ...
List devices in settings file and print versions
def list_devices(names=None, continue_from=None, **kwargs): """List devices in settings file and print versions""" if not names: names = [device for device, _type in settings.GOLDEN_DEVICES if _type == 'OpenThread'] if continue_from: continue_from = names.index(continue_from) else: ...
Discover all test cases and skip those passed Args: pattern (str): Pattern to match case modules, refer python's unittest documentation for more details skip (str): types cases to skip
def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist=None, name_greps=None, manual_reset=False, delete_history=False, max_devices=0, continue_from=None, result_file='./result.json', auto_reboot=False, keep_explorer=False, add_all_devices=False): """D...
Find the `expected` line within `times` trials. Args: expected str: the expected string times int: number of trials
def _expect(self, expected, times=50): """Find the `expected` line within `times` trials. Args: expected str: the expected string times int: number of trials """ print '[%s] Expecting [%s]' % (self.port, expected) retry_times = 10 while ...
Read exactly one line from the device Returns: None on no data
def _readline(self): """Read exactly one line from the device Returns: None on no data """ logging.info('%s: reading line', self.port) if len(self._lines) > 1: return self._lines.pop(0) tail = '' if len(self._lines): tail = se...
Send exactly one line to the device Args: line str: data send to device
def _sendline(self, line): """Send exactly one line to the device Args: line str: data send to device """ logging.info('%s: sending line', self.port) # clear buffer self._lines = [] try: self._read() except socket.error: ...
send specific command to reference unit over serial port Args: cmd: OpenThread CLI string Returns: Done: successfully send the command to reference unit and parse it Value: successfully retrieve the desired value from reference unit Error: some errors oc...
def __sendCommand(self, cmd): """send specific command to reference unit over serial port Args: cmd: OpenThread CLI string Returns: Done: successfully send the command to reference unit and parse it Value: successfully retrieve the desired value from referen...
get specific type of IPv6 address configured on thread device Args: addressType: the specific type of IPv6 address link local: link local unicast IPv6 address that's within one-hop scope global: global unicast IPv6 address rloc: mesh local unicast IPv6 address f...
def __getIp6Address(self, addressType): """get specific type of IPv6 address configured on thread device Args: addressType: the specific type of IPv6 address link local: link local unicast IPv6 address that's within one-hop scope global: global unicast IPv6 address ...
set router upgrade threshold Args: iThreshold: the number of active routers on the Thread network partition below which a REED may decide to become a Router. Returns: True: successful to set the ROUTER_UPGRADE_THRESHOLD False: fail to set ROU...
def __setRouterUpgradeThreshold(self, iThreshold): """set router upgrade threshold Args: iThreshold: the number of active routers on the Thread network partition below which a REED may decide to become a Router. Returns: True: successful to set t...
set ROUTER_SELECTION_JITTER parameter for REED to upgrade to Router Args: iRouterJitter: a random period prior to request Router ID for REED Returns: True: successful to set the ROUTER_SELECTION_JITTER False: fail to set ROUTER_SELECTION_JITTER
def __setRouterSelectionJitter(self, iRouterJitter): """set ROUTER_SELECTION_JITTER parameter for REED to upgrade to Router Args: iRouterJitter: a random period prior to request Router ID for REED Returns: True: successful to set the ROUTER_SELECTION_JITTER ...
set address filter mode Returns: True: successful to set address filter mode. False: fail to set address filter mode.
def __setAddressfilterMode(self, mode): """set address filter mode Returns: True: successful to set address filter mode. False: fail to set address filter mode. """ print 'call setAddressFilterMode() ' + mode try: cmd = 'macfilter addr ' + mo...
start OpenThread stack Returns: True: successful to start OpenThread stack and thread interface up False: fail to start OpenThread stack
def __startOpenThread(self): """start OpenThread stack Returns: True: successful to start OpenThread stack and thread interface up False: fail to start OpenThread stack """ print 'call startOpenThread' try: if self.hasActiveDatasetToCommit: ...
stop OpenThread stack Returns: True: successful to stop OpenThread stack and thread interface down False: fail to stop OpenThread stack
def __stopOpenThread(self): """stop OpenThread stack Returns: True: successful to stop OpenThread stack and thread interface down False: fail to stop OpenThread stack """ print 'call stopOpenThread' try: if self.__sendCommand('thread stop')[0]...
mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader
def __convertRlocToRouterId(self, xRloc16): """mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader """ routerList = [] routerList = self.__sendCommand('router list')[0].split() ...
convert IPv6 prefix string to IPv6 dotted-quad format for example: 2001000000000000 -> 2001:: Args: strIp6Prefix: IPv6 address string Returns: IPv6 address dotted-quad format
def __convertIp6PrefixStringToIp6Address(self, strIp6Prefix): """convert IPv6 prefix string to IPv6 dotted-quad format for example: 2001000000000000 -> 2001:: Args: strIp6Prefix: IPv6 address string Returns: IPv6 address dotted-quad format ...
convert a long hex integer to string remove '0x' and 'L' return string Args: iValue: long integer in hex format Returns: string of this long integer without "0x" and "L"
def __convertLongToString(self, iValue): """convert a long hex integer to string remove '0x' and 'L' return string Args: iValue: long integer in hex format Returns: string of this long integer without "0x" and "L" """ string = '' strVa...
read logs during the commissioning process Args: durationInSeconds: time duration for reading commissioning logs Returns: Commissioning logs
def __readCommissioningLogs(self, durationInSeconds): """read logs during the commissioning process Args: durationInSeconds: time duration for reading commissioning logs Returns: Commissioning logs """ self.logThreadStatus = self.logStatus['running'] ...
convert channelsArray to bitmask format Args: channelsArray: channel array (i.e. [21, 22]) Returns: bitmask format corresponding to a given channel array
def __convertChannelMask(self, channelsArray): """convert channelsArray to bitmask format Args: channelsArray: channel array (i.e. [21, 22]) Returns: bitmask format corresponding to a given channel array """ maskSet = 0 for eachChannel in channe...
set the Key switch guard time Args: iKeySwitchGuardTime: key switch guard time Returns: True: successful to set key switch guard time False: fail to set key switch guard time
def __setKeySwitchGuardTime(self, iKeySwitchGuardTime): """ set the Key switch guard time Args: iKeySwitchGuardTime: key switch guard time Returns: True: successful to set key switch guard time False: fail to set key switch guard time """ pri...
close current serial port connection
def closeConnection(self): """close current serial port connection""" print '%s call closeConnection' % self.port try: if self.handle: self.handle.close() self.handle = None except Exception, e: ModuleHelper.WriteIntoDebugLogger("cl...
initialize the serial port with baudrate, timeout parameters
def intialize(self): """initialize the serial port with baudrate, timeout parameters""" print '%s call intialize' % self.port try: self.deviceConnected = False # init serial port self._connect() if self.firmwarePrefix in self.UIStatusMsg: ...
set Thread Network name Args: networkName: the networkname string to be set Returns: True: successful to set the Thread Networkname False: fail to set the Thread Networkname
def setNetworkName(self, networkName='GRL'): """set Thread Network name Args: networkName: the networkname string to be set Returns: True: successful to set the Thread Networkname False: fail to set the Thread Networkname """ print '%s call s...
set channel of Thread device operates on. Args: channel: (0 - 10: Reserved) (11 - 26: 2.4GHz channels) (27 - 65535: Reserved) Returns: True: successful to set the channel False: fail to set the channel
def setChannel(self, channel=11): """set channel of Thread device operates on. Args: channel: (0 - 10: Reserved) (11 - 26: 2.4GHz channels) (27 - 65535: Reserved) Returns: True: successful to set the channel ...
get rloc16 short address
def getRloc16(self): """get rloc16 short address""" print '%s call getRloc16' % self.port rloc16 = self.__sendCommand('rloc16')[0] return int(rloc16, 16)
get current partition id of Thread Network Partition from LeaderData Returns: The Thread network Partition Id
def getNetworkFragmentID(self): """get current partition id of Thread Network Partition from LeaderData Returns: The Thread network Partition Id """ print '%s call getNetworkFragmentID' % self.port if not self.__isOpenThreadRunning(): print 'OpenThread is...
get Thread device's parent extended address and rloc16 short address Returns: The extended address of parent in hex format
def getParentAddress(self): """get Thread device's parent extended address and rloc16 short address Returns: The extended address of parent in hex format """ print '%s call getParentAddress' % self.port parentInfo = [] parentInfo = self.__sendCommand('parent'...
power down the Thread device
def powerDown(self): """power down the Thread device""" print '%s call powerDown' % self.port self._sendline('reset') self.isPowerDown = True
power up the Thread device
def powerUp(self): """power up the Thread device""" print '%s call powerUp' % self.port if not self.handle: self._connect() self.isPowerDown = False if not self.__isOpenThreadRunning(): self.__startOpenThread()
reset and rejoin to Thread Network without any timeout Returns: True: successful to reset and rejoin the Thread Network False: fail to reset and rejoin the Thread Network
def reboot(self): """reset and rejoin to Thread Network without any timeout Returns: True: successful to reset and rejoin the Thread Network False: fail to reset and rejoin the Thread Network """ print '%s call reboot' % self.port try: self._s...
send ICMPv6 echo request with a given length to a unicast destination address Args: destination: the unicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload
def ping(self, destination, length=20): """ send ICMPv6 echo request with a given length to a unicast destination address Args: destination: the unicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload """ pri...
factory reset
def reset(self): """factory reset""" print '%s call reset' % self.port try: self._sendline('factoryreset') self._read() except Exception, e: ModuleHelper.WriteIntoDebugLogger("reset() Error: " + str(e))
get data polling rate for sleepy end device
def getPollingRate(self): """get data polling rate for sleepy end device""" print '%s call getPollingRate' % self.port sPollingRate = self.__sendCommand('pollperiod')[0] try: iPollingRate = int(sPollingRate)/1000 fPollingRate = round(float(sPollingRate)/1000, 3) ...
set custom LinkQualityIn for all receiving messages from the specified EUIadr Args: EUIadr: a given extended address LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) ...
def setLinkQuality(self, EUIadr, LinkQuality): """set custom LinkQualityIn for all receiving messages from the specified EUIadr Args: EUIadr: a given extended address LinkQuality: a given custom link quality link quality/link margin mapping table ...
set custom LinkQualityIn for all receiving messages from the any address Args: LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) 2: 11 - 20 (dB) 1: 3 - ...
def setOutBoundLinkQuality(self, LinkQuality): """set custom LinkQualityIn for all receiving messages from the any address Args: LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) ...
remove the configured prefix on a border router Args: prefixEntry: a on-mesh prefix entry Returns: True: successful to remove the prefix entry from border router False: fail to remove the prefix entry from border router
def removeRouterPrefix(self, prefixEntry): """remove the configured prefix on a border router Args: prefixEntry: a on-mesh prefix entry Returns: True: successful to remove the prefix entry from border router False: fail to remove the prefix entry from border...
reset and join back Thread Network with a given timeout delay Args: timeout: a timeout interval before rejoin Thread Network Returns: True: successful to reset and rejoin Thread Network False: fail to reset and rejoin the Thread Network
def resetAndRejoin(self, timeout): """reset and join back Thread Network with a given timeout delay Args: timeout: a timeout interval before rejoin Thread Network Returns: True: successful to reset and rejoin Thread Network False: fail to reset and rejoin th...
set networkid timeout for Thread device Args: iNwkIDTimeOut: a given NETWORK_ID_TIMEOUT Returns: True: successful to set NETWORK_ID_TIMEOUT False: fail to set NETWORK_ID_TIMEOUT
def setNetworkIDTimeout(self, iNwkIDTimeOut): """set networkid timeout for Thread device Args: iNwkIDTimeOut: a given NETWORK_ID_TIMEOUT Returns: True: successful to set NETWORK_ID_TIMEOUT False: fail to set NETWORK_ID_TIMEOUT """ print '%s c...
set whether the Thread device requires the full network data or only requires the stable network data Args: eDataRequirement: is true if requiring the full network data Returns: True: successful to set the network requirement
def setNetworkDataRequirement(self, eDataRequirement): """set whether the Thread device requires the full network data or only requires the stable network data Args: eDataRequirement: is true if requiring the full network data Returns: True: successful to set...
configure border router with a given external route prefix entry Args: P_Prefix: IPv6 prefix for the route P_Stable: is true if the external route prefix is stable network data R_Preference: a two-bit signed integer indicating Router preference 1: h...
def configExternalRouter(self, P_Prefix, P_stable, R_Preference=0): """configure border router with a given external route prefix entry Args: P_Prefix: IPv6 prefix for the route P_Stable: is true if the external route prefix is stable network data R_Preference: a two...
get neighboring routers information Returns: neighboring routers' extended address
def getNeighbouringRouters(self): """get neighboring routers information Returns: neighboring routers' extended address """ print '%s call getNeighbouringRouters' % self.port try: routerInfo = [] routerList = [] routerList = self._...
get all children information Returns: children's extended address
def getChildrenInfo(self): """get all children information Returns: children's extended address """ print '%s call getChildrenInfo' % self.port try: childrenInfoAll = [] childrenInfo = {'EUI': 0, 'Rloc16': 0, 'MLEID': ''} childrenL...
gets the neighboring devices' extended address to compute the DUT extended address automatically Returns: A list including extended address of neighboring routers, parent as well as children
def getNeighbouringDevices(self): """gets the neighboring devices' extended address to compute the DUT extended address automatically Returns: A list including extended address of neighboring routers, parent as well as children """ print '%s call getNe...
get expected global unicast IPv6 address of Thread device Args: filterByPrefix: a given expected global IPv6 prefix to be matched Returns: a global IPv6 address
def getGUA(self, filterByPrefix=None): """get expected global unicast IPv6 address of Thread device Args: filterByPrefix: a given expected global IPv6 prefix to be matched Returns: a global IPv6 address """ print '%s call getGUA' % self.port prin...
set mesh local prefix
def setMLPrefix(self, sMeshLocalPrefix): """set mesh local prefix""" print '%s call setMLPrefix' % self.port try: cmd = 'dataset meshlocalprefix %s' % sMeshLocalPrefix self.hasActiveDatasetToCommit = True return self.__sendCommand(cmd)[0] == 'Done' exc...
force to set a slaac IPv6 address to Thread interface Args: slaacAddress: a slaac IPv6 address to be set Returns: True: successful to set slaac address to Thread interface False: fail to set slaac address to Thread interface
def forceSetSlaac(self, slaacAddress): """force to set a slaac IPv6 address to Thread interface Args: slaacAddress: a slaac IPv6 address to be set Returns: True: successful to set slaac address to Thread interface False: fail to set slaac address to Thread i...
start Collapsed Commissioner Returns: True: successful to start Commissioner False: fail to start Commissioner
def startCollapsedCommissioner(self): """start Collapsed Commissioner Returns: True: successful to start Commissioner False: fail to start Commissioner """ print '%s call startCollapsedCommissioner' % self.port if self.__startOpenThread(): tim...
scan Joiner Args: xEUI: Joiner's EUI-64 strPSKd: Joiner's PSKd for commissioning Returns: True: successful to add Joiner's steering data False: fail to add Joiner's steering data
def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'): """scan Joiner Args: xEUI: Joiner's EUI-64 strPSKd: Joiner's PSKd for commissioning Returns: True: successful to add Joiner's steering data False: fail to add Joiner's steering data ...
start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20): """start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner """ print '%s call joinCommissioned' % self.port se...
get Commissioning logs Returns: Commissioning logs
def getCommissioningLogs(self): """get Commissioning logs Returns: Commissioning logs """ rawLogs = self.logThread.get() ProcessedLogs = [] payload = [] while not rawLogs.empty(): rawLogEach = rawLogs.get() print rawLogEach ...
send MGMT_ED_SCAN message to a given destinaition. Args: sAddr: IPv6 destination address for this message xCommissionerSessionId: commissioner session id listChannelMask: a channel array to indicate which channels to be scaned xCount: number of IEEE 802.15.4 ED S...
def MGMT_ED_SCAN(self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod, xScanDuration): """send MGMT_ED_SCAN message to a given destinaition. Args: sAddr: IPv6 destination address for this message xCommissionerSessionId: commissioner session id listCh...
send MGMT_PANID_QUERY message to a given destination Args: xPanId: a given PAN ID to check the conflicts Returns: True: successful to send MGMT_PANID_QUERY message. False: fail to send MGMT_PANID_QUERY message.
def MGMT_PANID_QUERY(self, sAddr, xCommissionerSessionId, listChannelMask, xPanId): """send MGMT_PANID_QUERY message to a given destination Args: xPanId: a given PAN ID to check the conflicts Returns: True: successful to send MGMT_PANID_QUERY message. False:...
send MGMT_ACTIVE_SET command Returns: True: successful to send MGMT_ACTIVE_SET False: fail to send MGMT_ACTIVE_SET
def MGMT_ACTIVE_SET(self, sAddr='', xCommissioningSessionId=None, listActiveTimestamp=None, listChannelMask=None, xExtendedPanId=None, sNetworkName=None, sPSKc=None, listSecurityPolicy=None, xChannel=None, sMeshLocalPrefix=None, xMasterKey=None, xPanId=None, xTmfPort=None...
send MGMT_PENDING_SET command Returns: True: successful to send MGMT_PENDING_SET False: fail to send MGMT_PENDING_SET
def MGMT_PENDING_SET(self, sAddr='', xCommissionerSessionId=None, listPendingTimestamp=None, listActiveTimestamp=None, xDelayTimer=None, xChannel=None, xPanId=None, xMasterKey=None, sMeshLocalPrefix=None, sNetworkName=None): """send MGMT_PENDING_SET command Returns: ...
send MGMT_COMM_GET command Returns: True: successful to send MGMT_COMM_GET False: fail to send MGMT_COMM_GET
def MGMT_COMM_GET(self, Addr='ff02::1', TLVs=[]): """send MGMT_COMM_GET command Returns: True: successful to send MGMT_COMM_GET False: fail to send MGMT_COMM_GET """ print '%s call MGMT_COMM_GET' % self.port try: cmd = 'commissioner mgmtget' ...
send MGMT_COMM_SET command Returns: True: successful to send MGMT_COMM_SET False: fail to send MGMT_COMM_SET
def MGMT_COMM_SET(self, Addr='ff02::1', xCommissionerSessionID=None, xSteeringData=None, xBorderRouterLocator=None, xChannelTlv=None, ExceedMaxPayload=False): """send MGMT_COMM_SET command Returns: True: successful to send MGMT_COMM_SET False: fail to send ...
set Joiner UDP Port Args: portNumber: Joiner UDP Port number Returns: True: successful to set Joiner UDP Port False: fail to set Joiner UDP Port
def setUdpJoinerPort(self, portNumber): """set Joiner UDP Port Args: portNumber: Joiner UDP Port number Returns: True: successful to set Joiner UDP Port False: fail to set Joiner UDP Port """ print '%s call setUdpJoinerPort' % self.port ...
stop commissioner Returns: True: successful to stop commissioner False: fail to stop commissioner
def commissionerUnregister(self): """stop commissioner Returns: True: successful to stop commissioner False: fail to stop commissioner """ print '%s call commissionerUnregister' % self.port cmd = 'commissioner stop' print cmd return self._...