source: ReferenceDesigns/w3_802.11/python/examples/log/log_capture_continuous.py

Last change on this file was 6320, checked in by chunter, 5 years ago

1.8.0 release wlan-exp

File size: 9.7 KB
Line 
1"""
2------------------------------------------------------------------------------
3Mango 802.11 Reference Design Experiments Framework - Continuous Log capture
4------------------------------------------------------------------------------
5License:   Copyright 2014-2019, Mango Communications. All rights reserved.
6           Distributed under the WARP license (http://warpproject.org/license)
7------------------------------------------------------------------------------
8This script uses the 802.11 ref design and wlan_exp to create a log
9file that contains all data assocated with an interactive experiment.
10
11Hardware Setup:
12  - Requires one WARP v3 node
13  - PC NIC and ETH B on WARP v3 nodes connected to common Ethernet switch
14
15Required Script Changes:
16  - Set NETWORK to the IP address of your host PC NIC network (eg X.Y.Z.0 for IP X.Y.Z.W)
17  - Set NODE_SERIAL_LIST to the serial number of your WARP node
18
19Description:
20  This script initializes one WARP v3 node.  It will periodically update
21information on the screen about the log.  The script will also read the log
22data every LOG_READ_TIME seconds, write it to the hdf5 file, HDF5_FILENAME,
23and continue until MAX_LOG_SIZE is reached or the user ends the experiment.
24------------------------------------------------------------------------------
25"""
26import sys
27import time
28import datetime
29import threading
30
31import wlan_exp.util as wlan_exp_util
32import wlan_exp.config as wlan_exp_config
33
34import wlan_exp.log.util as log_util
35import wlan_exp.log.util_hdf as hdf_util
36
37# Fix to support Python 2.x and 3.x
38if sys.version[0]=="3": raw_input=input
39
40
41#-----------------------------------------------------------------------------
42# Experiment Variables
43#-----------------------------------------------------------------------------
44# Network / Node information
45NETWORK              = '10.0.0.0'
46USE_JUMBO_ETH_FRAMES = False
47NODE_SERIAL_LIST     = ['W3-a-00001']
48
49# HDF5 File to log information
50HDF5_FILENAME        = 'log_continuous_capture.hdf5'
51
52# Interval for printing
53PRINT_TIME           = 1
54
55# Logging variables
56LOG_READ_TIME        = 30
57MAX_LOG_SIZE         = 2**30             # Max size is 1GB
58
59
60#-----------------------------------------------------------------------------
61# Global Variables
62#-----------------------------------------------------------------------------
63network_config     = None
64nodes              = []
65node               = None
66exp_done           = False
67input_done         = False
68timeout            = 0.1
69
70h5_file            = None
71log_container      = None
72
73attr_dict          = {}
74
75
76#-----------------------------------------------------------------------------
77# Local Helper Utilities
78#-----------------------------------------------------------------------------
79def add_data_to_log():
80    """Adds data to the log."""
81    global node
82    global log_container
83
84    buffer = node.log_get_all_new()
85    data   = buffer.get_bytes()
86
87    if (len(data) > 0):
88        # Write Log Files for processing by other scripts
89        print("\nWriting {0:15,d} bytes of data to log file {1}...".format(len(data), h5_file.filename))
90        log_container.write_log_data(data)
91
92# End def
93
94
95def get_log_size_str(nodes):
96    """Gets the log size str for each node."""
97
98    msg  = "Log Size:"
99
100    for node in nodes:
101        log_size  = node.log_get_size()
102        msg += "    {0:10d} bytes".format(log_size)
103
104    return msg
105
106# End def
107
108
109def get_exp_duration_str(start_time):
110    """Gets the duration str of the experiment since start_time."""
111    return "Duration:  {0:8.0f} sec".format(time.time() - start_time)
112
113# End def
114
115
116def print_node_state(start_time):
117    """Print the current state of the node."""
118
119    msg  = "\r"
120    msg += get_exp_duration_str(start_time)
121    msg += " " * 5
122    msg += get_log_size_str(nodes)
123    msg += " " * 5
124
125    sys.stdout.write(msg)
126    sys.stdout.flush()
127
128# End def
129
130
131
132#-----------------------------------------------------------------------------
133# Experiment Script
134#-----------------------------------------------------------------------------
135def init_experiment():
136    """Initialize the experiment."""
137    global network_config, nodes, attr_dict
138
139    print("\nInitializing experiment\n")
140
141    # Log attributes about the experiment
142    attr_dict['exp_start_time'] = log_util.convert_datetime_to_log_time_str(datetime.datetime.utcnow())
143
144    # Create an object that describes the network configuration of the host PC
145    network_config = wlan_exp_config.WlanExpNetworkConfiguration(network=NETWORK,
146                                                                 jumbo_frame_support=USE_JUMBO_ETH_FRAMES)
147
148    # Create an object that describes the WARP v3 nodes that will be used in this experiment
149    nodes_config   = wlan_exp_config.WlanExpNodesConfiguration(network_config=network_config,
150                                                               serial_numbers=NODE_SERIAL_LIST)
151
152    # Initialize the Nodes
153    #   This command will fail if either WARP v3 node does not respond
154    nodes = wlan_exp_util.init_nodes(nodes_config, network_config)
155
156    # Do not set the node into a known state.  This example will just read
157    # what the node currently has in the log.  However, the below code could
158    # be used to initialize all nodes into a default state:
159    #
160    # Set each node into the default state
161    # for tmp_node in nodes:
162    #     # Issue a reset command to stop current operation / initialize components
163    #     tmp_node.reset(log=True, txrx_counts=True, ltg=True, tx_queues=True) # Do not reset associations/bss_info
164    #
165    #     # Configure the log
166    #     tmp_node.log_configure(log_full_payloads=True)
167
168# End def
169
170
171def setup_experiment():
172    """Setup the experiment."""
173    global node
174
175    # Check that setup is valid
176    if (len(nodes) == 1):
177        # Extract the node from the list for easier referencing below
178        node = nodes[0]
179    else:
180        print("ERROR: Node configurations did not match requirements of script.\n")
181        return
182
183# End def
184
185
186def run_experiment():
187    """Run the experiment."""
188    global network_config, node, log_container, exp_done, input_done
189
190    print("\nRun Experiment:\n")
191    print("Log data will be retrieved every {0} seconds\n".format(LOG_READ_TIME))
192    print("Use 'q' or Ctrl-C to end the experiment.\n")
193    print("    When using IPython, press return to see status update.\n")
194
195    # Add the current time to all the nodes
196    wlan_exp_util.broadcast_cmd_write_time_to_logs(network_config)
197
198    # Get the start time
199    start_time = time.time()
200    last_print = time.time()
201    last_read  = time.time()
202
203    # Print the current state of the node
204    print_node_state(start_time)
205
206    while not exp_done:
207        loop_time = time.time()
208
209        if ((loop_time - last_print) > PRINT_TIME):
210            # Print the current state of the node
211            print_node_state(start_time)
212
213            # Set the last_print time
214            last_print = time.time()
215
216        if ((loop_time - last_read) > LOG_READ_TIME):
217            # Write the data to the log
218            add_data_to_log()
219
220            # Set the last_read time
221            last_read  = time.time()
222
223            # Log size stop condition
224            if (log_container.get_log_data_size() > MAX_LOG_SIZE):
225                print("\n!!! Reached Max Log Size.  Ending experiment. !!!\n")
226                input_done = True
227                exp_done   = True
228
229# End def
230
231
232def end_experiment():
233    """Experiment cleanup / post processing."""
234    global node, log_container
235    print("\nEnding experiment\n")
236
237    # Get the last of the data
238    add_data_to_log()
239
240    # Create the log index
241    log_container.write_log_index()
242
243    # Get the end time as an attribute
244    attr_dict['exp_end_time'] = log_util.convert_datetime_to_log_time_str(datetime.datetime.utcnow())
245
246    # Add the attribute dictionary to the log file
247    log_container.write_attr_dict(attr_dict)
248
249    # Print final log size
250    log_size = log_container.get_log_data_size()
251
252    print("Final log size:  {0:15,d} bytes".format(log_size))
253
254    # Clost the Log file for processing by other scripts
255    hdf_util.hdf5_close_file(h5_file)
256
257    print("Done.")
258    return
259
260# End def
261
262
263#-----------------------------------------------------------------------------
264# Main Function
265#-----------------------------------------------------------------------------
266if __name__ == '__main__':
267
268    # Use log file given as command line argument, if present
269    if(len(sys.argv) == 1):
270        #No filename on command line
271        LOGFILE = HDF5_FILENAME
272    else:
273        LOGFILE = str(sys.argv[1])
274
275    # Create Log Container
276    h5_file       = hdf_util.hdf5_open_file(LOGFILE)
277    log_container = hdf_util.HDF5LogContainer(h5_file)
278
279    # Log attributes about the experiment
280    attr_dict['exp_name'] = 'Interactive Capture, Continuous Log Read'
281
282    # Create thread for experiment
283    exp_thread = threading.Thread(target=run_experiment)
284    exp_thread.daemon = True
285
286    try:
287        # Initialize the experiment
288        init_experiment()
289
290        # Setup the experiment
291        setup_experiment()
292
293        # Start the experiment loop thread
294        exp_thread.start()
295
296        # See if there is any input from the user
297        while not input_done:
298            sys.stdout.flush()
299            temp = raw_input("")
300
301            if temp is not '':
302                user_input = temp.strip()
303                user_input = user_input.upper()
304
305                if ((user_input == 'Q') or (user_input == 'QUIT') or (user_input == 'EXIT')):
306                    input_done = True
307                    exp_done   = True
308
309        # Wait for all threads
310        exp_thread.join()
311        sys.stdout.flush()
312
313        # End the experiment
314        end_experiment()
315
316    except KeyboardInterrupt:
317        exp_done   = True
318        input_done = True
319
320        # If there is a keyboard interrupt, then end the experiment
321        end_experiment()
322
323    print("\nExperiment Finished.")
Note: See TracBrowser for help on using the repository browser.