Instruction:
Implement a Python 3 function for
waiting for dialogs and handle them until done.

Response:
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._browser.find_element_by_id('RemoteConfirm')
            except:
                logger.exception('Failed to get dialog.')
            else:
                if dialog and dialog.get_attribute('aria-hidden') == 'false':
                    title = dialog.find_element_by_class_name('modal-title').text
                    time.sleep(1)
                    logger.info('Handling dialog[%s]', title)

                    try:
                        done = self._handle_dialog(dialog, title)
                    except:
                        logger.exception('Error handling dialog: %s', title)
                        error = True

                    if done is None:
                        raise FailError('Unexpected dialog occurred')

                    dialog.find_element_by_id('ConfirmOk').click()

            time.sleep(1)

            try:
                stop_button = self._browser.find_element_by_id('stopTest')
                if done:
                    stop_button.click()
                    # wait for stop procedure end
                    time.sleep(10)
            except NoSuchElementException:
                logger.info('Test stopped')
                time.sleep(5)
                done = True

            self.timeout -= 1

            # check if already ended capture
            if self.timeout % 10 == 0:
                lines = self._hc.tail()
                if 'SUCCESS: The process "dumpcap.exe" with PID ' in lines:
                    logger.info('Tshark should be ended now, lets wait at most 30 seconds.')
                    if not wait_until(lambda: 'tshark.exe' not in subprocess.check_output('tasklist'), 30):
                        res = subprocess.check_output('taskkill /t /f /im tshark.exe',
                                                      stderr=subprocess.STDOUT, shell=True)
                        logger.info(res)

        # Wait until case really stopped
        wait_until(lambda: self._browser.find_element_by_id('runTest') and True, 30)

        if error:
            raise FailError('Fail for previous exceptions')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _handle_dialog(self, dialog, title):
        done = self.on_dialog(dialog, title)
        if isinstance(done, bool):
            return done

        if title.startswith('Start DUT'):
            body = dialog.find_element_by_id('cnfrmMsg').text
            if 'Sleepy End Device' in body:
                self.dut.mode = 's'
                self.dut.child_timeout = self.child_timeout
            elif 'End Device' in body:
                self.dut.mode = 'rsn'
                self.dut.child_timeout = self.child_timeout
            else:
                self.dut.mode = 'rsdn'

            if 'at channel' in body:
                self.channel = int(body.split(':')[1])

            self.dut.channel = self.channel
            self.dut.panid = settings.THREAD_PANID
            self.dut.networkname = settings.THREAD_NETWORKNAME
            self.dut.extpanid = settings.THREAD_EXTPANID
            self.dut.start()

        elif (title.startswith('MAC Address Required')
              or title.startswith('DUT Random Extended MAC Address Required')):
            mac = self.dut.mac
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys('0x%s' % mac)

        elif title.startswith('LL64 Address'):
            ll64 = None
            for addr in self.dut.addrs:
                addr = addr.lower()
                if addr.startswith('fe80') and not re.match('.+ff:fe00:[0-9a-f]{0,4}$', addr):
                    ll64 = addr
                    break

            if not ll64:
                raise FailError('No link local address found')

            logger.info('Link local address is %s', ll64)
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(ll64)

        elif title.startswith('Enter Channel'):
            self.dut.channel = self.channel
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(str(self.dut.channel))

        elif title.startswith('User Action Needed'):
            body = dialog.find_element_by_id('cnfrmMsg').text
            if body.startswith('Power Down the DUT'):
                self.dut.stop()
            return True

        elif title.startswith('Short Address'):
            short_addr = '0x%s' % self.dut.short_addr
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(short_addr)

        elif title.startswith('ML64 Address'):
            ml64 = None
            for addr in self.dut.addrs:
                if addr.startswith('fd') and not re.match('.+ff:fe00:[0-9a-f]{0,4}$', addr):
                    ml64 = addr
                    break

            if not ml64:
                raise Exception('No mesh local address found')

            logger.info('Mesh local address is %s', ml64)
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(ml64)

        elif title.startswith('Shield Devices') or title.startswith('Sheild DUT'):
            if self.rf_shield:
                logger.info('Shielding devices')
                with self.rf_shield:
                    self.rf_shield.shield()
            elif self.dut and settings.SHIELD_SIMULATION:
                self.dut.channel = (self.channel == THREAD_CHANNEL_MAX
                                    and THREAD_CHANNEL_MIN) or (self.channel + 1)
            else:
                raw_input('Shield DUT and press enter to continue..')

        elif title.startswith('Unshield Devices') or title.startswith('Bring DUT Back to network'):
            if self.rf_shield:
                logger.info('Unshielding devices')
                with self.rf_shield:
                    self.rf_shield.unshield()
            elif self.dut and settings.SHIELD_SIMULATION:
                self.dut.channel = self.channel
            else:
                raw_input('Bring DUT and press enter to continue..')

        elif title.startswith('Configure Prefix on DUT'):
            body = dialog.find_element_by_id('cnfrmMsg').text
            body = body.split(': ')[1]
            params = reduce(lambda params, param: params.update(((param[0].strip(' '), param[1]),)) or params,
                            [it.split('=') for it in body.split(', ')], {})
            prefix = params['P_Prefix'].strip('\0\r\n\t ')
            flags = []
            if params.get('P_slaac_preferred', 0) == '1':
                flags.append('p')
            flags.append('ao')
            if params.get('P_stable', 0) == '1':
                flags.append('s')
            if params.get('P_default', 0) == '1':
                flags.append('r')
            prf = 'high'
            self.dut.add_prefix(prefix, ''.join(flags), prf)

        return False

Response:
Handle a dialog.

        Returns:
            bool True if no more dialogs expected,
                 False if more dialogs needed, and
                 None if not handled


Instruction:
Can you implement a function in Python 3 that
lists devices in settings file and print versions

Response:
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:
        continue_from = 0

    for port in names[continue_from:]:
        try:
            with OpenThreadController(port) as otc:
                print('%s: %s' % (port, otc.version))
        except:
            logger.exception('failed to get version of %s' % port)


Instruction:
Create a Python 3 function for
discovering all test cases and skip them

Response:
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):
    """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
    """
    if not os.path.exists(settings.OUTPUT_PATH):
        os.mkdir(settings.OUTPUT_PATH)

    if delete_history:
        os.system('del history.json')

    if blacklist:
        try:
            excludes = [line.strip('\n') for line in open(blacklist, 'r').readlines()
                        if not line.startswith('#')]
        except:
            logger.exception('Failed to open test case black list file')
            raise
    else:
        excludes = []

    log = None
    if os.path.isfile(result_file):
        try:
            log = json.load(open(result_file, 'r'))
        except:
            logger.exception('Failed to open result file')

    if not log:
        log = {}
        json.dump(log, open(result_file, 'w'), indent=2)

    suite = unittest.TestSuite()
    discovered = unittest.defaultTestLoader.discover('cases', pattern)

    if names and continue_from:
        names = names[names.index(continue_from):]

    for s1 in discovered:
        for s2 in s1:
            for case in s2:
                if case.__class__ is HarnessCase:
                    continue
                case_name = unicode(case.__class__.__name__)

                # grep name
                if name_greps and not any(fnmatch.fnmatch(case_name, name_grep) for name_grep in name_greps):
                    logger.info('case[%s] skipped by name greps', case_name)
                    continue

                # whitelist
                if len(names) and case_name not in names:
                    logger.info('case[%s] skipped', case_name)
                    continue

                # skip cases
                if case_name in log.keys():
                    if (log[case_name]['passed'] and ('p' in skip)) \
                        or (log[case_name]['passed'] is False and ('f' in skip)) \
                        or (log[case_name]['passed'] is None and ('e' in skip)):
                        logger.warning('case[%s] skipped for its status[%s]', case_name, log[case_name]['passed'])
                        continue

                # continue from
                if continue_from:
                    if continue_from != case_name:
                        logger.warning('case[%s] skipped for continue from[%s]', case_name, continue_from)
                        continue
                    else:
                        continue_from = None

                # black list
                if case_name in excludes:
                    logger.warning('case[%s] skipped for blacklist', case_name)
                    continue

                # max devices
                if max_devices and case.golden_devices_required > max_devices:
                    logger.warning('case[%s] skipped for exceeding max golden devices allowed[%d]', case_name, max_devices)
                    continue

                suite.addTest(case)
                logger.info('case[%s] added', case_name)

    if auto_reboot:
        argv = []
        argv.append('"%s"' % os.sep.join([os.getcwd(), 'start.bat']))
        argv.extend(['-p', pattern])
        argv.extend(['-k', skip])
        argv.extend(['-o', result_file])
        argv.append('-a')

        if manual_reset:
            argv.append('-m')

        if delete_history:
            argv.append('-d')

        auto_reboot_args = argv + names
    else:
        auto_reboot_args = None
        os.system('del "%s"' % RESUME_SCRIPT_PATH)

    # manual reset
    if manual_reset:
        settings.PDU_CONTROLLER_TYPE = 'MANUAL_PDU_CONTROLLER'
        settings.PDU_CONTROLLER_OPEN_PARAMS = {}
        settings.PDU_CONTROLLER_REBOOT_PARAMS = {}

    result = SimpleTestResult(result_file, auto_reboot_args, keep_explorer, add_all_devices)
    for case in suite:
        logger.info(case.__class__.__name__)

    if dry_run:
        return

    suite.run(result)
    return result


Instruction:
Implement a Python 3 function for
finding the expected string within times.

Response:
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 times > 0 and retry_times > 0:
            line = self._readline()
            print '[%s] Got line [%s]' % (self.port, line)

            if line == expected:
                print '[%s] Expected [%s]' % (self.port, expected)
                return

            if not line:
                retry_times -= 1
                time.sleep(0.1)

            times -= 1

        raise Exception('failed to find expected string[%s]' % expected)


Instruction:
Can you tell what is the following Python 3 function doing
def _readline(self):
        logging.info('%s: reading line', self.port)
        if len(self._lines) > 1:
            return self._lines.pop(0)

        tail = ''
        if len(self._lines):
            tail = self._lines.pop()

        try:
            tail += self._read()
        except socket.error:
            logging.exception('%s: No new data', self.port)
            time.sleep(0.1)

        self._lines += LINESEPX.split(tail)
        if len(self._lines) > 1:
            return self._lines.pop(0)

Response: Read exactly one line from the device returning the first line on success Returns None on no data


Instruction:
Write a Python 3 script for
sending exactly one line to the device

Response:
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:
            logging.debug('%s: Nothing cleared', self.port)

        print 'sending [%s]' % line
        self._write(line + '\r\n')

        # wait for write to complete
        time.sleep(0.1)


Instruction:
Write a Python 3 function that can
send specific command to the OpenThread CLI string and parse the response

Response:
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 reference unit
            Error: some errors occur, indicates by the followed specific error number
        """
        logging.info('%s: sendCommand[%s]', self.port, cmd)
        if self.logThreadStatus == self.logStatus['running']:
            self.logThreadStatus = self.logStatus['pauseReq']
            while self.logThreadStatus != self.logStatus['paused'] and self.logThreadStatus != self.logStatus['stop']:
                pass

        try:
            # command retransmit times
            retry_times = 3
            while retry_times > 0:
                retry_times -= 1
                try:
                    self._sendline(cmd)
                    self._expect(cmd)
                except Exception as e:
                    logging.exception('%s: failed to send command[%s]: %s', self.port, cmd, str(e))
                    if retry_times == 0:
                        raise
                else:
                    break

            line = None
            response = []
            retry_times = 10
            while retry_times > 0:
                line = self._readline()
                logging.info('%s: the read line is[%s]', self.port, line)
                if line:
                    response.append(line)
                    if line == 'Done':
                        break
                else:
                    retry_times -= 1
                    time.sleep(0.2)
            if line != 'Done':
                raise Exception('%s: failed to find end of response' % self.port)
            logging.info('%s: send command[%s] done!', self.port, cmd)
            return response
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("sendCommand() Error: " + str(e))
            raise


Instruction:
Write a Python 3 script for
getting specific type of IPv6 address configured on thread device

Response:
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
            rloc: mesh local unicast IPv6 address for routing in thread network
            mesh EID: mesh Endpoint Identifier

        Returns:
            IPv6 address string
        """
        addrType = ['link local', 'global', 'rloc', 'mesh EID']
        addrs = []
        globalAddr = []
        linkLocal64Addr = ''
        rlocAddr = ''
        meshEIDAddr = ''

        addrs = self.__sendCommand('ipaddr')
        for ip6Addr in addrs:
            if ip6Addr == 'Done':
                break

            ip6AddrPrefix = ip6Addr.split(':')[0]
            if ip6AddrPrefix == 'fe80':
                # link local address
                if ip6Addr.split(':')[4] != '0':
                    linkLocal64Addr = ip6Addr
            elif ip6Addr.startswith(self.meshLocalPrefix):
                # mesh local address
                if ip6Addr.split(':')[4] == '0':
                    # rloc
                    rlocAddr = ip6Addr
                else:
                    # mesh EID
                    meshEIDAddr = ip6Addr
            else:
                # global ipv6 address
                if ip6Addr != None:
                    globalAddr.append(ip6Addr)
                else:
                    pass

        if addressType == addrType[0]:
            return linkLocal64Addr
        elif addressType == addrType[1]:
            return globalAddr
        elif addressType == addrType[2]:
            return rlocAddr
        elif addressType == addrType[3]:
            return meshEIDAddr
        else:
            pass


Instruction:
Make a summary of the following Python 3 code
def __setRouterUpgradeThreshold(self, iThreshold):
        print 'call __setRouterUpgradeThreshold'
        try:
            cmd = 'routerupgradethreshold %s' % str(iThreshold)
            print cmd
            return self.__sendCommand(cmd) == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setRouterUpgradeThreshold() Error: " + str(e))

Response: set the router upgrade threshold


Instruction:
How would you explain what the following Python 3 function does
def __setRouterSelectionJitter(self, iRouterJitter):
        print 'call _setRouterSelectionJitter'
        try:
            cmd = 'routerselectionjitter %s' % str(iRouterJitter)
            print cmd
            return self.__sendCommand(cmd) == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setRouterSelectionJitter() Error: " + str(e))

Response: set the ROUTER_SELECTION_JITTER parameter for REED to upgrade to Router


Instruction:
Explain what the following Python 3 code does
def __setAddressfilterMode(self, mode):
        print 'call setAddressFilterMode() ' +  mode
        try:
            cmd = 'macfilter addr ' + mode
            if self.__sendCommand(cmd)[0] == 'Done':
                return True
            return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("__setAddressFilterMode() Error: " + str(e))

Response: set the mode of the mac filter addr


Instruction:
Given the following Python 3 function, write the documentation
def __startOpenThread(self):
        print 'call startOpenThread'
        try:
            if self.hasActiveDatasetToCommit:
                if self.__sendCommand('dataset commit active')[0] != 'Done':
                    raise Exception('failed to commit active dataset')
                else:
                    self.hasActiveDatasetToCommit = False

            # restore whitelist/blacklist address filter mode if rejoin after reset
            if self.isPowerDown:
                if self._addressfilterMode == 'whitelist':
                    if self.__setAddressfilterMode('whitelist'):
                        for addr in self._addressfilterSet:
                            self.addAllowMAC(addr)
                elif self._addressfilterMode == 'blacklist':
                    if self.__setAddressfilterMode('blacklist'):
                        for addr in self._addressfilterSet:
                            self.addBlockedMAC(addr)

            if self.deviceRole in [Thread_Device_Role.Leader, Thread_Device_Role.Router, Thread_Device_Role.REED]:
                self.__setRouterSelectionJitter(1)

            if self.__sendCommand('ifconfig up')[0] == 'Done':
                if self.__sendCommand('thread start')[0] == 'Done':
                    self.isPowerDown = False
                    return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("startOpenThread() Error: " + str(e))

Response: start OpenThread stack and thread interface up


Instruction:
Here you have a function in Python 3, explain what it does
def __stopOpenThread(self):
        print 'call stopOpenThread'
        try:
            if self.__sendCommand('thread stop')[0] == 'Done':
                return self.__sendCommand('ifconfig down')[0] == 'Done'
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("stopOpenThread() Error: " + str(e))

Response: stop OpenThread stack and thread interface down


Instruction:
Explain what the following Python 3 code does
def __convertRlocToRouterId(self, xRloc16):
        routerList = []
        routerList = self.__sendCommand('router list')[0].split()
        print routerList
        print xRloc16

        for index in routerList:
            router = []
            cmd = 'router %s' % index
            router = self.__sendCommand(cmd)

            for line in router:
                if 'Done' in line:
                    break
                elif 'Router ID' in line:
                    routerid = line.split()[2]
                elif 'Rloc' in line:
                    rloc16 = line.split()[1]
                else:
                    pass

            # process input rloc16
            if isinstance(xRloc16, str):
                rloc16 = '0x' + rloc16
                if rloc16 == xRloc16:
                    return routerid
            elif isinstance(xRloc16, int):
                if int(rloc16, 16) == xRloc16:
                    return routerid
            else:
                pass

        return None

Response: This function converts Rloc to Router ID.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __convertIp6PrefixStringToIp6Address(self, strIp6Prefix):
        prefix1 = strIp6Prefix.rstrip('L')
        prefix2 = prefix1.lstrip("0x")
        hexPrefix = str(prefix2).ljust(16,'0')
        hexIter = iter(hexPrefix)
        finalMac = ':'.join(a + b + c + d for a,b,c,d in zip(hexIter, hexIter,hexIter,hexIter))
        prefix = str(finalMac)
        strIp6Prefix = prefix[:20]
        return strIp6Prefix +':'

Response: convert IPv6 prefix string to IPv6 dotted - quad format


Instruction:
Can you write a function in Python 3 where it
converts a long hex integer to string

Response:
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 = ''
        strValue = str(hex(iValue))

        string = strValue.lstrip('0x')
        string = string.rstrip('L')

        return string


Instruction:
Can you generate the documentation for the following Python 3 function
def __readCommissioningLogs(self, durationInSeconds):
        self.logThreadStatus = self.logStatus['running']
        logs = Queue()
        t_end = time.time() + durationInSeconds
        while time.time() < t_end:
            time.sleep(0.3)

            if self.logThreadStatus == self.logStatus['pauseReq']:
                self.logThreadStatus = self.logStatus['paused']

            if self.logThreadStatus != self.logStatus['running']:
                continue

            try:
                line = self._readline()
                if line:
                    print line
                    logs.put(line)

                    if "Join success" in line:
                        self.joinCommissionedStatus = self.joinStatus['succeed']
                        break
                    elif "Join failed" in line:
                        self.joinCommissionedStatus = self.joinStatus['failed']
                        break

            except Exception:
                pass

        self.logThreadStatus = self.logStatus['stop']
        return logs

Response: read logs during the commissioning process


Instruction:
Make a summary of the following Python 3 code
def __convertChannelMask(self, channelsArray):
        maskSet = 0

        for eachChannel in channelsArray:
            mask = 1 << eachChannel
            maskSet = (maskSet | mask)

        return maskSet

Response: convert channelsArray to bitmask format corresponding to a given channel array


Instruction:
Given the following Python 3 function, write the documentation
def __setKeySwitchGuardTime(self, iKeySwitchGuardTime):
        print '%s call setKeySwitchGuardTime' % self.port
        print iKeySwitchGuardTime
        try:
            cmd = 'keysequence guardtime %s' % str(iKeySwitchGuardTime)
            if self.__sendCommand(cmd)[0] == 'Done':
                time.sleep(1)
                return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setKeySwitchGuardTime() Error; " + str(e))

Response: set the Key switch guard time


Instruction:
Write a Python 3 function that can
close current serial port connection

Response:
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("closeConnection() Error: " + str(e))


Instruction:
Can you write a function in Python 3 where it
initializes the serial port with baudrate timeout parameters

Response:
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:
                self.deviceConnected = True
            else:
                self.UIStatusMsg = "Firmware Not Matching Expecting " + self.firmwarePrefix + " Now is " + self.UIStatusMsg
                ModuleHelper.WriteIntoDebugLogger("Err: OpenThread device Firmware not matching..")

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("intialize() Error: " + str(e))
            self.deviceConnected = False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setNetworkName(self, networkName='GRL'):
        print '%s call setNetworkName' % self.port
        print networkName
        try:
            cmd = 'networkname %s' % networkName
            datasetCmd = 'dataset networkname %s' % networkName
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] == 'Done' and self.__sendCommand(datasetCmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setNetworkName() Error: " + str(e))

Response: set Thread Network name


Instruction:
Make a summary of the following Python 3 code
def setChannel(self, channel=11):
        print '%s call setChannel' % self.port
        print channel
        try:
            cmd = 'channel %s' % channel
            datasetCmd = 'dataset channel %s' % channel
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] == 'Done' and self.__sendCommand(datasetCmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setChannel() Error: " + str(e))

Response: set the channel of Thread device operates on


Instruction:
Given the following Python 3 function, write the documentation
def getMAC(self, bType=MacType.RandomMac):
        print '%s call getMAC' % self.port
        print bType
        # if power down happens, return extended address assigned previously
        if self.isPowerDown:
            macAddr64 = self.mac
        else:
            if bType == MacType.FactoryMac:
                macAddr64 = self.__sendCommand('eui64')[0]
            elif bType == MacType.HashMac:
                macAddr64 = self.__sendCommand('joinerid')[0]
            else:
                macAddr64 = self.__sendCommand('extaddr')[0]
        print macAddr64

        return int(macAddr64, 16)

Response: get one specific type of MAC address


Instruction:
How would you explain what the following Python 3 function does
def getRloc16(self):
        print '%s call getRloc16' % self.port
        rloc16 = self.__sendCommand('rloc16')[0]
        return int(rloc16, 16)

Response: get rloc16 short address


Instruction:
Given the following Python 3 function, write the documentation
def getNetworkFragmentID(self):
        print '%s call getNetworkFragmentID' % self.port
        if not self.__isOpenThreadRunning():
            print 'OpenThread is not running'
            return None

        leaderData = []
        leaderData = self.__sendCommand('leaderdata')
        return int(leaderData[0].split()[2], 16)

Response: get current partition id of Thread Network Partition from LeaderData


Instruction:
Can you generate the documentation for the following Python 3 function
def getParentAddress(self):
        print '%s call getParentAddress' % self.port
        parentInfo = []
        parentInfo = self.__sendCommand('parent')

        for line in parentInfo:
            if 'Done' in line:
                break
            elif 'Ext Addr' in line:
                eui = line.split()[2]
                print eui
            #elif 'Rloc' in line:
            #    rloc16 = line.split()[1]
            #    print rloc16
            else:
                pass

        return int(eui, 16)

Response: get Thread device s parent extended address and rloc16 short address


Instruction:
Implement a Python 3 function for
powering down the Thread device

Response:
def powerDown(self):
        """power down the Thread device"""
        print '%s call powerDown' % self.port
        self._sendline('reset')
        self.isPowerDown = True


Instruction:
Make a summary of the following Python 3 code
def powerUp(self):
        print '%s call powerUp' % self.port
        if not self.handle:
            self._connect()

        self.isPowerDown = False

        if not self.__isOpenThreadRunning():
            self.__startOpenThread()

Response: power up the Thread device


Instruction:
Can you implement a function in Python 3 that
resets and rejoin Thread Network without any timeout

Response:
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._sendline('reset')
            self.isPowerDown = True
            time.sleep(3)

            self.__startOpenThread()
            time.sleep(3)

            if self.__sendCommand('state')[0] == 'disabled':
                print '[FAIL] reboot'
                return False
            else:
                return True
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("reboot() Error: " + str(e))


Instruction:
Create a Python 3 function to
send ICMPv6 echo request with a given length to a unicast destination

Response:
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
        """
        print '%s call ping' % self.port
        print 'destination: %s' %destination
        try:
            cmd = 'ping %s %s' % (destination, str(length))
            print cmd
            self._sendline(cmd)
            self._expect(cmd)
            # wait echo reply
            time.sleep(1)
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("ping() Error: " + str(e))


Instruction:
Write a Python 3 script for
resetting the internal state of the object

Response:
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))


Instruction:
How would you code a function in Python 3 to
get data polling rate for sleepy end device

Response:
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)
            return fPollingRate if fPollingRate > iPollingRate else iPollingRate
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("getPollingRate() Error: " + str(e))


Instruction:
Can you tell what is the following Python 3 function doing
def setLinkQuality(self, EUIadr, LinkQuality):
        print '%s call setLinkQuality' % self.port
        print EUIadr
        print LinkQuality
        try:
            # process EUIadr
            euiHex = hex(EUIadr)
            euiStr = str(euiHex)
            euiStr = euiStr.rstrip('L')
            address64 = ''
            if '0x' in euiStr:
                address64 = euiStr.lstrip('0x')
                # prepend 0 at the beginning
                if len(address64) < 16:
                   address64 = address64.zfill(16)
                   print address64

            cmd = 'macfilter rss add-lqi %s %s' % (address64, str(LinkQuality))
            print cmd
            return self.__sendCommand(cmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setLinkQuality() Error: " + str(e))

Response: set custom link quality for all receiving messages from the specified EUIadr


Instruction:
How would you implement a function in Python 3 that
sets custom link quality for all receiving messages from the any address

Response:
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)
                         2: 11 - 20 (dB)
                         1: 3 - 9 (dB)
                         0: 0 - 2 (dB)

        Returns:
            True: successful to set the link quality
            False: fail to set the link quality
        """
        print '%s call setOutBoundLinkQuality' % self.port
        print LinkQuality
        try:
            cmd = 'macfilter rss add-lqi * %s' % str(LinkQuality)
            print cmd
            return self.__sendCommand(cmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setOutBoundLinkQuality() Error: " + str(e))


Instruction:
Can you tell what is the following Python 3 function doing
def removeRouterPrefix(self, prefixEntry):
        print '%s call removeRouterPrefix' % self.port
        print prefixEntry
        prefix = self.__convertIp6PrefixStringToIp6Address(str(prefixEntry))
        try:
            prefixLen = 64
            cmd = 'prefix remove %s/%d' % (prefix, prefixLen)
            print cmd
            if self.__sendCommand(cmd)[0] == 'Done':
                # send server data ntf to leader
                return self.__sendCommand('netdataregister')[0] == 'Done'
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("removeRouterPrefix() Error: " + str(e))

Response: remove the configured router prefix on a border


Instruction:
Write a Python 3 script for
resetting and rejoin Thread Network with a given timeout delay

Response:
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 the Thread Network
        """
        print '%s call resetAndRejoin' % self.port
        print timeout
        try:
            self._sendline('reset')
            self.isPowerDown = True
            time.sleep(timeout)

            if self.deviceRole == Thread_Device_Role.SED:
                self.setPollingRate(self.sedPollingRate)

            self.__startOpenThread()
            time.sleep(3)

            if self.__sendCommand('state')[0] == 'disabled':
                print '[FAIL] reset and rejoin'
                return False
            return True
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("resetAndRejoin() Error: " + str(e))


Instruction:
Write a Python 3 script for
setting networkid timeout for Thread device

Response:
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 call setNetworkIDTimeout' % self.port
        print iNwkIDTimeOut
        iNwkIDTimeOut /= 1000
        try:
            cmd = 'networkidtimeout %s' % str(iNwkIDTimeOut)
            print cmd
            return self.__sendCommand(cmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setNetworkIDTimeout() Error: " + str(e))