#! /usr/bin/env python3

#
#   Example script for interfacing with SDRPlay radio.
#
# Modified from: https://github.com/pothosware/SoapySDR/wiki/PythonSupport
#

import SoapySDR
from SoapySDR import * #SOAPY_SDR_ constants
import numpy as np
import sys
import struct

#enumerate devices
devices = [dict(device) for device in SoapySDR.Device.enumerate()]

if len(devices) == 0:
    print('No SDR devices available.')
    sys.exit(1)

#create device instance
sdr = SoapySDR.Device(devices[0])

#apply settings
sdr.setSampleRate(SOAPY_SDR_RX, 0, 1e6)
sdr.setFrequency(SOAPY_SDR_RX, 0, 105500000)

#setup a stream (complex floats)
samples = 10000
buff = np.array([0]*samples*2, np.int16)
rxStream = sdr.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CS16)
sdr.activateStream(rxStream)


#receive some samples
for i in range(1000):
    sr = sdr.readStream(rxStream, [buff], samples*2)

    print(sr.ret, sr.flags, sr.timeNs, file=sys.stderr)

    sys.stdout.buffer.write(struct.pack('=%dh' % len(buff), *buff))

#shutdown the stream
sdr.deactivateStream(rxStream) #stop streaming
sdr.closeStream(rxStream)





'''
#create a re-usable buffer for rx samples
# https://stackoverflow.com/a/32877245

    #while True:
    sr = sdr.readStream(rxStream, [buff], samples)
    #print(sr.ret) #num samples or error code
    #print(sr.flags) #flags set by receive operation
    #print(sr.timeNs) #timestamp for receive buffer

    # we now have a np buffer of [(re_16:1, im_16:1), re_16:2, im_16:2), ...]
    # that needs to become a buffer of [re_8:1, im_8:1, re_8:2, im_8:2, ...]
    #print(buff)
    #output = buff.flatten('F')
    #print(output)

    #output = np.empty(len(buff) * 2, dtype=np.float32)
    #output[0::2] = output_left
    #output[1::2] = output_right
    #output = output.astype(int)
    #print(output)

    #scale_factor = 127 / np.max(buff)

    # scale the values using numpy.interp
    #uint8_buffer = np.interp(buff, (buff.min(), buff.max()), (-127, 127)).astype(np.int8)

    output = buff
    #output /= (np.max(np.int16) / np.max(np.int8))
    #output /= (32768 / 127)
    #output = np.divide(output, 1).astype(np.int8)
'''