#!/usr/bin/env python
from twisted.internet import reactor, protocol, task
from twisted.protocols import basic
from urllib import quote
import time

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

    def connectionMade(self):
        print "connected to host"
        self.sendLine("clear 0")
        updater.start(intervall) # start when we are connected

    def lineReceived(self, line):
        if line == "ERR":
            print "ERR"
        #    print "Error: '%s' coused an error" % lastcmd
        #else:
        #    print "%s: OK" % lastcmd

    def connectionLost(self, reason):
        print "lost connection: '%s" % reason


class LisFactory(protocol.ClientFactory):
    def buildProtocol(self, addr):
        global protocol
        protocol = LisProtocol()
        return protocol
    
    def sendstr(self, string, x, y):
        string = quote(string)
        lastcmd = 'PUT "%s" %i %i' % (string, x, y)
        protocol.sendLine(lastcmd)

    def sendclear(self, ctype):
        lastcmd = 'CLEAR %i' % ctype
        protocol.sendLine(lastcmd)

def UpdateLCD():
    # Here is the "main" non protocoll code
    upfile = open('/proc/uptime')
    uptime = upfile.read()
    upfile.close()
    tuptime = uptime.split(' ')
    uptime = float( tuptime[0] )
    uphour = ( uptime / 60 ) / 60
    upmin = ( uptime / 60 ) % 60
    upsec = ( uptime % 60 ) % 60
    uptime = "uptime %i:%i:%i" %(uphour, upmin, upsec)
    x = (20 - len(uptime)) / 2 # centrerings formel
    factory.sendstr(uptime,x,0)
    # heart beat:
    beat = int(time.time()) % 2
    if beat == 1:
        factory.sendstr(chr(165), 19, 1)
    else:
        factory.sendstr(chr(46), 19, 1)
    

if __name__ == '__main__':
    global lastcmd

    host = "ghoul"
    port = 2003
    intervall = 1
    factory = LisFactory()
    updater = task.LoopingCall(UpdateLCD)
    reactor.connectTCP(host, port, factory)
    reactor.run()

