##################################################
#Project Name    : j-radio_recorder (AM)
#File Name       : jam_rec_(version No.), jam_recorder_(version No.)
#Encoding        : python3.9(inclueding GRC3.8)
#Creation Date   : 2022.1.16
#Release note:
#2022.2.24 : 録音ファイルの保存pathをiniファイルで設定できるようにした
#
#Copyright c 2021-2022 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 python3
# -*- coding: utf-8 -*-
###################################################
#
# SPDX-License-Identifier: GPL-3.0
#
# GNU Radio Python Flow Graph
# Title: Top Block
# GNU Radio version: v3.8.2.0-57-gd71cd177

from gnuradio import analog
from gnuradio import blocks
from gnuradio import filter
from gnuradio.filter import firdes
from gnuradio import gr
import sys
import signal
from argparse import ArgumentParser
from gnuradio.eng_arg import eng_float, intx
from gnuradio import eng_notation
import osmosdr
import datetime,time
import schedule
import sys

import configparser
# 初期設定値ファイルセット
inifile = configparser.ConfigParser()
inifile.read('settings_am.ini',encoding='utf-8-sig')

print('AM Radio Recorder Ver.0.4 Copyright 2022 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 = 90
        self.tune_freq = tune_freq = TUNE_FREQ*1e3
        self.samp_rate = samp_rate = 2.560*1e6
        self.rf_gain = rf_gain = 20
        self.center_freq = center_freq = 1280*1e3

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

        ##################################################
        # Blocks
        ##################################################
        self.rtlsdr_source_0 = osmosdr.source(
            args="numchan=" + str(1) + " " + str(DEV_ARG)
        )
        self.rtlsdr_source_0.set_time_unknown_pps(osmosdr.time_spec_t())
        self.rtlsdr_source_0.set_sample_rate(samp_rate)
        self.rtlsdr_source_0.set_center_freq(center_freq, 0)
        self.rtlsdr_source_0.set_freq_corr(0, 0)
        self.rtlsdr_source_0.set_dc_offset_mode(0, 0)
        self.rtlsdr_source_0.set_iq_balance_mode(0, 0)
        self.rtlsdr_source_0.set_gain_mode(False, 0)
        self.rtlsdr_source_0.set_gain(rf_gain, 0)
        self.rtlsdr_source_0.set_if_gain(20, 0)
        self.rtlsdr_source_0.set_bb_gain(20, 0)
        self.rtlsdr_source_0.set_antenna('', 0)
        self.rtlsdr_source_0.set_bandwidth(0, 0)
        self.low_pass_filter_0 = filter.fir_filter_ccf(
            80,
            firdes.low_pass(
                1,
                samp_rate,
                8000,
                2000,
                firdes.WIN_HAMMING,
                6.76))
        self.blocks_wavfile_sink_0 = blocks.wavfile_sink(PATH + 'am' + str(TUNE_FREQ) + now.strftime('_%Y%m%d_%H%M') +'.wav', 1, 32000, 16)
        self.blocks_multiply_xx_0 = blocks.multiply_vcc(1)
        self.blocks_multiply_const_vxx_0 = blocks.multiply_const_ff(volume*0.01)
        self.band_pass_filter_0 = filter.fir_filter_ccc(
            1,
            firdes.complex_band_pass(
                1,
                samp_rate,
                500e3 - center_freq,
                1700e3 - center_freq,
                200e3,
                firdes.WIN_HAMMING,
                6.76))
        self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, center_freq-tune_freq, 1, 0, 0)
        self.analog_am_demod_cf_0 = analog.am_demod_cf(
        	channel_rate=32*1e3,
        	audio_decim=1,
        	audio_pass=5000,
        	audio_stop=5500,
        )
        self.analog_agc_xx_0 = analog.agc_cc(1e-4, 1.0, 1.0)
        self.analog_agc_xx_0.set_max_gain(65536)



        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_agc_xx_0, 0), (self.analog_am_demod_cf_0, 0))
        self.connect((self.analog_am_demod_cf_0, 0), (self.blocks_multiply_const_vxx_0, 0))
        self.connect((self.analog_sig_source_x_0, 0), (self.blocks_multiply_xx_0, 1))
        self.connect((self.band_pass_filter_0, 0), (self.blocks_multiply_xx_0, 0))
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_wavfile_sink_0, 0))
        self.connect((self.blocks_multiply_xx_0, 0), (self.low_pass_filter_0, 0))
        self.connect((self.low_pass_filter_0, 0), (self.analog_agc_xx_0, 0))
        self.connect((self.rtlsdr_source_0, 0), (self.band_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.analog_sig_source_x_0.set_frequency(self.center_freq-self.tune_freq)

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
        self.band_pass_filter_0.set_taps(firdes.complex_band_pass(1, self.samp_rate, 500e3 - self.center_freq, 1700e3 - self.center_freq, 200e3, firdes.WIN_HAMMING, 6.76))
        self.low_pass_filter_0.set_taps(firdes.low_pass(1, self.samp_rate, 8000, 2000, firdes.WIN_HAMMING, 6.76))
        self.rtlsdr_source_0.set_sample_rate(self.samp_rate)

    def get_rf_gain(self):
        return self.rf_gain

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

    def get_center_freq(self):
        return self.center_freq

    def set_center_freq(self, center_freq):
        self.center_freq = center_freq
        self.analog_sig_source_x_0.set_frequency(self.center_freq-self.tune_freq)
        self.band_pass_filter_0.set_taps(firdes.complex_band_pass(1, self.samp_rate, 500e3 - self.center_freq, 1700e3 - self.center_freq, 200e3, firdes.WIN_HAMMING, 6.76))
        self.rtlsdr_source_0.set_center_freq(self.center_freq, 0)


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

    global exe_counter
    tb = top_block_cls()

#    def sig_handler(sig=None, frame=None):
#        tb.stop()
#        tb.wait()
#
#        sys.exit(0)
#
#    signal.signal(signal.SIGINT, sig_handler)
#    signal.signal(signal.SIGTERM, sig_handler)

    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(KHz)> <XX:YY> <record times> <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]
PATH = inifile.get('SECTION1', 'data4')

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

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

if (set_weekday == 0):
    loop_counter = 14
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=14)'
elif (set_weekday == 1):
    loop_counter = 1
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=1)'
elif (set_weekday == 2):
    loop_counter = 2
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=2)'
elif (set_weekday == 3):
    loop_counter = 3
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=3)'
elif (set_weekday == 4):
    loop_counter = 4
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=4)'
elif (set_weekday == 5):
    loop_counter = 5
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=5)'
elif (set_weekday == 6):
    loop_counter = 6
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=6)'
elif (set_weekday == 7):
    loop_counter = 7
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=7)'
elif (set_weekday == 8):
    loop_counter = 8
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=8)'
elif (set_weekday == 9):
    loop_counter = 9
    schedule.every().day.at(s_time).do(main)
    week_no = 'Day(times=9)'

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

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

