#! /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()]

for device in devices:
    print(device)

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, 912.3e6)

# setup a stream (complex floats)
rxStream = sdr.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32)
sdr.activateStream(rxStream)  # start streaming

# create a re-usable buffer for rx samples
samples = 1000
buff = np.array([0] * samples * 2, np.float32)

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

    print(
        f"Samples: {sr.ret}, flags: {sr.flags}, timestamp {sr.timeNs}", file=sys.stderr
    )

    sys.stdout.buffer.write(struct.pack("=%df" % len(buff), *buff))

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