#!/usr/bin/python
#coding: utf8

# Copyright CERN, 2011 - 2013 (INCAA Computers BV)
# Author: Samuel Iglesias Gonsalvez <siglesia@cern.ch>
# Author: Julian Lewis (Julian.Lewis@cern.ch)
# Author: INCAA Computers BV (info@incaacomputers.com)
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org
# Website: http://www.incaacomputers.com
# Version: 2.0 (Last modifications: 13/06/2013)
#
# FPGA firmware: spec_pts_usb.bin
#
# Description 
#  Testing of the "USB to UART" chip IC17. For this test a USB cable needs to be
#  plugged between a USB port of the PC and the USB connector of the SPEC under test.
#
#  This test reads the alphabet that has been written to the USB tty.
#  Note that the firmware loaded to the FPGA implements the loop between
#  the transmitter and the receiver of the USB to UART chip.

import sys
import rr
import time
import os
import serial

from ptsexcept import *

"""
test10: Access to the USB UART.
"""

def main (default_directory='.'):
    # Configure the FPGA using the program fpga_loader
    path_fpga_loader = '../firmwares/fpga_loader';
    path_firmware = '../firmwares/spec_pts_usb.bin';
    firmware_loader = os.path.join(default_directory, path_fpga_loader)
    bitstream = os.path.join(default_directory, path_firmware)
    print "Loading firmware: %s" % (firmware_loader + ' ' + bitstream)
    os.system( firmware_loader + ' ' + bitstream)
    #time.sleep(2);

    alpha = list("abcdefghijklmnopqrstuvwxyz")

    # Load serial interface to communicate via loopback on the SPEC board
    print "Opening serial port\n"
    ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200, timeout=5);
    ser.flushOutput()

    print "Test10 Start"
    init_test_time = time.time()
    ret_error = None

    for ch in alpha:
        ser.write(ch)
        ser.flush()
        rc = ser.read()

        if len(rc) == 0:
            msg = "ERROR: USB-UART IC21: Not responding"
            print("\n%s" % msg)
            ret_error = msg
            break;

        if rc != ch:
            msg = "ERROR: USB-UART IC21: Unexpected character received:0x%x expected:0x%x\n" % (rc,ch)
            print("\n%s" % msg)
            ret_error = msg
            break

    end_test_time = time.time()
    print "End of Test10"
    print "RESULT: [{}]".format("FAIL" if ret_error else "OK")
    print 'Test10 elapsed time: {:.2f} seconds'.format(end_test_time-init_test_time)
    if ret_error:
        raise PtsError(ret_error)
    

if __name__ == '__main__' :
    main();
