from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.figure import Figure

from numpy import append, linspace, log10, zeros

from RealtekSDR.TCPclient import RtlTCP, BUFFER_SIZE
from RealtekSDR.stations import FM_freq

logging.basicConfig()
mylogger = logging.getLogger()

# Configure SDR    
sr = 200000
freq = FM_freq["KCRW"]
sdr = RtlTCP(samplerate=sr, freq=int(freq*1e6))

# Initialize plot
nspec = 256
last_read = nspec # initial value
nch = BUFFER_SIZE/2
oldest_displayed = 0
history = 16384

fig = plt.figure()
waterfall_axes = fig.add_axes([.1,.1,.75,.9])
data = zeros((nspec,nch))
for index in range(nspec):
  time.sleep(0.003)
  data[index,:] = log10(sdr.grab_SDR_spectrum())
image = data[oldest_displayed:oldest_displayed + nspec, :]
"""
import logging
from math import log10
from matplotlib import pyplot as plt
from matplotlib import animation
from numpy import linspace

from RealtekSDR.TCPclient import RtlTCP, BUFFER_SIZE
from RealtekSDR.stations import FM_freq

mylogger = logging.getLogger()

# Configure SDR    
sr = 200000
freq = FM_freq["KCRW"]
sdr = RtlTCP(samplerate=sr, freq=int(freq*1e6))

# Initialize plot
spectrum = sdr.grab_SDR_spectrum()
yminexp = int(log10(spectrum.min()))
ymaxexp = int(log10(spectrum.max())+1)
mylogger.debug(" Y axis limits: %e, %e", yminexp,ymaxexp)
fig = plt.figure()
ax = plt.axes(xlim=(freq-sr/2e6, freq+sr/2e6), ylim=(10**yminexp,10**ymaxexp))
x = linspace(freq-sr/2e6, freq+sr/2e6, BUFFER_SIZE/2)
line, = ax.semilogy([], [])
ax.grid(True)
ax.set_xlabel("Frequency (MHz)")

def init():
    line.set_data([], [])