// 秒寻科技
// 手机路由模块
// zt
// 2023-04-25

#include "../../includes/includes.h"

// 基于蓝牙基站路由，找出主站(即用户当前在哪个基站附近)
// pstBluetoothBtsList:蓝牙站队列
// byBleBtsNum:蓝牙站数量
// pstInstallBtsList:安装站列表
// pstMainBtsData:返回参数，主站数据
// 返回值：1，成功；0，失败
uint8 route_bluetooth_route(ROUTE_BLUETOOTH_BTS_T *pstBluetoothBtsList, uint32 dwBtsNum, BTS_INSTALL_BTS_LIST_T *pstInstallBtsList, BTS_INSTALL_BTS_T *pstMainBts)
{
    uint8 byFlag = 0;

    // 按照接收电平倒排序
    route_bluetooth_bts_sort(pstBluetoothBtsList, dwBtsNum);

    // 从安装基站队列中查找蓝牙基站
    byFlag = route_bluetooth_find_bluetooth_bts_from_install_bts(pstBluetoothBtsList, (uint8)dwBtsNum, pstInstallBtsList, pstMainBts);

    return byFlag;
}

// 按照接收电平排序
// pstBluetoothBtsList:蓝牙站队列
// dwBtsNum:蓝牙站数量
void route_bluetooth_bts_sort(ROUTE_BLUETOOTH_BTS_T *pstBluetoothBtsList, uint32 dwBtsNum)
{
    ROUTE_BLUETOOTH_BTS_T stTmp = {0};

    for (uint8 i = 0; i < dwBtsNum; i++)
    {
        for (uint8 j = i + 1; j < dwBtsNum; j++)
        {
            if (pstBluetoothBtsList[j].dwRssi > pstBluetoothBtsList[i].dwRssi)
            {
                stTmp = pstBluetoothBtsList[i];
                pstBluetoothBtsList[i] = pstBluetoothBtsList[j];
                pstBluetoothBtsList[j] = stTmp;
            }
        }
    }

    return;
}

// 从本地安装基站中查找蓝牙基站
// pstBluetoothBtsList:蓝牙站队列
// byBleBtsNum:蓝牙站数量
// pstInstallBtsList:安装站列表
// pstMainBtsData:返回参数，主站数据
// 返回值:0，失败；1，成功
uint8 route_bluetooth_find_bluetooth_bts_from_install_bts(ROUTE_BLUETOOTH_BTS_T *pstBluetoothBtsList, uint8 byBleBtsNum, BTS_INSTALL_BTS_LIST_T *pstInstallBtsList, BTS_INSTALL_BTS_T *pstMainBtsData)
{
    ROUTE_BLUETOOTH_BTS_T stBluetoothBts = {0};

    uint32 dwInstallBtsNum = pstInstallBtsList->dwBtsNum;
    BTS_INSTALL_BTS_T stInstallBts = {0};

    uint8 byValidFlag = 0;

    for (uint8 i = 0; i < byBleBtsNum; i++)
    {
        stBluetoothBts = pstBluetoothBtsList[i];
        for (uint16 j = 0; j < dwInstallBtsNum; j++)
        {
            stInstallBts = pstInstallBtsList->astLocalBtsList[j];

            // 判断MAC地址是否相同
            byValidFlag = 1;
            for (uint8 k = 0; k < PUB_MAC_ADDRESS_LEN; k++)
            {
                // 不相符
                if (stBluetoothBts.adwMac[k] != stInstallBts.adwBluetoothMac[k])
                {
                    byValidFlag = 0;
                    break;
                }
            }

            // 在本地安装基站中找到了该蓝牙基站
            if (byValidFlag)
            {
                break;
            }
        }

        // 在本地安装基站中找到了该蓝牙基站
        if (byValidFlag)
        {
            break;
        }
    }

    // 找到了主站
    if (byValidFlag)
    {
        *pstMainBtsData = stInstallBts;
        return 1;
    }

    return 0;
}
