import requests
import datetime
import argparse
import time

# Copyright Trimble 2024

# Demonstrates how to get FFT data using the server push end point

headers={'Accept-Encoding':'gzip'}
proxies={'http':None,'https':None}

if __name__ == '__main__':
    # Used to estimate the throughput rate of the messages
    numMessages = 0
    startTime   = 0

    # Create an argument parser
    parser = argparse.ArgumentParser(description='Server Event FFT Client')

    # Add command line arguments
    parser.add_argument('--ip', type=str, help='IP address of the server (receiver)')
    parser.add_argument('--prefix', type=str, help='Log file name prefix')
    parser.add_argument('--username', type=str, help='Username for authentication')
    parser.add_argument('--password', type=str, help='Password for authentication')

    # default values - we'll override these if the user specifies them on the command line
    ipAddr = '10.1.150.129'
    filePrefix = 'FFTData'
    username = 'admin'
    password = 'password'

    # Parse the command line arguments
    args = parser.parse_args()

    # Get the values from the command line arguments
    if(args.ip is not None):
        ipAddr = args.ip
       
    # Log file name prefix - we'll add this to the front of each datafile
    if(args.prefix is not None):
        filePrefix = args.prefix        

    if(args.username is not None):
        username = args.username
    
    if(args.password is not None):
        password = args.password

    lastTimeTag = -1
    maxDelta = 0

    url = 'http://' + ipAddr + '/xml/dynamic/push_rfSpectrumAnalyzer.csv?rfBand=L1,L2,L5,E6&minRate=200&dB=1'

    with requests.get(url, auth=(username,password), stream=True, headers=headers, proxies=proxies, timeout=60) as resp:
        for line in resp.iter_lines():
            try:
                thisLine = line.decode('utf-8')
                if(thisLine.startswith('data: ')):
                    # Dump "data: " which is part of the streamed standard
                    thisLine = thisLine[6:]
                    tokens = thisLine.split(',') # Data is CSV

                    if(len(tokens) == 2053):
                        # col 0 = GPS time of week in milliseconds
                        # col 1 = Center frequency (middle of FFT) in MHz
                        # col 2 = pre or post mitigation FFT (M7 will always be pre == 0)
                        # col 3 = Position or Vector antenna
                        # col 4 = RSSI (place holder for M8)
                        # 2048 columns of FFT data
                        # Total = 2053 columns
                        thisTimeTag = int(tokens[0])
                        if(lastTimeTag != -1):
                            delta = thisTimeTag - lastTimeTag
                            if(delta > maxDelta):
                                maxDelta = delta
                        lastTimeTag = thisTimeTag

                        # Calculate the message rate
                        if(numMessages == 0):
                            startTime =  thisTimeTag
                        else:
                            totalTime = (thisTimeTag - startTime)/1000.0 # in seconds 
                            rate  = numMessages / totalTime # messages per second
                            # But we asked for 4 FFTs each time
                            rate /= 4.0
                            # Output status to the command line - overwritting the old information
                            # Add plenty of space to handle when the number of characters in the time changes
                            # at week roll
                            print('Time: %d ms Center Freq:%.0f MHz Update rate: %.2f Hz          ' 
                                % (thisTimeTag, float(tokens[1]),rate), end='\r',flush=True)
                        numMessages += 1

                        #print(tokens[0],tokens[1])
                        if(True):
                            now = datetime.datetime.now(datetime.timezone.utc)
                            dateTimeStr  = str(now.year) + '-' + str(now.month).zfill(2) + '-' + str(now.day).zfill(2)
                            dateTimeStr += '-' + str(now.hour).zfill(2)
                            dateTimeStr += '.txt'
                            with open(filePrefix + '-' + dateTimeStr,'a') as fid:
                                fid.write(thisLine)
                                fid.write('\n')
            except:
                time.sleep(0.1) # And try again


