#coding:utf-8
'''
Created on Oct 17, 2014

@author: root
'''
import commands

from PyQt4.QtCore import QThread, SIGNAL
import serial


class NetSwitch(QThread):
    _instance = 0
    def __init__(self,parent=None):
        super(NetSwitch,self).__init__(parent)
        self.netportData = ["FF01030101AA", "FF01030201AA", "FF01030301AA", "FF01030401AA"]
        
        
    @classmethod 
    def instance(cls):
        if (cls._instance == 0):
            cls._instance = NetSwitch()
            
        return cls._instance
        
    def getUsbList(self):    
        cmd = "ls /dev/ttyUSB*"
        statusoutput = commands.getstatusoutput(cmd)
        if statusoutput[0] == 0:
            output = statusoutput[1]
            return output.split("\n")
        else:
            return []
            
            
    def setNetNum(self,num):
        self.num = num
        
    def changeNetSwitchPort(self, num):
        usbList = self.getUsbList()
        if not usbList:
            return False
        
        for serialPortName in usbList:
            t = serial.Serial(serialPortName, 9600)
            t.setByteSize(serial.EIGHTBITS)
            t.setStopbits(serial.STOPBITS_ONE)
            t.setParity(serial.PARITY_NONE)
            t.setTimeout(10)
            strhex = self.netportData[num-1].decode('hex')
            t.write(strhex)
            t.close()
        return True
        
        
    def run(self):
        if self.changeNetSwitchPort(self.num):
            self.emit(SIGNAL("setswitchover"),0)
        else:
            self.emit(SIGNAL("setswitchover"),1)
            
        return
        

