#!/usr/bin/env python
#
# Copyright 2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#

import threading
import os, sys, time
from optparse import OptionParser

import Ice
from gnuradio.ctrlport import GNURadio


class monitor_gui:
    def __init__(self, host, port, options):

        locator = None

        # Extract options into a locator
        locator = "{0} -t:{1} -h {2} -p {3}".format(
            options.app, options.protocol, host, port)


        # Ice/GRCP init
        self.comm = Ice.initialize()
        proxy = self.comm.stringToProxy(locator)
        self.radio = GNURadio.ControlPortPrx.checkedCast(proxy)
        self.updateKnobs()

        while(True):
            self.updateKnobs()
            self.printValues()
            time.sleep(.5)


    def updateKnobs(self):
        self.knobs = self.radio.get([])


    def printValues(self):
        for k in self.knobs.keys():
            (nb,k) = k.split("::", 2)

        keys = self.knobs.keys()
        keys.sort()
        for k in keys:
            (nb,sk) = k.split("::", 2)
            v = self.knobs[k].value
            sv = str(v)
            print(nb + " " + k + " " + sv)


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-P", "--protocol", type="string", default="tcp",
                      help="Type of protocol to use (usually tcp). [default=%default]")
    parser.add_option("-a", "--app", type="string", default="gnuradio",
                      help="Name of application [default=%default]")
    (options, args) = parser.parse_args()

    mg = monitor_gui(args[0], args[1], options)

