#!/usr/bin/python

import sys
import rr
import time

class USB_UART:
    STAT_REG = 0x0;
    BAUD_REG = 0x4;
    TX_REG = 0x8;
    RX_REG = 0xc;
    CLK_FREQ = 50000000;

    def __init__ (self, gennum, base, base_reset, baud):
        self.bus = gennum;
        self.base = base;
        self.base_reset = base_reset;
        self.baud = baud;
        
        self.reset();
        self.setup_baud_rate(self.calculate_baud_rate(baud));

    def calculate_baud_rate(self, baud):
            return ((((baud*8) << (16 -7))+(self.CLK_FREQ >> 8))/(self.CLK_FREQ>>7))

    def reset(self):
        """Resets the UART core to initialize the Baud counter """
        self.bus.iwrite(0,self.base_reset,4,0);
        self.bus.iwrite(0,self.base_reset,4,1);

    def read_ready(self):
        return ((self.bus.iread(0, self.base + self.STAT_REG, 4) & 0x2) >> 1)

    def read(self):
        return self.bus.iread(0, self.base + self.RX_REG, 4)
             
    def send(self,data):
        self.bus.iwrite(0, self.base + self.TX_REG, 4, data)
        while(self.bus.iread(0, self.base + self.STAT_REG, 4) & 0x1) :
            pass;

    def setup_baud_rate(self, baud):
        self.bus.iwrite(0, self.base + self.BAUD_REG, 4, baud)
