Instruction:
How would you code a function in Python 3 to
set whether the Thread device requires the full network data or only requires the stable network data

Response:
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 the network requirement
        """
        print '%s call setNetworkDataRequirement' % self.port
        print eDataRequirement

        if eDataRequirement == Device_Data_Requirement.ALL_DATA:
            self.networkDataRequirement = 'n'
        return True


Instruction:
Can you write a function in Python 3 where it
configures the border router with a given external route prefix entry

Response:
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-bit signed integer indicating Router preference
                          1: high
                          0: medium
                         -1: low

        Returns:
            True: successful to configure the border router with a given external route prefix
            False: fail to configure the border router with a given external route prefix
        """
        print '%s call configExternalRouter' % self.port
        print P_Prefix
        stable = ''
        prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix))
        try:
            if R_Preference == 1:
                prf = 'high'
            elif R_Preference == 0:
                prf = 'med'
            elif R_Preference == -1:
                prf = 'low'
            else:
                pass

            if P_stable:
                stable += 's'
                cmd = 'route add %s/64 %s %s' % (prefix, stable, prf)
            else:
                cmd = 'route add %s/64 %s' % (prefix, prf)
            print cmd

            if self.__sendCommand(cmd)[0] == 'Done':
                # send server data ntf to leader
                return self.__sendCommand('netdataregister')[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("configExternalRouter() Error: " + str(e))


Instruction:
Write a Python 3 function that can
get neighboring routers information

Response:
def getNeighbouringRouters(self):
        """get neighboring routers information

        Returns:
            neighboring routers' extended address
        """
        print '%s call getNeighbouringRouters' % self.port
        try:
            routerInfo = []
            routerList = []
            routerList = self.__sendCommand('router list')[0].split()
            print routerList

            if 'Done' in routerList:
                print 'no neighbouring routers'
                return None

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

                for line in router:
                    if 'Done' in line:
                        break
                    #elif 'Rloc' in line:
                    #    rloc16 = line.split()[1]
                    elif 'Ext Addr' in line:
                        eui = line.split()[2]
                        routerInfo.append(int(eui, 16))
                    #elif 'LQI In' in line:
                    #    lqi_in = line.split()[1]
                    #elif 'LQI Out' in line:
                    #    lqi_out = line.split()[1]
                    else:
                        pass

            print routerInfo
            return routerInfo
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("getNeighbouringDevice() Error: " + str(e))


Instruction:
Implement a function in Python 3 to
get all children information

Response:
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': ''}
            childrenList = self.__sendCommand('child list')[0].split()
            print childrenList

            if 'Done' in childrenList:
                print 'no children'
                return None

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

                for line in child:
                    if 'Done' in line:
                        break
                    elif 'Rloc' in line:
                        rloc16 = line.split()[1]
                    elif 'Ext Addr' in line:
                        eui = line.split()[2]
                    #elif 'Child ID' in line:
                    #    child_id = line.split()[2]
                    #elif 'Mode' in line:
                    #    mode = line.split()[1]
                    else:
                        pass

                childrenInfo['EUI'] = int(eui, 16)
                childrenInfo['Rloc16'] = int(rloc16, 16)
                #children_info['MLEID'] = self.getMLEID()

                childrenInfoAll.append(childrenInfo['EUI'])
                #childrenInfoAll.append(childrenInfo)

            print childrenInfoAll
            return childrenInfoAll
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("getChildrenInfo() Error: " + str(e))


Instruction:
Can you create a Python 3 function that
gets the neighboring devices extended address to compute the DUT extended address automatically

Response:
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 getNeighbouringDevices' % self.port
        neighbourList = []

        # get parent info
        parentAddr = self.getParentAddress()
        if parentAddr != 0:
            neighbourList.append(parentAddr)

        # get ED/SED children info
        childNeighbours = self.getChildrenInfo()
        if childNeighbours != None and len(childNeighbours) > 0:
            for entry in childNeighbours:
                neighbourList.append(entry)

        # get neighboring routers info
        routerNeighbours = self.getNeighbouringRouters()
        if routerNeighbours != None and len(routerNeighbours) > 0:
            for entry in routerNeighbours:
                neighbourList.append(entry)

        print neighbourList
        return neighbourList


Instruction:
Can you create a Python 3 function that
gets the global unicast IPv6 address of Thread device

Response:
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
        print filterByPrefix
        globalAddrs = []
        try:
            # get global addrs set if multiple
            globalAddrs = self.getGlobal()

            if filterByPrefix is None:
                return globalAddrs[0]
            else:
                for line in globalAddrs:
                    fullIp = ModuleHelper.GetFullIpv6Address(line)
                    if fullIp.startswith(filterByPrefix):
                        return fullIp
                print 'no global address matched'
                return str(globalAddrs[0])
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("getGUA() Error: " + str(e))


Instruction:
Write a Python 3 script to
set mesh local prefix

Response:
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'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setMLPrefix() Error: " + str(e))


Instruction:
Create a Python 3 function for
forcing to set a slaac address to Thread interface

Response:
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 interface
        """
        print '%s call forceSetSlaac' % self.port
        print slaacAddress
        try:
            cmd = 'ipaddr add %s' % str(slaacAddress)
            print cmd
            return self.__sendCommand(cmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("forceSetSlaac() Error: " + str(e))


Instruction:
Write a Python 3 function for
starting Collapsed Commissioner Returns: True: successful to start Commissioner False: fail to start Commissioner

Response:
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():
            time.sleep(20)
            cmd = 'commissioner start'
            print cmd
            if self.__sendCommand(cmd)[0] == 'Done':
                self.isActiveCommissioner = True
                time.sleep(20) # time for petition process
                return True
        return False


Instruction:
Can you generate the documentation for the following Python 3 function
def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'):
        print '%s call scanJoiner' % self.port

        # long timeout value to avoid automatic joiner removal (in seconds)
        timeout = 500

        if not isinstance(xEUI, str):
            eui64 = self.__convertLongToString(xEUI)

            # prepend 0 at the beginning
            if len(eui64) < 16:
                eui64 = eui64.zfill(16)
                print eui64
        else:
            eui64 = xEUI

        cmd = 'commissioner joiner add %s %s %s' % (eui64, strPSKd, str(timeout))
        print cmd
        if self.__sendCommand(cmd)[0] == 'Done':
            if self.logThreadStatus == self.logStatus['stop']:
                self.logThread = ThreadRunner.run(target=self.__readCommissioningLogs, args=(120,))
            return True
        else:
            return False

Response: add a new Joiner s steering data to the current Thread


Instruction:
Implement a Python 3 function for
starting joiner s PSKd

Response:
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
        self.__sendCommand('ifconfig up')
        cmd = 'joiner start %s %s' %(strPSKd, self.provisioningUrl)
        print cmd
        if self.__sendCommand(cmd)[0] == "Done":
            maxDuration = 150 # seconds
            self.joinCommissionedStatus = self.joinStatus['ongoing']

            if self.logThreadStatus == self.logStatus['stop']:
                self.logThread = ThreadRunner.run(target=self.__readCommissioningLogs, args=(maxDuration,))

            t_end = time.time() + maxDuration
            while time.time() < t_end:
                if self.joinCommissionedStatus == self.joinStatus['succeed']:
                    break
                elif self.joinCommissionedStatus == self.joinStatus['failed']:
                    return False

                time.sleep(1)

            self.__sendCommand('thread start')
            time.sleep(30)
            return True
        else:
            return False


Instruction:
Write a Python 3 function that can
get Commissioning logs in the logThread

Response:
def getCommissioningLogs(self):
        """get Commissioning logs

        Returns:
           Commissioning logs
        """
        rawLogs = self.logThread.get()
        ProcessedLogs = []
        payload = []
        while not rawLogs.empty():
            rawLogEach = rawLogs.get()
            print rawLogEach
            if "[THCI]" not in rawLogEach:
                continue

            EncryptedPacket = PlatformDiagnosticPacket()
            infoList = rawLogEach.split('[THCI]')[1].split(']')[0].split('|')
            for eachInfo in infoList:
                print eachInfo
                info = eachInfo.split("=")
                infoType = info[0].strip()
                infoValue = info[1].strip()
                if "direction" in infoType:
                    EncryptedPacket.Direction = PlatformDiagnosticPacket_Direction.IN if 'recv' in infoValue \
                        else PlatformDiagnosticPacket_Direction.OUT if 'send' in infoValue \
                        else PlatformDiagnosticPacket_Direction.UNKNOWN
                elif "type" in infoType:
                    EncryptedPacket.Type = PlatformDiagnosticPacket_Type.JOIN_FIN_req if 'JOIN_FIN.req' in infoValue \
                        else PlatformDiagnosticPacket_Type.JOIN_FIN_rsp if 'JOIN_FIN.rsp' in infoValue \
                        else PlatformDiagnosticPacket_Type.JOIN_ENT_req if 'JOIN_ENT.ntf' in infoValue \
                        else PlatformDiagnosticPacket_Type.JOIN_ENT_rsp if 'JOIN_ENT.rsp' in infoValue \
                        else PlatformDiagnosticPacket_Type.UNKNOWN
                elif "len" in infoType:
                    bytesInEachLine = 16
                    EncryptedPacket.TLVsLength = int(infoValue)
                    payloadLineCount = (int(infoValue) + bytesInEachLine - 1)/bytesInEachLine
                    while payloadLineCount > 0:
                        payloadLineCount = payloadLineCount - 1
                        payloadLine = rawLogs.get()
                        payloadSplit = payloadLine.split('|')
                        for block in range(1, 3):
                            payloadBlock = payloadSplit[block]
                            payloadValues = payloadBlock.split(' ')
                            for num in range(1, 9):
                                if ".." not in payloadValues[num]:
                                    payload.append(int(payloadValues[num], 16))

                    EncryptedPacket.TLVs = PlatformPackets.read(EncryptedPacket.Type, payload) if payload != [] else []

            ProcessedLogs.append(EncryptedPacket)
        return ProcessedLogs


Instruction:
Write a Python 3 function that can
send MGMT_ED_SCAN message to a given destination

Response:
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
            listChannelMask: a channel array to indicate which channels to be scaned
            xCount: number of IEEE 802.15.4 ED Scans (milliseconds)
            xPeriod: Period between successive IEEE802.15.4 ED Scans (milliseconds)
            xScanDuration: IEEE 802.15.4 ScanDuration to use when performing an IEEE 802.15.4 ED Scan (milliseconds)

        Returns:
            True: successful to send MGMT_ED_SCAN message.
            False: fail to send MGMT_ED_SCAN message
        """
        print '%s call MGMT_ED_SCAN' % self.port
        channelMask = ''
        channelMask = '0x' + self.__convertLongToString(self.__convertChannelMask(listChannelMask))
        try:
            cmd = 'commissioner energy %s %s %s %s %s' % (channelMask, xCount, xPeriod, xScanDuration, sAddr)
            print cmd
            return self.__sendCommand(cmd) == 'Done'
        except Exception, e:
            ModuleHelper.writeintodebuglogger("MGMT_ED_SCAN() error: " + str(e))


Instruction:
Write a Python 3 function that can
send MGMT_PANID_QUERY message to a given destination

Response:
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: fail to send MGMT_PANID_QUERY message.
        """
        print '%s call MGMT_PANID_QUERY' % self.port
        panid = ''
        channelMask = ''
        channelMask = '0x' + self.__convertLongToString(self.__convertChannelMask(listChannelMask))

        if not isinstance(xPanId, str):
            panid = str(hex(xPanId))

        try:
            cmd = 'commissioner panid %s %s %s' % (panid, channelMask, sAddr)
            print cmd
            return self.__sendCommand(cmd) == 'Done'
        except Exception, e:
            ModuleHelper.writeintodebuglogger("MGMT_PANID_QUERY() error: " + str(e))


Instruction:
Can you generate the documentation for the following Python 3 function
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, xSteeringData=None, xBorderRouterLocator=None, BogusTLV=None, xDelayTimer=None):
        """send MGMT_ACTIVE_SET command

        Returns:
            True: successful to send MGMT_ACTIVE_SET
            False: fail to send MGMT_ACTIVE_SET
        """
        print '%s call MGMT_ACTIVE_SET' % self.port
        try:
            cmd = 'dataset mgmtsetcommand active'

            if listActiveTimestamp != None:
                cmd += ' activetimestamp '
                cmd += str(listActiveTimestamp[0])

            if xExtendedPanId != None:
                cmd += ' extpanid '
                xpanid = self.__convertLongToString(xExtendedPanId)

                if len(xpanid) < 16:
                    xpanid = xpanid.zfill(16)

                cmd += xpanid

            if sNetworkName != None:
                cmd += ' networkname '
                cmd += str(sNetworkName)

            if xChannel != None:
                cmd += ' channel '
                cmd += str(xChannel)

            if sMeshLocalPrefix != None:
                cmd += ' localprefix '
                cmd += str(sMeshLocalPrefix)

            if xMasterKey != None:
                cmd += ' masterkey '
                key = self.__convertLongToString(xMasterKey)

                if len(key) < 32:
                    key = key.zfill(32)

                cmd += key

            if xPanId != None:
                cmd += ' panid '
                cmd += str(xPanId)

            if listChannelMask != None:
                cmd += ' channelmask '
                cmd += '0x' + self.__convertLongToString(self.__convertChannelMask(listChannelMask))

            if sPSKc != None or listSecurityPolicy != None or \
               xCommissioningSessionId != None or xTmfPort != None or xSteeringData != None or xBorderRouterLocator != None or \
               BogusTLV != None:
                cmd += ' binary '

            if sPSKc != None:
                cmd += '0410'
                stretchedPskc = Thread_PBKDF2.get(sPSKc,ModuleHelper.Default_XpanId,ModuleHelper.Default_NwkName)
                pskc = hex(stretchedPskc).rstrip('L').lstrip('0x')

                if len(pskc) < 32:
                    pskc = pskc.zfill(32)

                cmd += pskc

            if listSecurityPolicy != None:
                cmd += '0c03'

                rotationTime = 0
                policyBits = 0

                # previous passing way listSecurityPolicy=[True, True, 3600, False, False, True]
                if (len(listSecurityPolicy) == 6):
                    rotationTime = listSecurityPolicy[2]

                    # the last three reserved bits must be 1
                    policyBits = 0b00000111

                    if listSecurityPolicy[0]:
                        policyBits = policyBits | 0b10000000
                    if listSecurityPolicy[1]:
                        policyBits = policyBits | 0b01000000
                    if listSecurityPolicy[3]:
                        policyBits = policyBits | 0b00100000
                    if listSecurityPolicy[4]:
                        policyBits = policyBits | 0b00010000
                    if listSecurityPolicy[5]:
                        policyBits = policyBits | 0b00001000
                else:
                    # new passing way listSecurityPolicy=[3600, 0b11001111]
                    rotationTime = listSecurityPolicy[0]
                    policyBits = listSecurityPolicy[1]

                policy = str(hex(rotationTime))[2:]

                if len(policy) < 4:
                    policy = policy.zfill(4)

                cmd += policy

                cmd += str(hex(policyBits))[2:]

            if xCommissioningSessionId != None:
                cmd += '0b02'
                sessionid = str(hex(xCommissioningSessionId))[2:]

                if len(sessionid) < 4:
                    sessionid = sessionid.zfill(4)

                cmd += sessionid

            if xBorderRouterLocator != None:
                cmd += '0902'
                locator = str(hex(xBorderRouterLocator))[2:]

                if len(locator) < 4:
                    locator = locator.zfill(4)

                cmd += locator

            if xSteeringData != None:
                steeringData = self.__convertLongToString(xSteeringData)
                cmd += '08' + str(len(steeringData)/2).zfill(2)
                cmd += steeringData

            if BogusTLV != None:
                cmd += "8202aa55"

            print cmd

            return self.__sendCommand(cmd)[0] == 'Done'

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("MGMT_ACTIVE_SET() Error: " + str(e))

Response: send MGMT_ACTIVE_SET command to set the state of the active MESH in the specified session


Instruction:
Write a Python 3 function for
sending MGMT_PENDING_SET command to the device

Response:
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:
            True: successful to send MGMT_PENDING_SET
            False: fail to send MGMT_PENDING_SET
        """
        print '%s call MGMT_PENDING_SET' % self.port
        try:
            cmd = 'dataset mgmtsetcommand pending'

            if listPendingTimestamp != None:
                cmd += ' pendingtimestamp '
                cmd += str(listPendingTimestamp[0])

            if listActiveTimestamp != None:
                cmd += ' activetimestamp '
                cmd += str(listActiveTimestamp[0])

            if xDelayTimer != None:
                cmd += ' delaytimer '
                cmd += str(xDelayTimer)
                #cmd += ' delaytimer 3000000'

            if xChannel != None:
                cmd += ' channel '
                cmd += str(xChannel)

            if xPanId != None:
                cmd += ' panid '
                cmd += str(xPanId)

            if xMasterKey != None:
                cmd += ' masterkey '
                key = self.__convertLongToString(xMasterKey)

                if len(key) < 32:
                    key = key.zfill(32)

                cmd += key

            if sMeshLocalPrefix != None:
                cmd += ' localprefix '
                cmd += str(sMeshLocalPrefix)

            if sNetworkName != None:
                cmd += ' networkname '
                cmd += str(sNetworkName)

            if xCommissionerSessionId != None:
                cmd += ' binary '
                cmd += '0b02'
                sessionid = str(hex(xCommissionerSessionId))[2:]

                if len(sessionid) < 4:
                    sessionid = sessionid.zfill(4)

                cmd += sessionid

            print cmd

            return self.__sendCommand(cmd)[0] == 'Done'

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("MGMT_PENDING_SET() Error: " + str(e))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def MGMT_COMM_GET(self, Addr='ff02::1', TLVs=[]):
        print '%s call MGMT_COMM_GET' % self.port
        try:
            cmd = 'commissioner mgmtget'

            if len(TLVs) != 0:
                tlvs = "".join(hex(tlv).lstrip("0x").zfill(2) for tlv in TLVs)
                cmd += ' binary '
                cmd += tlvs

            print cmd

            return self.__sendCommand(cmd)[0] == 'Done'

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("MGMT_COMM_GET() Error: " + str(e))

Response:
send MGMT_COMM_GET command

        Returns:
            True: successful to send MGMT_COMM_GET
            False: fail to send MGMT_COMM_GET


Instruction:
Make a summary of the following Python 3 code
def setUdpJoinerPort(self, portNumber):
        print '%s call setUdpJoinerPort' % self.port
        cmd = 'joinerport %d' % portNumber
        print cmd
        return self.__sendCommand(cmd)[0] == 'Done'

Response: set Joiner UDP Port


Instruction:
How would you implement a function in Python 3 that
stops commissioner Returns: True: successful to stop commissioner False: fail to stop commissioner

Response:
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.__sendCommand(cmd)[0] == 'Done'


Instruction:
Write a Python 3 function that can
force update to router as if there is child id request

Response:
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 state == 'child':
                break
            else:
                return False

        cmd = 'state router'
        return self.__sendCommand(cmd)[0] == 'Done'


Instruction:
Write a Python 3 script 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
        """
        logger.debug('[%s] Expecting [%s]', self.port, expected)
        retry_times = 10
        while times:
            if not retry_times:
                break

            line = self._readline()

            if line == expected:
                return

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

            times -= 1

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


Instruction:
Given the following Python 3 function, write the documentation
def _readline(self):
        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('No new data')
            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 nonblocking.


Instruction:
Implement a Python 3 function 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
        """
        self.lines = []
        try:
            self._read()
        except socket.error:
            logging.debug('Nothing cleared')

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

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


Instruction:
Can you generate the documentation for the following Python 3 function
def _req(self, req):
        logger.debug('DUT> %s', req)
        self._log and self.pause()
        times = 3
        res = None

        while times:
            times = times - 1
            try:
                self._sendline(req)
                self._expect(req)

                line = None
                res = []

                while True:
                    line = self._readline()
                    logger.debug('Got line %s', line)

                    if line == 'Done':
                        break

                    if line:
                        res.append(line)
                break

            except:
                logger.exception('Failed to send command')
                self.close()
                self._init()

        self._log and self.resume()
        return res

Response: Send command and wait for response.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def reset(self):
        logger.debug('DUT> reset')
        self._log and self.pause()
        self._sendline('reset')
        self._read()
        self._log and self.resume()

Response: Reset the openthread device not equivalent to stop and start


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_prefix(self, prefix, flags, prf):
        self._req('prefix add %s %s %s' % (prefix, flags, prf))
        time.sleep(1)
        self._req('netdataregister')

Response: Add a network prefix.


Instruction:
Write a Python 3 function for
initializing the telnet connection

Response:
def _init(self):
        """Initialize the telnet connection
        """
        self.tn = telnetlib.Telnet(self.ip, self.port)
        self.tn.read_until('User Name')
        self.tn.write('apc\r\n')
        self.tn.read_until('Password')
        self.tn.write('apc\r\n')
        self.until_done()


Instruction:
Make a summary of the following Python 3 code
def open(self, **params):
        logger.info('opening telnet')
        self.port = params['port']
        self.ip = params['ip']
        self.tn = None
        self._init()

Response: Open a new telnet connection


Instruction:
Write a Python 3 function for
waiting until the regex encountered

Response:
def until(self, regex):
        """Wait until the regex encountered
        """
        logger.debug('waiting for %s', regex)
        r = re.compile(regex, re.M)
        self.tn.expect([r])


Instruction:
Make a summary of the following Python 3 code
def __sendCommand(self, cmd):
        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

        ssh_stdin = None
        ssh_stdout = None
        ssh_stderr = None
        try:
            # command retransmit times
            retry_times = 3
            while retry_times > 0:
                retry_times -= 1
                try:
                    if self._is_net:
                        ssh_stdin, ssh_stdout, ssh_stderr = self.handle.exec_command(cmd)
                    else:
                        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 = 20
            stdout_lines = []
            stderr_lines = []
            if self._is_net:
                stdout_lines = ssh_stdout.readlines()
                stderr_lines = ssh_stderr.readlines()
                if stderr_lines:
                    for stderr_line in stderr_lines:
                        if re.search(r'Not\s+Found|failed\s+with\s+error', stderr_line.strip(), re.M | re.I):
                            print "Command failed:" + stderr_line
                            return 'Fail'
                        print "Got line: " + stderr_line
                        logging.info('%s: the read line is[%s]', self.port, stderr_line)
                        response.append(str(stderr_line.strip()))
                elif stdout_lines:
                    for stdout_line in stdout_lines:
                        logging.info('%s: the read line is[%s]', self.port, stdout_line)
                        if re.search(r'Not\s+Found|failed\s+with\s+error', stdout_line.strip(), re.M | re.I):
                            print "Command failed"
                            return 'Fail'
                        print "Got line: " + stdout_line
                        logging.info('%s: send command[%s] done!', self.port, cmd)
                        response.append(str(stdout_line.strip()))
                response.append(WPAN_CARRIER_PROMPT)
                return response
            else:
                while retry_times > 0:
                    line = self._readline()
                    print "read line: %s" % line
                    logging.info('%s: the read line is[%s]', self.port, line)
                    if line:
                        response.append(line)
                        if re.match(WPAN_CARRIER_PROMPT, line):
                            break
                        elif re.search(r'Not\s+Found|failed\s+with\s+error', line, re.M | re.I):
                            print "Command failed"
                            return 'Fail'

                    retry_times -= 1
                    time.sleep(0.1)

                if retry_times == 0:
                    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

Response: send specific command to the reference unit and parse the result


Instruction:
How would you explain what the following Python 3 function does
def __stripValue(self, value):
        if isinstance(value, str):
            if ( value[0] == '"' and value[-1] == '"' ) or ( value[0] == '[' and value[-1] == ']' ):
                return value[1:-1]
        return value

Response:
strip the special characters in the value
COOKIENAME


Instruction:
Given the following Python 3 function, write the documentation
def __getIp6Address(self, addressType):
        addrType = ['link local', 'global', 'rloc', 'mesh EID']
        addrs = []
        globalAddr = []
        linkLocal64Addr = ''
        rlocAddr = ''
        meshEIDAddr = ''

        addrs = self.__sendCommand(WPANCTL_CMD + 'getprop -v IPv6:AllAddresses')
        for ip6AddrItem in addrs:
            if re.match('\[|\]', ip6AddrItem):
                continue
            if re.match(WPAN_CARRIER_PROMPT, ip6AddrItem, re.M|re.I):
                break
            ip6AddrItem = ip6AddrItem.strip()
            ip6Addr = self.__stripValue(ip6AddrItem).split(' ')[0]
            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
                    print 'meshEIDAddr:' + meshEIDAddr
            else:
                # global ipv6 address
                if ip6Addr:
                    print 'globalAddr: ' + ip6Addr
                    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

Response: get specific type of IPv6 address configured on OpenThread_WpanCtl


Instruction:
Write a Python 3 script to
set the thread device mode

Response:
def __setDeviceMode(self, mode):
        """set thread device mode:

        Args:
           mode: thread device mode. 15=rsdn, 13=rsn, 4=s
           r: rx-on-when-idle
           s: secure IEEE 802.15.4 data request
           d: full thread device
           n: full network data

        Returns:
           True: successful to set the device mode
           False: fail to set the device mode
        """
        print 'call __setDeviceMode'

        try:
            cmd = WPANCTL_CMD + 'setprop Thread:DeviceMode %d' % mode
            return self.__sendCommand(cmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setDeviceMode() Error: ' + str(e))


Instruction:
Explain what the following Python 3 code does
def __setAddressfilterMode(self, mode):
        print 'call setAddressFilterMode() ' +  mode
        try:
            if re.match('list', mode, re.M|re.I):
                cmd = WPANCTL_CMD + 'setprop MAC:' + mode + ':Enabled 1'
            elif mode == 'disabled':
                cmd = WPANCTL_CMD + 'setprop MAC:' + mode + ':Enabled 0'
            else:
                print 'no such option'
                return False
            if self.__sendCommand(cmd)[0] != 'Fail':
                return True
            return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('__setAddressFilterMode() Error: ' + str(e))

Response: set the address filter mode for the current user


Instruction:
Can you generate the documentation for the following Python 3 function
def __startOpenThreadWpan(self):
        print 'call startOpenThreadWpan'
        try:

            # 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)
            time.sleep(1)
            if ModuleHelper.LeaderDutChannelFound:
                self.channel = ModuleHelper.Default_Channel
            nodeType = 'router'
            startType = 'join'
            if self.deviceRole == Thread_Device_Role.Leader:
                nodeType = 'router'
                startType = 'form'
            elif self.deviceRole == Thread_Device_Role.Router:
                nodeType = 'router'
            elif self.deviceRole == Thread_Device_Role.SED:
                nodeType = 'sed'
            elif self.deviceRole == Thread_Device_Role.EndDevice:
                nodeType = 'end'
            elif self.deviceRole == Thread_Device_Role.REED:
                nodeType = 'router'
            elif self.deviceRole == Thread_Device_Role.EndDevice_FED:
                nodeType = 'router'
            elif self.deviceRole == Thread_Device_Role.EndDevice_MED:
                nodeType = 'end'
            else:
                pass

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

            if startType == 'form':
                startCmd = WPANCTL_CMD + '%s %s -c %s -T %s ' % (startType, self.networkName, str(self.channel), nodeType)
            else:
                startCmd = WPANCTL_CMD + '%s %s -p %s -c %s -T %s ' % (startType, self.networkName, str(hex(self.panId)), str(self.channel), nodeType)
            if self.__sendCommand(startCmd)[0] != 'Fail':
                if self.__isOpenThreadWpanRunning():
                    self.isPowerDown = False
                    if self.hasActiveDatasetToCommit:
                        if self.__sendCommand(WPANCTL_CMD + 'setprop Dataset:Command SetActive')[0] == 'Fail':
                            raise Exception('failed to commit active dataset')
                        else:
                            self.hasActiveDatasetToCommit = False

                    return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('startOpenThreadWpan() Error: ' + str(e))

Response: start OpenThreadWpan with the current Thread_Device_Role


Instruction:
Implement a function in Python 3 to
stop OpenThreadWpan Returns: True: successfully stop OpenThreadWpan False: failed to stop OpenThreadWpan

Response:
def __stopOpenThreadWpan(self):
        """stop OpenThreadWpan

        Returns:
            True: successfully stop OpenThreadWpan
            False: failed to stop OpenThreadWpan
        """
        print 'call stopOpenThreadWpan'
        try:
            if self.__sendCommand(WPANCTL_CMD + 'leave')[0] != 'Fail' and self.__sendCommand(WPANCTL_CMD + 'dataset erase')[0] != 'Fail':
                return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('stopOpenThreadWpan() Error: ' + str(e))


Instruction:
Implement a Python 3 function for
checking whether or not the OpenThreadWpan is running

Response:
def __isOpenThreadWpanRunning(self):
        """check whether or not OpenThreadWpan is running

        Returns:
            True: OpenThreadWpan is running
            False: OpenThreadWpan is not running
        """
        print 'call __isOpenThreadWpanRunning'
        if self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0]) == 'associated':
            print '*****OpenThreadWpan is running'
            return True
        else:
            print '*****Wrong OpenThreadWpan state'
            return False


Instruction:
Can you tell what is the following Python 3 function doing
def __convertRlocToRouterId(self, xRloc16):
        routerList = []
        routerList = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:RouterTable')
        print routerList
        print xRloc16

        for line in routerList:
            if re.match('\[|\]', line):
                continue
            if re.match(WPAN_CARRIER_PROMPT, line, re.M|re.I):
                break
            router = []
            router = self.__stripValue(line).split(',')

            for item in router:
                if 'RouterId' in item:
                    routerid = item.split(':')[1]
                elif 'RLOC16' 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: converts RLOC16 to RouterId


Instruction:
Make a summary of the following Python 3 code
def __ChannelMaskListToStr(self, channelList):
        chan_mask_range = ''
        if isinstance(channelList, list):
            if len(channelList):
                chan_mask_range = ",".join(str(chan) for chan in channelList)
            else:
                print 'empty list'
        else:
            print 'not a valid channel list:', channelList

        return chan_mask_range

Response: convert a list of channels to a comma separated string


Instruction:
Can you generate a brief explanation for the following Python 3 code
def intialize(self):
        print '%s call intialize' % self.port
        try:
            # init serial port
            self.deviceConnected = False
            self._connect()

            if self.deviceConnected:
                self.UIStatusMsg = self.getVersionNumber()
                if self.firmwarePrefix not in self.UIStatusMsg:
                    self.deviceConnected = False
                    self.UIStatusMsg = 'Firmware Not Matching Expecting ' + self.firmwarePrefix + ' Now is ' + self.UIStatusMsg
                    raise Exception('Err: OpenThread device Firmware not matching..')
                self.__sendCommand(WPANCTL_CMD + 'leave')
                self.__sendCommand(WPANCTL_CMD + 'dataset erase')
            else:
                raise Exception('Err: Device not connected ..')

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('intialize() Error: ' + str(e))

Response: initialize the serial port with baudrate timeout parameters


Instruction:
How would you explain what the following Python 3 function does
def getNetworkName(self):
        print '%s call getNetworkname' % self.port
        networkName = self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:Name')[0]
        return self.__stripValue(networkName)

Response: get Thread Network name


Instruction:
Can you create a Python 3 function that
sets the extended address of Thread device

Response:
def setMAC(self, xEUI):
        """set the extended addresss of Thread device

        Args:
            xEUI: extended address in hex format

        Returns:
            True: successful to set the extended address
            False: fail to set the extended address
        """
        print '%s call setMAC' % self.port

        address64 = ''
        try:
            if not xEUI:
                address64 = self.mac

            if not isinstance(xEUI, str):
                address64 = self.__convertLongToString(xEUI)

                # prepend 0 at the beginning
                if len(address64) < 16:
                    address64 = address64.zfill(16)
                    print address64
            else:
                address64 = xEUI

            cmd = WPANCTL_CMD + 'setprop NCP:MACAddress %s' % address64

            if self.__sendCommand(cmd)[0] != 'Fail':
                self.mac = address64
                return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setMAC() Error: ' + str(e))


Instruction:
Make a summary of the following Python 3 code
def getMAC(self, bType=MacType.RandomMac):
        print '%s call getMAC' % self.port

        # if power down happens, return extended address assigned previously
        if self.isPowerDown:
            macAddr64 = self.mac
        else:
            if bType == MacType.FactoryMac:
                macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:HardwareAddress')[0])
            elif bType == MacType.HashMac:
                macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:MACAddress')[0])
            else:
                macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:ExtendedAddress')[0])

        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 getLL64(self):
        print '%s call getLL64' % self.port
        return self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v IPv6:LinkLocalAddress')[0])

Response: get link local unicast IPv6 address


Instruction:
Create a Python 3 function for
getting router locator unicast IPv6 address

Response:
def getRloc(self):
        """get router locator unicast IPv6 address"""
        print '%s call getRloc' % self.port
        prefix = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v IPv6:MeshLocalPrefix')[0])
        mlprefix = prefix.split('/')[0]
        rloc16 = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:RLOC16')[0].lstrip('0x')
        print "prefix: " + prefix
        print "mlprefix: " + mlprefix
        print "rloc16: " + rloc16

        rloc = self.__padIp6Addr(mlprefix + '00ff:fe00:' + rloc16)
        print "rloc: " + rloc
        return rloc


Instruction:
How would you code a function in Python 3 to
set Thread Network master key used in secure the MLE / 802. 15. 4 packet

Response:
def setNetworkKey(self, key):
        """set Thread Network master key

        Args:
            key: Thread Network master key used in secure the MLE/802.15.4 packet

        Returns:
            True: successful to set the Thread Network master key
            False: fail to set the Thread Network master key
        """
        masterKey = ''
        print '%s call setNetworkKey' % self.port

        try:
            if not isinstance(key, str):
                masterKey = self.__convertLongToString(key)

                # prpend '0' at the beginning
                if len(masterKey) < 32:
                    masterKey = masterKey.zfill(32)

                cmd = WPANCTL_CMD + 'setprop Network:Key %s' % masterKey
                datasetCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey %s' % masterKey
            else:
                masterKey = key
                cmd = WPANCTL_CMD + 'setprop Network:Key %s' % masterKey
                datasetCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey %s' % masterKey

            self.networkKey = masterKey
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setNetworkkey() Error: ' + str(e))


Instruction:
Can you generate the documentation for the following Python 3 function
def addAllowMAC(self, xEUI):
        print '%s call addAllowMAC' % self.port
        print xEUI
        if isinstance(xEUI, str):
            macAddr = xEUI
        else:
            macAddr = self.__convertLongToString(xEUI)

        try:
            if self._addressfilterMode != 'whitelist':
                if self.__setAddressfilterMode('Whitelist'):
                    self._addressfilterMode = 'whitelist'

            cmd = WPANCTL_CMD + 'insert MAC:Whitelist:Entries %s' % macAddr
            ret = self.__sendCommand(cmd)[0] != 'Fail'

            self._addressfilterSet.add(macAddr)
            print 'current whitelist entries:'
            for addr in self._addressfilterSet:
                print addr
            return ret

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('addAllowMAC() Error: ' + str(e))

Response: add a given extended address to the whitelist


Instruction:
Implement a Python 3 function for
clearing all entries in whitelist table

Response:
def clearAllowList(self):
        """clear all entries in whitelist table

        Returns:
            True: successful to clear the whitelist
            False: fail to clear the whitelist
        """
        print '%s call clearAllowList' % self.port

        # remove all entries in whitelist
        try:
            print 'clearing whitelist entries:'
            for addr in self._addressfilterSet:
                print addr

            # disable whitelist
            if self.__setAddressfilterMode('disable'):
                self._addressfilterMode = 'disable'
                # clear ops
                cmd = WPANCTL_CMD + 'insert MAC:Whitelist:Entries'
                if self.__sendCommand(cmd)[0] != 'Fail':
                    self._addressfilterSet.clear()
                    return True
            return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('clearAllowList() Error: ' + str(e))


Instruction:
Implement a function in Python 3 to
get current device role in Thread Network

Response:
def getDeviceRole(self):
        """get current device role in Thread Network"""
        print '%s call getDeviceRole' % self.port
        return self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:NodeType')[0])


Instruction:
How would you implement a function in Python 3 that
makes device ready to join the Thread Network with a given role id

Response:
def joinNetwork(self, eRoleId):
        """make device ready to join the Thread Network with a given role

        Args:
            eRoleId: a given device role id

        Returns:
            True: ready to set Thread Network parameter for joining desired Network
        """
        print '%s call joinNetwork' % self.port
        print eRoleId

        self.deviceRole = eRoleId
        mode = 15
        try:
            if ModuleHelper.LeaderDutChannelFound:
                self.channel = ModuleHelper.Default_Channel

            # FIXME: when Harness call setNetworkDataRequirement()?
            # only sleep end device requires stable networkdata now
            if eRoleId == Thread_Device_Role.Leader:
                print 'join as leader'
                #rsdn
                mode = 15
                if self.AutoDUTEnable is False:
                    # set ROUTER_DOWNGRADE_THRESHOLD
                    self.__setRouterDowngradeThreshold(33)
            elif eRoleId == Thread_Device_Role.Router:
                print 'join as router'
                #rsdn
                mode = 15
                if self.AutoDUTEnable is False:
                    # set ROUTER_DOWNGRADE_THRESHOLD
                    self.__setRouterDowngradeThreshold(33)
            elif eRoleId == Thread_Device_Role.SED:
                print 'join as sleepy end device'
                #s
                mode = 4
                self.setPollingRate(self.sedPollingRate)
            elif eRoleId == Thread_Device_Role.EndDevice:
                print 'join as end device'
                #rsn
                mode = 13
            elif eRoleId == Thread_Device_Role.REED:
                print 'join as REED'
                #rsdn
                mode = 15
                # set ROUTER_UPGRADE_THRESHOLD
                self.__setRouterUpgradeThreshold(0)
            elif eRoleId == Thread_Device_Role.EndDevice_FED:
                # always remain an ED, never request to be a router
                print 'join as FED'
                #rsdn
                mode = 15
                # set ROUTER_UPGRADE_THRESHOLD
                self.__setRouterUpgradeThreshold(0)
            elif eRoleId == Thread_Device_Role.EndDevice_MED:
                print 'join as MED'
                #rsn
                mode = 13
            else:
                pass

            # set Thread device mode with a given role
            self.__setDeviceMode(mode)
            self.__setKeySwitchGuardTime(0)  #temporally
            time.sleep(0.1)
            # start OpenThreadWpan
            self.__startOpenThreadWpan()
            time.sleep(3)
            return True
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('joinNetwork() Error: ' + str(e))


Instruction:
Write a Python 3 script for
getting current Thread Network Partition from LeaderData

Response:
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.____isOpenThreadWpanRunning():
            print 'OpenThreadWpan is not running'
            return None

        return self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:PartitionId')[0]


Instruction:
Write a Python 3 function for
getting Thread device s parent extended address and rloc16 short address

Response:
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.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getporp -v Thread:Parent')).split(' ')

        return parentInfo[0]


Instruction:
Write a Python 3 function for
powering down the OpenThreadWpan

Response:
def powerDown(self):
        """power down the OpenThreadWpan"""
        print '%s call powerDown' % self.port
        if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false')[0] != 'Fail':
            time.sleep(0.5)
            if self.__sendCommand(WPANCTL_CMD + 'reset')[0] != 'Fail':
                self.isPowerDown = True
                return True
            else:
                return False
        else:
            return False


Instruction:
Can you generate the documentation for the following Python 3 function
def powerUp(self):
        print '%s call powerUp' % self.port
        if not self.handle:
            self._connect()

        self.isPowerDown = False
        if self.__sendCommand(WPANCTL_CMD + 'attach')[0] != 'Fail':
            time.sleep(3)
        else:
            return False

        if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset true')[0] == 'Fail':
            return False

        if self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0]) != 'associated':
            print 'powerUp failed'
            return False
        else:
            return True

Response: power up the Thread device


Instruction:
Write a Python 3 function for
resetting and rejoin Thread Network with 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(WPANCTL_CMD + 'reset')
            self.isPowerDown = True

            if self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0] != 'associated':
                print '[FAIL] reboot'
                return False
            else:
                return True
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('reboot() Error: ' + str(e))


Instruction:
How would you code a function in Python 3 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 -c 1 -s %s -I %s'  % (destination, str(length), WPAN_INTERFACE)
            if self._is_net:
                ssh_stdin, ssh_stdout, ssh_stderr = self.handle.exec_command(cmd)
            else:
                self._sendline(cmd)
                self._expect(cmd)
            # wait echo reply
            time.sleep(1)
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('ping() Error: ' + str(e))


Instruction:
Create a Python 3 function for
getting OpenThreadWpan stack firmware version number

Response:
def getVersionNumber(self):
        """get OpenThreadWpan stack firmware version number"""
        print '%s call getVersionNumber' % self.port
        versionStr = self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:Version')[0]

        return self.__stripValue(versionStr)


Instruction:
Write a Python 3 function for
setting Thread Network PAN ID to a given PAN ID

Response:
def setPANID(self, xPAN):
        """set Thread Network PAN ID

        Args:
            xPAN: a given PAN ID in hex format

        Returns:
            True: successful to set the Thread Network PAN ID
            False: fail to set the Thread Network PAN ID
        """
        print '%s call setPANID' % self.port
        print xPAN
        panid = ''
        try:
            if not isinstance(xPAN, str):
                panid = str(hex(xPAN))
                print panid

            cmd = WPANCTL_CMD + 'setprop -s Network:PANID %s' % panid
            datasetCmd = WPANCTL_CMD + 'setprop Dataset:PanId %s' % panid
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setPANID() Error: ' + str(e))


Instruction:
Can you write a function in Python 3 where it
resets the internal state of the object

Response:
def reset(self):
        """factory reset"""
        print '%s call reset' % self.port
        try:
            if self._is_net:
                self.__sendCommand(WPANCTL_CMD + 'leave')
            else:
                self._sendline(WPANCTL_CMD + 'leave')

            self.__sendCommand(WPANCTL_CMD + 'dataset erase')
            time.sleep(2)
            if not self._is_net:
                self._read()
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('reset() Error: ' + str(e))


Instruction:
Explain what the following Python 3 code does
def removeRouter(self, xRouterId):
        print '%s call removeRouter' % self.port
        print xRouterId
        routerId = ''
        routerId = self.__convertRlocToRouterId(xRouterId)
        print routerId

        if routerId == None:
            print 'no matched xRouterId'
            return False

        try:
            cmd = 'releaserouterid %s' % routerId
            return self.__sendCommand(cmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('removeRouter() Error: ' + str(e))

Response:
kick router with a given router id from the Thread Network Network
            returns True if the router was removed False otherwise


Instruction:
Can you generate the documentation for the following Python 3 function
def setDefaultValues(self):
        print '%s call setDefaultValues' % self.port

        # initialize variables
        self.networkName = ModuleHelper.Default_NwkName
        self.networkKey = ModuleHelper.Default_NwkKey
        self.channel = ModuleHelper.Default_Channel
        self.channelMask = "0x7fff800" #(0xffff << 11)
        self.panId = ModuleHelper.Default_PanId
        self.xpanId = ModuleHelper.Default_XpanId
        self.meshLocalPrefix = ModuleHelper.Default_MLPrefix
        self.pskc = "00000000000000000000000000000000"  # OT only accept hex format PSKc for now
        self.securityPolicySecs = ModuleHelper.Default_SecurityPolicy
        self.securityPolicyFlags = "onrcb"
        self.activetimestamp = ModuleHelper.Default_ActiveTimestamp
        #self.sedPollingRate = ModuleHelper.Default_Harness_SED_Polling_Rate
        self.sedPollingRate = 3
        self.deviceRole = None
        self.provisioningUrl = ''
        self.hasActiveDatasetToCommit = False
        self.logThread = Queue()
        self.logThreadStatus = self.logStatus['stop']
        self.networkDataRequirement = ''      # indicate Thread device requests full or stable network data
        self.isPowerDown = False              # indicate if Thread device experiences a power down event
        self._addressfilterMode = 'disable'   # indicate AddressFilter mode ['disable', 'whitelist', 'blacklist']
        self._addressfilterSet = set()        # cache filter entries
        self.isActiveCommissioner = False     # indicate if Thread device is an active commissioner
        self._lines = None                    # buffered lines read from device

        # initialize device configuration
        try:
            self.setMAC(self.mac)
            self.__setChannelMask(self.channelMask)
            self.__setSecurityPolicy(self.securityPolicySecs, self.securityPolicyFlags)
            self.setChannel(self.channel)
            self.setPANID(self.panId)
            self.setXpanId(self.xpanId)
            self.setNetworkName(self.networkName)
            self.setNetworkKey(self.networkKey)
            self.setMLPrefix(self.meshLocalPrefix)
            self.setPSKc(self.pskc)
            self.setActiveTimestamp(self.activetimestamp)
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setDefaultValue() Error: ' + str(e))

Response: set default mandatory Thread Network parameter value


Instruction:
Can you implement a function in Python 3 that
sets data polling rate for sleepy end device

Response:
def setPollingRate(self, iPollingRate):
        """set data polling rate for sleepy end device

        Args:
            iPollingRate: data poll period of sleepy end device

        Returns:
            True: successful to set the data polling rate for sleepy end device
            False: fail to set the data polling rate for sleepy end device
        """
        print '%s call setPollingRate' % self.port
        print iPollingRate
        try:
            cmd = WPANCTL_CMD + 'setprop NCP:SleepyPollInterval %s' % str(iPollingRate*1000)
            print cmd
            return self.__sendCommand(cmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setPollingRate() Error: ' + str(e))


Instruction:
Given the following Python 3 function, write the documentation
def resetAndRejoin(self, timeout):
        print '%s call resetAndRejoin' % self.port
        print timeout
        try:
            if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false')[0] != 'Fail':
                time.sleep(0.5)
                if self.__sendCommand(WPANCTL_CMD + 'reset')[0] != 'Fail':
                    self.isPowerDown = True
                else:
                    return False
            else:
                return False
            time.sleep(timeout)

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

            if self.__sendCommand(WPANCTL_CMD + 'attach')[0] != 'Fail':
                time.sleep(3)
            else:
                return False

            if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset true')[0] == 'Fail':
                return False

            if self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0]) != 'associated':
                print '[FAIL] reset and rejoin'
                return False
            return True
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('resetAndRejoin() Error: ' + str(e))

Response: reset and rejoin Thread Network with a given timeout delay


Instruction:
Write a Python 3 function that can
configure the border router with a given prefix entry parameters

Response:
def configBorderRouter(self, P_Prefix, P_stable=1, P_default=1, P_slaac_preferred=0, P_Dhcp=0, P_preference=0, P_on_mesh=1, P_nd_dns=0):
        """configure the border router with a given prefix entry parameters

        Args:
            P_Prefix: IPv6 prefix that is available on the Thread Network
            P_stable: is true if the default router is expected to be stable network data
            P_default: is true if border router offers the default route for P_Prefix
            P_slaac_preferred: is true if Thread device is allowed auto-configure address using P_Prefix
            P_Dhcp: is true if border router is a DHCPv6 Agent
            P_preference: is two-bit signed integer indicating router preference
            P_on_mesh: is true if P_Prefix is considered to be on-mesh
            P_nd_dns: is true if border router is able to supply DNS information obtained via ND

        Returns:
            True: successful to configure the border router with a given prefix entry
            False: fail to configure the border router with a given prefix entry
        """
        print '%s call configBorderRouter' % self.port
        prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix))
        print prefix
        try:
            parameter = ''

            if P_slaac_preferred == 1:
                parameter += ' -a -f'

            if P_stable == 1:
                parameter += ' -s'

            if P_default == 1:
                parameter += ' -r'

            if P_Dhcp == 1:
                parameter += ' -d'

            if P_on_mesh == 1:
                parameter += ' -o'

            cmd = WPANCTL_CMD + 'add-prefix %s %s -P %d' % (prefix, parameter, P_preference)
            print parameter
            print cmd
            if self.__sendCommand(cmd)[0] != 'Fail':
                return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('configBorderRouter() Error: ' + str(e))


Instruction:
Make a summary of the following Python 3 code
def setKeepAliveTimeOut(self, iTimeOut):
        print '%s call setKeepAliveTimeOut' % self.port
        print iTimeOut
        try:
            cmd = WPANCTL_CMD + 'setprop NCP:SleepyPollInterval %s' % str(iTimeOut*1000)
            print cmd
            return self.__sendCommand(cmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setKeepAliveTimeOut() Error: ' + str(e))

Response: set keep alive timeout for a specific NCP device


Instruction:
Write a Python 3 function that can
set the Thread Network master key sequence counter corresponding to Thread Network master key sequence value

Response:
def setKeySequenceCounter(self, iKeySequenceValue):
        """ set the Key sequence counter corresponding to Thread Network master key

        Args:
            iKeySequenceValue: key sequence value

        Returns:
            True: successful to set the key sequence
            False: fail to set the key sequence
        """
        print '%s call setKeySequenceCounter' % self.port
        print iKeySequenceValue
        try:
            cmd = WPANCTL_CMD + 'setprop Network:KeyIndex %s' % str(iKeySequenceValue)
            if self.__sendCommand(cmd)[0] != 'Fail':
                time.sleep(1)
                return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setKeySequenceCounter() Error: ' + str(e))


Instruction:
Write a Python 3 function for
getting current Thread Network key sequence

Response:
def getKeySequenceCounter(self):
        """get current Thread Network key sequence"""
        print '%s call getKeySequenceCounter' % self.port
        keySequence = ''
        keySequence = self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:KeyIndex')[0]
        return keySequence


Instruction:
Can you generate a brief explanation for the following Python 3 code
def incrementKeySequenceCounter(self, iIncrementValue=1):
        print '%s call incrementKeySequenceCounter' % self.port
        print iIncrementValue
        currentKeySeq = ''
        try:
            currentKeySeq = self.getKeySequenceCounter()
            keySequence = int(currentKeySeq, 10) + iIncrementValue
            print keySequence
            return self.setKeySequenceCounter(keySequence)
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('incrementKeySequenceCounter() Error: ' + str(e))

Response: increment the key sequence counter for a given value


Instruction:
Can you write a function in Python 3 where it
sets the extended PAN ID of Thread Network Network

Response:
def setXpanId(self, xPanId):
        """set extended PAN ID of Thread Network

        Args:
            xPanId: extended PAN ID in hex format

        Returns:
            True: successful to set the extended PAN ID
            False: fail to set the extended PAN ID
        """
        xpanid = ''
        print '%s call setXpanId' % self.port
        print xPanId
        try:
            if not isinstance(xPanId, str):
                xpanid = self.__convertLongToString(xPanId)

                # prepend '0' at the beginning
                if len(xpanid) < 16:
                    xpanid = xpanid.zfill(16)
                    print xpanid
                    cmd = WPANCTL_CMD + 'setprop Network:XPANID %s' % xpanid
                    datasetCmd = WPANCTL_CMD + 'setprop Dataset:ExtendedPanId %s' % xpanid
            else:
                xpanid = xPanId
                cmd = WPANCTL_CMD + 'setprop Network:XPANID %s' % xpanid
                datasetCmd = WPANCTL_CMD + 'setprop Dataset:ExtendedPanId %s' % xpanid

            self.xpanId = xpanid
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setXpanId() Error: ' + str(e))


Instruction:
Write a Python 3 script for
setting the Thread Network Partition ID

Response:
def setPartationId(self, partationId):
        """set Thread Network Partition ID

        Args:
            partitionId: partition id to be set by leader

        Returns:
            True: successful to set the Partition ID
            False: fail to set the Partition ID
        """
        print '%s call setPartationId' % self.port
        print partationId

        cmd = WPANCTL_CMD + 'setprop Network:PartitionId %s' %(str(hex(partationId)).rstrip('L'))
        print cmd
        return self.__sendCommand(cmd)[0] != 'Fail'


Instruction:
Can you create a Python 3 function that
gets the global unicast IPv6 address of OpenThreadWpan

Response:
def getGUA(self, filterByPrefix=None):
        """get expected global unicast IPv6 address of OpenThreadWpan

        Args:
            filterByPrefix: a given expected global IPv6 prefix to be matched

        Returns:
            a global IPv6 address
        """
        print '%s call getGUA' % self.port
        print filterByPrefix
        globalAddrs = []
        try:
            # get global addrs set if multiple
            globalAddrs = self.getGlobal()

            if filterByPrefix is None:
                return self.__padIp6Addr(globalAddrs[0])
            else:
                for line in globalAddrs:
                    line = self.__padIp6Addr(line)
                    print "Padded IPv6 Address:" + line
                    if line.startswith(filterByPrefix):
                        return line
                print 'no global address matched'
                return str(globalAddrs[0])
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('getGUA() Error: ' + str(e))
            return e


Instruction:
Implement a function in Python 3 to
get child timeout value

Response:
def getChildTimeoutValue(self):
        """get child timeout"""
        print '%s call getChildTimeoutValue' % self.port
        childTimeout = self.__sendCommand(WPANCTL_CMD + 'getporp -v Thread:ChildTimeout')[0]
        return int(childTimeout)


Instruction:
Can you create a Python 3 function that
starts Collapsed Commissioner Returns: True: successful to start Commissioner False: fail to start Commissioner

Response:
def startCollapsedCommissioner(self):
        """start Collapsed Commissioner

        Returns:
            True: successful to start Commissioner
            False: fail to start Commissioner
        """
        print '%s call startCollapsedCommissioner' % self.port
        startCmd = WPANCTL_CMD + 'form %s -c %s -T router' % (self.networkName, str(self.channel))
        if self.__sendCommand(startCmd) != 'Fail':
            time.sleep(2)
            cmd = WPANCTL_CMD + 'commissioner start'
            print cmd
            if self.__sendCommand(cmd)[0] != 'Fail':
                self.isActiveCommissioner = True
                time.sleep(20) # time for petition process
                return True
        return False


Instruction:
Here you have a function in Python 3, explain what it does
def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'):
        print '%s call scanJoiner' % self.port
        if not isinstance(xEUI, str):
            eui64 = self.__convertLongToString(xEUI)

            # prepend 0 at the beginning
            if len(eui64) < 16:
                eui64 = eui64.zfill(16)
                print eui64
        else:
            eui64 = xEUI

        # long timeout value to avoid automatic joiner removal (in seconds)
        timeout = 500

        cmd = WPANCTL_CMD + 'commissioner joiner-add %s %s %s' % (eui64, str(timeout), strPSKd)
        print cmd
        if not self.isActiveCommissioner:
            self.startCollapsedCommissioner()
        if self.__sendCommand(cmd)[0] != 'Fail':
            return True
        else:
            return False

Response: add a new Joiner s steering data to the current Thread.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setProvisioningUrl(self, strURL='grl.com'):
        print '%s call setProvisioningUrl' % self.port
        self.provisioningUrl = strURL
        if self.deviceRole == Thread_Device_Role.Commissioner:
            cmd = WPANCTL_CMD + 'setprop Commissioner:ProvisioningUrl %s' %(strURL)
            print cmd
            return self.__sendCommand(cmd)[0] != "Fail"
        return True

Response:
set provisioning Url

        Args:
            strURL: Provisioning Url string

        Returns:
            True: successful to set provisioning Url
            False: fail to set provisioning Url


Instruction:
Here you have a function in Python 3, explain what it does
def allowCommission(self):
        print '%s call allowCommission' % self.port
        try:
            cmd = WPANCTL_CMD + 'commissioner start'
            print cmd
            if self.isActiveCommissioner:
                return True
            if self.__sendCommand(cmd)[0] != 'Fail':
                self.isActiveCommissioner = True
                time.sleep(40) # time for petition process and at least one keep alive
                return True
            else:
                return False
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('allowcommission() error: ' + str(e))

Response: start commissioner candidate petition process


Instruction:
Create a Python 3 function to
start joiner s PSKd

Response:
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
        cmd = WPANCTL_CMD + 'joiner --start %s %s' %(strPSKd, self.provisioningUrl)
        print cmd
        if self.__sendCommand(cmd)[0] != "Fail":
            if self.__getJoinerState():
                self.__sendCommand(WPANCTL_CMD + 'joiner --attach')
                time.sleep(30)
                return True
            else:
                return False
        else:
            return False


Instruction:
Write a Python 3 function that can
send MGMT_PANID_QUERY message to a given destination

Response:
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: fail to send MGMT_PANID_QUERY message.
        """
        print '%s call MGMT_PANID_QUERY' % self.port
        panid = ''
        channelMask = ''
        channelMask = self.__ChannelMaskListToStr(listChannelMask)

        if not isinstance(xPanId, str):
            panid = str(hex(xPanId))

        try:
            cmd = WPANCTL_CMD + 'commissioner pan-id-query %s %s %s' % (panid, channelMask, sAddr)
            print cmd
            return self.__sendCommand(cmd) != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('MGMT_PANID_QUERY() error: ' + str(e))


Instruction:
How would you explain what the following Python 3 function does
def MGMT_ANNOUNCE_BEGIN(self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod):
        print '%s call MGMT_ANNOUNCE_BEGIN' % self.port
        channelMask = ''
        channelMask = self.__ChannelMaskListToStr(listChannelMask)
        try:
            cmd = WPANCTL_CMD + 'commissioner announce-begin %s %s %s %s' % (channelMask, xCount, xPeriod, sAddr)
            print cmd
            return self.__sendCommand(cmd) != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('MGMT_ANNOUNCE_BEGIN() error: ' + str(e))

Response: send MGMT_ANNOUNCE_BEGIN message to a given destination


Instruction:
Can you generate a brief explanation for the following Python 3 code
def MGMT_ACTIVE_GET(self, Addr='', TLVs=[]):
        print '%s call MGMT_ACTIVE_GET' % self.port
        try:

            cmd = WPANCTL_CMD + 'dataset mgmt-get-active'

            if len(TLVs) != 0:
                tlvs = "".join(hex(tlv).lstrip("0x").zfill(2) for tlv in TLVs)
                setTLVCmd = WPANCTL_CMD + 'setprop Dataset:RawTlvs ' + tlvs
                if self.__sendCommand(setTLVCmd)[0] == 'Fail':
                    return False
            else:
                if self.__sendCommand(WPANCTL_CMD + 'dataset erase')[0] == 'Fail':
                    return False

            if Addr != '':
                setAddressCmd = WPANCTL_CMD + 'setprop Dataset:DestIpAddress ' + Addr
                if self.__sendCommand(setAddressCmd)[0] == 'Fail':
                    return False

            print cmd

            return self.__sendCommand(cmd)[0] != 'Fail'

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('MGMT_ACTIVE_GET() Error: ' + str(e))

Response:
send MGMT_ACTIVE_GET command

        Returns:
            True: successful to send MGMT_ACTIVE_GET
            False: fail to send MGMT_ACTIVE_GET


Instruction:
Given the following Python 3 function, write the documentation
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, xSteeringData=None, xBorderRouterLocator=None, BogusTLV=None, xDelayTimer=None):
        """send MGMT_ACTIVE_SET command

        Returns:
            True: successful to send MGMT_ACTIVE_SET
            False: fail to send MGMT_ACTIVE_SET
        """
        print '%s call MGMT_ACTIVE_SET' % self.port
        try:
            cmd = WPANCTL_CMD + 'dataset mgmt-set-active'

            if self.__sendCommand(WPANCTL_CMD + 'dataset erase')[0] == 'Fail':
                return False

            if listActiveTimestamp != None:
                sActiveTimestamp = str(hex(listActiveTimestamp[0]))
                if len(sActiveTimestamp) < 18:
                    sActiveTimestamp = sActiveTimestamp.lstrip('0x').zfill(16)
                setActiveTimeCmd = WPANCTL_CMD + 'setprop Dataset:ActiveTimestamp ' + sActiveTimestamp
                if self.__sendCommand(setActiveTimeCmd)[0] == 'Fail':
                    return False

            if xExtendedPanId != None:
                xpanid = self.__convertLongToString(xExtendedPanId)
                if len(xpanid) < 16:
                    xpanid = xpanid.zfill(16)
                setExtendedPanIdCmd = WPANCTL_CMD + 'setprop Dataset:ExtendedPanId ' + xpanid
                if self.__sendCommand(setExtendedPanIdCmd)[0] == 'Fail':
                    return False

            if sNetworkName != None:
                setNetworkNameCmd = WPANCTL_CMD + 'setprop Dataset:NetworkName ' + str(sNetworkName)
                if self.__sendCommand(setNetworkNameCmd)[0] == 'Fail':
                    return False

            if xChannel != None:
                setChannelCmd = WPANCTL_CMD + 'setprop Dataset:Channel ' + str(xChannel)
                if self.__sendCommand(setChannelCmd)[0] == 'Fail':
                    return False

            if sMeshLocalPrefix != None:
                setMLPrefixCmd = WPANCTL_CMD + 'setprop Dataset:MeshLocalPrefix ' + str(sMeshLocalPrefix)
                if self.__sendCommand(setMLPrefixCmd)[0] == 'Fail':
                    return False

            if xMasterKey != None:
                key = self.__convertLongToString(xMasterKey)

                if len(key) < 32:
                    key = key.zfill(32)

                setMasterKeyCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey ' + key
                if self.__sendCommand(setMasterKeyCmd)[0] == 'Fail':
                    return False

            if xPanId != None:
                setPanIdCmd = WPANCTL_CMD + 'setprop Dataset:PanId ' + str(xPanId)
                if self.__sendCommand(setPanIdCmd)[0] == 'Fail':
                    return False

            if listChannelMask != None:
                setChannelMaskCmd = WPANCTL_CMD + 'setprop Dataset:ChannelMaskPage0 ' \
                                    + '0x' + self.__convertLongToString(self.__convertChannelMask(listChannelMask))
                if self.__sendCommand(setChannelMaskCmd)[0] == 'Fail':
                    return False

            if sPSKc != None or listSecurityPolicy != None or \
                    xCommissioningSessionId != None or xTmfPort != None or xSteeringData != None or xBorderRouterLocator != None or \
                    BogusTLV != None:
                setRawTLVCmd = WPANCTL_CMD + 'setprop Dataset:RawTlvs '

            if sPSKc != None:
                setRawTLVCmd += '0410'
                stretchedPskc = Thread_PBKDF2.get(sPSKc, ModuleHelper.Default_XpanId, ModuleHelper.Default_NwkName)
                pskc = hex(stretchedPskc).rstrip('L').lstrip('0x')

                if len(pskc) < 32:
                    pskc = pskc.zfill(32)

                setRawTLVCmd += pskc

            if listSecurityPolicy != None:
                setRawTLVCmd += '0c03'

                rotationTime = 0
                policyBits = 0

                # previous passing way listSecurityPolicy=[True, True, 3600, False, False, True]
                if (len(listSecurityPolicy) == 6):
                    rotationTime = listSecurityPolicy[2]

                    # the last three reserved bits must be 1
                    policyBits = 0b00000111

                    if listSecurityPolicy[0]:
                        policyBits = policyBits | 0b10000000
                    if listSecurityPolicy[1]:
                        policyBits = policyBits | 0b01000000
                    if listSecurityPolicy[3]:
                        policyBits = policyBits | 0b00100000
                    if listSecurityPolicy[4]:
                        policyBits = policyBits | 0b00010000
                    if listSecurityPolicy[5]:
                        policyBits = policyBits | 0b00001000
                else:
                    # new passing way listSecurityPolicy=[3600, 0b11001111]
                    rotationTime = listSecurityPolicy[0]
                    policyBits = listSecurityPolicy[1]

                policy = str(hex(rotationTime))[2:]

                if len(policy) < 4:
                    policy = policy.zfill(4)

                setRawTLVCmd += policy

                setRawTLVCmd += str(hex(policyBits))[2:]

            if xCommissioningSessionId != None:
                setRawTLVCmd += '0b02'
                sessionid = str(hex(xCommissioningSessionId))[2:]

                if len(sessionid) < 4:
                    sessionid = sessionid.zfill(4)

                setRawTLVCmd += sessionid

            if xBorderRouterLocator != None:
                setRawTLVCmd += '0902'
                locator = str(hex(xBorderRouterLocator))[2:]

                if len(locator) < 4:
                    locator = locator.zfill(4)

                setRawTLVCmd += locator

            if xSteeringData != None:
                steeringData = self.__convertLongToString(xSteeringData)
                setRawTLVCmd += '08' + str(len(steeringData)/2).zfill(2)
                setRawTLVCmd += steeringData

            if BogusTLV != None:
                setRawTLVCmd += "8202aa55"

            print setRawTLVCmd
            print cmd

            if self.__sendCommand(setRawTLVCmd)[0] == 'Fail':
                return False

            return self.__sendCommand(cmd)[0] != 'Fail'

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('MGMT_ACTIVE_SET() Error: ' + str(e))

Response: send MGMT_ACTIVE_SET command to set the state of the active MESH object


Instruction:
Write a Python 3 function for
sending MGMT_PENDING_SET command to set the state of the current MGMT_PENDING_SET to the current state of the MGMT_PENDING_SET

Response:
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:
            True: successful to send MGMT_PENDING_SET
            False: fail to send MGMT_PENDING_SET
        """
        print '%s call MGMT_PENDING_SET' % self.port
        try:
            cmd = WPANCTL_CMD + 'dataset mgmt-set-pending'
            if self.__sendCommand(WPANCTL_CMD + 'dataset erase')[0] == 'Fail':
                return False

            if listPendingTimestamp != None:
                sActiveTimestamp = str(hex(listPendingTimestamp[0]))
                if len(sActiveTimestamp) < 18:
                    sActiveTimestamp = sActiveTimestamp.lstrip('0x').zfill(16)
                setPendingTimeCmd = WPANCTL_CMD + 'setprop Dataset:PendingTimestamp ' + sActiveTimestamp
                if self.__sendCommand(setPendingTimeCmd)[0] == 'Fail':
                    return False

            if listActiveTimestamp != None:
                sActiveTimestamp = str(hex(listActiveTimestamp[0]))
                if len(sActiveTimestamp) < 18:
                    sActiveTimestamp = sActiveTimestamp.lstrip('0x').zfill(16)
                setActiveTimeCmd = WPANCTL_CMD + 'setprop Dataset:ActiveTimestamp ' + sActiveTimestamp
                if self.__sendCommand(setActiveTimeCmd)[0] == 'Fail':
                    return False

            if xDelayTimer != None:
                setDelayTimerCmd = WPANCTL_CMD + 'setprop Dataset:Delay ' + str(xDelayTimer)
                if self.__sendCommand(setDelayTimerCmd)[0] == 'Fail':
                    return False

            if sNetworkName != None:
                setNetworkNameCmd = WPANCTL_CMD + 'setprop Dataset:NetworkName ' + str(sNetworkName)
                if self.__sendCommand(setNetworkNameCmd)[0] == 'Fail':
                    return False

            if xChannel != None:
                setChannelCmd = WPANCTL_CMD + 'setprop Dataset:Channel ' + str(xChannel)
                if self.__sendCommand(setChannelCmd)[0] == 'Fail':
                    return False

            if sMeshLocalPrefix != None:
                setMLPrefixCmd = WPANCTL_CMD + 'setprop Dataset:MeshLocalPrefix ' + str(sMeshLocalPrefix)
                if self.__sendCommand(setMLPrefixCmd)[0] == 'Fail':
                    return False

            if xMasterKey != None:
                key = self.__convertLongToString(xMasterKey)

                if len(key) < 32:
                    key = key.zfill(32)

                setMasterKeyCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey ' + key
                if self.__sendCommand(setMasterKeyCmd)[0] == 'Fail':
                    return False

            if xPanId != None:
                setPanIdCmd = WPANCTL_CMD + 'setprop Dataset:PanId ' + str(xPanId)
                if self.__sendCommand(setPanIdCmd)[0] == 'Fail':
                    return False

            if xCommissionerSessionId != None:
               print 'not handle xCommissionerSessionId'

            print cmd

            return self.__sendCommand(cmd)[0] != 'Fail'

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('MGMT_PENDING_SET() Error: ' + str(e))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def commissionerUnregister(self):
        print '%s call commissionerUnregister' % self.port
        cmd = WPANCTL_CMD + 'commissioner stop'
        print cmd
        if self.__sendCommand(cmd)[0] != 'Fail':
            self.isActiveCommissioner = False
            return True
        else:
            return False

Response:
stop commissioner

        Returns:
            True: successful to stop commissioner
            False: fail to stop commissioner


Instruction:
Can you tell what is the following Python 3 function doing
def start(self, host, nornir):
        self.host = host
        self.nornir = nornir

        try:
            logger.debug("Host %r: running task %r", self.host.name, self.name)
            r = self.task(self, **self.params)
            if not isinstance(r, Result):
                r = Result(host=host, result=r)

        except NornirSubTaskError as e:
            tb = traceback.format_exc()
            logger.error(
                "Host %r: task %r failed with traceback:\n%s",
                self.host.name,
                self.name,
                tb,
            )
            r = Result(host, exception=e, result=str(e), failed=True)

        except Exception as e:
            tb = traceback.format_exc()
            logger.error(
                "Host %r: task %r failed with traceback:\n%s",
                self.host.name,
                self.name,
                tb,
            )
            r = Result(host, exception=e, result=tb, failed=True)

        r.name = self.name
        r.severity_level = logging.ERROR if r.failed else self.severity_level

        self.results.insert(0, r)
        return self.results

Response: Starts the task for the given host and returns a list of the results and the subtasks that were executed.


Instruction:
Here you have a function in Python 3, explain what it does
def is_dry_run(self, override: bool = None) -> bool:
        return override if override is not None else self.nornir.data.dry_run

Response: Returns whether the current task is a dry_run or not.


Instruction:
Can you generate the documentation for the following Python 3 function
def failed_hosts(self):
        return {h: r for h, r in self.items() if r.failed}

Response: Returns a dict of hosts that failed during the execution of the task.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def napalm_validate(
    task: Task,
    src: Optional[str] = None,
    validation_source: ValidationSourceData = None,
) -> Result:
    """
    Gather information with napalm and validate it:

        http://napalm.readthedocs.io/en/develop/validate/index.html

    Arguments:
        src: file to use as validation source
        validation_source (list): data to validate device's state

    Returns:
        Result object with the following attributes set:
        * result (``dict``): dictionary with the result of the validation
        * complies (``bool``): Whether the device complies or not
    """
    device = task.host.get_connection("napalm", task.nornir.config)
    r = device.compliance_report(
        validation_file=src, validation_source=validation_source
    )
    return Result(host=task.host, result=r)

Response: Gather information with napalm and validate it


Instruction:
Make a summary of the following Python 3 code
def netmiko_save_config(
    task: Task, cmd: str = "", confirm: bool = False, confirm_response: str = ""
) -> Result:
    """
    Execute Netmiko save_config method
    Arguments:
        cmd(str, optional): Command used to save the configuration.
        confirm(bool, optional): Does device prompt for confirmation before executing save operation
        confirm_response(str, optional): Response send to device when it prompts for confirmation

    Returns:
        :obj: `nornir.core.task.Result`:
          * result (``str``): String showing the CLI output from the save operation
    """
    conn = task.host.get_connection("netmiko", task.nornir.config)
    if cmd:
        result = conn.save_config(
            cmd=cmd, confirm=confirm, confirm_response=confirm_response
        )
    else:
        result = conn.save_config(confirm=confirm, confirm_response=confirm_response)
    return Result(host=task.host, result=result, changed=True)

Response: Execute Netmiko save_config method on the node with optional command


Instruction:
Can you tell what is the following Python 3 function doing
def netmiko_send_command(
    task: Task,
    command_string: str,
    use_timing: bool = False,
    enable: bool = False,
    **kwargs: Any
) -> Result:
    """
    Execute Netmiko send_command method (or send_command_timing)

    Arguments:
        command_string: Command to execute on the remote network device.
        use_timing: Set to True to switch to send_command_timing method.
        enable: Set to True to force Netmiko .enable() call.
        kwargs: Additional arguments to pass to send_command method.

    Returns:
        Result object with the following attributes set:
          * result: Result of the show command (generally a string, but depends on use of TextFSM).
    """
    net_connect = task.host.get_connection("netmiko", task.nornir.config)
    if enable:
        net_connect.enable()
    if use_timing:
        result = net_connect.send_command_timing(command_string, **kwargs)
    else:
        result = net_connect.send_command(command_string, **kwargs)
    return Result(host=task.host, result=result)

Response: Execute a Netmiko command on the remote network device.


Instruction:
Write a Python 3 function for
returning the value of the given item from the host or hosts group variables.

Response:
def get(self, item, default=None):
        """
        Returns the value ``item`` from the host or hosts group variables.

        Arguments:
            item(``str``): The variable to get
            default(``any``): Return value if item not found
        """
        if hasattr(self, item):
            return getattr(self, item)
        try:
            return self.__getitem__(item)

        except KeyError:
            return default