#!/usr/bin/env python3
"""
device_status.py - Retrieve radio front-end status from a GRX receiver.

This example connects to a GRX receiver and queries the status of all
radio front-ends, including gain settings, noise levels, and antenna
information.

Usage:
    python device_status.py [HOST]

Arguments:
    HOST    IP address or hostname of the GRX (default: YOUR_GRX_IP)

Prerequisites:
    pip install grpcio grpcio-tools
    Run gen_pb.sh to generate the Python bindings.
"""

import sys

import grpc
from google.protobuf.empty_pb2 import Empty

# Import the generated gRPC stubs for the Receiver API
import Receiverd_pb2_grpc

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------

# GRX receiver address (override with command-line argument)
host = sys.argv[1] if len(sys.argv) >= 2 else "YOUR_GRX_IP"

# The Receiver API listens on TCP port 5303
RECEIVERD_PORT = 5303

# ---------------------------------------------------------------------------
# Connect to the GRX receiver
# ---------------------------------------------------------------------------

print(f"Connecting to {host}:{RECEIVERD_PORT}...")
channel = grpc.insecure_channel(f"{host}:{RECEIVERD_PORT}")
receiverd = Receiverd_pb2_grpc.ReceiverdStub(channel)

# ---------------------------------------------------------------------------
# Query radio front-end status
# ---------------------------------------------------------------------------

status = receiverd.GetRadioFrontEndStatus(Empty())

# Print radio front-end information
print(f"\nThe receiver has {len(status.radio_front_end_status)} radio front-end(s).\n")

for rf in status.radio_front_end_status:
    # The 'band' field is a numeric enum value; we print its name for clarity
    print(f"  Radio front-end (band={rf.band}):")
    print(f"    Fixed gain (internal):    {rf.rx_chain_fixed_gain} dB")
    print(f"    Fixed gain (external):    {rf.external_fixed_gain} dB")
    print(f"    Noise level:              {rf.noise_level:.1f} dBm")
    print()

# Print antenna information
print(f"The receiver has {len(status.antenna_status)} antenna port(s).\n")

for ant_id, ant in status.antenna_status.items():
    supply = "not available"
    if ant.has_supply_enable:
        supply = "enabled" if ant.supply_enable else "disabled"
    print(f"  Antenna '{ant_id}' ({ant.label}):")
    print(f"    Power supply: {supply}")
    print()

# ---------------------------------------------------------------------------
# Clean up
# ---------------------------------------------------------------------------

channel.close()
