INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
force update to router as if there is child id request | def updateRouterStatus(self):
"""force update to router as if there is child id request"""
print '%s call updateRouterStatus' % self.port
cmd = 'state'
while True:
state = self.__sendCommand(cmd)[0]
if state == 'detached':
continue
elif... |
Find the `expected` line within `times` trials.
Args:
expected str: the expected string
times int: number of trials | def _expect(self, expected, times=50):
"""Find the `expected` line within `times` trials.
Args:
expected str: the expected string
times int: number of trials
"""
logger.debug('[%s] Expecting [%s]', self.port, expected)
retry_times = 10
wh... |
Read exactly one line from the device, nonblocking.
Returns:
None on no data | def _readline(self):
"""Read exactly one line from the device, nonblocking.
Returns:
None on no data
"""
if len(self.lines) > 1:
return self.lines.pop(0)
tail = ''
if len(self.lines):
tail = self.lines.pop()
try:
... |
Send exactly one line to the device
Args:
line str: data send to device | def _sendline(self, line):
"""Send exactly one line to the device
Args:
line str: data send to device
"""
self.lines = []
try:
self._read()
except socket.error:
logging.debug('Nothing cleared')
logger.debug('sending [%s]', lin... |
Send command and wait for response.
The command will be repeated 3 times at most in case data loss of serial port.
Args:
req (str): Command to send, please do not include new line in the end.
Returns:
[str]: The output lines | def _req(self, req):
"""Send command and wait for response.
The command will be repeated 3 times at most in case data loss of serial port.
Args:
req (str): Command to send, please do not include new line in the end.
Returns:
[str]: The output lines
"""
... |
Threading callback | def run(self):
"""Threading callback"""
self.viewing = True
while self.viewing and self._lock.acquire():
try:
line = self._readline()
except:
pass
else:
logger.info(line)
self._lock.release()
... |
Reset openthread device, not equivalent to stop and start | def reset(self):
"""Reset openthread device, not equivalent to stop and start
"""
logger.debug('DUT> reset')
self._log and self.pause()
self._sendline('reset')
self._read()
self._log and self.resume() |
Add network prefix.
Args:
prefix (str): network prefix.
flags (str): network prefix flags, please refer thread documentation for details
prf (str): network prf, please refer thread documentation for details | def add_prefix(self, prefix, flags, prf):
"""Add network prefix.
Args:
prefix (str): network prefix.
flags (str): network prefix flags, please refer thread documentation for details
prf (str): network prf, please refer thread documentation for details
"""
... |
Remove network prefix. | def remove_prefix(self, prefix):
"""Remove network prefix.
"""
self._req('prefix remove %s' % prefix)
time.sleep(1)
self._req('netdataregister') |
Initialize the telnet connection | 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() |
Open telnet connection
Args:
params (dict), must contain two parameters "ip" - ip address or hostname and "port" - port number
Example:
params = {'port': 23, 'ip': 'localhost'} | def open(self, **params):
"""Open telnet connection
Args:
params (dict), must contain two parameters "ip" - ip address or hostname and "port" - port number
Example:
params = {'port': 23, 'ip': 'localhost'}
"""
logger.info('opening telnet')
self.p... |
Wait until the regex encountered | 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]) |
Reboot outlet
Args:
params (dict), must contain parameter "outlet" - outlet number
Example:
params = {'outlet': 1} | def reboot(self, **params):
"""Reboot outlet
Args:
params (dict), must contain parameter "outlet" - outlet number
Example:
params = {'outlet': 1}
"""
outlet = params['outlet']
# main menu
self.tn.write('\x1b\r\n')
self.until_done... |
send specific command to reference unit over serial port
Args:
cmd: OpenThread_WpanCtl command string
Returns:
Fail: Failed to send the command to reference unit and parse it
Value: successfully retrieve the desired value from reference unit
Error: some ... | def __sendCommand(self, cmd):
"""send specific command to reference unit over serial port
Args:
cmd: OpenThread_WpanCtl command string
Returns:
Fail: Failed to send the command to reference unit and parse it
Value: successfully retrieve the desired value fro... |
strip the special characters in the value
Args:
value: value string
Returns:
value string without special characters | def __stripValue(self, value):
"""strip the special characters in the value
Args:
value: value string
Returns:
value string without special characters
"""
if isinstance(value, str):
if ( value[0] == '"' and val... |
get specific type of IPv6 address configured on OpenThread_WpanCtl
Args:
addressType: the specific type of IPv6 address
link local: link local unicast IPv6 address that's within one-hop scope
global: global unicast IPv6 address
rloc: mesh local unicast IPv6 addr... | def __getIp6Address(self, addressType):
"""get specific type of IPv6 address configured on OpenThread_WpanCtl
Args:
addressType: the specific type of IPv6 address
link local: link local unicast IPv6 address that's within one-hop scope
global: global unicast IPv6 add... |
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
... | 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: s... |
set address filter mode
Returns:
True: successful to set address filter mode.
False: fail to set address filter mode. | def __setAddressfilterMode(self, mode):
"""set address filter mode
Returns:
True: successful to set address filter mode.
False: fail to set address filter mode.
"""
print 'call setAddressFilterMode() ' + mode
try:
if re.match('list', mode, re... |
start OpenThreadWpan
Returns:
True: successful to start OpenThreadWpan up
False: fail to start OpenThreadWpan | def __startOpenThreadWpan(self):
"""start OpenThreadWpan
Returns:
True: successful to start OpenThreadWpan up
False: fail to start OpenThreadWpan
"""
print 'call startOpenThreadWpan'
try:
# restore whitelist/blacklist address filter mode if r... |
stop OpenThreadWpan
Returns:
True: successfully stop OpenThreadWpan
False: failed to stop OpenThreadWpan | 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 ... |
check whether or not OpenThreadWpan is running
Returns:
True: OpenThreadWpan is running
False: OpenThreadWpan is not running | 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... |
mapping Rloc16 to router id
Args:
xRloc16: hex rloc16 short address
Returns:
actual router id allocated by leader | def __convertRlocToRouterId(self, xRloc16):
"""mapping Rloc16 to router id
Args:
xRloc16: hex rloc16 short address
Returns:
actual router id allocated by leader
"""
routerList = []
routerList = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:... |
convert a channel list to a string
Args:
channelList: channel list (i.e. [21, 22, 23])
Returns:
a comma separated channel string (i.e. '21, 22, 23') | def __ChannelMaskListToStr(self, channelList):
"""convert a channel list to a string
Args:
channelList: channel list (i.e. [21, 22, 23])
Returns:
a comma separated channel string (i.e. '21, 22, 23')
"""
chan_mask_range = ''
if isinstance(channelL... |
get joiner state | def __getJoinerState(self):
""" get joiner state """
maxDuration = 150 # seconds
t_end = time.time() + maxDuration
while time.time() < t_end:
joinerState = self.__stripValue(self.__sendCommand('sudo wpanctl getprop -v NCP:State')[0])
if joinerState == 'offline:co... |
initialize the serial port with baudrate, timeout parameters | def intialize(self):
"""initialize the serial port with baudrate, timeout parameters"""
print '%s call intialize' % self.port
try:
# init serial port
self.deviceConnected = False
self._connect()
if self.deviceConnected:
self.UIStat... |
get Thread Network name | def getNetworkName(self):
"""get Thread Network name"""
print '%s call getNetworkname' % self.port
networkName = self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:Name')[0]
return self.__stripValue(networkName) |
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 | 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.p... |
get one specific type of MAC address
currently OpenThreadWpan only supports Random MAC address
Args:
bType: indicate which kind of MAC address is required
Returns:
specific type of MAC address | def getMAC(self, bType=MacType.RandomMac):
"""get one specific type of MAC address
currently OpenThreadWpan only supports Random MAC address
Args:
bType: indicate which kind of MAC address is required
Returns:
specific type of MAC address
"""
... |
get link local unicast IPv6 address | def getLL64(self):
"""get link local unicast IPv6 address"""
print '%s call getLL64' % self.port
return self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v IPv6:LinkLocalAddress')[0]) |
get router locator unicast IPv6 address | 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 + 'getpr... |
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 | 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
... |
add a given extended address to the whitelist addressfilter
Args:
xEUI: a given extended address in hex format
Returns:
True: successful to add a given extended address to the whitelist entry
False: fail to add a given extended address to the whitelist entry | def addAllowMAC(self, xEUI):
"""add a given extended address to the whitelist addressfilter
Args:
xEUI: a given extended address in hex format
Returns:
True: successful to add a given extended address to the whitelist entry
False: fail to add a given extende... |
clear all entries in whitelist table
Returns:
True: successful to clear the whitelist
False: fail to clear the whitelist | 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:
... |
get current device role in Thread Network | 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]) |
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 | 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' % sel... |
get current partition id of Thread Network Partition from LeaderData
Returns:
The Thread network Partition Id | def getNetworkFragmentID(self):
"""get current partition id of Thread Network Partition from LeaderData
Returns:
The Thread network Partition Id
"""
print '%s call getNetworkFragmentID' % self.port
if not self.____isOpenThreadWpanRunning():
print 'OpenThr... |
get Thread device's parent extended address and rloc16 short address
Returns:
The extended address of parent in hex format | def getParentAddress(self):
"""get Thread device's parent extended address and rloc16 short address
Returns:
The extended address of parent in hex format
"""
print '%s call getParentAddress' % self.port
parentInfo = []
parentInfo = self.__stripValue(self.__se... |
power down the OpenThreadWpan | 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':
... |
power up the Thread device | def powerUp(self):
"""power up the Thread device"""
print '%s call powerUp' % self.port
if not self.handle:
self._connect()
self.isPowerDown = False
if self.__sendCommand(WPANCTL_CMD + 'attach')[0] != 'Fail':
time.sleep(3)
else:
return... |
reset and rejoin to Thread Network without any timeout
Returns:
True: successful to reset and rejoin the Thread Network
False: fail to reset and rejoin the Thread Network | def reboot(self):
"""reset and rejoin to Thread Network without any timeout
Returns:
True: successful to reset and rejoin the Thread Network
False: fail to reset and rejoin the Thread Network
"""
print '%s call reboot' % self.port
try:
self._s... |
send ICMPv6 echo request with a given length to a unicast destination
address
Args:
destination: the unicast destination address of ICMPv6 echo request
length: the size of ICMPv6 echo request payload | def ping(self, destination, length=20):
""" send ICMPv6 echo request with a given length to a unicast destination
address
Args:
destination: the unicast destination address of ICMPv6 echo request
length: the size of ICMPv6 echo request payload
"""
pri... |
get OpenThreadWpan stack firmware version number | 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) |
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 | 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
... |
factory reset | 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'... |
kick router with a given router id from the Thread Network
Args:
xRouterId: a given router id in hex format
Returns:
True: successful to remove the router from the Thread Network
False: fail to remove the router from the Thread Network | def removeRouter(self, xRouterId):
"""kick router with a given router id from the Thread Network
Args:
xRouterId: a given router id in hex format
Returns:
True: successful to remove the router from the Thread Network
False: fail to remove the router from the... |
set default mandatory Thread Network parameter value | def setDefaultValues(self):
"""set default mandatory Thread Network parameter value"""
print '%s call setDefaultValues' % self.port
# initialize variables
self.networkName = ModuleHelper.Default_NwkName
self.networkKey = ModuleHelper.Default_NwkKey
self.channel = ModuleH... |
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 | 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 ... |
reset and join back Thread Network with a given timeout delay
Args:
timeout: a timeout interval before rejoin Thread Network
Returns:
True: successful to reset and rejoin Thread Network
False: fail to reset and rejoin the Thread Network | def resetAndRejoin(self, timeout):
"""reset and join back Thread Network with a given timeout delay
Args:
timeout: a timeout interval before rejoin Thread Network
Returns:
True: successful to reset and rejoin Thread Network
False: fail to reset and rejoin th... |
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... | 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_stab... |
set keep alive timeout for device
has been deprecated and also set SED polling rate
Args:
iTimeOut: data poll period for sleepy end device
Returns:
True: successful to set the data poll period for SED
False: fail to set the data poll period for SED | def setKeepAliveTimeOut(self, iTimeOut):
"""set keep alive timeout for device
has been deprecated and also set SED polling rate
Args:
iTimeOut: data poll period for sleepy end device
Returns:
True: successful to set the data poll period for SED
Fa... |
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 | 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
... |
get current Thread Network key sequence | 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 |
increment the key sequence with a given value
Args:
iIncrementValue: specific increment value to be added
Returns:
True: successful to increment the key sequence with a given value
False: fail to increment the key sequence with a given value | def incrementKeySequenceCounter(self, iIncrementValue=1):
"""increment the key sequence with a given value
Args:
iIncrementValue: specific increment value to be added
Returns:
True: successful to increment the key sequence with a given value
False: fail to i... |
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 | 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 ca... |
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 | 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 setPartatio... |
get expected global unicast IPv6 address of OpenThreadWpan
Args:
filterByPrefix: a given expected global IPv6 prefix to be matched
Returns:
a global IPv6 address | def getGUA(self, filterByPrefix=None):
"""get expected global unicast IPv6 address of OpenThreadWpan
Args:
filterByPrefix: a given expected global IPv6 prefix to be matched
Returns:
a global IPv6 address
"""
print '%s call getGUA' % self.port
pri... |
get child timeout | 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) |
start Collapsed Commissioner
Returns:
True: successful to start Commissioner
False: fail to start Commissioner | def startCollapsedCommissioner(self):
"""start Collapsed Commissioner
Returns:
True: successful to start Commissioner
False: fail to start Commissioner
"""
print '%s call startCollapsedCommissioner' % self.port
startCmd = WPANCTL_CMD + 'form %s -c %s -T r... |
scan Joiner
Args:
xEUI: Joiner's EUI-64
strPSKd: Joiner's PSKd for commissioning
Returns:
True: successful to add Joiner's steering data
False: fail to add Joiner's steering data | def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'):
"""scan Joiner
Args:
xEUI: Joiner's EUI-64
strPSKd: Joiner's PSKd for commissioning
Returns:
True: successful to add Joiner's steering data
False: fail to add Joiner's steering data
... |
set provisioning Url
Args:
strURL: Provisioning Url string
Returns:
True: successful to set provisioning Url
False: fail to set provisioning Url | def setProvisioningUrl(self, strURL='grl.com'):
"""set provisioning Url
Args:
strURL: Provisioning Url string
Returns:
True: successful to set provisioning Url
False: fail to set provisioning Url
"""
print '%s call setProvisioningUrl' % self.... |
start commissioner candidate petition process
Returns:
True: successful to start commissioner candidate petition process
False: fail to start commissioner candidate petition process | def allowCommission(self):
"""start commissioner candidate petition process
Returns:
True: successful to start commissioner candidate petition process
False: fail to start commissioner candidate petition process
"""
print '%s call allowCommission' % self.port
... |
start joiner
Args:
strPSKd: Joiner's PSKd
Returns:
True: successful to start joiner
False: fail to start joiner | def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20):
"""start joiner
Args:
strPSKd: Joiner's PSKd
Returns:
True: successful to start joiner
False: fail to start joiner
"""
print '%s call joinCommissioned' % self.port
cm... |
send MGMT_PANID_QUERY message to a given destination
Args:
xPanId: a given PAN ID to check the conflicts
Returns:
True: successful to send MGMT_PANID_QUERY message.
False: fail to send MGMT_PANID_QUERY message. | def MGMT_PANID_QUERY(self, sAddr, xCommissionerSessionId, listChannelMask, xPanId):
"""send MGMT_PANID_QUERY message to a given destination
Args:
xPanId: a given PAN ID to check the conflicts
Returns:
True: successful to send MGMT_PANID_QUERY message.
False:... |
send MGMT_ANNOUNCE_BEGIN message to a given destination
Returns:
True: successful to send MGMT_ANNOUNCE_BEGIN message.
False: fail to send MGMT_ANNOUNCE_BEGIN message. | def MGMT_ANNOUNCE_BEGIN(self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod):
"""send MGMT_ANNOUNCE_BEGIN message to a given destination
Returns:
True: successful to send MGMT_ANNOUNCE_BEGIN message.
False: fail to send MGMT_ANNOUNCE_BEGIN message.
"""
... |
send MGMT_ACTIVE_GET command
Returns:
True: successful to send MGMT_ACTIVE_GET
False: fail to send MGMT_ACTIVE_GET | def MGMT_ACTIVE_GET(self, Addr='', TLVs=[]):
"""send MGMT_ACTIVE_GET command
Returns:
True: successful to send MGMT_ACTIVE_GET
False: fail to send MGMT_ACTIVE_GET
"""
print '%s call MGMT_ACTIVE_GET' % self.port
try:
cmd = WPANCTL_CMD + 'datas... |
send MGMT_ACTIVE_SET command
Returns:
True: successful to send MGMT_ACTIVE_SET
False: fail to send MGMT_ACTIVE_SET | def MGMT_ACTIVE_SET(self, sAddr='', xCommissioningSessionId=None, listActiveTimestamp=None, listChannelMask=None, xExtendedPanId=None,
sNetworkName=None, sPSKc=None, listSecurityPolicy=None, xChannel=None, sMeshLocalPrefix=None, xMasterKey=None,
xPanId=None, xTmfPort=None... |
send MGMT_PENDING_SET command
Returns:
True: successful to send MGMT_PENDING_SET
False: fail to send MGMT_PENDING_SET | def MGMT_PENDING_SET(self, sAddr='', xCommissionerSessionId=None, listPendingTimestamp=None, listActiveTimestamp=None, xDelayTimer=None,
xChannel=None, xPanId=None, xMasterKey=None, sMeshLocalPrefix=None, sNetworkName=None):
"""send MGMT_PENDING_SET command
Returns:
... |
send MGMT_COMM_SET command
Returns:
True: successful to send MGMT_COMM_SET
False: fail to send MGMT_COMM_SET | def MGMT_COMM_SET(self, Addr='ff02::1', xCommissionerSessionID=None, xSteeringData=None, xBorderRouterLocator=None,
xChannelTlv=None, ExceedMaxPayload=False):
"""send MGMT_COMM_SET command
Returns:
True: successful to send MGMT_COMM_SET
False: fail to send ... |
stop commissioner
Returns:
True: successful to stop commissioner
False: fail to stop commissioner | def commissionerUnregister(self):
"""stop commissioner
Returns:
True: successful to stop commissioner
False: fail to stop commissioner
"""
print '%s call commissionerUnregister' % self.port
cmd = WPANCTL_CMD + 'commissioner stop'
print cmd
... |
This is a utility method to call a task from within a task. For instance:
def grouped_tasks(task):
task.run(my_first_task)
task.run(my_second_task)
nornir.run(grouped_tasks)
This method will ensure the subtask is run only for the host in the current thr... | def run(self, task, **kwargs):
"""
This is a utility method to call a task from within a task. For instance:
def grouped_tasks(task):
task.run(my_first_task)
task.run(my_second_task)
nornir.run(grouped_tasks)
This method will ensure the ... |
Returns whether current task is a dry_run or not. | def is_dry_run(self, override: bool = None) -> bool:
"""
Returns whether current task is a dry_run or not.
"""
return override if override is not None else self.nornir.data.dry_run |
Hosts that failed during the execution of the task. | def failed_hosts(self):
"""Hosts that failed during the execution of the task."""
return {h: r for h, r in self.items() if r.failed} |
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:
... | 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 sou... |
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
... | 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 be... |
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... | 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.
... |
Retuns whether the object is a child of the :obj:`Group` ``group`` | def has_parent_group(self, group):
"""Retuns whether the object is a child of the :obj:`Group` ``group``"""
if isinstance(group, str):
return self._has_parent_group_by_name(group)
else:
return self._has_parent_group_by_object(group) |
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 | 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... |
The function of this method is twofold:
1. If an existing connection is already established for the given type return it
2. If none exists, establish a new connection of that type with default parameters
and return it
Raises:
AttributeError: if it's unknown h... | def get_connection(self, connection: str, configuration: Config) -> Any:
"""
The function of this method is twofold:
1. If an existing connection is already established for the given type return it
2. If none exists, establish a new connection of that type with default parameter... |
For an already established connection return its state. | def get_connection_state(self, connection: str) -> Dict[str, Any]:
"""
For an already established connection return its state.
"""
if connection not in self.connections:
raise ConnectionNotOpen(connection)
return self.connections[connection].state |
Open a new connection.
If ``default_to_host_attributes`` is set to ``True`` arguments will default to host
attributes if not specified.
Raises:
AttributeError: if it's unknown how to establish a connection for the given type
Returns:
An already established conn... | def open_connection(
self,
connection: str,
configuration: Config,
hostname: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
port: Optional[int] = None,
platform: Optional[str] = None,
extras: Optional[Dict[str... |
Close the connection | def close_connection(self, connection: str) -> None:
""" Close the connection"""
if connection not in self.connections:
raise ConnectionNotOpen(connection)
self.connections.pop(connection).close() |
Returns set of hosts that belongs to a group including those that belong
indirectly via inheritance | def children_of_group(self, group: Union[str, Group]) -> Set[Host]:
"""
Returns set of hosts that belongs to a group including those that belong
indirectly via inheritance
"""
hosts: List[Host] = set()
for host in self.hosts.values():
if host.has_parent_group(... |
Add a host to the inventory after initialization | def add_host(self, name: str, **kwargs) -> None:
"""
Add a host to the inventory after initialization
"""
host = {
name: deserializer.inventory.InventoryElement.deserialize_host(
name=name, defaults=self.defaults, **kwargs
)
}
self.... |
Add a group to the inventory after initialization | def add_group(self, name: str, **kwargs) -> None:
"""
Add a group to the inventory after initialization
"""
group = {
name: deserializer.inventory.InventoryElement.deserialize_group(
name=name, defaults=self.defaults, **kwargs
)
}
s... |
Returns serialized dictionary of defaults from inventory | def get_defaults_dict(self) -> Dict:
"""
Returns serialized dictionary of defaults from inventory
"""
return deserializer.inventory.Defaults.serialize(self.defaults).dict() |
Returns serialized dictionary of groups from inventory | def get_groups_dict(self) -> Dict:
"""
Returns serialized dictionary of groups from inventory
"""
return {
k: deserializer.inventory.InventoryElement.serialize(v).dict()
for k, v in self.groups.items()
} |
Returns serialized dictionary of hosts from inventory | def get_hosts_dict(self) -> Dict:
"""
Returns serialized dictionary of hosts from inventory
"""
return {
k: deserializer.inventory.InventoryElement.serialize(v).dict()
for k, v in self.hosts.items()
} |
Transfer files from/to the device using sftp protocol
Example::
nornir.run(files.sftp,
action="put",
src="README.md",
dst="/tmp/README.md")
Arguments:
dry_run: Whether to apply changes or not
src: source file
dst: des... | def sftp(
task: Task, src: str, dst: str, action: str, dry_run: Optional[bool] = None
) -> Result:
"""
Transfer files from/to the device using sftp protocol
Example::
nornir.run(files.sftp,
action="put",
src="README.md",
dst="/tmp/REA... |
Renders contants of a file with jinja2. All the host data is available in the template
Arguments:
template: filename
path: path to dir with templates
jinja_filters: jinja filters to enable. Defaults to nornir.config.jinja2.filters
**kwargs: additional data to pass to the template
... | def template_file(
task: Task,
template: str,
path: str,
jinja_filters: FiltersDict = None,
**kwargs: Any
) -> Result:
"""
Renders contants of a file with jinja2. All the host data is available in the template
Arguments:
template: filename
path: path to dir with template... |
This is a convenience task that uses `requests <http://docs.python-requests.org/en/master/>`_ to
interact with an HTTP server.
Arguments:
method: HTTP method to call
url: URL to connect to
raise_for_status: Whether to call `raise_for_status
<http://docs.python-requests.org/e... | def http_method(
task: Optional[Task] = None,
method: str = "get",
url: str = "",
raise_for_status: bool = True,
**kwargs: Any
) -> Result:
"""
This is a convenience task that uses `requests <http://docs.python-requests.org/en/master/>`_ to
interact with an HTTP server.
Arguments:
... |
Execute Netmiko send_config_set method (or send_config_from_file)
Arguments:
config_commands: Commands to configure on the remote network device.
config_file: File to read configuration commands from.
kwargs: Additional arguments to pass to method.
Returns:
Result object with t... | def netmiko_send_config(
task: Task,
config_commands: Optional[List[str]] = None,
config_file: Optional[str] = None,
**kwargs: Any
) -> Result:
"""
Execute Netmiko send_config_set method (or send_config_from_file)
Arguments:
config_commands: Commands to configure on the remote netwo... |
Loads configuration into a network devices using napalm
Arguments:
dry_run: Whether to apply changes or not
filename: filename containing the configuration to load into the device
configuration: configuration to load into the device
replace: whether to replace or merge the configura... | def napalm_configure(
task: Task,
dry_run: Optional[bool] = None,
filename: Optional[str] = None,
configuration: Optional[str] = None,
replace: bool = False,
) -> Result:
"""
Loads configuration into a network devices using napalm
Arguments:
dry_run: Whether to apply changes or ... |
Loads a json file.
Arguments:
file: path to the file containing the json file to load
Examples:
Simple example with ``ordered_dict``::
> nr.run(task=load_json,
file="mydata.json")
file: path to the file containing the json file to load
Returns:
... | def load_json(task: Task, file: str) -> Result:
"""
Loads a json file.
Arguments:
file: path to the file containing the json file to load
Examples:
Simple example with ``ordered_dict``::
> nr.run(task=load_json,
file="mydata.json")
file: path... |
Helper function to print a title. | def print_title(title: str) -> None:
"""
Helper function to print a title.
"""
msg = "**** {} ".format(title)
print("{}{}{}{}".format(Style.BRIGHT, Fore.GREEN, msg, "*" * (80 - len(msg)))) |
Prints the :obj:`nornir.core.task.Result` from a previous task to screen
Arguments:
result: from a previous task
host: # TODO
vars: Which attributes you want to print
failed: if ``True`` assume the task failed
severity_level: Print only errors with this severity level or hig... | def print_result(
result: Result,
host: Optional[str] = None,
vars: List[str] = None,
failed: bool = False,
severity_level: int = logging.INFO,
) -> None:
"""
Prints the :obj:`nornir.core.task.Result` from a previous task to screen
Arguments:
result: from a previous task
... |
Executes a command locally
Arguments:
command: command to execute
Returns:
Result object with the following attributes set:
* result (``str``): stderr or stdout
* stdout (``str``): stdout
* stderr (``str``): stderr
Raises:
:obj:`nornir.core.exceptions... | def command(task: Task, command: str) -> Result:
"""
Executes a command locally
Arguments:
command: command to execute
Returns:
Result object with the following attributes set:
* result (``str``): stderr or stdout
* stdout (``str``): stdout
* stderr (``str... |
Execute Netmiko file_transfer method
Arguments:
source_file: Source file.
dest_file: Destination file.
kwargs: Additional arguments to pass to file_transfer
Returns:
Result object with the following attributes set:
* result (``bool``): file exists and MD5 is valid
... | def netmiko_file_transfer(
task: Task, source_file: str, dest_file: str, **kwargs: Any
) -> Result:
"""
Execute Netmiko file_transfer method
Arguments:
source_file: Source file.
dest_file: Destination file.
kwargs: Additional arguments to pass to file_transfer
Returns:
... |
Run commands on remote devices using napalm
Arguments:
commands: commands to execute
Returns:
Result object with the following attributes set:
* result (``dict``): result of the commands execution | def napalm_cli(task: Task, commands: List[str]) -> Result:
"""
Run commands on remote devices using napalm
Arguments:
commands: commands to execute
Returns:
Result object with the following attributes set:
* result (``dict``): result of the commands execution
"""
devi... |
See :py:meth:`nornir.core.inventory.Inventory.filter`
Returns:
:obj:`Nornir`: A new object with same configuration as ``self`` but filtered inventory. | def filter(self, *args, **kwargs):
"""
See :py:meth:`nornir.core.inventory.Inventory.filter`
Returns:
:obj:`Nornir`: A new object with same configuration as ``self`` but filtered inventory.
"""
b = Nornir(**self.__dict__)
b.inventory = self.inventory.filter(*... |
Run task over all the hosts in the inventory.
Arguments:
task (``callable``): function or callable that will be run against each device in
the inventory
num_workers(``int``): Override for how many hosts to run in paralell for this task
raise_on_error (``bool``)... | def run(
self,
task,
num_workers=None,
raise_on_error=None,
on_good=True,
on_failed=False,
**kwargs,
):
"""
Run task over all the hosts in the inventory.
Arguments:
task (``callable``): function or callable that will be run... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.