# File: g (Python 1.5)

import MDM
import MOD
import GPIO

class Module:
    
    def __init__(self, config):
        self.config = config
        self.current_sim_number = 0
        self.has_data = 0
        self.no_carrier = 1

    
    def sendAT(self, command, timeout = 2, okInResult = 0, repeats = 1, timeout_between_commands = 0):
        while repeats >= 1:
            result = MDM.read()
            self.check_for_data(result)
            self.check_for_carrier(result)
            MDM.send(command + '\r', 0)
            print 'SEND COMMAND: ', command
            result = ''
            timeout_time = MOD.secCounter() + timeout
            while 1:
                MOD.sleep(timeout_between_commands)
                result = result + MDM.read()
                if len(result) > 0:
                    print 'RESULT OF COMMAND'
                    print '-' * 80
                    print result
                    print '-' * 80
                    result = result[2:]
                    result = self.check_for_data(result)
                    result = self.check_for_carrier(result)
                    if result.find('ERROR') != -1:
                        print 'ERROR when send:', command
                        break
                    
                    if okInResult:
                        if result.find('OK') != -1:
                            result = result[:-8]
                        
                    
                    return result
                
                if MOD.secCounter() > timeout_time:
                    break
                
            repeats = repeats - 1
        return None

    
    def reboot(self):
        self.sendAT('AT#REBOOT')

    
    def check_for_data(self, data):
        if data.find('SRING: 1\r\n') != -1:
            self.has_data = 1
            data = data.replace('SRING: 1\r\n', '')
        
        return data

    
    def check_for_carrier(self, data):
        if data.find('NO CARRIER') != -1:
            self.no_carrier = 1
            data = data.replace('NO CARRIER\r\n', '')
        
        return data

    
    def tray_status(self, gpio = None):
        if gpio is None:
            sim0_tray_status = int(GPIO.getIOvalue(6))
            sim1_tray_status = int(GPIO.getIOvalue(7))
            if sim0_tray_status == 1:
                pass
            return sim1_tray_status == 1
        else:
            return int(GPIO.getIOvalue(gpio))

    
    def sim_status(self):
        for x in range(3):
            recv = self.sendAT('AT+CPIN?', okInResult = 1, timeout = 15)
            if recv == '+CPIN: READY':
                tmt = MOD.secCounter() + 180
                while MOD.secCounter() < tmt:
                    if self.tray_status():
                        return 0
                    
                    recv = self.sendAT('AT+CREG?', okInResult = 1)
                    recv = recv[9]
                    if recv == '1' or recv == '5':
                        return 1
                    elif recv == '0':
                        return 0
                    elif recv == '3':
                        print 'REGISTRATION DENIED'
                    
                    MOD.sleep(20)
                    continue
                    0
                return 0
            elif recv == '+CPIN: SIM PIN':
                recv = self.sendAT('AT+CPIN=' + self.conf.get('pin' + str(self.current_sim_number + 1)), okInResult = 1)
                if recv is None:
                    print 'WRONG SIM PIN'
                    return 0
                
                return 1
            
            MOD.sleep(20)
        
        return 0

    
    def get_imei(self):
        recv = self.sendAT('AT+CGSN', timeout = 15, okInResult = 1)
        return recv

    
    def get_csq(self):
        recv = self.sendAT('AT+CSQ', timeout = 30, okInResult = 1)
        if recv is not None:
            recv = recv.split(':')[1].split(',')[0].strip()
        else:
            recv = '99'
        return recv

    
    def change_sim(self):
        print 'SWITCH SIM CARD'
        recv = self.sendAT('AT+CFUN?', okInResult = 1, timeout = 30, timeout_between_commands = 40)
        if recv is None:
            self.reboot()
        elif recv[7] != '4':
            self.sendAT('AT#SIMDET=0', okInResult = 1, timeout = 30, timeout_between_commands = 40)
            self.sendAT('AT+CFUN=4', okInResult = 1, timeout = 30, timeout_between_commands = 40)
            self.current_sim_number = not (self.current_sim_number)
            self.has_data = 0
            self.no_carrier = 1
            GPIO.setIOdir(5, self.current_sim_number, 1)
            self.sendAT('AT+CFUN=1', okInResult = 1, timeout = 30, timeout_between_commands = 40)
            self.sendAT('AT#SIMDET=1', okInResult = 1, timeout = 30, timeout_between_commands = 40)
        
        MOD.sleep(20)


