#!/usr/bin/env python
# This program controlls the LCD and recives signals on what to display from an client app.
from twisted.internet import reactor, protocol
from twisted.protocols import basic
from urllib import unquote #, quote
import pylislcd

class LisProtocol(basic.LineReceiver):
    delimiter = '\n'

    def lineReceived(self, line):
        print "from client '%s' we recived: %s" %(str(self.transport.client),line)
        linearg = line.split(' ')
        if linearg[0].lower() == "put" and len(linearg) == 4:
            try:
                string = unquote( linearg[1].strip('"') )
                x = int( linearg[2] )
                y = int( linearg[3] )
                lcd.writestr( string, x, y)
                # sicka texten till lib:en
                self.sendLine("OK")
            except:
                self.sendLine("ERR")
                
        elif linearg[0].lower() == "get" and len(linearg) == 4:
            try:
                size = int( linearg[1] )
                x = int( linearg[2] )
                y = int( linearg[3] )
                string = lcd.readstr(size, x, y)
                self.sendLine("OK: %s" % string)
            except:
                self.sendLine("ERR")
                
        elif linearg[0].lower() == "clear" and len(linearg) == 2:
            # sicka till lib:en
            lcd.clear() # just nu skiter vi i allt annat
            self.sendLine("OK")
        else:
            self.sendLine("ERR")

    def connectionMade(self):
        print "%s connected" % str(self.transport.client)

    def connectionLost(self, reason):
        print "%s is lost" % str(self.transport.client)

class LisFactory(protocol.ServerFactory):
    def buildProtocol(self, addr):
        p = LisProtocol()
        p.factory = self
        return p
 

if __name__ == '__main__':
    # init lcd
    lcd = pylislcd.lcd('/dev/ttyS0')
    lcd.clear()

    reactor.listenTCP(2003, LisFactory())
    try:
        print "Starting LIS Server v0.0.2"
        reactor.run()
    except KeybordInterrupt:
        reactor.stop()

