#!/usr/bin/env python

from cpphlib import *
import sys
       
class SSOFFCONTROLCLASS:

    def __init__(self, CAEIF, IOIF):
        """Initializing class of the control program"""
        self.CAEIF = CAEIF
        self.IOIF = IOIF
        self.FINGERPROTECT = PPPASSIVETIMER()
        
        self.DIOH = PPDIGINOUTHANDLER(self.CAEIF, self.IOIF)
        self.DIOH.registerinchannel("SWITCH", 1, 0, 0) # block 0 ext in0
        self.DIOH.registerinchannel("EXIT BUTTON", 1, 1, 7) # block 1 button 7
        self.DIOH.registerinoneventaliases(["PRESS"])  # input "on" event alias
        
        self.CAEIF.commandstatemachine("POLLON:1\r\n",">",500)
        self.CAEIF.commandstatemachine("ENABLEPOLL\r\n",">",500)
        self.runworkingloop()        
        self.CAEIF.commandstatemachine("DISABLEPOLL\r\n",">",500)
        self.CAEIF.commandstatemachine("POLLOFF:1\r\n",">",500)
    
    def moveservo(self, servocommand):
        CMDdict = {"SWITCH OFF":"a2b0d78\r\n", "GO BACK":"a2b0dB0\r\n"}
        interfacecommand = CMDdict.get(servocommand,"WRONG")  
        if interfacecommand != "WRONG":
            self.IOIF.send(interfacecommand)
            
    def runworkingloop(self):
        while(1):
            self.DIOH.chekinchannelschanges("MASTER")
            if self.DIOH.inputevent("EXIT BUTTON", "PRESS"):
                break
            if self.DIOH.inputevent("SWITCH", "ON"):
                self.FINGERPROTECT.set(0.6)                
            if self.FINGERPROTECT.isexpired():
                self.moveservo("SWITCH OFF")
            if self.DIOH.inputevent("SWITCH", "OFF"):
                self.moveservo("GO BACK")      
                
if __name__ == '__main__': 
    """Main program"""
    PPDriver = PPDRIVER();
    PPDriver.registerCAEinterface("localhost", 8000) 
    PPDriver.registerIOinterface("localhost", 12000)
    PPDriver.connectinterfaces()
    CAEIF, IOIF, MONIF = PPDriver.getinterfaces()
    SsoffInstance = SSOFFCONTROLCLASS(CAEIF, IOIF)
    PPDriver.disconnectinterfaces()
    sys.exit(0) 