INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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.
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.
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 transformer:: param attributes_to_serialize: Tupl...
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
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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
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
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
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
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
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
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
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
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
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
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::
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
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
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
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
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
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.
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 one specific type of MAC address currently OpenThread only supports Random MAC address
def getMAC(self, bType=MacType.RandomMac): """get one specific type of MAC address currently OpenThread only supports Random MAC address Args: bType: indicate which kind of MAC address is required Returns: specific type of MAC address """ prin...
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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
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
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
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
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
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
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
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._...
force update to router as if there is child id request
def updateRouterStatus(self): """force update to router as if there is child id request""" print '%s call updateRouterStatus' % self.port cmd = 'state' while True: state = self.__sendCommand(cmd)[0] if state == 'detached': continue elif...
Find the expected line within times 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 """ logger.debug('[%s] Expecting [%s]', self.port, expected) retry_times = 10 wh...
Read exactly one line from the device nonblocking.
def _readline(self): """Read exactly one line from the device, nonblocking. Returns: None on no data """ if len(self.lines) > 1: return self.lines.pop(0) tail = '' if len(self.lines): tail = self.lines.pop() try: ...
Send exactly one line to the device
def _sendline(self, line): """Send exactly one line to the device Args: line str: data send to device """ self.lines = [] try: self._read() except socket.error: logging.debug('Nothing cleared') logger.debug('sending [%s]', lin...
Send command and wait for response.
def _req(self, req): """Send command and wait for response. The command will be repeated 3 times at most in case data loss of serial port. Args: req (str): Command to send, please do not include new line in the end. Returns: [str]: The output lines """ ...
Threading callback
def run(self): """Threading callback""" self.viewing = True while self.viewing and self._lock.acquire(): try: line = self._readline() except: pass else: logger.info(line) self._lock.release() ...
Reset openthread device not equivalent to stop and start
def reset(self): """Reset openthread device, not equivalent to stop and start """ logger.debug('DUT> reset') self._log and self.pause() self._sendline('reset') self._read() self._log and self.resume()
Add network prefix.
def add_prefix(self, prefix, flags, prf): """Add network prefix. Args: prefix (str): network prefix. flags (str): network prefix flags, please refer thread documentation for details prf (str): network prf, please refer thread documentation for details """ ...