#!/usr/bin/python

# this source is part of my Hackster.io project:  https://www.hackster.io/mariocannistra/radio-astronomy-with-rtl-sdr-raspberrypi-and-amazon-aws-iot-45b617

# this program will determine the overall range of signal strengths received during the whole session. 

# this program can be run standalone but is usually run at end of session by  doscan.py

# Its output will be stored in 2 files: 
# dbminmax.txt and session-overview.png . The first contains two rows of text with just the maximum 
# and minimum of the whole session. The second contains a chart of all the min and max values for each of
# the scan files 

from glob import glob
import numpy as np
import radioConfig
import subprocess
import os
import datetime

import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt

globmax = -9000
globmin = 9000

sessmin = np.empty(shape=[0, 1])
sessmax = np.empty(shape=[0, 1])
scantimeline = np.empty(shape=[0, 1])

files_in_dir = sorted(glob("*.csv"))
for fname in files_in_dir:
    dbs = np.genfromtxt(fname,dtype='float',delimiter = ',', skip_header=0, skip_footer=0, usecols=(6,),usemask=True)
    thismin=dbs.min()
    thismax=dbs.max()
    scantime=str(fname)[11:17]
    print scantime,thismin,thismax

    if thismin < globmin:
        globmin = thismin
    if thismax > globmax:
        globmax = thismax
    sessmin = np.append(sessmin, thismin)
    sessmax = np.append(sessmax, thismax)
    scantimeline = np.append(scantimeline, scantime)

mytitle = 'Signal strength range: min %f .. max %f' % (globmin,globmax)
print mytitle

xs = range(len(scantimeline))
plt.plot(xs,sessmin )
plt.plot(xs,sessmax )
plt.xticks(xs,scantimeline,rotation=70)
plt.grid()
plt.title(mytitle)
#plt.show()
plt.savefig('session-overview.png')

sessfile = open("dbminmax.txt", "w")
sessfile.write(str(globmax))
sessfile.write("\n")
sessfile.write(str(globmin))
sessfile.write("\n")
sessfile.close()
