#!/usr/bin/env python

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
from cpphlib import *
import getopt
import sys
import time
import threading
import ccinterfaces

class PPDSCrossConnector(WebSocketApplication):
    
    def on_open(self):
        ccinterfaces.WSSINTERFACE=self.ws

    def on_message(self, DataToPPDS):
        ccinterfaces.PPDSINTERFACE.send(DataToPPDS)
        if ccinterfaces.Verbose:
            print "WS->PPDS: %s"%DataToPPDS

    def on_close(self, reason):
        pass
        #print reason #if you want to see 
        
        
class SendThread(threading.Thread):

    def __init__(self, ):
        threading.Thread.__init__(self)
        self.RunFlag = True
        self.start()
        
    def run(self):
        for i in range(5):
            ccinterfaces.PPDSINTERFACE.getinputdata()
        while self.RunFlag:
            if ccinterfaces.PPDSINTERFACE.getinputflag():
                Data = ccinterfaces.PPDSINTERFACE.getinputdata()
                DataToWS = Data.replace('\r','').replace('\n','')
                if DataToWS != "":
                    if ccinterfaces.Verbose:
                        print "PPDS->WS: %s"%DataToWS
                    if ccinterfaces.WSSINTERFACE:
                        ccinterfaces.WSSINTERFACE.send(DataToWS)
            time.sleep(0.001)
            
def usage():
    print
    print "Usage: ./wsccppds.py -w websocketport -p ppdsport -i interfacename [-v]"
    print "       websocketport may above 1024 as you want, and not used by any other service"
    print "       you can check the number of ppdsport in /etc/ppds/ppdsconf.xml"
    print "       interface name must be IO or CAE"
    print "       -v option switch on verbose mode, you can see the communication between WS and PPDS"
    print
    print "Example: ./wsccppds.py -p 12000 -w 9998 -i IO >/dev/null 2>&1 &"
    print

if __name__ == '__main__': 
    """Main program"""
    WSSPort = None
    PPDSPort = None
    IfName = None
    Options, Arguments = getopt.getopt(sys.argv[1:], "hvw:p:i:")
    for option in Options:            
        if option[0] == "-w":    
            WSSPort = int(option[1])    
        if option[0] == "-p":
            PPDSPort = int(option[1])
        if option[0] == "-i":
            IfName = option[1]
        if option[0] == "-v":
            ccinterfaces.Verbose = True
        if option[0] == "-h":
            usage()
            sys.exit(0)
              
    if not(IfName and PPDSPort and WSSPort):
        usage()
        sys.exit(1)
    
    PPDriver = PPDRIVER();
    if "CAE" in IfName:
        PPDriver.registerCAEinterface("localhost", PPDSPort)
        PPDriver.connectinterfaces(True,False,False)
    if "IO" in IfName:
        PPDriver.registerIOinterface("localhost", PPDSPort)
        PPDriver.connectinterfaces(False,True,False)
    CAEIF, IOIF, MONIF = PPDriver.getinterfaces()    
                  
    if "CAE" in IfName:
        ccinterfaces.PPDSINTERFACE = CAEIF
    if "IO" in IfName:
        ccinterfaces.PPDSINTERFACE = IOIF
    
    ST = SendThread()   
    
    WebSocketServer(
        ('', WSSPort),
        Resource({'/': PPDSCrossConnector})
    ).serve_forever()
