import serial

class lcd:
    def __init__(self, dev):
        """Initialize the LCD, if dev is undefined we will crash..."""
        self.ser = serial.Serial(
            port = dev,
            baudrate = 19200,
            bytesize = serial.EIGHTBITS,
            parity = serial.PARITY_NONE,
            stopbits = serial.STOPBITS_ONE,
        )
        self.vLCD = {} # the virual LCD (Mirror of the real)
    
    def writechr(self, char, x, y):
        """The char _is_ the character ex "e" not the char code for e.
        This will put your char on the LCD at your specified location."""
        self.ser.write( chr(0) )
        self.ser.write( chr(161 + y) )
        self.ser.write( chr(x) )
        self.ser.write( chr(167) )
        self.ser.write( char )
        self.vLCD[( x, y)] = char # vLCD is simpler then the real thing ;)

    def writestr(self, string, x, y):
        """Put's a string on the display, at your specified location."""
        for xmod in range(0, len(string)):
            curchr = string[xmod]
            self.writechr(curchr, x + xmod, y)

    def readchr(self, x, y):
        """Read a character from x, y (OBS: this is read from vLCD)"""
        char = self.vLCD[(x, y)]
        print "DEB-driver: x:%i y:%i c:%s" %(x, y, char)
        return char

    def readstr(self, x, y, size):
        """Read x, y to x + size, y as an string"""
        string = str()
        for xmod in range(0, size):
            string += self.readchr(x + xmod, y)
        return string

    def clear(self):
        """Blank's the LCD screen"""
        for y in range(0,2):
            for x in range(0,20):
                self.writechr(' ', x, y)
            
    def close(self):
        """Close's the LCD connection, any nice program whould call this at the end."""
        self.ser.close()
