//#include <proc/p32mx440f256h.h>

#include "E220Module.h"
#include "BoardCfg.h"
#include "timer.h"
#include "Uart.h"
#include "ProtocolDefs.h"


int InitLoraModule()
{
    
	return RET_OK;
}

int SetLoraModuleTxMode()
{
    LORA_MODULE_M0_PIN = 1;
    LORA_MODULE_M1_PIN = 1;
    return RET_OK;
}

int SetLoraModuleConfigMode()
{
    LORA_MODULE_M0_PIN = 0;
    LORA_MODULE_M1_PIN = 0;
    return RET_OK;
}

int ReadLoraModuleConfig()
{
    char Cmd[3]={0xC1,0x00,E220_CONFIG_SIZE};
    SetLoraModuleConfigMode();
    Sleep(100);
    SendInternalUartDataBlocking(Cmd,3,LORA_MODULE_UART_PORT);
    return RET_OK;
}

int ReadLoraModuleRSSI()
{
    char Cmd[6]={0xC0,0xC1,0xC2,0xC3,0x00,0x02};
    Sleep(100);
    SendInternalUartDataBlocking(Cmd,6,LORA_MODULE_UART_PORT);
    return RET_OK;
}

int AnalyzeLoraModuleConfigData(char *Data, int size)
{
    char header = Data[0];
    if(header != (char)0xC1)
    {
        return RET_ERROR;
    }
    unsigned char StartAddress = Data[1];
    unsigned char DataLength = Data[2];
    
    if(DataLength != E220_CONFIG_SIZE)
    {
        //This function must be use to analyze all registers.
        return RET_ERROR;
    }
    
    mModuleInternalAddress = Data[3];
    mModuleInternalAddress <<= 8;
    mModuleInternalAddress |= Data[4];
    
    unsigned char Byte2 = Data[5];
    mModuleAirRate = Byte2 & E220_AIR_RATE_MASK;
    Byte2 >>= 3;
    
    mModuleUARTParity = Byte2 & E220_UART_PARITY_MASK;
    Byte2 >>= 2;
    
    mModuleUARTRate = Byte2 & E220_UART_RATE_MASK;

    
    unsigned char Byte3 = Data[6];
    mModuleTxPower = Byte3 & E220_TX_POWER_MASK;
    Byte3 >>= 5; //Bit 4,3,2 are reserved
    
    mModuleRSSIEnabled = Byte3 & 0x01;
    Byte3 >>= 1;
    
    mModuleSubPacket = Byte3 & E220_PACKET_SIZE_MASK;
    
    
    mModuleInternalChannel = Data[7];
    
    unsigned char Byte5 = Data[8];
    mModuleWORCycle = Byte5 & E220_WOR_CYCLE_MASK;
    Byte5 >>= 4; //Bit 3 is reserved
    
    mModuleLBTEnabled = Byte5 & 0x01;
    Byte5 >>= 2; //Bit 5 is reserved
    
    mModuleTxMethod = Byte5 & 0x01;
    Byte5 >>= 1; 
    
    mModuleRSSIByteEnabled = Byte5 & 0x01;

    
    return RET_OK;
    
}

int AnalyzeLoraModuleRSSI(char *Data, int size)
{
    char header = Data[0];
    if(header != (char)0xC1)
    {
        return RET_ERROR;
    }
    char StartAddress = Data[1];
    char Size = Data[2];
    
    mModuleAmbientRSSI = Data[3];
    if(Size == (char)2)
    {
        mModuleLastRxRSSI = Data[4];
    }
}
