/**
 * @file comms_sband_rx.c
 *
 * @brief #TODO
 *
 * @copyright Copyright 2023 Antaris, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

#include <stdio.h>
#include "comms_csw.h"
#include "comms_sband_api_map.h"

/** SRS4 carrier locked status bit */  
#define SRS4_CARRIER_LOCKED  (0x1 << 0)
/** SRS4 frame locked status bit */
#define SRS4_FRAME_LOCKED    (0x1 << 1)
/** SRS4 RX detected status bit */
#define SRS4_RX_DETECTED     (0x1 << 2)
/** SRS4 RX decoded status bit */
#define SRS4_RX_DECODED      (0x1 << 3)

/** External - Global RX configuration struct */
extern s_comms_rx_cfg PLACE_IN_EXT_RAM_MEM rx_cfg_global;

/**
 * @brief This function is used to fetch the carrier lock and frame lock information from the S-Band module
 * @brief Checks the link status of the S-Band receiver.
 * 
 * This function checks the carrier lock, frame lock, RX detection and RX decoding 
 * status of the S-Band receiver module. It reads the receiver telemetry data
 * to determine the current link status.
 * 
 * @return rx_sts - Bitmask containing the link status flags:
 * - Bit 0: Carrier lock status (1 = Locked, 0 = Not locked)
 * - Bit 1: Frame lock status (1 = Locked, 0 = Not locked) 
 * - Bit 2: RX detection status (1 = Detected, 0 = Not detected)
 * - Bit 3: RX decoding status (1 = Decoded, 0 = Not decoded)
 */
uint8_t comms_sband_rx_link_check(void)
{
    uint8_t rx_sts = 0;

    s_comms_rx_tm  *rx_tm = (s_comms_rx_tm *)&rx_cfg_global.rx_cfg_frames;

#ifdef SDR_SBAND_SRS4
    uint16_t size = 0;
    SDR_SBAND_GET_RX_TM_PROP(rx_tm, &size);
#endif

    if(rx_tm->rx_cfg_carrier_lock)
    {
        rx_sts |= SRS4_CARRIER_LOCKED;
    }

    if(rx_tm->rx_frame_lock)
    {
        rx_sts |= SRS4_FRAME_LOCKED;
    }

    if(rx_tm->rx_cfg_detected)
    {
        rx_sts |= SRS4_RX_DETECTED;
    }

    if(rx_tm->rx_cfg_frames)
    {
        rx_sts |= SRS4_RX_DECODED;
    }

    return rx_sts;
}
