##################################################
#Project Name    : jfmradio_recorder
#File Name       : jfmradio_recorder_(date)
#Encoding        : python2.7(inclueding GRC3.7)
#Creation Date   : 2021.10.29
#
#Copyright c 2021 falconblog.org. All rights reserved.
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <https://www.gnu.org/licenses/>.
##################################################
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# GNU Radio version: 3.7.13.5
##################################################

from gnuradio import analog
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import filter
from gnuradio import gr
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
import osmosdr
import datetime,time
import schedule
import sys

print('FM Radio Recorder Ver.0.1 Copyright 2021 falconblog.org. All rights reserved.')

class top_block(gr.top_block):

    def __init__(self):
        gr.top_block.__init__(self, "Top Block")

        ##################################################
        # Variables
        ##################################################
        self.volume = volume = 50
        self.tune_freq = tune_freq = TUNE_FREQ
        self.samp_rate = samp_rate = 1536000
        self.rf_gain = rf_gain = 30

	#############################
        now = datetime.datetime.now()
	#############################

        ##################################################
        # Blocks
        ##################################################
        self.osmosdr_source_0 = osmosdr.source( args="numchan=" + str(1) + " " + str(DEV_ARG) )
        self.osmosdr_source_0.set_sample_rate(samp_rate)
        self.osmosdr_source_0.set_center_freq(tune_freq*1e6, 0)
        self.osmosdr_source_0.set_freq_corr(0, 0)
        self.osmosdr_source_0.set_dc_offset_mode(0, 0)
        self.osmosdr_source_0.set_iq_balance_mode(0, 0)
        self.osmosdr_source_0.set_gain_mode(False, 0)
        self.osmosdr_source_0.set_gain(rf_gain, 0)
        self.osmosdr_source_0.set_if_gain(20, 0)
        self.osmosdr_source_0.set_bb_gain(20, 0)
        self.osmosdr_source_0.set_antenna('', 0)
        self.osmosdr_source_0.set_bandwidth(500*1e3, 0)

        self.low_pass_filter_0 = filter.fir_filter_ccf(4, firdes.low_pass(
        	1, samp_rate, 96000, 96000, firdes.WIN_BLACKMAN, 6.76))
        self.blocks_wavfile_sink_0 = blocks.wavfile_sink('.\\fm' + str(TUNE_FREQ) + now.strftime('_%Y%m%d_%H%M') +'.wav', 1, 48000, 16)
        self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((volume*0.01, ))
        self.analog_fm_demod_cf_0 = analog.fm_demod_cf(
        	channel_rate=samp_rate/4,
        	audio_decim=8,
        	deviation=75000,
        	audio_pass=16000,
        	audio_stop=18500,
        	gain=1,
        	tau=50e-6,
        )



        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_fm_demod_cf_0, 0), (self.blocks_multiply_const_vxx_0, 0))
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_wavfile_sink_0, 0))
        self.connect((self.low_pass_filter_0, 0), (self.analog_fm_demod_cf_0, 0))
        self.connect((self.osmosdr_source_0, 0), (self.low_pass_filter_0, 0))

    def get_volume(self):
        return self.volume

    def set_volume(self, volume):
        self.volume = volume
        self.blocks_multiply_const_vxx_0.set_k((self.volume*0.01, ))

    def get_tune_freq(self):
        return self.tune_freq

    def set_tune_freq(self, tune_freq):
        self.tune_freq = tune_freq
        self.osmosdr_source_0.set_center_freq(self.tune_freq*1e6, 0)

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.osmosdr_source_0.set_sample_rate(self.samp_rate)
        self.low_pass_filter_0.set_taps(firdes.low_pass(1, self.samp_rate, 96000, 96000, firdes.WIN_BLACKMAN, 6.76))

    def get_rf_gain(self):
        return self.rf_gain

    def set_rf_gain(self, rf_gain):
        self.rf_gain = rf_gain
        self.osmosdr_source_0.set_gain(self.rf_gain, 0)


def main(top_block_cls=top_block, options=None):

    global exe_counter
    tb = top_block_cls()
    tb.start()

    start= time.time()
    print('Now Recording... Dulation Time = ' + str(dulation_time))

    while time.time() - start <= dulation_time:
        time.sleep(1)
        
    else:
        tb.stop()

    tb.wait()
    print("Finish to Recording.")
    exe_counter = 1

#
#
#
if __name__ == '__main__':
    args = sys.argv
 
    if len(args) == 6:
        pass
    else:
        print('Option Error!')
        print('$ fmradio_recorder.exe <FREQ> <XX:YY> <week:No.> <Dulation:min> <device arg.>')
        quit()

TUNE_FREQ = float(sys.argv[1])
s_time = sys.argv[2]
set_weekday = int(sys.argv[3])
dulation_time = int(sys.argv[4]) * 60
DEV_ARG = sys.argv[5]

#TUNE_FREQ = 85.1
#s_time = "17:24"
#dulation_time = 5 * 60
exe_counter = 0
week_no = 'Monday'

now_weekday = datetime.date.today().weekday()
#print(set_weekday,now_weekday)

if (set_weekday == 0):
    schedule.every().monday.at(s_time).do(main)
    week_no = 'Monday'
elif (set_weekday == 1):
    schedule.every().tuesday.at(s_time).do(main)
    week_no = 'Tuesday'
elif (set_weekday == 2):
    schedule.every().wednesday.at(s_time).do(main)
    week_no = 'Wednesday'
elif (set_weekday == 3):
    schedule.every().thursday.at(s_time).do(main)
    week_no = 'Thursday'
elif (set_weekday == 4):
    schedule.every().friday.at(s_time).do(main)
    week_no = 'Friday'
elif (set_weekday == 5):
    schedule.every().saturday.at(s_time).do(main)
    week_no = 'Saturday'
elif (set_weekday == 6):
    schedule.every().sunday.at(s_time).do(main)
    week_no = 'Sunday'

print('Recording schedule = '+ 'Every '+ str(week_no) + ' ' + s_time)
print('Dulation Time = ' + str(dulation_time / 60) + 'min')


while True:
    schedule.run_pending()
#    print(exe_counter)
    if (exe_counter == 1):
        break
    time.sleep(5)

