# -*- coding: utf-8 -*-
"""

@author: David S. De Lorenzo

Simple calibration script for the HackRF One.

Important:  You must run this from a GNURadio Command Prompt!!

Your signal path should be:

    HackRF One  -->  8482A Power Sensor  -->  E4418B Power Meter

"""

import time
import requests
import numpy as np
import xml.etree.ElementTree as ET
import hackrf


# Hard-code the device ID
DEVICE_ID = '0000000000000000a06063c82416705f'
# DEVICE_ID = '0000000000000000a06063c824237e5f'
# DEVICE_ID = '0000000000000000f75461dc2684a9c3'


# Hard-code the interference type
INTERFERENCE_TYPE = 'CW'
# INTERFERENCE_TYPE = 'GAUSSIAN_RFI_1MHz'
# INTERFERENCE_TYPE = 'GAUSSIAN_RFI_2MHz'
# INTERFERENCE_TYPE = 'GAUSSIAN_RFI_5MHz'
# INTERFERENCE_TYPE = 'BANDLIMITED_RFI_400kHz'
# INTERFERENCE_TYPE = 'BANDLIMITED_RFI_1MHz'
# INTERFERENCE_TYPE = 'BANDLIMITED_RFI_2MHz'
# INTERFERENCE_TYPE = 'PULSED_RFI_1msec'
# INTERFERENCE_TYPE = 'PULSED_RFI_20msec'
# INTERFERENCE_TYPE = 'PULSED_RFI_500msec'


# Hard-code the center frequency
CENTER_FREQ_MHz = 1575.42


# Set the RF gain to 0 or 14
# RF_GAIN = 0
RF_GAIN = 14


# Set range of IF gain over which to loop
#
#   either range(1, 48) or range(47, 0, -1)
#
IF_GAIN_RANGE = range(1, 48)
# IF_GAIN_RANGE = range(47, 0, -1)


def main():

    print('\nSTARTING TEST!!!\n')

    # Allocate results storage
    r = np.zeros((0, 2))

    # Connect to the HackRF One
    hack_rf = hackrf.device_connect(DEVICE_ID, INTERFERENCE_TYPE)
    hack_rf.start()

    # Turn on the RF source
    hack_rf.set_center_freq_MHz(CENTER_FREQ_MHz)
    hack_rf.set_rf_gain_dB(RF_GAIN)
    hack_rf.set_if_gain_dB(0)
    hack_rf.set_on_or_off(True)

    # Pause to enable HackRF to start itself
    #
    #   This is mostly important for the CW source
    #
    time.sleep(10)

    # Loop over IF gain
    for if_gain_dB in IF_GAIN_RANGE:

        # Set the IF gain
        hack_rf.set_if_gain_dB(if_gain_dB)

        # Short pause
        time.sleep(5)

        # Read the Met-Tilt interface
        request_str = 'http://10.1.150.132/xml/dynamic/metResult.xml'
        resp = requests.get(request_str, auth=('admin', 'password'))

        # Parse the <result> element and cast to float
        x = float(ET.fromstring(resp.text).find('result').text)

        # Print results to screen
        print('  IF = ' + str(if_gain_dB) + ' dB | Power = ' + str(x) + ' dBm')

        # Store the results
        r = np.append(r, [[if_gain_dB, x]], axis=0)

    # Turn off the RF source
    hack_rf.set_on_or_off(False)

    # Disconnect from the HackRF One
    hack_rf.stop()
    hack_rf.wait()

    print('\n\nTEST FINISHED!!!\n')

    print('    r = [; ...')
    for row in r:
        print('        {:+05.1f},   {:+07.3f}; ...'.format(row[0], row[1]))
    print('        ];')


if __name__ == '__main__':
    main()
