• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3#  Copyright (c) 2018, The OpenThread Authors.
4#  All rights reserved.
5#
6#  Redistribution and use in source and binary forms, with or without
7#  modification, are permitted provided that the following conditions are met:
8#  1. Redistributions of source code must retain the above copyright
9#     notice, this list of conditions and the following disclaimer.
10#  2. Redistributions in binary form must reproduce the above copyright
11#     notice, this list of conditions and the following disclaimer in the
12#     documentation and/or other materials provided with the distribution.
13#  3. Neither the name of the copyright holder nor the
14#     names of its contributors may be used to endorse or promote products
15#     derived from this software without specific prior written permission.
16#
17#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27#  POSSIBILITY OF SUCH DAMAGE.
28#
29
30import sys
31import os
32import time
33import re
34import random
35import weakref
36import subprocess
37import socket
38import asyncore
39import inspect
40
41# ----------------------------------------------------------------------------------------------------------------------
42# wpantund properties
43
44WPAN_STATE = 'NCP:State'
45WPAN_NAME = 'Network:Name'
46WPAN_PANID = 'Network:PANID'
47WPAN_XPANID = 'Network:XPANID'
48WPAN_KEY = 'Network:Key'
49WPAN_KEY_INDEX = 'Network:KeyIndex'
50WPAN_CHANNEL = 'NCP:Channel'
51WPAN_HW_ADDRESS = 'NCP:HardwareAddress'
52WPAN_EXT_ADDRESS = 'NCP:ExtendedAddress'
53WPAN_POLL_INTERVAL = 'NCP:SleepyPollInterval'
54WPAN_NODE_TYPE = 'Network:NodeType'
55WPAN_ROLE = 'Network:Role'
56WPAN_PARTITION_ID = 'Network:PartitionId'
57WPAN_NCP_VERSION = 'NCP:Version'
58WPAN_NCP_MCU_POWER_STATE = "NCP:MCUPowerState"
59WPAN_NETWORK_PASSTHRU_PORT = 'com.nestlabs.internal:Network:PassthruPort'
60WPAN_RCP_VERSION = "POSIXApp:RCPVersion"
61
62WPAN_IP6_LINK_LOCAL_ADDRESS = "IPv6:LinkLocalAddress"
63WPAN_IP6_MESH_LOCAL_ADDRESS = "IPv6:MeshLocalAddress"
64WPAN_IP6_MESH_LOCAL_PREFIX = "IPv6:MeshLocalPrefix"
65WPAN_IP6_ALL_ADDRESSES = "IPv6:AllAddresses"
66WPAN_IP6_MULTICAST_ADDRESSES = "IPv6:MulticastAddresses"
67WPAN_IP6_INTERFACE_ROUTES = "IPv6:Routes"
68
69WPAN_DAEMON_OFF_MESH_ROUTE_AUTO_ADD_ON_INTERFACE = "Daemon:OffMeshRoute:AutoAddOnInterface"
70WPAN_DAEMON_OFF_MESH_ROUTE_FILTER_SELF_AUTO_ADDED = "Daemon:OffMeshRoute:FilterSelfAutoAdded"
71WPAN_DAEMON_ON_MESH_PREFIX_AUTO_ADD_AS_INTERFACE_ROUTE = "Daemon:OnMeshPrefix:AutoAddAsInterfaceRoute"
72
73WPAN_THREAD_RLOC16 = "Thread:RLOC16"
74WPAN_THREAD_ROUTER_ID = "Thread:RouterID"
75WPAN_THREAD_LEADER_ADDRESS = "Thread:Leader:Address"
76WPAN_THREAD_LEADER_ROUTER_ID = "Thread:Leader:RouterID"
77WPAN_THREAD_LEADER_WEIGHT = "Thread:Leader:Weight"
78WPAN_THREAD_LEADER_LOCAL_WEIGHT = "Thread:Leader:LocalWeight"
79WPAN_THREAD_LEADER_NETWORK_DATA = "Thread:Leader:NetworkData"
80WPAN_THREAD_STABLE_LEADER_NETWORK_DATA = "Thread:Leader:StableNetworkData"
81WPAN_THREAD_NETWORK_DATA = "Thread:NetworkData"
82WPAN_THREAD_CHILD_TABLE = "Thread:ChildTable"
83WPAN_THREAD_CHILD_TABLE_ASVALMAP = "Thread:ChildTable:AsValMap"
84WPAN_THREAD_CHILD_TABLE_ADDRESSES = "Thread:ChildTable:Addresses"
85WPAN_THREAD_NEIGHBOR_TABLE = "Thread:NeighborTable"
86WPAN_THREAD_NEIGHBOR_TABLE_ASVALMAP = "Thread:NeighborTable:AsValMap"
87WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES = "Thread:NeighborTable:ErrorRates"
88WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES_AVVALMAP = "Thread:NeighborTable:ErrorRates:AsValMap"
89WPAN_THREAD_ROUTER_TABLE = "Thread:RouterTable"
90WPAN_THREAD_ROUTER_TABLE_ASVALMAP = "Thread:RouterTable:AsValMap"
91WPAN_THREAD_CHILD_TIMEOUT = "Thread:ChildTimeout"
92WPAN_THREAD_PARENT = "Thread:Parent"
93WPAN_THREAD_PARENT_ASVALMAP = "Thread:Parent:AsValMap"
94WPAN_THREAD_NETWORK_DATA_VERSION = "Thread:NetworkDataVersion"
95WPAN_THREAD_STABLE_NETWORK_DATA = "Thread:StableNetworkData"
96WPAN_THREAD_STABLE_NETWORK_DATA_VERSION = "Thread:StableNetworkDataVersion"
97WPAN_THREAD_PREFERRED_ROUTER_ID = "Thread:PreferredRouterID"
98WPAN_THREAD_COMMISSIONER_ENABLED = "Thread:Commissioner:Enabled"
99WPAN_THREAD_DEVICE_MODE = "Thread:DeviceMode"
100WPAN_THREAD_OFF_MESH_ROUTES = "Thread:OffMeshRoutes"
101WPAN_THREAD_ON_MESH_PREFIXES = "Thread:OnMeshPrefixes"
102WPAN_THREAD_ROUTER_ROLE_ENABLED = "Thread:RouterRole:Enabled"
103WPAN_THREAD_CONFIG_FILTER_RLOC_ADDRESSES = "Thread:Config:FilterRLOCAddresses"
104WPAN_THREAD_ROUTER_UPGRADE_THRESHOLD = "Thread:RouterUpgradeThreshold"
105WPAN_THREAD_ROUTER_DOWNGRADE_THRESHOLD = "Thread:RouterDowngradeThreshold"
106WPAN_THREAD_ACTIVE_DATASET = "Thread:ActiveDataset"
107WPAN_THREAD_ACTIVE_DATASET_ASVALMAP = "Thread:ActiveDataset:AsValMap"
108WPAN_THREAD_PENDING_DATASET = "Thread:PendingDataset"
109WPAN_THREAD_PENDING_DATASET_ASVALMAP = "Thread:PendingDataset:AsValMap"
110WPAN_THREAD_ADDRESS_CACHE_TABLE = "Thread:AddressCacheTable"
111WPAN_THREAD_ADDRESS_CACHE_TABLE_ASVALMAP = "Thread:AddressCacheTable:AsValMap"
112WPAN_THREAD_JOINER_DISCERNER_VALUE = "Joiner:Discerner:Value"
113WPAN_THREAD_JOINER_DISCERNER_BIT_LENGTH = "Joiner:Discerner:BitLength"
114WPAN_THREAD_COMMISSIONER_JOINERS = "Commissioner:Joiners"
115
116WPAN_OT_LOG_LEVEL = "OpenThread:LogLevel"
117WPAN_OT_SLAAC_ENABLED = "OpenThread:SLAAC:Enabled"
118WPAN_OT_STEERING_DATA_ADDRESS = "OpenThread:SteeringData:Address"
119WPAN_OT_STEERING_DATA_SET_WHEN_JOINABLE = "OpenThread:SteeringData:SetWhenJoinable"
120WPAN_OT_MSG_BUFFER_COUNTERS = "OpenThread:MsgBufferCounters"
121WPAN_OT_MSG_BUFFER_COUNTERS_AS_STRING = "OpenThread:MsgBufferCounters:AsString"
122WPAN_OT_DEBUG_TEST_ASSERT = "OpenThread:Debug:TestAssert"
123WPAN_OT_DEBUG_TEST_WATCHDOG = "OpenThread:Debug:TestWatchdog"
124WPAN_OT_SUPPORTED_RADIO_LINKS = "OpenThread:SupportedRadioLinks"
125WPAN_OT_NEIGHBOR_TABLE_MULTI_RADIO_INFO = "OpenThread:NeighborTable::MultiRadioInfo"
126WPAN_OT_TREL_TEST_MODE_ENABLE = "OpenThread:Trel:TestMode:Enable"
127
128WPAN_MAC_ALLOWLIST_ENABLED = "MAC:Allowlist:Enabled"
129WPAN_MAC_ALLOWLIST_ENTRIES = "MAC:Allowlist:Entries"
130WPAN_MAC_ALLOWLIST_ENTRIES_ASVALMAP = "MAC:Allowlist:Entries:AsValMap"
131WPAN_MAC_DENYLIST_ENABLED = "MAC:Denylist:Enabled"
132WPAN_MAC_DENYLIST_ENTRIES = "MAC:Denylist:Entries"
133WPAN_MAC_DENYLIST_ENTRIES_ASVALMAP = "MAC:Denylist:Entries:AsValMap"
134
135WPAN_MAC_FILTER_FIXED_RSSI = "MAC:Filter:FixedRssi"
136WPAN_MAC_FILTER_ENTRIES = "MAC:Filter:Entries"
137WPAN_MAC_FILTER_ENTRIES_ASVALMAP = "MAC:Filter:Entries:AsValMap"
138
139WPAN_CHILD_SUPERVISION_INTERVAL = "ChildSupervision:Interval"
140WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT = "ChildSupervision:CheckTimeout"
141
142WPAN_JAM_DETECTION_STATUS = "JamDetection:Status"
143WPAN_JAM_DETECTION_ENABLE = "JamDetection:Enable"
144WPAN_JAM_DETECTION_RSSI_THRESHOLD = "JamDetection:RssiThreshold"
145WPAN_JAM_DETECTION_WINDOW = "JamDetection:Window"
146WPAN_JAM_DETECTION_BUSY_PERIOD = "JamDetection:BusyPeriod"
147WPAN_JAM_DETECTION_DEBUG_HISTORY_BITMAP = "JamDetection:Debug:HistoryBitmap"
148
149WPAN_CHANNEL_MONITOR_SAMPLE_INTERVAL = "ChannelMonitor:SampleInterval"
150WPAN_CHANNEL_MONITOR_RSSI_THRESHOLD = "ChannelMonitor:RssiThreshold"
151WPAN_CHANNEL_MONITOR_SAMPLE_WINDOW = "ChannelMonitor:SampleWindow"
152WPAN_CHANNEL_MONITOR_SAMPLE_COUNT = "ChannelMonitor:SampleCount"
153WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY = "ChannelMonitor:ChannelQuality"
154WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY_ASVALMAP = "ChannelMonitor:ChannelQuality:AsValMap"
155
156WPAN_CHANNEL_MANAGER_NEW_CHANNEL = "ChannelManager:NewChannel"
157WPAN_CHANNEL_MANAGER_DELAY = "ChannelManager:Delay"
158WPAN_CHANNEL_MANAGER_CHANNEL_SELECT = "ChannelManager:ChannelSelect"
159WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED = "ChannelManager:AutoSelect:Enabled"
160WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL = "ChannelManager:AutoSelect:Interval"
161WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK = "ChannelManager:SupportedChannelMask"
162WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK = "ChannelManager:FavoredChannelMask"
163
164WPAN_NCP_COUNTER_ALL_MAC = "NCP:Counter:AllMac"
165WPAN_NCP_COUNTER_ALL_MAC_ASVALMAP = "NCP:Counter:AllMac:AsValMap"
166WPAN_NCP_COUNTER_TX_PKT_TOTAL = "NCP:Counter:TX_PKT_TOTAL"
167WPAN_NCP_COUNTER_TX_PKT_UNICAST = "NCP:Counter:TX_PKT_UNICAST"
168WPAN_NCP_COUNTER_TX_PKT_BROADCAST = "NCP:Counter:TX_PKT_BROADCAST"
169WPAN_NCP_COUNTER_TX_PKT_ACK_REQ = "NCP:Counter:TX_PKT_ACK_REQ"
170WPAN_NCP_COUNTER_TX_PKT_ACKED = "NCP:Counter:TX_PKT_ACKED"
171WPAN_NCP_COUNTER_TX_PKT_NO_ACK_REQ = "NCP:Counter:TX_PKT_NO_ACK_REQ"
172WPAN_NCP_COUNTER_TX_PKT_DATA = "NCP:Counter:TX_PKT_DATA"
173WPAN_NCP_COUNTER_TX_PKT_DATA_POLL = "NCP:Counter:TX_PKT_DATA_POLL"
174WPAN_NCP_COUNTER_TX_PKT_BEACON = "NCP:Counter:TX_PKT_BEACON"
175WPAN_NCP_COUNTER_TX_PKT_BEACON_REQ = "NCP:Counter:TX_PKT_BEACON_REQ"
176WPAN_NCP_COUNTER_TX_PKT_OTHER = "NCP:Counter:TX_PKT_OTHER"
177WPAN_NCP_COUNTER_TX_PKT_RETRY = "NCP:Counter:TX_PKT_RETRY"
178WPAN_NCP_COUNTER_TX_ERR_CCA = "NCP:Counter:TX_ERR_CCA"
179WPAN_NCP_COUNTER_TX_ERR_ABORT = "NCP:Counter:TX_ERR_ABORT"
180WPAN_NCP_COUNTER_RX_PKT_TOTAL = "NCP:Counter:RX_PKT_TOTAL"
181WPAN_NCP_COUNTER_RX_PKT_UNICAST = "NCP:Counter:RX_PKT_UNICAST"
182WPAN_NCP_COUNTER_RX_PKT_BROADCAST = "NCP:Counter:RX_PKT_BROADCAST"
183WPAN_NCP_COUNTER_RX_PKT_DATA = "NCP:Counter:RX_PKT_DATA"
184WPAN_NCP_COUNTER_RX_PKT_DATA_POLL = "NCP:Counter:RX_PKT_DATA_POLL"
185WPAN_NCP_COUNTER_RX_PKT_BEACON = "NCP:Counter:RX_PKT_BEACON"
186WPAN_NCP_COUNTER_RX_PKT_BEACON_REQ = "NCP:Counter:RX_PKT_BEACON_REQ"
187WPAN_NCP_COUNTER_RX_PKT_OTHER = "NCP:Counter:RX_PKT_OTHER"
188WPAN_NCP_COUNTER_RX_PKT_FILT_WL = "NCP:Counter:RX_PKT_FILT_WL"
189WPAN_NCP_COUNTER_RX_PKT_FILT_DA = "NCP:Counter:RX_PKT_FILT_DA"
190WPAN_NCP_COUNTER_RX_ERR_EMPTY = "NCP:Counter:RX_ERR_EMPTY"
191WPAN_NCP_COUNTER_RX_ERR_UKWN_NBR = "NCP:Counter:RX_ERR_UKWN_NBR"
192WPAN_NCP_COUNTER_RX_ERR_NVLD_SADDR = "NCP:Counter:RX_ERR_NVLD_SADDR"
193WPAN_NCP_COUNTER_RX_ERR_SECURITY = "NCP:Counter:RX_ERR_SECURITY"
194WPAN_NCP_COUNTER_RX_ERR_BAD_FCS = "NCP:Counter:RX_ERR_BAD_FCS"
195WPAN_NCP_COUNTER_RX_ERR_OTHER = "NCP:Counter:RX_ERR_OTHER"
196WPAN_NCP_COUNTER_TX_IP_SEC_TOTAL = "NCP:Counter:TX_IP_SEC_TOTAL"
197WPAN_NCP_COUNTER_TX_IP_INSEC_TOTAL = "NCP:Counter:TX_IP_INSEC_TOTAL"
198WPAN_NCP_COUNTER_TX_IP_DROPPED = "NCP:Counter:TX_IP_DROPPED"
199WPAN_NCP_COUNTER_RX_IP_SEC_TOTAL = "NCP:Counter:RX_IP_SEC_TOTAL"
200WPAN_NCP_COUNTER_RX_IP_INSEC_TOTAL = "NCP:Counter:RX_IP_INSEC_TOTAL"
201WPAN_NCP_COUNTER_RX_IP_DROPPED = "NCP:Counter:RX_IP_DROPPED"
202WPAN_NCP_COUNTER_TX_SPINEL_TOTAL = "NCP:Counter:TX_SPINEL_TOTAL"
203WPAN_NCP_COUNTER_RX_SPINEL_TOTAL = "NCP:Counter:RX_SPINEL_TOTAL"
204WPAN_NCP_COUNTER_RX_SPINEL_ERR = "NCP:Counter:RX_SPINEL_ERR"
205WPAN_NCP_COUNTER_IP_TX_SUCCESS = "NCP:Counter:IP_TX_SUCCESS"
206WPAN_NCP_COUNTER_IP_RX_SUCCESS = "NCP:Counter:IP_RX_SUCCESS"
207WPAN_NCP_COUNTER_IP_TX_FAILURE = "NCP:Counter:IP_TX_FAILURE"
208WPAN_NCP_COUNTER_IP_RX_FAILURE = "NCP:Counter:IP_RX_FAILURE"
209
210# ----------------------------------------------------------------------------------------------------------------------
211# Valid state values
212
213STATE_UNINITIALIZED = '"uninitialized"'
214STATE_FAULT = '"uninitialized:fault"'
215STATE_UPGRADING = '"uninitialized:upgrading"'
216STATE_DEEP_SLEEP = '"offline:deep-sleep"'
217STATE_OFFLINE = '"offline"'
218STATE_COMMISSIONED = '"offline:commissioned"'
219STATE_ASSOCIATING = '"associating"'
220STATE_CREDENTIALS_NEEDED = '"associating:credentials-needed"'
221STATE_ASSOCIATED = '"associated"'
222STATE_ISOLATED = '"associated:no-parent"'
223STATE_NETWAKE_ASLEEP = '"associated:netwake-asleep"'
224STATE_NETWAKE_WAKING = '"associated:netwake-waking"'
225
226# -----------------------------------------------------------------------------------------------------------------------
227# MCU Power state from `WPAN_NCP_MCU_POWER_STATE`
228
229MCU_POWER_STATE_ON = '"on"'
230MCU_POWER_STATE_LOW_POWER = '"low-power"'
231MCU_POWER_STATE_OFF = '"off"'
232
233# -----------------------------------------------------------------------------------------------------------------------
234# Node Radio Link Types (Use as input to `Node()` initializer)
235
236NODE_15_4 = "-15.4"
237NODE_TREL = "-trel"
238NODE_15_4_TREL = "-15.4-trel"
239
240# -----------------------------------------------------------------------------------------------------------------------
241# Node types (from `WPAN_NODE_TYPE` property)
242
243NODE_TYPE_UNKNOWN = '"unknown"'
244NODE_TYPE_LEADER = '"leader"'
245NODE_TYPE_ROUTER = '"router"'
246NODE_TYPE_END_DEVICE = '"end-device"'
247NODE_TYPE_SLEEPY_END_DEVICE = '"sleepy-end-device"'
248NODE_TYPE_COMMISSIONER = '"commissioner"'
249NODE_TYPE_NEST_LURKER = '"nl-lurker"'
250
251# -----------------------------------------------------------------------------------------------------------------------
252# Node types used by `Node.join()`
253
254JOIN_TYPE_ROUTER = 'r'
255JOIN_TYPE_END_DEVICE = 'e'
256JOIN_TYPE_SLEEPY_END_DEVICE = 's'
257
258# -----------------------------------------------------------------------------------------------------------------------
259# Address Cache Table Entry States
260
261ADDRESS_CACHE_ENTRY_STATE_CACHED = "cached"
262ADDRESS_CACHE_ENTRY_STATE_SNOOPED = "snooped"
263ADDRESS_CACHE_ENTRY_STATE_QUERY = "query"
264ADDRESS_CACHE_ENTRY_STATE_RETRY_QUERY = "retry-query"
265
266# -----------------------------------------------------------------------------------------------------------------------
267# Bit Flags for Thread Device Mode `WPAN_THREAD_DEVICE_MODE`
268
269THREAD_MODE_FLAG_FULL_NETWORK_DATA = (1 << 0)
270THREAD_MODE_FLAG_FULL_THREAD_DEV = (1 << 1)
271THREAD_MODE_FLAG_RX_ON_WHEN_IDLE = (1 << 3)
272
273# -----------------------------------------------------------------------------------------------------------------------
274# Radio Link type
275
276RADIO_LINK_IEEE_802_15_4 = "IEEE_802_15_4"
277RADIO_LINK_TREL_UDP6 = "TREL_UDP6"
278RADIO_LINK_TOBLE = "TOBLE"
279
280_OT_BUILDDIR = os.getenv('top_builddir', '../../..')
281_WPANTUND_PREFIX = os.getenv('WPANTUND_PREFIX', '/usr/local')
282
283# -----------------------------------------------------------------------------------------------------------------------
284
285
286def _log(text, new_line=True, flush=True):
287    sys.stdout.write(text)
288    if new_line:
289        sys.stdout.write('\n')
290    if flush:
291        sys.stdout.flush()
292
293
294# -----------------------------------------------------------------------------------------------------------------------
295# Node class
296
297
298class Node(object):
299    """ A wpantund OT NCP instance """
300    # defines the default verbosity setting (can be changed per `Node`)
301    _VERBOSE = os.getenv('TORANJ_VERBOSE', 'no').lower() in ['true', '1', 't', 'y', 'yes', 'on']
302    _SPEED_UP_FACTOR = 1  # defines the default time speed up factor
303
304    # path to `wpantund`, `wpanctl` and `ot-ncp-ftd`
305    _WPANTUND = '%s/sbin/wpantund' % _WPANTUND_PREFIX
306    _WPANCTL = '%s/bin/wpanctl' % _WPANTUND_PREFIX
307
308    _OT_NCP_FTD = '%s/examples/apps/ncp/ot-ncp-ftd' % _OT_BUILDDIR
309
310    # determines if the wpantund logs are saved in file or sent to stdout
311    _TUND_LOG_TO_FILE = True
312    # name of wpantund log file (if # name of wpantund _TUND_LOG_TO_FILE is
313    # True)
314    _TUND_LOG_FNAME = 'wpantund-logs'
315
316    # interface name
317    _INTFC_NAME_PREFIX = 'utun' if sys.platform == 'darwin' else 'wpan'
318    _START_INDEX = 4 if sys.platform == 'darwin' else 1
319
320    _cur_index = _START_INDEX
321    _all_nodes = weakref.WeakSet()
322
323    def __init__(self, radios=None, verbose=_VERBOSE):
324        """Creates a new `Node` instance"""
325
326        index = Node._cur_index
327        Node._cur_index += 1
328
329        self._index = index
330        self._interface_name = self._INTFC_NAME_PREFIX + str(index)
331        self._verbose = verbose
332
333        ncp_socket_path = 'system:{}{} {} --time-speed={}'.format(self._OT_NCP_FTD, '' if radios is None else radios,
334                                                                  index, self._SPEED_UP_FACTOR)
335
336        cmd = self._WPANTUND + \
337            ' -o Config:NCP:SocketPath \"{}\"'.format(ncp_socket_path) + \
338            ' -o Config:TUN:InterfaceName {}'.format(self._interface_name) + \
339            ' -o Config:NCP:DriverName spinel' + \
340            ' -o Daemon:SyslogMask \"all -debug\"'
341
342        if Node._TUND_LOG_TO_FILE:
343            self._tund_log_file = open(self._TUND_LOG_FNAME + str(index) + '.log', 'wb')
344        else:
345            self._tund_log_file = None
346
347        if self._verbose:
348            _log('$ Node{}.__init__() cmd: {}'.format(index, cmd))
349
350        self._wpantund_process = subprocess.Popen(cmd, shell=True, stderr=self._tund_log_file)
351
352        self._wpanctl_cmd = self._WPANCTL + ' -I ' + self._interface_name + ' '
353
354        # map from local_port to `AsyncReceiver` object
355        self._recvers = weakref.WeakValueDictionary()
356        Node._all_nodes.add(self)
357
358    def __del__(self):
359        self._wpantund_process.poll()
360        if self._wpantund_process.returncode is None:
361            self._wpantund_process.terminate()
362            self._wpantund_process.wait()
363
364    def __repr__(self):
365        return 'Node (index={}, interface_name={})'.format(self._index, self._interface_name)
366
367    @property
368    def index(self):
369        return self._index
370
371    @property
372    def interface_name(self):
373        return self._interface_name
374
375    @property
376    def tund_log_file(self):
377        return self._tund_log_file
378
379    # ------------------------------------------------------------------------------------------------------------------
380    # Executing a `wpanctl` command
381
382    def wpanctl(self, cmd):
383        """ Runs a wpanctl command on the given wpantund/OT-NCP instance and returns the output """
384
385        if self._verbose:
386            _log('$ Node{}.wpanctl(\'{}\')'.format(self._index, cmd), new_line=False)
387
388        result = subprocess.check_output(self._wpanctl_cmd + cmd, shell=True, stderr=subprocess.STDOUT)
389
390        if len(result) >= 1 and result[-1] == '\n':  # remove the last char if it is '\n',
391            result = result[:-1]
392
393        if self._verbose:
394            if '\n' in result:
395                _log(':')
396                for line in result.splitlines():
397                    _log('     ' + line)
398            else:
399                _log(' -> \'{}\''.format(result))
400
401        return result
402
403    # ------------------------------------------------------------------------------------------------------------------
404    # APIs matching `wpanctl` commands.
405
406    def get(self, prop_name, value_only=True):
407        return self.wpanctl('get ' + ('-v ' if value_only else '') + prop_name)
408
409    def set(self, prop_name, value, binary_data=False):
410        return self._update_prop('set', prop_name, value, binary_data)
411
412    def add(self, prop_name, value, binary_data=False):
413        return self._update_prop('add', prop_name, value, binary_data)
414
415    def remove(self, prop_name, value, binary_data=False):
416        return self._update_prop('remove', prop_name, value, binary_data)
417
418    def _update_prop(self, action, prop_name, value, binary_data):
419        return self.wpanctl(action + ' ' + prop_name + ' ' + ('-d ' if binary_data else '') + '-v ' +
420                            value)  # use -v to handle values starting with `-`.
421
422    def reset(self):
423        return self.wpanctl('reset')
424
425    def status(self):
426        return self.wpanctl('status')
427
428    def leave(self):
429        return self.wpanctl('leave')
430
431    def form(self,
432             name,
433             channel=None,
434             channel_mask=None,
435             panid=None,
436             xpanid=None,
437             key=None,
438             key_index=None,
439             node_type=None,
440             mesh_local_prefix=None,
441             legacy_prefix=None):
442        return self.wpanctl('form \"' + name + '\"' + (' -c {}'.format(channel) if channel is not None else '') +
443                            (' -m {}'.format(channel_mask) if channel_mask is not None else '') +
444                            (' -p {}'.format(panid) if panid is not None else '') +
445                            (' -x {}'.format(xpanid) if xpanid is not None else '') +
446                            (' -k {}'.format(key) if key is not None else '') +
447                            (' -i {}'.format(key_index) if key_index is not None else '') +
448                            (' -T {}'.format(node_type) if node_type is not None else '') +
449                            (' -M {}'.format(mesh_local_prefix) if mesh_local_prefix is not None else '') +
450                            (' -L {}'.format(legacy_prefix) if legacy_prefix is not None else ''))
451
452    def join(self, name, channel=None, node_type=None, panid=None, xpanid=None, key=None):
453        return self.wpanctl('join \"' + name + '\"' + (' -c {}'.format(channel) if channel is not None else '') +
454                            (' -T {}'.format(node_type) if node_type is not None else '') +
455                            (' -p {}'.format(panid) if panid is not None else '') +
456                            (' -x {}'.format(xpanid) if xpanid is not None else '') +
457                            (' -k {}'.format(key) if key is not None else '') + (' -n'))
458
459    def active_scan(self, channel=None):
460        return self.wpanctl('scan' + (' -c {}'.format(channel) if channel is not None else ''))
461
462    def energy_scan(self, channel=None):
463        return self.wpanctl('scan -e' + (' -c {}'.format(channel) if channel is not None else ''))
464
465    def discover_scan(self, channel=None, joiner_only=False, enable_filtering=False, panid_filter=None):
466        return self.wpanctl('scan -d' + (' -c {}'.format(channel) if channel is not None else '') +
467                            (' -j' if joiner_only else '') + (' -f' if enable_filtering else '') +
468                            (' -p {}'.format(panid_filter) if panid_filter is not None else ''))
469
470    def permit_join(self, duration_sec=None, port=None, udp=True, tcp=True):
471        if not udp and not tcp:  # incorrect use!
472            return ''
473        traffic_type = ''
474        if udp and not tcp:
475            traffic_type = ' --udp'
476        if tcp and not udp:
477            traffic_type = ' --tcp'
478        if port is not None and duration_sec is None:
479            duration_sec = '240'
480
481        return self.wpanctl('permit-join' + (' {}'.format(duration_sec) if duration_sec is not None else '') +
482                            (' {}'.format(port) if port is not None else '') + traffic_type)
483
484    def config_gateway(self, prefix, default_route=False, priority=None):
485        return self.wpanctl('config-gateway ' + prefix + (' -d' if default_route else '') +
486                            (' -P {}'.format(priority) if priority is not None else ''))
487
488    def add_prefix(self,
489                   prefix,
490                   prefix_len=None,
491                   priority=None,
492                   stable=True,
493                   on_mesh=False,
494                   slaac=False,
495                   dhcp=False,
496                   configure=False,
497                   default_route=False,
498                   preferred=False):
499        return self.wpanctl('add-prefix ' + prefix + (' -l {}'.format(prefix_len) if prefix_len is not None else '') +
500                            (' -P {}'.format(priority) if priority is not None else '') + (' -s' if stable else '') +
501                            (' -f' if preferred else '') + (' -a' if slaac else '') + (' -d' if dhcp else '') +
502                            (' -c' if configure else '') + (' -r' if default_route else '') +
503                            (' -o' if on_mesh else ''))
504
505    def remove_prefix(self, prefix, prefix_len=None):
506        return self.wpanctl('remove-prefix ' + prefix +
507                            (' -l {}'.format(prefix_len) if prefix_len is not None else ''))
508
509    def add_route(self, route_prefix, prefix_len=None, priority=None, stable=True):
510        """route priority [(>0 for high, 0 for medium, <0 for low)]"""
511        return self.wpanctl('add-route ' + route_prefix +
512                            (' -l {}'.format(prefix_len) if prefix_len is not None else '') +
513                            (' -p {}'.format(priority) if priority is not None else '') + ('' if stable else ' -n'))
514
515    def remove_route(self, route_prefix, prefix_len=None, priority=None, stable=True):
516        """route priority [(>0 for high, 0 for medium, <0 for low)]"""
517        return self.wpanctl('remove-route ' + route_prefix +
518                            (' -l {}'.format(prefix_len) if prefix_len is not None else '') +
519                            (' -p {}'.format(priority) if priority is not None else ''))
520
521    def commissioner_start(self):
522        return self.wpanctl('commissioner start')
523
524    def commissioner_add_joiner(self, eui64, pskd, timeout='100'):
525        return self.wpanctl('commissioner joiner-add {} {} {}'.format(eui64, timeout, pskd))
526
527    def commissioner_add_joiner_with_discerner(self, discerner_value, discerner_bit_len, pskd, timeout='100'):
528        return self.wpanctl('commissioner joiner-add-discerner {} {} {} {}'.format(discerner_value, discerner_bit_len,
529                                                                                   timeout, pskd))
530
531    def joiner_join(self, pskd):
532        return self.wpanctl('joiner --join {}'.format(pskd))
533
534    def joiner_attach(self):
535        return self.wpanctl('joiner --attach')
536
537    # ------------------------------------------------------------------------------------------------------------------
538    # Helper methods
539
540    def is_associated(self):
541        return self.get(WPAN_STATE) == STATE_ASSOCIATED
542
543    def join_node(self, node, node_type=JOIN_TYPE_ROUTER, should_set_key=True):
544        """Join a network specified by another node, `node` should be a Node"""
545
546        if not node.is_associated():
547            return "{} is not associated".format(node)
548
549        return self.join(node.get(WPAN_NAME)[1:-1],
550                         channel=node.get(WPAN_CHANNEL),
551                         node_type=node_type,
552                         panid=node.get(WPAN_PANID),
553                         xpanid=node.get(WPAN_XPANID),
554                         key=node.get(WPAN_KEY)[1:-1] if should_set_key else None)
555
556    def allowlist_node(self, node):
557        """Adds a given node (of type `Node`) to the allowlist of `self` and enables allowlisting on `self`"""
558
559        self.add(WPAN_MAC_ALLOWLIST_ENTRIES, node.get(WPAN_EXT_ADDRESS)[1:-1])
560        self.set(WPAN_MAC_ALLOWLIST_ENABLED, '1')
561
562    def un_allowlist_node(self, node):
563        """Removes a given node (of node `Node) from the allowlist"""
564        self.remove(WPAN_MAC_ALLOWLIST_ENTRIES, node.get(WPAN_EXT_ADDRESS)[1:-1])
565
566    def is_in_scan_result(self, scan_result):
567        """Checks if node is in the scan results
568           `scan_result` must be an array of `ScanResult` object (see `parse_scan_result`).
569        """
570        panid = self.get(WPAN_PANID)
571        xpanid = self.get(WPAN_XPANID)[2:]
572        name = self.get(WPAN_NAME)[1:-1]
573        channel = self.get(WPAN_CHANNEL)
574        ext_address = self.get(WPAN_EXT_ADDRESS)[1:-1]
575
576        for item in scan_result:
577            if all([item.panid == panid, item.channel == channel, item.ext_address == ext_address]):
578                if (item.type == ScanResult.TYPE_DISCOVERY_SCAN):
579                    if all([item.network_name == name, item.xpanid == xpanid]):
580                        return True
581                    else:
582                        continue
583                return True
584
585        return False
586
587    def find_ip6_address_with_prefix(self, prefix):
588        """Find an IPv6 address on node matching a given prefix.
589           `prefix` should be an string containing the prefix.
590           Returns a string containing the IPv6 address matching the prefix or empty string if no address found.
591        """
592        if len(prefix) > 2 and prefix[-1] == ':' and prefix[-2] == ':':
593            prefix = prefix[:-1]
594        all_addrs = parse_list(self.get(WPAN_IP6_ALL_ADDRESSES))
595        matched_addr = [addr for addr in all_addrs if addr.startswith(prefix)]
596        return matched_addr[0] if len(matched_addr) >= 1 else ''
597
598    def add_ip6_address_on_interface(self, address, prefix_len=64):
599        """Adds an IPv6 interface on the network interface.
600           `address` should be string containing the IPv6 address.
601           `prefix_len` is an `int` specifying the prefix length.
602           NOTE: this method uses linux `ip` command.
603        """
604        cmd = 'ip -6 addr add ' + address + \
605            '/{} dev '.format(prefix_len) + self.interface_name
606        if self._verbose:
607            _log('$ Node{} \'{}\')'.format(self._index, cmd))
608
609        result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
610        return result
611
612    def remove_ip6_address_on_interface(self, address, prefix_len=64):
613        """Removes an IPv6 interface on the network interface.
614           `address` should be string containing the IPv6 address.
615           `prefix_len` is an `int` specifying the prefix length.
616           NOTE: this method uses linux `ip` command.
617        """
618        cmd = 'ip -6 addr del ' + address + \
619            '/{} dev '.format(prefix_len) + self.interface_name
620        if self._verbose:
621            _log('$ Node{} \'{}\')'.format(self._index, cmd))
622
623        result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
624        return result
625
626    # ------------------------------------------------------------------------------------------------------------------
627    # class methods
628
629    @classmethod
630    def init_all_nodes(cls, disable_logs=not _VERBOSE, wait_time=15):
631        """Issues a `wpanctl.leave` on all `Node` objects and waits for them to be ready"""
632        random.seed(123456)
633        time.sleep(0.5)
634        for node in Node._all_nodes:
635            start_time = time.time()
636            while True:
637                try:
638                    node._wpantund_process.poll()
639                    if node._wpantund_process.returncode is not None:
640                        print('Node {} wpantund instance has terminated unexpectedly'.format(node))
641                    if disable_logs:
642                        node.set(WPAN_OT_LOG_LEVEL, '0')
643                    node.leave()
644                except subprocess.CalledProcessError as e:
645                    if (node._verbose):
646                        _log(' -> \'{}\' exit code: {}'.format(e.output, e.returncode))
647                    interval = time.time() - start_time
648                    if interval > wait_time:
649                        print('Took too long to init node {} ({}>{} sec)'.format(node, interval, wait_time))
650                        raise
651                except BaseException:
652                    raise
653                else:
654                    break
655                time.sleep(0.4)
656
657    @classmethod
658    def finalize_all_nodes(cls):
659        """Finalizes all previously created `Node` instances (stops the wpantund process)"""
660        for node in Node._all_nodes:
661            node._wpantund_process.terminate()
662            node._wpantund_process.wait()
663
664    @classmethod
665    def set_time_speedup_factor(cls, factor):
666        """Sets up the time speed up factor - should be set before creating any `Node` objects"""
667        if len(Node._all_nodes) != 0:
668            raise Node._NodeError('set_time_speedup_factor() cannot be called after creating a `Node`')
669        Node._SPEED_UP_FACTOR = factor
670
671    # ------------------------------------------------------------------------------------------------------------------
672    # IPv6 message Sender and Receiver class
673
674    class _NodeError(Exception):
675        pass
676
677    def prepare_tx(self, src, dst, data=40, count=1, mcast_hops=None):
678        """Prepares an IPv6 msg transmission.
679
680        - `src` and `dst` can be either a string containing IPv6 address, or a tuple (ipv6 address as string, port),
681           if no port is given, a random port number is used.
682        - `data` can be either a string containing the message to be sent, or an int indicating size of the message (a
683           random message with the given length will be used).
684        - `count` gives number of times the message will be sent (default is 1).
685        - `mcast_hops` specifies multicast hop limit (only applicable for multicast tx).
686
687        Returns an `AsyncSender` object.
688
689        """
690        if isinstance(src, tuple):
691            src_addr = src[0]
692            src_port = src[1]
693        else:
694            src_addr = src
695            src_port = random.randint(49152, 65535)
696
697        if isinstance(dst, tuple):
698            dst_addr = dst[0]
699            dst_port = dst[1]
700        else:
701            dst_addr = dst
702            dst_port = random.randint(49152, 65535)
703
704        if isinstance(data, int):
705            # create a random message with the given length.
706            all_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,><?;:[]=-+)(*&^%$#@'
707            msg = ''.join(random.choice(all_chars) for _ in range(data))
708        else:
709            msg = data
710
711        return AsyncSender(self, src_addr, src_port, dst_addr, dst_port, msg, count, mcast_hops)
712
713    def _get_receiver(self, local_port):
714        # Gets or creates a receiver (an `AsyncReceiver`) tied to given port
715        # number
716        if local_port in self._recvers:
717            receiver = self._recvers[local_port]
718        else:
719            receiver = AsyncReceiver(self, local_port)
720            self._recvers[local_port] = receiver
721        return receiver
722
723    def _remove_recver(self, recvr):
724        # Removes a receiver from weak dictionary - called when the receiver is
725        # done and its socket is closed
726        local_port = recvr.local_port
727        if local_port in self._recvers:
728            del self._recvers[local_port]
729
730    def prepare_rx(self, sender):
731        """Prepare to receive messages from a sender (an `AsyncSender`)"""
732        receiver = self._get_receiver(sender.dst_port)
733        receiver._add_sender(sender.src_addr, sender.src_port, sender.msg, sender.count)
734        return receiver
735
736    def prepare_listener(self, local_port, timeout=1):
737        """Prepares a listener (an `AsyncReceiver`) listening on the given `local_port` for given `timeout` (sec)"""
738        receiver = self._get_receiver(local_port)
739        receiver._set_listen_timeout(timeout)
740        return receiver
741
742    @staticmethod
743    def perform_async_tx_rx(timeout=20):
744        """Called to perform all previously prepared async rx/listen and tx operations"""
745        try:
746            start_time = time.time()
747            while asyncore.socket_map:
748                elapsed_time = time.time() - start_time
749                if elapsed_time > timeout:
750                    print('Performing aysnc tx/tx took too long ({}>{} sec)'.format(elapsed_time, timeout))
751                    raise Node._NodeError('perform_tx_rx timed out ({}>{} sec)'.format(elapsed_time, timeout))
752                # perform a single asyncore loop
753                asyncore.loop(timeout=0.5, count=1)
754        except BaseException:
755            print('Failed to perform async rx/tx')
756            raise
757
758
759# -----------------------------------------------------------------------------------------------------------------------
760# `AsyncSender` and `AsyncReceiver classes
761
762_SO_BINDTODEVICE = 25
763
764
765def _is_ipv6_addr_link_local(ip_addr):
766    """Indicates if a given IPv6 address is link-local"""
767    return ip_addr.lower().startswith('fe80::')
768
769
770def _create_socket_address(ip_address, port):
771    """Convert a given IPv6 address (string) and port number into a socket address"""
772    # `socket.getaddrinfo()` returns a list of `(family, socktype, proto, canonname, sockaddr)` where `sockaddr`
773    # (at index 4) can be used as input in socket methods (like `sendto()`, `bind()`, etc.).
774    return socket.getaddrinfo(ip_address, port)[0][4]
775
776
777class AsyncSender(asyncore.dispatcher):
778    """ An IPv6 async message sender - use `Node.prepare_tx()` to create one"""
779
780    def __init__(self, node, src_addr, src_port, dst_addr, dst_port, msg, count, mcast_hops=None):
781        self._node = node
782        self._src_addr = src_addr
783        self._src_port = src_port
784        self._dst_addr = dst_addr
785        self._dst_port = dst_port
786        self._msg = msg
787        self._count = count
788        self._dst_sock_addr = _create_socket_address(dst_addr, dst_port)
789        self._tx_buffer = self._msg
790        self._tx_counter = 0
791
792        # Create a socket, bind it to the node's interface
793        sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
794        sock.setsockopt(socket.SOL_SOCKET, _SO_BINDTODEVICE, node.interface_name + '\0')
795        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
796
797        # Set the IPV6_MULTICAST_HOPS
798        if mcast_hops is not None:
799            sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, mcast_hops)
800
801        # Bind the socket to the given src address
802        if _is_ipv6_addr_link_local(src_addr):
803            # If src is a link local address it requires the interface name to
804            # be specified.
805            src_sock_addr = _create_socket_address(src_addr + '%' + node.interface_name, src_port)
806        else:
807            src_sock_addr = _create_socket_address(src_addr, src_port)
808        sock.bind(src_sock_addr)
809
810        asyncore.dispatcher.__init__(self, sock)
811
812    # Property getters
813
814    @property
815    def node(self):
816        return self._node
817
818    @property
819    def src_addr(self):
820        return self._src_addr
821
822    @property
823    def src_port(self):
824        return self._src_port
825
826    @property
827    def dst_addr(self):
828        return self._dst_addr
829
830    @property
831    def dst_port(self):
832        return self._dst_port
833
834    @property
835    def msg(self):
836        return self._msg
837
838    @property
839    def count(self):
840        return self._count
841
842    @property
843    def was_successful(self):
844        """Indicates if the transmission of IPv6 messages finished successfully"""
845        return self._tx_counter == self._count
846
847    # asyncore.dispatcher callbacks
848
849    def readable(self):
850        return False
851
852    def writable(self):
853        return True
854
855    def handle_write(self):
856        sent_len = self.sendto(self._tx_buffer, self._dst_sock_addr)
857
858        if self._node._verbose:
859            if sent_len < 30:
860                info_text = '{} bytes ("{}")'.format(sent_len, self._tx_buffer[:sent_len])
861            else:
862                info_text = '{} bytes'.format(sent_len)
863            _log('- Node{} sent {} to [{}]:{} from [{}]:{}'.format(self._node._index, info_text, self._dst_addr,
864                                                                   self._dst_port, self._src_addr, self._src_port))
865
866        self._tx_buffer = self._tx_buffer[sent_len:]
867
868        if len(self._tx_buffer) == 0:
869            self._tx_counter += 1
870            if self._tx_counter < self._count:
871                self._tx_buffer = self._msg
872            else:
873                self.handle_close()
874
875    def handle_close(self):
876        self.close()
877
878
879# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
880
881
882class AsyncReceiver(asyncore.dispatcher):
883    """ An IPv6 async message receiver - use `prepare_rx()` to create one"""
884
885    _MAX_RECV_SIZE = 2048
886
887    class _SenderInfo(object):
888
889        def __init__(self, sender_addr, sender_port, msg, count):
890            self._sender_addr = sender_addr
891            self._sender_port = sender_port
892            self._msg = msg
893            self._count = count
894            self._rx_counter = 0
895
896        def _check_received(self, msg, sender_addr, sender_port):
897            if self._msg == msg and self._sender_addr == sender_addr and self._sender_port == sender_port:
898                self._rx_counter += 1
899            return self._did_recv_all()
900
901        def _did_recv_all(self):
902            return self._rx_counter >= self._count
903
904    def __init__(self, node, local_port):
905        self._node = node
906        self._local_port = local_port
907        self._senders = []  # list of `_SenderInfo` objects
908        # contains all received messages as a list of (pkt, (src_addr,
909        # src_port))
910        self._all_rx = []
911        self._timeout = 0  # listen timeout (zero means forever)
912        self._started = False
913        self._start_time = 0
914
915        # Create a socket, bind it to the node's interface
916        sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
917        sock.setsockopt(socket.SOL_SOCKET, _SO_BINDTODEVICE, node.interface_name + '\0')
918        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
919
920        # Bind the socket to any IPv6 address with the given local port
921        local_sock_addr = _create_socket_address('::', local_port)
922        sock.bind(local_sock_addr)
923
924        asyncore.dispatcher.__init__(self, sock)
925
926    def _add_sender(self, sender_addr, sender_port, msg, count):
927        self._senders.append(AsyncReceiver._SenderInfo(sender_addr, sender_port, msg, count))
928
929    def _set_listen_timeout(self, timeout):
930        self._timeout = timeout
931
932    # Property getters
933
934    @property
935    def node(self):
936        return self._node
937
938    @property
939    def local_port(self):
940        return self._local_port
941
942    @property
943    def all_rx_msg(self):
944        """returns all received messages as a list of (msg, (src_addr, src_port))"""
945        return self._all_rx
946
947    @property
948    def was_successful(self):
949        """Indicates if all expected IPv6 messages were received successfully"""
950        return len(self._senders) == 0 or all([sender._did_recv_all() for sender in self._senders])
951
952    # asyncore.dispatcher callbacks
953
954    def readable(self):
955        if not self._started:
956            self._start_time = time.time()
957            self._started = True
958        if self._timeout != 0 and time.time() - self._start_time >= self._timeout:
959            self.handle_close()
960            if self._node._verbose:
961                _log('- Node{} finished listening on port {} for {} sec, received {} msg(s)'.format(
962                    self._node._index, self._local_port, self._timeout, len(self._all_rx)))
963            return False
964        return True
965
966    def writable(self):
967        return False
968
969    def handle_read(self):
970        (msg, src_sock_addr) = self.recvfrom(AsyncReceiver._MAX_RECV_SIZE)
971        src_addr = src_sock_addr[0]
972        src_port = src_sock_addr[1]
973
974        if (_is_ipv6_addr_link_local(src_addr)):
975            if '%' in src_addr:
976                # remove the interface name from address
977                src_addr = src_addr.split('%')[0]
978
979        if self._node._verbose:
980            if len(msg) < 30:
981                info_text = '{} bytes ("{}")'.format(len(msg), msg)
982            else:
983                info_text = '{} bytes'.format(len(msg))
984            _log('- Node{} received {} on port {} from [{}]:{}'.format(self._node._index, info_text, self._local_port,
985                                                                       src_addr, src_port))
986
987        self._all_rx.append((msg, (src_addr, src_port)))
988
989        if all([sender._check_received(msg, src_addr, src_port) for sender in self._senders]):
990            self.handle_close()
991
992    def handle_close(self):
993        self.close()
994        # remove the receiver from the node once the socket is closed
995        self._node._remove_recver(self)
996
997
998# -----------------------------------------------------------------------------------------------------------------------
999
1000
1001class VerifyError(Exception):
1002    pass
1003
1004
1005_is_in_verify_within = False
1006
1007
1008def verify(condition):
1009    """Verifies that a `condition` is true, otherwise raises a VerifyError"""
1010    global _is_in_verify_within
1011    if not condition:
1012        calling_frame = inspect.currentframe().f_back
1013        error_message = 'verify() failed at line {} in "{}"'.format(calling_frame.f_lineno,
1014                                                                    calling_frame.f_code.co_filename)
1015        if not _is_in_verify_within:
1016            print(error_message)
1017        raise VerifyError(error_message)
1018
1019
1020def verify_within(condition_checker_func, wait_time, delay_time=0.1):
1021    """Verifies that a given function `condition_checker_func` passes successfully within a given wait timeout.
1022       `wait_time` is maximum time waiting for condition_checker to pass (in seconds).
1023       `delay_time` specifies a delay interval added between failed attempts (in seconds).
1024    """
1025    global _is_in_verify_within
1026    start_time = time.time()
1027    old_is_in_verify_within = _is_in_verify_within
1028    _is_in_verify_within = True
1029    while True:
1030        try:
1031            condition_checker_func()
1032        except VerifyError as e:
1033            if time.time() - start_time > wait_time:
1034                print('Took too long to pass the condition ({}>{} sec)'.format(time.time() - start_time, wait_time))
1035                print(e.message)
1036                raise e
1037        except BaseException:
1038            raise
1039        else:
1040            break
1041        if delay_time != 0:
1042            time.sleep(delay_time)
1043    _is_in_verify_within = old_is_in_verify_within
1044
1045
1046# -----------------------------------------------------------------------------------------------------------------------
1047# Parsing `wpanctl` output
1048
1049# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1050
1051
1052class ScanResult(object):
1053    """ This object encapsulates a scan result (active/discover/energy scan)"""
1054
1055    TYPE_ACTIVE_SCAN = 'active-scan'
1056    TYPE_DISCOVERY_SCAN = 'discover-scan'
1057    TYPE_ENERGY_SCAN = 'energy-scan'
1058
1059    def __init__(self, result_text):
1060
1061        items = [item.strip() for item in result_text.split('|')]
1062
1063        if len(items) == 2:
1064            self._type = ScanResult.TYPE_ENERGY_SCAN
1065            self._channel = items[0]
1066            self._rssi = items[1]
1067        if len(items) == 7 and '------ NONE ------' in items[1]:
1068            self._type = ScanResult.TYPE_ACTIVE_SCAN
1069            self._index = items[0]
1070            self._panid = items[2]
1071            self._channel = items[3]
1072            self._ext_address = items[5]
1073            self._rssi = items[6]
1074        elif len(items) == 7:
1075            self._type = ScanResult.TYPE_DISCOVERY_SCAN
1076            self._index = items[0]
1077            self._network_name = items[1][1:-1]
1078            self._panid = items[2]
1079            self._channel = items[3]
1080            self._xpanid = items[4]
1081            self._ext_address = items[5]
1082            self._rssi = items[6]
1083        else:
1084            raise ValueError('"%s" does not seem to be a valid scan result string' % result_text)
1085
1086    @property
1087    def type(self):
1088        return self._type
1089
1090    @property
1091    def joinable(self):
1092        return self._joinable
1093
1094    @property
1095    def network_name(self):
1096        return self._network_name
1097
1098    @property
1099    def panid(self):
1100        return self._panid
1101
1102    @property
1103    def channel(self):
1104        return self._channel
1105
1106    @property
1107    def xpanid(self):
1108        return self._xpanid
1109
1110    @property
1111    def ext_address(self):
1112        return self._ext_address
1113
1114    @property
1115    def rssi(self):
1116        return self._rssi
1117
1118    def __repr__(self):
1119        return 'ScanResult({})'.format(self.__dict__)
1120
1121
1122def parse_scan_result(scan_result):
1123    """ Parses scan result string and returns an array of `ScanResult` objects"""
1124    return [ScanResult(item) for item in scan_result.split('\n')[2:]]  # skip first two lines which are table headers
1125
1126
1127def parse_list(list_string):
1128    """
1129    Parses IPv6/prefix/route list string (output of wpanctl get for properties WPAN_IP6_ALL_ADDRESSES,
1130    IP6_MULTICAST_ADDRESSES, WPAN_THREAD_ON_MESH_PREFIXES, ...)
1131    Returns an array of strings each containing an IPv6/prefix/route entry.
1132    """
1133    # List string example (get(WPAN_IP6_ALL_ADDRESSES) output):
1134    #
1135    # '[\n
1136    # \t"fdf4:5632:4940:0:8798:8701:85d4:e2be     prefix_len:64   origin:ncp      valid:forever   preferred:forever"\n
1137    # \t"fe80::2092:9358:97ea:71c6                prefix_len:64   origin:ncp      valid:forever   preferred:forever"\n
1138    # ]'
1139    #
1140    # We split the lines ('\n' as separator) and skip the first and last lines which are '['  and ']'.
1141    # For each line, skip the first two characters (which are '\t"') and last character ('"'), then split the string
1142    # using whitespace as separator. The first entry is the IPv6 address.
1143    #
1144    return [line[2:-1].split()[0] for line in list_string.split('\n')[1:-1]]
1145
1146
1147# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1148
1149
1150class OnMeshPrefix(object):
1151    """ This object encapsulates an on-mesh prefix"""
1152
1153    def __init__(self, text):
1154
1155        # Example of expected text:
1156        #
1157        # '\t"fd00:abba:cafe::       prefix_len:64   origin:user     stable:yes flags:0x31'
1158        # ' [on-mesh:1 def-route:0 config:0 dhcp:0 slaac:1 pref:1 prio:med] rloc:0x0000"'
1159
1160        m = re.match(
1161            r'\t"([0-9a-fA-F:]+)\s*prefix_len:(\d+)\s+origin:(\w*)\s+stable:(\w*).* \[' +
1162            r'on-mesh:(\d)\s+def-route:(\d)\s+config:(\d)\s+dhcp:(\d)\s+slaac:(\d)\s+pref:(\d)\s+.*prio:(\w*)\]' +
1163            r'\s+rloc:(0x[0-9a-fA-F]+)', text)
1164        verify(m is not None)
1165        data = m.groups()
1166
1167        self._prefix = data[0]
1168        self._prefix_len = data[1]
1169        self._origin = data[2]
1170        self._stable = (data[3] == 'yes')
1171        self._on_mesh = (data[4] == '1')
1172        self._def_route = (data[5] == '1')
1173        self._config = (data[6] == '1')
1174        self._dhcp = (data[7] == '1')
1175        self._slaac = (data[8] == '1')
1176        self._preferred = (data[9] == '1')
1177        self._priority = (data[10])
1178        self._rloc16 = (data[11])
1179
1180    @property
1181    def prefix(self):
1182        return self._prefix
1183
1184    @property
1185    def prefix_len(self):
1186        return self._prefix_len
1187
1188    @property
1189    def origin(self):
1190        return self._origin
1191
1192    @property
1193    def priority(self):
1194        return self._priority
1195
1196    def is_stable(self):
1197        return self._stable
1198
1199    def is_on_mesh(self):
1200        return self._on_mesh
1201
1202    def is_def_route(self):
1203        return self._def_route
1204
1205    def is_config(self):
1206        return self._config
1207
1208    def is_dhcp(self):
1209        return self._dhcp
1210
1211    def is_slaac(self):
1212        return self._slaac
1213
1214    def is_preferred(self):
1215        return self._preferred
1216
1217    def rloc16(self):
1218        return self._rloc16
1219
1220    def __repr__(self):
1221        return 'OnMeshPrefix({})'.format(self.__dict__)
1222
1223
1224def parse_on_mesh_prefix_result(on_mesh_prefix_list):
1225    """ Parses on-mesh prefix list string and returns an array of `OnMeshPrefix` objects"""
1226    return [OnMeshPrefix(item) for item in on_mesh_prefix_list.split('\n')[1:-1]]
1227
1228
1229# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1230
1231
1232class ChildEntry(object):
1233    """ This object encapsulates a child entry"""
1234
1235    def __init__(self, text):
1236
1237        # Example of expected text:
1238        #
1239        # `\t"E24C5F67F4B8CBB9, RLOC16:d402, NetDataVer:175, LQIn:3, AveRssi:-20, LastRssi:-20, Timeout:120, Age:0, `
1240        # `RxOnIdle:no, FTD:no, SecDataReq:yes, FullNetData:yes"`
1241        #
1242
1243        # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
1244        # Then remove any ',' at end of items in the list.
1245        items = [item[:-1] if item[-1] == ',' else item for item in text[2:-1].split()]
1246
1247        # First item in the extended address
1248        self._ext_address = items[0]
1249
1250        # Convert the rest into a dictionary by splitting using ':' as
1251        # separator
1252        dict = {item.split(':')[0]: item.split(':')[1] for item in items[1:]}
1253
1254        self._rloc16 = dict['RLOC16']
1255        self._timeout = dict['Timeout']
1256        self._rx_on_idle = (dict['RxOnIdle'] == 'yes')
1257        self._ftd = (dict['FTD'] == 'yes')
1258        self._sec_data_req = (dict['SecDataReq'] == 'yes')
1259        self._full_net_data = (dict['FullNetData'] == 'yes')
1260
1261    @property
1262    def ext_address(self):
1263        return self._ext_address
1264
1265    @property
1266    def rloc16(self):
1267        return self._rloc16
1268
1269    @property
1270    def timeout(self):
1271        return self._timeout
1272
1273    def is_rx_on_when_idle(self):
1274        return self._rx_on_idle
1275
1276    def is_ftd(self):
1277        return self._ftd
1278
1279    def is_sec_data_req(self):
1280        return self._sec_data_req
1281
1282    def is_full_net_data(self):
1283        return self._full_net_data
1284
1285    def __repr__(self):
1286        return 'ChildEntry({})'.format(self.__dict__)
1287
1288
1289def parse_child_table_result(child_table_list):
1290    """ Parses child table list string and returns an array of `ChildEntry` objects"""
1291    return [ChildEntry(item) for item in child_table_list.split('\n')[1:-1]]
1292
1293
1294# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1295
1296
1297class NeighborEntry(object):
1298    """ This object encapsulates a neighbor entry"""
1299
1300    def __init__(self, text):
1301
1302        # Example of expected text:
1303        #
1304        # `\t"5AC95ED4646D6565, RLOC16:9403, LQIn:3, AveRssi:-20, LastRssi:-20, Age:0, LinkFC:8, MleFC:0, IsChild:yes,'
1305        # 'RxOnIdle:no, FTD:no, SecDataReq:yes, FullNetData:yes"'
1306        #
1307
1308        # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
1309        # Then remove any ',' at end of items in the list.
1310        items = [item[:-1] if item[-1] == ',' else item for item in text[2:-1].split()]
1311
1312        # First item in the extended address
1313        self._ext_address = items[0]
1314
1315        # Convert the rest into a dictionary by splitting the text using ':' as
1316        # separator
1317        dict = {item.split(':')[0]: item.split(':')[1] for item in items[1:]}
1318
1319        self._rloc16 = dict['RLOC16']
1320        self._is_child = (dict['IsChild'] == 'yes')
1321        self._rx_on_idle = (dict['RxOnIdle'] == 'yes')
1322        self._ftd = (dict['FTD'] == 'yes')
1323
1324    @property
1325    def ext_address(self):
1326        return self._ext_address
1327
1328    @property
1329    def rloc16(self):
1330        return self._rloc16
1331
1332    def is_rx_on_when_idle(self):
1333        return self._rx_on_idle
1334
1335    def is_ftd(self):
1336        return self._ftd
1337
1338    def is_child(self):
1339        return self._is_child
1340
1341    def __repr__(self):
1342        return 'NeighborEntry({})'.format(self.__dict__)
1343
1344
1345def parse_neighbor_table_result(neighbor_table_list):
1346    """ Parses neighbor table list string and returns an array of `NeighborEntry` objects"""
1347    return [NeighborEntry(item) for item in neighbor_table_list.split('\n')[1:-1]]
1348
1349
1350# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1351
1352
1353class RouterTableEntry(object):
1354    """ This object encapsulates a router table entry"""
1355
1356    def __init__(self, text):
1357
1358        # Example of expected text:
1359        #
1360        # `\t"8A970B3251810826, RLOC16:4000, RouterId:16, NextHop:43, PathCost:1, LQIn:3, LQOut:3, Age:3, LinkEst:yes"`
1361        #
1362
1363        # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
1364        # Then remove any ',' at end of items in the list.
1365        items = [item[:-1] if item[-1] == ',' else item for item in text[2:-1].split()]
1366
1367        # First item in the extended address
1368        self._ext_address = items[0]
1369
1370        # Convert the rest into a dictionary by splitting the text using ':' as
1371        # separator
1372        dict = {item.split(':')[0]: item.split(':')[1] for item in items[1:]}
1373
1374        self._rloc16 = int(dict['RLOC16'], 16)
1375        self._router_id = int(dict['RouterId'], 0)
1376        self._next_hop = int(dict['NextHop'], 0)
1377        self._path_cost = int(dict['PathCost'], 0)
1378        self._age = int(dict['Age'], 0)
1379        self._le = (dict['LinkEst'] == 'yes')
1380
1381    @property
1382    def ext_address(self):
1383        return self._ext_address
1384
1385    @property
1386    def rloc16(self):
1387        return self._rloc16
1388
1389    @property
1390    def router_id(self):
1391        return self._router_id
1392
1393    @property
1394    def next_hop(self):
1395        return self._next_hop
1396
1397    @property
1398    def path_cost(self):
1399        return self._path_cost
1400
1401    def is_link_established(self):
1402        return self._le
1403
1404    def __repr__(self):
1405        return 'RouterTableEntry({})'.format(self.__dict__)
1406
1407
1408def parse_router_table_result(router_table_list):
1409    """ Parses router table list string and returns an array of `RouterTableEntry` objects"""
1410    return [RouterTableEntry(item) for item in router_table_list.split('\n')[1:-1]]
1411
1412
1413# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1414
1415
1416class AddressCacheEntry(object):
1417    """ This object encapsulates an address cache entry"""
1418
1419    def __init__(self, text):
1420
1421        # Example of expected text:
1422        #
1423        # '\t"fd00:1234::100:8 -> 0xfffe, Age:1, State:query, CanEvict:no, Timeout:3, RetryDelay:15"`
1424        # '\t"fd00:1234::3:2 -> 0x2000, Age:0, State:cached, LastTrans:0, ML-EID:fd40:ea58:a88c:0:b7ab:4919:aa7b:11a3"`
1425
1426        # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
1427        # Then remove any ',' at end of items in the list.
1428        items = [item[:-1] if item[-1] == ',' else item for item in text[2:-1].split()]
1429
1430        # First item in the extended address
1431        self._address = items[0]
1432        self._rloc16 = int(items[2], 16)
1433
1434        # Convert the rest into a dictionary by splitting the text using ':' as
1435        # separator
1436        dict = {item.split(':')[0]: item.split(':')[1] for item in items[3:]}
1437
1438        self._age = int(dict['Age'], 0)
1439
1440        self._state = dict['State']
1441
1442        if self._state == ADDRESS_CACHE_ENTRY_STATE_CACHED:
1443            self._last_trans = int(dict.get("LastTrans", "-1"), 0)
1444        else:
1445            self._can_evict = (dict['CanEvict'] == 'yes')
1446            self._timeout = int(dict['Timeout'])
1447            self._retry_delay = int(dict['RetryDelay'])
1448
1449    @property
1450    def address(self):
1451        return self._address
1452
1453    @property
1454    def rloc16(self):
1455        return self._rloc16
1456
1457    @property
1458    def age(self):
1459        return self._age
1460
1461    @property
1462    def state(self):
1463        return self._state
1464
1465    def can_evict(self):
1466        return self._can_evict
1467
1468    @property
1469    def timeout(self):
1470        return self._timeout
1471
1472    @property
1473    def retry_delay(self):
1474        return self._retry_delay
1475
1476    @property
1477    def last_trans(self):
1478        return self._last_trans
1479
1480    def __repr__(self):
1481        return 'AddressCacheEntry({})'.format(self.__dict__)
1482
1483
1484def parse_address_cache_table_result(addr_cache_table_list):
1485    """ Parses address cache table list string and returns an array of `AddressCacheEntry` objects"""
1486    return [AddressCacheEntry(item) for item in addr_cache_table_list.split('\n')[1:-1]]
1487
1488
1489# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1490
1491
1492class InterfaceRoute(object):
1493    """ This object encapsulates an interface route entry"""
1494
1495    def __init__(self, text):
1496
1497        # Example of expected text:
1498        #
1499        # '\t"fd00:abba::/64             metric:256   "'
1500        #
1501
1502        # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
1503        # Then remove any ',' at end of items in the list.
1504        items = [item[:-1] if item[-1] == ',' else item for item in text[2:-1].split()]
1505
1506        # First item in the extended address
1507        self._route_prefix = items[0].split('/')[0]
1508        self._prefix_len = int(items[0].split('/')[1], 0)
1509        self._metric = int(items[1].split(':')[1], 0)
1510
1511    @property
1512    def route_prefix(self):
1513        return self._route_prefix
1514
1515    @property
1516    def prefix_len(self):
1517        return self._prefix_len
1518
1519    @property
1520    def metric(self):
1521        return self._metric
1522
1523    def __repr__(self):
1524        return 'InterfaceRoute({})'.format(self.__dict__)
1525
1526
1527def parse_interface_routes_result(interface_routes_list):
1528    """ Parses interface routes list string and returns an array of `InterfaceRoute` objects"""
1529    return [InterfaceRoute(item) for item in interface_routes_list.split('\n')[1:-1]]
1530
1531
1532# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1533
1534
1535class MultiRadioEntry(object):
1536    """ This object encapsulates a multi radio info entry"""
1537
1538    def __init__(self, text):
1539
1540        # Example of expected text:
1541        #
1542        # `\t"0EB758375B4976E7, RLOC16:f403, Radios:[IEEE_802_15_4(200), TREL_UDP6(255)]"`
1543        #
1544
1545        # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
1546        # Then remove any ',' at end of items in the list.
1547        items = [item[:-1] if item[-1] == ',' else item for item in text[2:-1].split()]
1548
1549        # First item is the extended address
1550        self._ext_address = items[0]
1551
1552        # Second items is 'RLCO16:{rloc}'
1553        self._rloc16 = items[1].split(':')[1]
1554
1555        # Join back rest of items, split using ":" to get list of radios of form "[IEEE_802_15_4(200) TREL_UDP6(255)]"
1556        radios = " ".join(items[2:]).split(":")[1]
1557
1558        if radios != "[]":
1559            # Get rid of `[ and `]`, then split using " ",  then convert to dictionary mapping radio type
1560            # to its preference value.
1561            self._radios = {radio.split("(")[0]: radio.split("(")[1][:-1] for radio in radios[1:-1].split(' ')}
1562        else:
1563            self._radios = {}
1564
1565    @property
1566    def ext_address(self):
1567        return self._ext_address
1568
1569    @property
1570    def rloc16(self):
1571        return self._rloc16
1572
1573    @property
1574    def radios(self):
1575        return self._radios
1576
1577    def supports(self, radio_type):
1578        return radio_type in self._radios
1579
1580    def preference(self, radio_type):
1581        return int(self._radios[radio_type], 0) if self.supports(radio_type) else None
1582
1583    def __repr__(self):
1584        return 'MultiRadioEntry({})'.format(self.__dict__)
1585
1586
1587def parse_multi_radio_result(multi_radio_list):
1588    """ Parses multi radio neighbor list string and returns an array of `MultiRadioEntry` objects"""
1589    return [MultiRadioEntry(item) for item in multi_radio_list.split('\n')[1:-1]]
1590