#!/usr/bin/python3
# LAVA Mobility Setup - Copyright 2021 LAVA Controls - Stephen Loeckle

import argparse
import inspect
import lavamobilitylib
import os
import serial
import sys
from time import sleep
import traceback

# port = '/dev/ttyACM2'
portbase = '/dev/ttyACM'

def modemsetup(carrier, port=None):
    gotthefunc = inspect.stack()[0][3]
    if port:
        serialport = port
    else:
        print('Searching for communication port...')
        y = range(3)
        for x in y:
            serialport = portbase+str(x)
            try:
                s = serial.Serial(serialport, baudrate=9600, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=1)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                msg = ('Connected to {}'.format(serialport))
                # print(msg)
            cmd = b'AT\r\n'
            try:
                with lavamobilitylib.Timeout(5):
                    lavamobilitylib.senddata(s,cmd)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                try:
                    with lavamobilitylib.Timeout(30):
                        received = lavamobilitylib.recvdata(s)
                except:
                    msg = ("Unexpected Error in {}!:".format(gotthefunc))
                    print(gotthefunc, msg, 40)
                    err = traceback.format_exc()
                    msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                    print(gotthefunc, msg, 10)
                else:
                    if len(received) >= 1 and 'OK' in received:
                        break
            finally:
                s.close()
    try:
        s = serial.Serial(serialport, baudrate=9600, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=1)
    except:
        msg = ('Serial port {} busy'.format(serialport))
        print(msg)
    else:
        msg = ('Connected to {}'.format(serialport))
        print(msg)
        cmd = 'AT+CGACT=0,1'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        cmd = 'AT+CGACT=0,2'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        cmd = 'AT+CGATT=0'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        cmd = 'AT+CPIN?'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(60):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        sleep(1)
        cmd = 'AT+CSQ'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(60):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        cmd = 'AT+COPS?'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(60):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        sleep(3)
        cmd = 'AT+CGREG?'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(60):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        sleep(3)
        cmd = 'AT+CGDCONT=1,"IP","wap.vodafone.co.uk"'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        sleep(1)
#        cmd = 'AT+CGDCONT=2,"IP","pp.vodafone.co.uk"'
#        print('Sending {} to {}'.format(cmd,serialport))
#        cmd = cmd+'\r\n'
#        cmd = cmd.encode()
#        try:
#            with lavamobilitylib.Timeout(5):
#                lavamobilitylib.senddata(s,cmd)
#        except:
#            msg = ("Unexpected Error in {}!:".format(gotthefunc))
#            print(gotthefunc, msg, 40)
#            err = traceback.format_exc()
#            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
#            print(gotthefunc, msg, 10)
#            s.close()
#        else:
#            try:
#                with lavamobilitylib.Timeout(30):
#                    received = lavamobilitylib.recvdata(s)
#            except:
#                msg = ("Unexpected Error in {}!:".format(gotthefunc))
#                print(gotthefunc, msg, 40)
#                err = traceback.format_exc()
#                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
#                print(gotthefunc, msg, 10)
#            else:
#                if len(received) >= 1 and 'OK' in received:
#                    print('Response Begin:')
#                    print('{}'.format(received))
#                    print('Response End')
#                else:
#                    print('Empty response to {}'.format(cmd))
#        sleep(1)
        cmd = 'AT+CGDCONT?'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(60):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        cmd = 'AT+CGATT=1'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        sleep(3)
        cmd = 'AT+CGATT?'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        cmd = 'AT+CGACT=1,1'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
        sleep(3)
        cmd = 'AT+CGPADDR=1'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Response Begin:')
                    print('{}'.format(received))
                    print('Response End')
                else:
                    print('Empty response to {}'.format(cmd))
                    
        cmd = 'AT+CCID'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('ICCID Response Begin:')
                    print('{}'.format(received))
                    print('ICCID Response End')
                else:
                    print('Empty response to {}'.format(cmd))
                    
        cmd = 'AT+KGSN=1'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('IMEI Response Begin:')
                    print('{}'.format(received))
                    print('IMEI Response End')
                else:
                    print('Empty response to {}'.format(cmd))
                    
        cmd = 'AT+KGSN=4'
        print('Sending {} to {}'.format(cmd,serialport))
        cmd = cmd+'\r\n'
        cmd = cmd.encode()
        try:
            with lavamobilitylib.Timeout(5):
                lavamobilitylib.senddata(s,cmd)
        except:
            msg = ("Unexpected Error in {}!:".format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
            s.close()
        else:
            try:
                with lavamobilitylib.Timeout(30):
                    received = lavamobilitylib.recvdata(s)
            except:
                msg = ("Unexpected Error in {}!:".format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Unexpected Error in {0} Detail: {1}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                if len(received) >= 1 and 'OK' in received:
                    print('Product Serial Response Begin:')
                    print('{}'.format(received))
                    print('Product Serial Response End')
                else:
                    print('Empty response to {}'.format(cmd))

def ppp0setup(carrier):
    gotthefunc = inspect.stack()[0][3]
    ppp0file = '/etc/network/interfaces.d/ppp0'
    if carrier.lower() != 'disable':
        f = open(ppp0file,'w')
        os.chmod(ppp0file, 0o755)
        f.write('auto ppp0\n')
        f.write('iface ppp0 inet ppp\n')
        f.write('    provider {}\n'.format(carrier))
        f.close()
    else:
        try:
            os.remove(ppp0file)
        except:
            print('Could not remove {}!'.format(pp0file))
            pass
    
def main():
    gotthefunc = inspect.stack()[0][3]
    msg = ('Entered {} function'.format(gotthefunc))
    parser = argparse.ArgumentParser(description='LAVA Mobility Setup')
    carriergroup = parser.add_argument_group('carrier')
    carriergroup.add_argument('-c', '--carrier', help = 'Set carrier to use for mobility. Leave blank or type "disable" to disable mobility.', choices=['disable','att','vodafone'], action="store", const='disable', nargs='?')
    args = parser.parse_args()
    if len(sys.argv) == 0:
        parser.print_help()
    elif args.carrier:
        ppp0setup(args.carrier)
        modemsetup(args.carrier)
        print('Changes made to LAVA Mobility settings. Please reboot for changes to take effect.'.format(args.carrier))
    else:
        parser.print_help()

if __name__ == '__main__':
   main()

