#!/bin/env python

import random # For randint
import sys # For sys.argv and sys.exit
import uhal


if __name__ == '__main__':

    # PART 1: Argument parsing
    if len(sys.argv) != 4:
        print "Incorrect usage!"
        print "usage: read_write_block_of_fifo.py <path_to_connection_file> <connection_id> <node_name>"
        sys.exit(1)

    connectionFilePath = sys.argv[1];
    deviceId = sys.argv[2];
    nodeIdPath = sys.argv[3];


    # PART 2: Creating the HwInterface
    connectionMgr = uhal.ConnectionManager("file://" + connectionFilePath);
    hw = connectionMgr.getDevice(deviceId);
    node = hw.getNode(nodeIdPath)


    # PART 3: Reading from the memory block / FIFO
    print "Reading from memory block / FIFO '" + nodeIdPath + "' ..."
    mem = node.readBlock(node.getSize())
    # dispatch method sends read request to hardware, and waits for result to return
    # N.B. Before dispatch, mem.valid() == false, and mem.value() will throw
    hw.dispatch();

    print "... success!"
    print "Contents of memory block / FIFO '" + nodeIdPath + "':"
    for item in mem:
        print " ", hex(item)


    # PART 4: Writing (random data) to the memory block
    print "Writing random data to memory block / FIFO '" + nodeIdPath + "' ..."
    values = []
    for i in range(node.getSize()):
  	  values += [random.randint(0, 0xffffffff)]

    node.writeBlock(values);
    # N.B. Depending on the size of the memory block some/all of the values will only be sent to the device when the dispatch method is called
    hw.dispatch();
    # In case there are any problems with the transaction, an exception will be thrown from the dispatch method
    # Alternatively, if you want to check whether an individual write succeeded or failed, you can call the 'valid()' method of the uhal::ValHeader object that is returned by the write method
    print "... success!"
