[posix-app] enhance virtual time for posix app (#3016)

This commit is contained in:
Yakun Xu
2018-09-05 18:08:36 -07:00
committed by Jonathan Hui
parent 2742886134
commit bdffbe5671
28 changed files with 1035 additions and 305 deletions
@@ -100,6 +100,6 @@ class Cert_5_1_07_MaxChildCount(unittest.TestCase):
if addr[0:4] != 'fe80' and 'ff:fe00' not in addr:
self.assertTrue(self.nodes[LEADER].ping(addr, size=106))
break
if __name__ == '__main__':
unittest.main()
@@ -75,7 +75,6 @@ class Cert_6_3_2_NetworkDataUpdate(unittest.TestCase):
self.simulator.go(5)
addrs = self.nodes[ED].get_addrs()
self.simulator.go(5)
self.assertTrue(any('2001:2:0:1' in addr[0:10] for addr in addrs))
for addr in addrs:
if addr[0:10] == '2001:2:0:1':
@@ -56,7 +56,7 @@ class Cert_6_5_1_ChildResetSynchronize(unittest.TestCase):
def _setUpEd(self):
self.nodes[ED].add_whitelist(self.nodes[LEADER].get_addr64())
self.nodes[ED].enable_whitelist()
self.nodes[ED].enable_whitelist()
def tearDown(self):
for node in list(self.nodes.values()):
+1
View File
@@ -40,6 +40,7 @@ import config
class Node:
def __init__(self, nodeid, is_mtd=False, simulator=None):
self.simulator = simulator
self.interface = None
if sys.platform != 'win32':
self.interface = node_cli.otCli(nodeid, is_mtd, simulator=simulator)
+134 -111
View File
@@ -32,6 +32,7 @@ import sys
import time
import pexpect
import re
import socket
import ipaddress
import config
@@ -69,6 +70,7 @@ class otCli:
if 'RADIO_DEVICE' in os.environ:
cmd += ' %s' % os.environ['RADIO_DEVICE']
os.environ['NODE_ID'] = str(nodeid)
cmd += ' %d' % nodeid
print ("%s" % cmd)
@@ -76,13 +78,20 @@ class otCli:
self.pexpect = pexpect.spawn(cmd, timeout=4)
# Add delay to ensure that the process is ready to receive commands.
time.sleep(0.2)
timeout = 0.4
while timeout > 0:
self.pexpect.send('\r\n')
try:
self.pexpect.expect('> ', timeout=0.1)
break
except pexpect.TIMEOUT:
timeout -= 0.1
def __init_ncp_sim(self, nodeid, mode):
""" Initialize an NCP simulation node. """
if 'RADIO_DEVICE' in os.environ:
args = ' %s' % os.environ['RADIO_DEVICE']
os.environ['NODE_ID'] = str(nodeid)
else:
args = ''
@@ -97,10 +106,28 @@ class otCli:
print ("%s" % cmd)
self.pexpect = pexpect.spawn(cmd, timeout=4)
# Add delay to ensure that the process is ready to receive commands.
time.sleep(0.2)
self.pexpect.expect('spinel-cli >')
self._expect('spinel-cli >')
self.debug(int(os.getenv('DEBUG', '0')))
def _expect(self, pattern, timeout=-1, *args, **kwargs):
""" Process simulator events until expected the pattern. """
if timeout == -1:
timeout = self.pexpect.timeout
assert timeout > 0
while timeout > 0:
try:
return self.pexpect.expect(pattern, 0.1, *args, **kwargs)
except pexpect.TIMEOUT:
timeout -= 0.1
self.simulator.go(0)
if timeout <= 0:
raise
def __init_soc(self, nodeid):
""" Initialize a System-on-a-chip node connected via UART. """
import fdpexpect
@@ -112,26 +139,27 @@ class otCli:
def destroy(self):
if self.pexpect and self.pexpect.isalive():
self.send_command('exit')
self.pexpect.expect(pexpect.EOF)
print("%d: exit" % self.nodeid)
self.pexpect.send('exit\n')
self.pexpect.terminate()
self.pexpect.close(force=True)
self._expect(pexpect.EOF)
self.pexpect.wait()
self.pexpect = None
sys.stdout.flush()
def send_command(self, cmd):
def send_command(self, cmd, go=True):
print("%d: %s" % (self.nodeid, cmd))
self.pexpect.send(cmd + '\n')
if go:
self.simulator.go(0, nodeid=self.nodeid)
sys.stdout.flush()
if isinstance(self.simulator, simulator.VirtualTime):
self.simulator.receive_events()
def get_commands(self):
self.send_command('?')
self.pexpect.expect('Commands:')
self._expect('Commands:')
commands = []
while True:
i = self.pexpect.expect(['Done', '(\S+)'])
i = self._expect(['Done', '(\S+)'])
if i != 0:
commands.append(self.pexpect.match.groups()[0])
else:
@@ -141,56 +169,57 @@ class otCli:
def set_mode(self, mode):
cmd = 'mode ' + mode
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def debug(self, level):
self.send_command('debug '+str(level))
# `debug` command will not trigger interaction with simulator
self.send_command('debug '+ str(level), go=False)
def interface_up(self):
self.send_command('ifconfig up')
self.pexpect.expect('Done')
self._expect('Done')
def interface_down(self):
self.send_command('ifconfig down')
self.pexpect.expect('Done')
self._expect('Done')
def thread_start(self):
self.send_command('thread start')
self.pexpect.expect('Done')
self._expect('Done')
def thread_stop(self):
self.send_command('thread stop')
self.pexpect.expect('Done')
self._expect('Done')
def commissioner_start(self):
cmd = 'commissioner start'
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def commissioner_add_joiner(self, addr, psk):
cmd = 'commissioner joiner add ' + addr + ' ' + psk
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def joiner_start(self, pskd='', provisioning_url=''):
cmd = 'joiner start ' + pskd + ' ' + provisioning_url
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def clear_whitelist(self):
cmd = 'macfilter addr clear'
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def enable_whitelist(self):
cmd = 'macfilter addr whitelist'
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def disable_whitelist(self):
cmd = 'macfilter addr disable'
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def add_whitelist(self, addr, rssi=None):
cmd = 'macfilter addr add ' + addr
@@ -199,19 +228,19 @@ class otCli:
cmd += ' ' + str(rssi)
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def remove_whitelist(self, addr):
cmd = 'macfilter addr remove ' + addr
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_addr16(self):
self.send_command('rloc16')
i = self.pexpect.expect('([0-9a-fA-F]{4})')
i = self._expect('([0-9a-fA-F]{4})')
if i == 0:
addr16 = int(self.pexpect.match.groups()[0], 16)
self.pexpect.expect('Done')
self._expect('Done')
return addr16
def get_router_id(self):
@@ -220,83 +249,83 @@ class otCli:
def get_addr64(self):
self.send_command('extaddr')
i = self.pexpect.expect('([0-9a-fA-F]{16})')
i = self._expect('([0-9a-fA-F]{16})')
if i == 0:
addr64 = self.pexpect.match.groups()[0].decode("utf-8")
self.pexpect.expect('Done')
self._expect('Done')
return addr64
def get_eui64(self):
self.send_command('eui64')
i = self.pexpect.expect('([0-9a-fA-F]{16})')
i = self._expect('([0-9a-fA-F]{16})')
if i == 0:
addr64 = self.pexpect.match.groups()[0].decode("utf-8")
self.pexpect.expect('Done')
self._expect('Done')
return addr64
def get_joiner_id(self):
self.send_command('joinerid')
i = self.pexpect.expect('([0-9a-fA-F]{16})')
i = self._expect('([0-9a-fA-F]{16})')
if i == 0:
addr = self.pexpect.match.groups()[0].decode("utf-8")
self.pexpect.expect('Done')
self._expect('Done')
return addr
def get_channel(self):
self.send_command('channel')
i = self.pexpect.expect('(\d+)\r\n')
i = self._expect('(\d+)\r?\n')
if i == 0:
channel = int(self.pexpect.match.groups()[0])
self.pexpect.expect('Done')
self._expect('Done')
return channel
def set_channel(self, channel):
cmd = 'channel %d' % channel
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_masterkey(self):
self.send_command('masterkey')
i = self.pexpect.expect('([0-9a-fA-F]{32})')
i = self._expect('([0-9a-fA-F]{32})')
if i == 0:
masterkey = self.pexpect.match.groups()[0].decode("utf-8")
self.pexpect.expect('Done')
self._expect('Done')
return masterkey
def set_masterkey(self, masterkey):
cmd = 'masterkey ' + masterkey
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_key_sequence_counter(self):
self.send_command('keysequence counter')
i = self.pexpect.expect('(\d+)\r\n')
i = self._expect('(\d+)\r?\n')
if i == 0:
key_sequence_counter = int(self.pexpect.match.groups()[0])
self.pexpect.expect('Done')
self._expect('Done')
return key_sequence_counter
def set_key_sequence_counter(self, key_sequence_counter):
cmd = 'keysequence counter %d' % key_sequence_counter
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def set_key_switch_guardtime(self, key_switch_guardtime):
cmd = 'keysequence guardtime %d' % key_switch_guardtime
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def set_network_id_timeout(self, network_id_timeout):
cmd = 'networkidtimeout %d' % network_id_timeout
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_network_name(self):
self.send_command('networkname')
while True:
i = self.pexpect.expect(['Done', '(\S+)'])
i = self._expect(['Done', '(\S+)'])
if i != 0:
network_name = self.pexpect.match.groups()[0].decode('utf-8')
else:
@@ -306,103 +335,103 @@ class otCli:
def set_network_name(self, network_name):
cmd = 'networkname ' + network_name
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_panid(self):
self.send_command('panid')
i = self.pexpect.expect('([0-9a-fA-F]{4})')
i = self._expect('([0-9a-fA-F]{4})')
if i == 0:
panid = int(self.pexpect.match.groups()[0], 16)
self.pexpect.expect('Done')
self._expect('Done')
return panid
def set_panid(self, panid):
cmd = 'panid %d' % panid
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_partition_id(self):
self.send_command('leaderpartitionid')
i = self.pexpect.expect('(\d+)\r\n')
i = self._expect('(\d+)\r?\n')
if i == 0:
weight = self.pexpect.match.groups()[0]
self.pexpect.expect('Done')
self._expect('Done')
return weight
def set_partition_id(self, partition_id):
cmd = 'leaderpartitionid %d' % partition_id
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def set_router_upgrade_threshold(self, threshold):
cmd = 'routerupgradethreshold %d' % threshold
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def set_router_downgrade_threshold(self, threshold):
cmd = 'routerdowngradethreshold %d' % threshold
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def release_router_id(self, router_id):
cmd = 'releaserouterid %d' % router_id
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_state(self):
states = ['detached', 'child', 'router', 'leader']
self.send_command('state')
match = self.pexpect.expect(states)
self.pexpect.expect('Done')
match = self._expect(states)
self._expect('Done')
return states[match]
def set_state(self, state):
cmd = 'state ' + state
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_timeout(self):
self.send_command('childtimeout')
i = self.pexpect.expect('(\d+)\r\n')
i = self._expect('(\d+)\r?\n')
if i == 0:
timeout = self.pexpect.match.groups()[0]
self.pexpect.expect('Done')
self._expect('Done')
return timeout
def set_timeout(self, timeout):
cmd = 'childtimeout %d' % timeout
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def set_max_children(self, number):
cmd = 'childmax %d' % number
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_weight(self):
self.send_command('leaderweight')
i = self.pexpect.expect('(\d+)\r\n')
i = self._expect('(\d+)\r?\n')
if i == 0:
weight = self.pexpect.match.groups()[0]
self.pexpect.expect('Done')
self._expect('Done')
return weight
def set_weight(self, weight):
cmd = 'leaderweight %d' % weight
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def add_ipaddr(self, ipaddr):
cmd = 'ipaddr add ' + ipaddr
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def get_addrs(self):
addrs = []
self.send_command('ipaddr')
while True:
i = self.pexpect.expect(['(\S+:\S+)\r\n', 'Done'])
i = self._expect(['(\S+(:\S*)+)\r?\n', 'Done'])
if i == 0:
addrs.append(self.pexpect.match.groups()[0].decode("utf-8"))
elif i == 1:
@@ -426,7 +455,7 @@ class otCli:
self.send_command('eidcache')
while True:
i = self.pexpect.expect(['([a-fA-F0-9\:]+) ([a-fA-F0-9]+)\r\n', 'Done'])
i = self._expect(['([a-fA-F0-9\:]+) ([a-fA-F0-9]+)\r?\n', 'Done'])
if i == 0:
eid = self.pexpect.match.groups()[0].decode("utf-8")
rloc = self.pexpect.match.groups()[1].decode("utf-8")
@@ -439,12 +468,12 @@ class otCli:
def add_service(self, enterpriseNumber, serviceData, serverData):
cmd = 'service add ' + enterpriseNumber + ' ' + serviceData+ ' ' + serverData
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def remove_service(self, enterpriseNumber, serviceData):
cmd = 'service remove ' + enterpriseNumber + ' ' + serviceData
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def __getLinkLocalAddress(self):
for ip6Addr in self.get_addrs():
@@ -515,40 +544,40 @@ class otCli:
def get_context_reuse_delay(self):
self.send_command('contextreusedelay')
i = self.pexpect.expect('(\d+)\r\n')
i = self._expect('(\d+)\r?\n')
if i == 0:
timeout = self.pexpect.match.groups()[0]
self.pexpect.expect('Done')
self._expect('Done')
return timeout
def set_context_reuse_delay(self, delay):
cmd = 'contextreusedelay %d' % delay
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def add_prefix(self, prefix, flags, prf = 'med'):
cmd = 'prefix add ' + prefix + ' ' + flags + ' ' + prf
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def remove_prefix(self, prefix):
cmd = 'prefix remove ' + prefix
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def add_route(self, prefix, prf = 'med'):
cmd = 'route add ' + prefix + ' ' + prf
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def remove_route(self, prefix):
cmd = 'route remove ' + prefix
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def register_netdata(self):
self.send_command('netdataregister')
self.pexpect.expect('Done')
self._expect('Done')
def energy_scan(self, mask, count, period, scan_duration, ipaddr):
cmd = 'commissioner energy ' + str(mask) + ' ' + str(count) + ' ' + str(period) + ' ' + str(scan_duration) + ' ' + ipaddr
@@ -560,7 +589,7 @@ class otCli:
else:
timeout = 8
self.pexpect.expect('Energy:', timeout=timeout)
self._expect('Energy:', timeout=timeout)
def panid_query(self, panid, mask, ipaddr):
cmd = 'commissioner panid ' + str(panid) + ' ' + str(mask) + ' ' + ipaddr
@@ -572,14 +601,14 @@ class otCli:
else:
timeout = 8
self.pexpect.expect('Conflict:', timeout=timeout)
self._expect('Conflict:', timeout=timeout)
def scan(self):
self.send_command('scan')
results = []
while True:
i = self.pexpect.expect(['\|\s(\S+)\s+\|\s(\S+)\s+\|\s([0-9a-fA-F]{4})\s\|\s([0-9a-fA-F]{16})\s\|\s(\d+)\r\n',
i = self._expect(['\|\s(\S+)\s+\|\s(\S+)\s+\|\s([0-9a-fA-F]{4})\s\|\s([0-9a-fA-F]{16})\s\|\s(\d+)\r?\n',
'Done'])
if i == 0:
results.append(self.pexpect.match.groups())
@@ -595,11 +624,6 @@ class otCli:
self.send_command(cmd)
try:
self.pexpect.expect('Done', timeout=0.01)
except pexpect.TIMEOUT:
pass
if isinstance(self.simulator, simulator.VirtualTime):
self.simulator.go(timeout)
@@ -607,87 +631,86 @@ class otCli:
try:
responders = {}
while len(responders) < num_responses:
i = self.pexpect.expect(['from (\S+):'])
i = self._expect(['from (\S+):'])
if i == 0:
responders[self.pexpect.match.groups()[0]] = 1
self.pexpect.expect('\n')
except pexpect.TIMEOUT:
self._expect('\n')
except (pexpect.TIMEOUT, socket.timeout):
result = False
if isinstance(self.simulator, simulator.VirtualTime):
self.simulator.sync_devices()
return result
def reset(self):
self.send_command('reset')
try:
self.pexpect.expect('Done', timeout=0.01)
except pexpect.TIMEOUT:
pass
time.sleep(0.1)
def set_router_selection_jitter(self, jitter):
cmd = 'routerselectionjitter %d' % jitter
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def set_active_dataset(self, timestamp, panid=None, channel=None, channel_mask=None, master_key=None):
self.send_command('dataset clear')
self.pexpect.expect('Done')
self._expect('Done')
cmd = 'dataset activetimestamp %d' % timestamp
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
if panid != None:
cmd = 'dataset panid %d' % panid
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
if channel != None:
cmd = 'dataset channel %d' % channel
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
if channel_mask != None:
cmd = 'dataset channelmask %d' % channel_mask
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
if master_key != None:
cmd = 'dataset masterkey ' + master_key
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
self.send_command('dataset commit active')
self.pexpect.expect('Done')
self._expect('Done')
def set_pending_dataset(self, pendingtimestamp, activetimestamp, panid=None, channel=None):
self.send_command('dataset clear')
self.pexpect.expect('Done')
self._expect('Done')
cmd = 'dataset pendingtimestamp %d' % pendingtimestamp
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
cmd = 'dataset activetimestamp %d' % activetimestamp
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
if panid != None:
cmd = 'dataset panid %d' % panid
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
if channel != None:
cmd = 'dataset channel %d' % channel
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
self.send_command('dataset commit pending')
self.pexpect.expect('Done')
self._expect('Done')
def announce_begin(self, mask, count, period, ipaddr):
cmd = 'commissioner announce ' + str(mask) + ' ' + str(count) + ' ' + str(period) + ' ' + ipaddr
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def send_mgmt_active_set(self, active_timestamp=None, channel=None, channel_mask=None, extended_panid=None,
panid=None, master_key=None, mesh_local=None, network_name=None, binary=None):
@@ -721,7 +744,7 @@ class otCli:
cmd += 'binary ' + binary + ' '
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
def send_mgmt_pending_set(self, pending_timestamp=None, active_timestamp=None, delay_timer=None, channel=None,
panid=None, master_key=None, mesh_local=None, network_name=None):
@@ -751,4 +774,4 @@ class otCli:
cmd += 'networkname ' + network_name + ' '
self.send_command(cmd)
self.pexpect.expect('Done')
self._expect('Done')
+190 -62
View File
@@ -27,19 +27,25 @@
# POSSIBILITY OF SUCH DAMAGE.
#
import binascii
import bisect
import cmd
import os
import socket
import struct
import time
import sys
import traceback
import time
import io
import config
import message
import pcap
def dbg_print(*args):
if False:
print args
class RealTime:
def __init__(self):
@@ -60,9 +66,29 @@ class RealTime:
class VirtualTime:
OT_SIM_EVENT_ALARM_FIRED = 0
OT_SIM_EVENT_RADIO_RECEIVED = 1
OT_SIM_EVENT_UART_WRITE = 2
OT_SIM_EVENT_RADIO_SPINEL_WRITE = 3
OT_SIM_EVENT_POSTCMD = 4
EVENT_TIME = 0
EVENT_SEQUENCE = 1
EVENT_ADDR = 2
EVENT_TYPE = 3
EVENT_DATA_LENGTH = 4
EVENT_DATA = 5
BASE_PORT = 9000
MAX_NODES = 34
PORT_OFFSET = int(os.getenv('PORT_OFFSET', "0"))
MAX_MESSAGE = 1024
END_OF_TIME = 0x7fffffff
PORT_OFFSET = int(os.getenv('PORT_OFFSET', '0'))
BLOCK_TIMEOUT = 4
RADIO_ONLY = os.getenv('RADIO_DEVICE') != None
NCP_SIM = os.getenv('NODE_TYPE', 'sim') == 'ncp-sim'
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -73,11 +99,17 @@ class VirtualTime:
self.devices = {}
self.event_queue = []
self.event_count = 0
# there could be events scheduled at exactly the same time
self.event_sequence = 0
self.current_time = 0
self.current_event = None;
self.current_event = None
self.awake_devices = set()
self._pcap = pcap.PcapCodec(os.getenv('TEST_NAME', 'current'))
# the addr for spinel-cli sending OT_SIM_EVENT_POSTCMD
self._spinel_cli_addr = (ip, self.BASE_PORT + self.port)
self.current_nodeid = None
self._pause_time = 0
self._message_factory = config.create_default_thread_message_factory()
@@ -102,7 +134,6 @@ class VirtualTime:
except Exception as e:
# Just print the exception to the console
print("EXCEPTION: %s" % e)
pass
def set_lowpan_context(self, cid, prefix):
self._message_factory.set_lowpan_context(cid, prefix)
@@ -125,24 +156,63 @@ class VirtualTime:
return message.MessagesSet(messages)
def receive_events(self):
def _is_radio(self, addr):
return addr[1] < self.BASE_PORT * 2
if self.current_event is None:
self.sock.setblocking(0)
def _to_core_addr(self, addr):
assert self._is_radio(addr)
return (addr[0], addr[1] + self.BASE_PORT)
def _to_radio_addr(self, addr):
assert not self._is_radio(addr)
return (addr[0], addr[1] - self.BASE_PORT)
def _core_addr_from(self, nodeid):
if self.RADIO_ONLY:
return ('127.0.0.1', self.BASE_PORT + self.port + nodeid)
else:
self.sock.setblocking(1)
return ('127.0.0.1', self.port + nodeid)
def _next_event_time(self):
if len(self.event_queue) == 0:
return self.END_OF_TIME
else:
return self.event_queue[0][0]
def receive_events(self):
""" Receive events until all devices are asleep. """
while True:
try:
msg, addr = self.sock.recvfrom(1024)
except socket.error:
break
if self.current_event or len(self.awake_devices) or (self._next_event_time() > self._pause_time and self.current_nodeid):
self.sock.settimeout(self.BLOCK_TIMEOUT)
try:
msg, addr = self.sock.recvfrom(self.MAX_MESSAGE)
except socket.error:
# print debug information on failure
print('Current nodeid:')
print(self.current_nodeid)
print('Current awake:')
print(self.awake_devices)
print('Current time:')
print(self.current_time)
print('Current event:')
print(self.current_event)
print('Events:')
for event in self.event_queue:
print(event)
raise
else:
self.sock.settimeout(0)
try:
msg, addr = self.sock.recvfrom(self.MAX_MESSAGE)
except socket.error:
break
if addr not in self.devices:
if addr != self._spinel_cli_addr and addr not in self.devices:
self.devices[addr] = {}
self.devices[addr]['alarm'] = None
self.devices[addr]['msgs'] = []
self.devices[addr]['time'] = self.current_time
self.awake_devices.discard(addr)
#print "New device:", addr, self.devices
delay, type, datalen = struct.unpack('=QBH', msg[:11])
@@ -150,31 +220,37 @@ class VirtualTime:
event_time = self.current_time + delay
if type == 0:
if data:
dbg_print("New event: ", event_time, addr, type, datalen, binascii.hexlify(data))
else:
dbg_print("New event: ", event_time, addr, type, datalen)
if type == self.OT_SIM_EVENT_ALARM_FIRED:
# remove any existing alarm event for device
try:
if self.devices[addr]['alarm']:
self.event_queue.remove(self.devices[addr]['alarm'])
#print "-- Remove\t", self.devices[addr]['alarm']
self.devices[addr]['alarm'] = None
except ValueError:
pass
# add alarm event to event queue
event = (event_time, addr, type, datalen)
event = (event_time, self.event_sequence, addr, type, datalen)
self.event_sequence += 1
#print "-- Enqueue\t", event, delay, self.current_time
bisect.insort(self.event_queue, event)
self.devices[addr]['alarm'] = event
if self.current_event is not None and self.current_event[1] == addr:
self.awake_devices.discard(addr)
if self.current_event and self.current_event[self.EVENT_ADDR] == addr:
#print "Done\t", self.current_event
self.current_event = None
return
elif type == 1:
elif type == self.OT_SIM_EVENT_RADIO_RECEIVED:
assert self._is_radio(addr)
# add radio receive events event queue
for device in self.devices:
if device != addr:
event = (event_time, device, type, datalen, data)
if device != addr and self._is_radio(device):
event = (event_time, self.event_sequence, device, type, datalen, data)
self.event_sequence += 1
#print "-- Enqueue\t", event
bisect.insort(self.event_queue, event)
@@ -182,34 +258,67 @@ class VirtualTime:
self._add_message(addr[1] - self.port, data)
# add radio transmit done events to event queue
event = (event_time, addr, type, datalen, data)
event = (event_time, self.event_sequence, addr, type, datalen, data)
self.event_sequence += 1
bisect.insort(self.event_queue, event)
self.awake_devices.add(addr)
elif type == self.OT_SIM_EVENT_RADIO_SPINEL_WRITE:
assert not self._is_radio(addr)
radio_addr = self._to_radio_addr(addr)
if not self.devices.has_key(radio_addr):
self.awake_devices.add(radio_addr)
event = (event_time, self.event_sequence, radio_addr, self.OT_SIM_EVENT_UART_WRITE, datalen, data)
self.event_sequence += 1
bisect.insort(self.event_queue, event)
self.awake_devices.add(addr)
elif type == self.OT_SIM_EVENT_UART_WRITE:
assert self._is_radio(addr)
core_addr = self._to_core_addr(addr)
if not self.devices.has_key(core_addr):
self.awake_devices.add(core_addr)
event = (event_time, self.event_sequence, core_addr, self.OT_SIM_EVENT_RADIO_SPINEL_WRITE, datalen, data)
self.event_sequence += 1
bisect.insort(self.event_queue, event)
self.awake_devices.add(addr)
elif type == self.OT_SIM_EVENT_POSTCMD:
assert self.current_time == self._pause_time
nodeid = struct.unpack('=B', data)[0]
if self.current_nodeid == nodeid:
self.current_nodeid = None
def _send_message(self, message, addr):
while True:
try:
sent = self.sock.sendto(message, addr)
except socket.error:
traceback.print_exc()
time.sleep(0)
else:
break
assert sent == len(message)
def process_next_event(self):
if self.current_event != None:
return
#print "Events", len(self.event_queue)
count = 0
for event in self.event_queue:
#print count, event
count += 1
assert self.current_event is None
assert self._next_event_time() < self.END_OF_TIME
# process next event
try:
event = self.event_queue.pop(0)
except IndexError:
return
event = self.event_queue.pop(0)
#print "Pop\t", event
if len(event) == 4:
event_time, addr, type, datalen = event
if len(event) == 5:
event_time, sequence, addr, type, datalen = event
dbg_print("Pop event: ", event_time, addr, type, datalen)
else:
event_time, addr, type, datalen, data = event
event_time, sequence, addr, type, datalen, data = event
dbg_print("Pop event: ", event_time, addr, type, datalen, binascii.hexlify(data))
self.event_count += 1
self.current_event = event
assert(event_time >= self.current_time)
@@ -220,33 +329,52 @@ class VirtualTime:
message = struct.pack('=QBH', elapsed, type, datalen)
if type == 0:
if type == self.OT_SIM_EVENT_ALARM_FIRED:
self.devices[addr]['alarm'] = None
self.sock.sendto(message, addr)
elif type == 1:
self._send_message(message, addr)
elif type == self.OT_SIM_EVENT_RADIO_RECEIVED:
message += data
self.sock.sendto(message, addr)
self._send_message(message, addr)
elif type == self.OT_SIM_EVENT_RADIO_SPINEL_WRITE:
message += data
self._send_message(message, addr)
elif type == self.OT_SIM_EVENT_UART_WRITE:
message += data
self._send_message(message, addr)
def sync_devices(self):
self.current_time = self._pause_time
for addr in self.devices:
elapsed = self.current_time - self.devices[addr]['time']
if elapsed == 0:
continue
dbg_print('syncing', addr, elapsed)
self.devices[addr]['time'] = self.current_time
message = struct.pack('=QBH', elapsed, 0, 0)
self.sock.sendto(message, addr)
def go(self, duration):
message = struct.pack('=QBH', elapsed, self.OT_SIM_EVENT_ALARM_FIRED, 0)
self._send_message(message, addr)
self.awake_devices.add(addr)
self.receive_events()
self.awake_devices.clear()
def go(self, duration, nodeid=None):
assert self.current_time == self._pause_time
duration = int(duration) * 1000000
start_time = self.current_time
self.current_event = None
print "running for %d us" % duration
dbg_print('running for %d us' % duration)
self._pause_time += duration
if nodeid:
if self.NCP_SIM:
self.current_nodeid = nodeid
self.awake_devices.add(self._core_addr_from(nodeid))
self.receive_events()
while (self.current_time - start_time) < duration:
while self._next_event_time() <= self._pause_time:
self.process_next_event()
self.receive_events()
if duration > 0:
self.sync_devices()
dbg_print('current time %d us' % self.current_time)
self.sync_devices()
if __name__ == '__main__':
simulator = VirtualTime()
while True:
simulator.go(0)