#!/usr/bin/python2

# Copyright 2014 Jared Boone <jared@sharebrained.com>
#
# This file is part of gr-tpms.
#
# 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 2, 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; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#

import numpy

from gnuradio import blocks
from gnuradio import digital
from gnuradio import gr

from tpms.source import source_file
from tpms.fsk import fsk_demodulator
from tpms.decode import clock_recovery, tag_print

class top_block(gr.top_block):
	def __init__(self, args):
		super(top_block, self).__init__(
			"top_block"
		)

		self.source = source_file(args.file)

		self.demodulator = fsk_demodulator(args.sample_rate, args.offset, args.deviation, 1, args.symbol_rate)
		self.connect((self.source, 0), (self.demodulator, 0))

		self.clock_recovery = clock_recovery(args.sample_rate, args.symbol_rate)
		self.connect((self.demodulator, 0), (self.clock_recovery, 0))

		self.correlator = digital.correlate_access_code_tag_bb(args.access_code, 0, "preamble")
		self.connect((self.clock_recovery, 0), (self.correlator, 0))

		self.tag_print = tag_print(args.symbol_rate, args.length)
		self.connect((self.correlator, 0), (self.tag_print, 0))

def main():
	from argparse import ArgumentParser

	parser = ArgumentParser()
	parser.add_argument('-f', '--file', type=str, default=None, help="Input file path")
	parser.add_argument('-r', '--sample-rate', type=float, default=None, help="Sample rate")
	parser.add_argument('-o', '--offset', type=float, default=0, help="Carrier offset from 0 Hz")
	parser.add_argument('-d', '--deviation', type=float, default=None, help="Deviation above/below carrier")
	parser.add_argument('-s', '--symbol-rate', type=float, default=None, help="Symbol rate")
	parser.add_argument('-a', '--access-code', type=str, default=None, help="Access code")
	parser.add_argument('-l', '--length', type=int, default=None, help="Number of bits to dump after detected access code")
	args = parser.parse_args()

	tb = top_block(args)
	tb.start()

	try:
		tb.wait()
	except KeyboardInterrupt:
		tb.stop()

if __name__ == '__main__':
	main()
