#!/usr/bin/python3

from datetime import datetime, timezone
import serial
import time
import argparse

at_port = '/dev/ttyUSB2'
agps_file = 'RAM:data.bin'
use_ssl = False 

def sendCmd(cmdstring):
    print(cmdstring)
    ser.reset_input_buffer()
    ser.flush()
    ser.write(f"{cmdstring}\r\n".encode('ascii'))
    res =  []
    while True:
        line = ser.readline()
        if (line == b''):
            break
        else:
            res.append(line)
    print(res)
    return res


parser = argparse.ArgumentParser("load_test_supl")
parser.add_argument("-s", "--ssl", help="use ssl", action="store_true")
args = parser.parse_args()

use_ssl = args.ssl 

print('open serial port')
ser = serial.Serial(at_port, timeout=3)
print('Check modem talk to us')
res = sendCmd('AT')


# delete all assistance data
res = sendCmd(f"AT+QGPSEND")
res = sendCmd(f"AT+QGPSXTRA=0")
res = sendCmd(f"AT+QGPSDEL=3")
res = sendCmd(f"AT+QGPSDEL=0")
res = sendCmd(f"AT+QGPSXTRADATA?")
res = sendCmd(f"AT+QFDEL=\"{agps_file}\"")

r = open('root-r1.crt','rb').read()

print('upload file to the modem')
res = sendCmd(f"AT+QFUPL=\"{agps_file}\",{len(r)}")
ser.write(r)
res = []
while True:
    line = ser.readline()
    if (line == b''):
        break
    else:
        res.append(line)
print(res)

print('set supl ca to file we uploaded')
res = sendCmd(f"AT+QGPSSUPLCA=\"{agps_file}\"")

print('write configuration')
if use_ssl:
    res = sendCmd(f"AT+QGPSCFG=\"plane\",1")
    res = sendCmd(f"AT+QGPSSUPLURL=\"supl.google.com:7275\"")
else:
    res = sendCmd(f"AT+QGPSCFG=\"plane\",0")
    res = sendCmd(f"AT+QGPSSUPLURL=\"supl.google.com:7276\"")


print('read configuration')
res = sendCmd(f"AT+QGPSCFG=\"suplver\"")
res = sendCmd(f"AT+QGPSCFG=\"plane\"")
res = sendCmd(f"AT+QGPSSUPLURL?")


print('start GNSS receiver (MSB)')
res = sendCmd(f"AT+QGPS=2")

for x in range(0, 5):
    time.sleep(1)
    res = sendCmd(f"AT+QGPSGNMEA=\"GSV\"")

print('stop GNSS receiver')    
res = sendCmd(f"AT+QGPSEND")
res = sendCmd(f"AT+QGPSDEL=3")
res = sendCmd(f"AT+QGPSDEL=0")

print('close serial port')
if ser.is_open:
    ser.close()
